Skip to content

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

feat(remove): add experimental --reap to kill worktree processes (#3396)

Worktrunk Botf593438e7c1b
diff --git a/docs/content/remove.md b/docs/content/remove.md
index 57ce43ab0..362dc9d3a 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -73,6 +73,27 @@ Removal runs in the background by default — the command returns immediately. T
After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+## Reaping processes
+
+<span class="badge-experimental"></span>
+
+`--reap` terminates processes left running in the worktree before it is removed — a `post-start` dev server, a file watcher, a language server — freeing the ports and file handles they hold. Processes are discovered by working directory: any process whose current directory is at or under the worktree path (`SIGTERM`, then `SIGKILL` for survivors).
+
+{% terminal(cmd="wt remove --reap feature") %}
+◎ Reaping 2 processes under feature worktree
+ ┃ 51234 node
+ ┃ 51240 esbuild
+✓ Reaped 2 processes
+◎ Removing feature worktree & branch in background (same commit as main, _)
+{% end %}
+
+To avoid killing work the user did not mean to kill, two guards keep `--reap` conservative:
+
+- **Interactive processes are spared.** A process holding a controlling terminal — an interactive shell, or a terminal editor such as `vim` with unsaved buffers — is never reaped. Only detached processes remain candidates.
+- **Discovery is by working directory only.** A process that started in the worktree and later changed directory, or a daemon that reparented to `init`, no longer reports a directory under the worktree and is not found. To reliably reap those, launch them with [`wt step tether`](@/step.md#wt-step-tether), which kills the whole process group when the worktree is removed.
+
+Reaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.
+
## Hooks
`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](@/hook.md) for configuration.
@@ -109,6 +130,13 @@ Usage: <b><span class=c>wt remove</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--foreground</span></b>
Run removal in foreground (block until complete)
+ <b><span class=c>--reap</span></b>
+ Kill processes started in the worktree [experimental]
+
+ Before removal, terminate processes whose working directory is under the worktree — dev
+ servers, watchers, language servers. Processes holding a controlling terminal (interactive
+ shells, terminal editors) are left alone. Unix only.
+
<b><span class=c>-f</span></b>, <b><span class=c>--force</span></b>
Force worktree removal
diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.md
index c5b103f8a..c5c9e4881 100644
--- a/skills/worktrunk/reference/remove.md
+++ b/skills/worktrunk/reference/remove.md
@@ -76,6 +76,26 @@ Removal runs in the background by default — the command returns immediately. T
After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+## Reaping processes [experimental]
+
+`--reap` terminates processes left running in the worktree before it is removed — a `post-start` dev server, a file watcher, a language server — freeing the ports and file handles they hold. Processes are discovered by working directory: any process whose current directory is at or under the worktree path (`SIGTERM`, then `SIGKILL` for survivors).
+
+```bash
+$ wt remove --reap feature
+◎ Reaping 2 processes under feature worktree
+ ┃ 51234 node
+ ┃ 51240 esbuild
+✓ Reaped 2 processes
+◎ Removing feature worktree & branch in background (same commit as main, _)
+```
+
+To avoid killing work the user did not mean to kill, two guards keep `--reap` conservative:
+
+- **Interactive processes are spared.** A process holding a controlling terminal — an interactive shell, or a terminal editor such as `vim` with unsaved buffers — is never reaped. Only detached processes remain candidates.
+- **Discovery is by working directory only.** A process that started in the worktree and later changed directory, or a daemon that reparented to `init`, no longer reports a directory under the worktree and is not found. To reliably reap those, launch them with [`wt step tether`](https://worktrunk.dev/step/#wt-step-tether), which kills the whole process group when the worktree is removed.
+
+Reaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.
+
## Hooks
`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](https://worktrunk.dev/hook/) for configuration.
@@ -107,6 +127,13 @@ Options:
--foreground
Run removal in foreground (block until complete)
+ --reap
+ Kill processes started in the worktree [experimental]
+
+ Before removal, terminate processes whose working directory is under the worktree — dev
+ servers, watchers, language servers. Processes holding a controlling terminal (interactive
+ shells, terminal editors) are left alone. Unix only.
+
-f, --force
Force worktree removal
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index db4e855e5..158d567b7 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -493,6 +493,15 @@ pub(crate) struct RemoveArgs {
#[arg(long)]
pub(crate) foreground: bool,
+ /// Kill processes started in the worktree \[experimental\]
+ ///
+ /// Before removal, terminate processes whose working directory is under
+ /// the worktree — dev servers, watchers, language servers. Processes
+ /// holding a controlling terminal (interactive shells, terminal editors)
+ /// are left alone. Unix only.
+ #[arg(long)]
+ pub(crate) reap: bool,
+
#[command(flatten)]
pub(crate) hooks: HookFlags,
@@ -1281,6 +1290,26 @@ Removal runs in the background by default — the command returns immediately. T
After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+## Reaping processes [experimental]
+
+`--reap` terminates processes left running in the worktree before it is removed — a `post-start` dev server, a file watcher, a language server — freeing the ports and file handles they hold. Processes are discovered by working directory: any process whose current directory is at or under the worktree path (`SIGTERM`, then `SIGKILL` for survivors).
+
+```console
+$ wt remove --reap feature
+◎ Reaping 2 processes under feature worktree
+ ┃ 51234 node
+ ┃ 51240 esbuild
+✓ Reaped 2 processes
+◎ Removing feature worktree & branch in background (same commit as main, _)
+```
+
+To avoid killing work the user did not mean to kill, two guards keep `--reap` conservative:
+
+- **Interactive processes are spared.** A process holding a controlling terminal — an interactive shell, or a terminal editor such as `vim` with unsaved buffers — is never reaped. Only detached processes remain candidates.
+- **Discovery is by working directory only.** A process that started in the worktree and later changed directory, or a daemon that reparented to `init`, no longer reports a directory under the worktree and is not found. To reliably reap those, launch them with [`wt step tether`](@/step.md#wt-step-tether), which kills the whole process group when the worktree is removed.
+
+Reaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.
+
## Hooks
`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](@/hook.md) for configuration.
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index cdf50449d..b999f0545 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -163,6 +163,74 @@ fn validate_remove_targets(
plans
}
+/// Terminate processes whose working directory is under a worktree, for
+/// `--reap` (experimental). Discovery, the controlling-terminal / self
+/// exclusions, and the `SIGTERM`→`SIGKILL` escalation live in
+/// [`worktrunk::git::reap`]; this wrapper renders the user-facing progress.
+///
+/// Called before the worktree directory is staged/renamed — cwd matching
+/// requires the directory at its original path. Best-effort: no candidate,
+/// or a survivor that ignored both signals, never blocks the removal.
+#[cfg(unix)]
+fn reap_worktree_processes(worktree_path: &Path, label: &str) {
+ use color_print::cformat;
+ use worktrunk::git::reap;
+ use worktrunk::styling::{
+ format_with_gutter, progress_message, success_message, warning_message,
+ };
+
+ let procs = reap::collect_reapable(worktree_path);
+ if procs.is_empty() {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "No processes to reap under <bold>{label}</> worktree"
+ ))
+ );
+ return;
+ }
+
+ let count = procs.len();
+ let noun = reap::process_noun(count);
+ eprintln!(
+ "{}",
+ progress_message(cformat!(
+ "Reaping {count} {noun} under <bold>{label}</> worktree"
+ ))
+ );
+ let listing = procs
+ .iter()
+ .map(|p| format!("{} {}", p.pid, p.command))
+ .collect::<Vec<_>>()
+ .join("\n");
+ eprintln!("{}", format_with_gutter(&listing, None));
+
+ let pids: Vec<u32> = procs.iter().map(|p| p.pid).collect();
+ let gone = reap::reap_pids(&pids);
+ match reap::reap_summary(count, gone) {
+ Ok(msg) => eprintln!("{}", success_message(msg)),
+ Err(msg) => eprintln!("{}", warning_message(msg)),
+ }
+}
+
+/// Reap the removed worktree's processes when `--reap` is set and the result
+/// removed a worktree (branch-only deletions have no directory to scope by).
+/// The display label prefers the branch name, falling back to the worktree
+/// directory name. No-op on non-Unix, where `--reap` is rejected up front.
+fn maybe_reap_result(result: &RemoveResult, reap_enabled: bool) {
+ #[cfg(unix)]
+ if reap_enabled && let Some(path) = result.removed_worktree_path() {
+ let label = result
+ .branch_name()
+ .map(str::to_string)
+ .or_else(|| path.file_name().map(|n| n.to_string_lossy().into_owned()))
+ .unwrap_or_else(|| "worktree".to_string());
+ reap_worktree_processes(path, &label);
+ }
+ #[cfg(not(unix))]
+ let _ = (result, reap_enabled);
+}
+
/// Entry point for the `wt remove` command.
///
/// # Command flow
@@ -209,6 +277,14 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
.into());
}
+ // `--reap` relies on per-process cwd discovery (`lsof`/`ps`), which
+ // has no cheap Windows equivalent — reject it there rather than
+ // silently no-op.
+ #[cfg(not(unix))]
+ if args.reap {
+ anyhow::bail!("--reap is not supported on Windows");
+ }
+
// Helper: build and approve, once, the frozen hook plan the
// removal will run. Every hook (`pre-remove` / `post-remove` per
// removed worktree, `post-switch` per post-removal destination) is
@@ -281,6 +357,8 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
yes,
)?;
+ maybe_reap_result(&result, args.reap);
+
let mut announcer = HookAnnouncer::new(&repo, false);
handle_remove_output(
&result,
@@ -344,6 +422,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
let show_branch =
plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;
let run = |result: &RemoveResult| -> anyhow::Result<()> {
+ maybe_reap_result(result, args.reap);
let mut announcer = HookAnnouncer::new(&repo, show_branch);
handle_remove_output(
result,
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 75ca89522..05021f2f6 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -204,6 +204,19 @@ impl RemoveResult {
}
}
+ /// Branch name of the removed worktree, if known. `None` for detached-HEAD
+ /// worktrees and (structurally) for branch-only deletions.
+ ///
+ /// Only the `--reap` label needs this, which is Unix-only; gated to avoid a
+ /// dead-code warning on Windows where nothing consumes it.
+ #[cfg(unix)]
+ pub fn branch_name(&self) -> Option<&str> {
+ match self {
+ RemoveResult::RemovedWorktree { branch_name, .. } => branch_name.as_deref(),
+ RemoveResult::BranchOnly { branch_name, .. } => Some(branch_name),
+ }
+ }
+
/// Post-removal working directory — where the user lands, and the worktree
/// whose `.config/wt.toml` `post-switch` reads. `None` for branch-only
/// deletions (no worktree was removed, so nothing was switched away from).
@@ -255,6 +268,32 @@ mod tests {
assert_eq!(result.path(), &path);
}
+ #[cfg(unix)]
+ #[test]
+ fn remove_result_branch_name_reads_both_variants() {
+ let removed = RemoveResult::RemovedWorktree {
+ main_path: PathBuf::from("/main"),
+ worktree_path: PathBuf::from("/wt"),
+ changed_directory: false,
+ branch_name: Some("feature".to_string()),
+ deletion_mode: BranchDeletionMode::default(),
+ target_branch: None,
+ force_worktree: false,
+ expected_path: None,
+ removed_commit: None,
+ };
+ assert_eq!(removed.branch_name(), Some("feature"));
+
+ let branch_only = RemoveResult::BranchOnly {
+ branch_name: "solo".to_string(),
+ deletion_mode: BranchDeletionMode::default(),
+ pruned: false,
+ target_branch: None,
+ integration_reason: None,
+ };
+ assert_eq!(branch_only.branch_name(), Some("solo"));
+ }
+
#[test]
fn test_switch_result_path_existing() {
let path = PathBuf::from("/test/existing");
diff --git a/src/git/mod.rs b/src/git/mod.rs
index ab035fcd8..3785f9391 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -8,6 +8,8 @@ mod diff;
mod error;
pub mod fsmonitor;
mod parse;
+#[cfg(unix)]
+pub mod reap;
pub mod recover;
pub mod remote_ref;
pub mod remove;
diff --git a/src/git/reap.rs b/src/git/reap.rs
new file mode 100644
index 000000000..2a862372a
--- /dev/null
+++ b/src/git/reap.rs
@@ -0,0 +1,391 @@
+//! Discover and terminate processes whose working directory is under a
+//! worktree, for `wt remove --reap` (experimental).
+//!
+//! # Purpose
+//!
+//! Removing a worktree leaves behind any long-running process started inside
+//! it — a `post-start` dev server, a watcher, a language server — still
+//! holding ports and file handles. `--reap` opts into terminating those
+//! processes as part of removal.
+//!
+//! # Discovery
+//!
+//! Processes are discovered by working directory: any process whose `cwd` is
+//! at or under the worktree path. `lsof -d cwd` reports every visible
+//! process's cwd in one call; [`parse_lsof_cwd`] parses it and the caller
+//! filters by path prefix. This is deliberately scoped to processes the
+//! invoking user can see (no root), matching the `lsof` reliance already
+//! established by [`super::fsmonitor`].
+//!
+//! # Data-safety contract
+//!
+//! Killing a process the user did not mean to kill — an editor with unsaved
+//! buffers, an interactive shell — is exactly the silent loss-of-work the
+//! project refuses without explicit consent. Two guards keep `--reap`
+//! conservative:
+//!
+//! - **Controlling-terminal exclusion.** A process holding a controlling
+//! terminal is an interactive shell (including the one `wt remove` was run
+//! from) or a terminal editor (`vim`, `nvim`, `emacs -nw`). These are the
+//! "keep-me" set; `without_controlling_terminal` drops them via `ps -o
+//! tty=`, so only detached processes (dev servers, watchers, daemons) remain
+//! candidates.
+//! - **Self-exclusion.** The current `wt` process is never a candidate.
+//!
+//! cwd-based discovery is also **under-inclusive by design**: a daemon that
+//! forked and `chdir`'d away, or reparented to pid 1, no longer reports a cwd
+//! under the path and is not found. Those are what [`wt step tether`] is built
+//! to reap (it kills the whole process group). `--reap` and `tether` cover
+//! different gaps and are not substitutes.
+//!
+//! # Platform
+//!
+//! Unix only. Windows has no cheap per-process cwd, so the whole module is
+//! `#[cfg(unix)]` and the `wt remove` command rejects `--reap` there.
+//!
+//! [`wt step tether`]: https://worktrunk.dev/step/#wt-step-tether
+
+#![cfg(unix)]
+
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use crate::shell_exec::Cmd;
+
+use super::fsmonitor::{NixSignaller, REAP_KILL_DEADLINE, escalate_terminate};
+
+/// One process discovered under a worktree: its PID, short command name, and
+/// the working directory `lsof` reported.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CwdProcess {
+ pub pid: u32,
+ /// Short command name from `lsof` (truncated to ~9 chars by `lsof`).
+ pub command: String,
+ pub cwd: PathBuf,
+}
+
+/// Timeout for the `lsof` / `ps` probes. Discovery is opt-in and off the hot
+/// path, but a hung probe should still not stall removal indefinitely.
+const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// Parse `lsof -d cwd -F pcn` field output into one [`CwdProcess`] per process.
+///
+/// `lsof` field output emits one record per line, prefixed by a field id:
+/// `p<pid>` opens a new process, `c<command>` names it, and `n<path>` gives the
+/// cwd (there is exactly one cwd file per process, selected by `-d cwd`). A
+/// process contributes a [`CwdProcess`] only once its `n` (cwd path) line is
+/// seen; records missing a path are skipped.
+pub fn parse_lsof_cwd(stdout: &str) -> Vec<CwdProcess> {
+ let mut out = Vec::new();
+ let mut pid: Option<u32> = None;
+ let mut command = String::new();
+
+ for line in stdout.lines() {
+ let Some((tag, rest)) = line.split_at_checked(1) else {
+ continue;
+ };
+ match tag {
+ "p" => {
+ pid = rest.trim().parse::<u32>().ok();
+ command = String::new();
+ }
+ "c" => command = rest.to_string(),
+ "n" => {
+ if let Some(pid) = pid {
+ out.push(CwdProcess {
+ pid,
+ command: command.clone(),
+ cwd: PathBuf::from(rest),
+ });
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+}
+
+/// Parse `ps -o pid=,tty=` output into `(pid, has_controlling_terminal)` pairs.
+///
+/// `ps` prints one line per PID: the PID, then the controlling terminal or a
+/// "none" marker (`?` / `??` on Linux/macOS, `-` on some platforms). A terminal
+/// name that starts with `?` or equals `-` means no controlling terminal.
+///
+/// This feeds a data-safety gate (a process *with* a terminal is spared), so
+/// the unreadable case fails safe: a line missing the tty column is reported as
+/// **having** a terminal, so an unparsable reading never turns into a reap.
+/// Real `ps -o tty=` always fills the column, so this only guards the anomaly.
+pub fn parse_ps_tty(stdout: &str) -> Vec<(u32, bool)> {
+ stdout
+ .lines()
+ .filter_map(|line| {
+ let mut fields = line.split_whitespace();
+ let pid = fields.next()?.parse::<u32>().ok()?;
+ let has_tty = match fields.next() {
+ Some(tty) => !(tty.starts_with('?') || tty == "-"),
+ None => true,
+ };
+ Some((pid, has_tty))
+ })
+ .collect()
+}
+
+/// Return the subset of `pids` that hold **no** controlling terminal.
+///
+/// Runs `ps -o pid=,tty=` over the candidate PIDs and keeps those whose
+/// terminal is a "none" marker — the detached processes safe to reap. A PID
+/// `ps` does not report (it exited between discovery and this probe, or `ps`
+/// exited non-zero because every requested PID was gone) simply doesn't appear
+/// in the output, so it's dropped. A `ps` spawn failure yields an empty set:
+/// without a terminal reading, nothing is reaped (fail-safe).
+fn without_controlling_terminal(pids: &[u32]) -> HashSet<u32> {
+ if pids.is_empty() {
+ return HashSet::new();
+ }
+ let pid_list = pids
+ .iter()
+ .map(u32::to_string)
+ .collect::<Vec<_>>()
+ .join(",");
+ // Parse whatever `ps` printed regardless of exit status: it exits non-zero
+ // when some requested PIDs are gone but still lists the live ones (the same
+ // partial-output shape `lsof` has in `processes_under`).
+ let Ok(output) = Cmd::new("ps")
+ .args(["-o", "pid=,tty=", "-p", &pid_list])
+ .timeout(PROBE_TIMEOUT)
+ .run()
+ else {
+ return HashSet::new();
+ };
+ parse_ps_tty(&String::from_utf8_lossy(&output.stdout))
+ .into_iter()
+ .filter_map(|(pid, has_tty)| (!has_tty).then_some(pid))
+ .collect()
+}
+
+/// Discover processes whose cwd is at or under `worktree_path`, excluding the
+/// current `wt` process. This is the raw discovery step, *before* the
+/// controlling-terminal guard — [`collect_reapable`] layers that on top.
+///
+/// Best-effort: an `lsof` spawn failure yields an empty list. `lsof -d cwd` is
+/// run system-wide rather than with `+D <path>` so it never walks the
+/// worktree's file tree; the prefix filter is applied here instead. Results
+/// are sorted by PID for stable output.
+pub fn processes_under(worktree_path: &Path) -> Vec<CwdProcess> {
+ let canonical =
+ dunce::canonicalize(worktree_path).unwrap_or_else(|_| worktree_path.to_path_buf());
+
+ // `lsof -d cwd` lists every visible process's cwd. It exits non-zero when
+ // some processes are inaccessible (other users), but still prints the
+ // accessible ones — so parse whatever stdout we got rather than gating on
+ // exit status. Only a spawn failure (lsof missing) means "no data".
+ let Ok(output) = Cmd::new("lsof")
+ .args(["-d", "cwd", "-F", "pcn"])
+ .timeout(PROBE_TIMEOUT)
+ .run()
+ else {
+ return Vec::new();
+ };
+
+ let self_pid = std::process::id();
+ let mut candidates: Vec<CwdProcess> = parse_lsof_cwd(&String::from_utf8_lossy(&output.stdout))
+ .into_iter()
+ .filter(|p| p.pid != self_pid)
+ .filter(|p| p.cwd.starts_with(&canonical))
+ .collect();
+ candidates.sort_by_key(|p| p.pid);
+ candidates
+}
+
+/// Discover the processes eligible for reaping under `worktree_path`.
+///
+/// Applies the full data-safety contract: [`processes_under`] (cwd prefix,
+/// self-exclusion) then drops any process holding a controlling terminal.
+/// Returns candidates sorted by PID for stable output.
+pub fn collect_reapable(worktree_path: &Path) -> Vec<CwdProcess> {
+ let mut candidates = processes_under(worktree_path);
+ if candidates.is_empty() {
+ return candidates;
+ }
+
+ let pids: Vec<u32> = candidates.iter().map(|p| p.pid).collect();
+ let reapable = without_controlling_terminal(&pids);
+ candidates.retain(|p| reapable.contains(&p.pid));
+ candidates
+}
+
+/// `SIGTERM`→wait→`SIGKILL` each PID, returning the count confirmed gone.
+///
+/// Thin wrapper over `escalate_terminate` with the production
+/// `NixSignaller` and the shared `REAP_KILL_DEADLINE`, so `--reap` uses the
+/// same bounded escalation as the fsmonitor sweep.
+pub fn reap_pids(pids: &[u32]) -> usize {
+ escalate_terminate(&NixSignaller, pids, REAP_KILL_DEADLINE)
+}
+
+/// Pluralized noun for a process count (`"process"` / `"processes"`).
+pub fn process_noun(count: usize) -> &'static str {
+ if count == 1 { "process" } else { "processes" }
+}
+
+/// Human summary of a reap outcome. `Ok` when every process was terminated (the
+/// caller renders it as success); `Err` when some survived both `SIGTERM` and
+/// `SIGKILL` (rendered as a warning).
+pub fn reap_summary(count: usize, gone: usize) -> Result<String, String> {
+ let noun = process_noun(count);
+ if gone >= count {
+ Ok(format!("Reaped {count} {noun}"))
+ } else {
+ let survived = count - gone;
+ Err(format!(
+ "Reaped {gone} of {count} {noun}; {survived} ignored SIGTERM & SIGKILL"
+ ))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_lsof_cwd_extracts_pid_command_and_path() {
+ let stdout = "\
+p101
+cnode
+fcwd
+n/home/user/repo.feature
+p202
+cesbuild
+fcwd
+n/home/user/repo.feature/node_modules/.bin
+";
+ let procs = parse_lsof_cwd(stdout);
+ assert_eq!(
+ procs,
+ vec![
+ CwdProcess {
+ pid: 101,
+ command: "node".into(),
+ cwd: PathBuf::from("/home/user/repo.feature"),
+ },
+ CwdProcess {
+ pid: 202,
+ command: "esbuild".into(),
+ cwd: PathBuf::from("/home/user/repo.feature/node_modules/.bin"),
+ },
+ ]
+ );
+ }
+
+ #[test]
+ fn parse_lsof_cwd_skips_process_without_cwd_line() {
+ // A process whose cwd lsof could not read (no `n` line) is dropped; a
+ // blank line and unknown field tags (`f`) are ignored.
+ let stdout = "\
+p101
+cbash
+
+p202
+czsh
+fcwd
+n/home/user/repo.feature
+";
+ let procs = parse_lsof_cwd(stdout);
+ assert_eq!(procs.len(), 1);
+ assert_eq!(procs[0].pid, 202);
+ }
+
+ #[test]
+ fn parse_ps_tty_classifies_terminal_presence() {
+ // Linux `?`, macOS `??`, and `-` all mean "no controlling terminal";
+ // `pts/2` / `s001` are real terminals.
+ let stdout = "\
+ 101 ?
+ 202 pts/2
+ 303 ??
+ 404 s001
+ 505 -
+";
+ let ttys = parse_ps_tty(stdout);
+ assert_eq!(
+ ttys,
+ vec![
+ (101, false),
+ (202, true),
+ (303, false),
+ (404, true),
+ (505, false),
+ ]
+ );
+ }
+
+ #[test]
+ fn parse_ps_tty_ignores_unparsable_lines() {
+ // A pid-only line (no tty column) fails safe as "has terminal" so an
+ // unreadable reading never becomes a reap candidate.
+ let stdout = "\
+header junk
+ 101 ?
+ 707
+not-a-pid tty
+";
+ assert_eq!(parse_ps_tty(stdout), vec![(101, false), (707, true)]);
+ }
+
+ #[test]
+ fn without_controlling_terminal_empty_input_is_empty() {
+ assert!(without_controlling_terminal(&[]).is_empty());
+ }
+
+ #[test]
+ fn discovery_on_nonexistent_path_is_empty() {
+ // A path that can't be canonicalized falls back to itself; no live
+ // process has a cwd under it, so both discovery layers return empty.
+ let missing = Path::new("/nonexistent/worktrunk-reap-xyz");
+ assert!(processes_under(missing).is_empty());
+ assert!(collect_reapable(missing).is_empty());
+ }
+
+ #[test]
+ fn reap_summary_reports_success_and_survivors() {
+ assert_eq!(process_noun(1), "process");
+ assert_eq!(process_noun(2), "processes");
+ assert_eq!(reap_summary(1, 1), Ok("Reaped 1 process".into()));
+ assert_eq!(reap_summary(3, 3), Ok("Reaped 3 processes".into()));
+ assert_eq!(
+ reap_summary(3, 1),
+ Err("Reaped 1 of 3 processes; 2 ignored SIGTERM & SIGKILL".into())
+ );
+ }
+
+ /// `reap_pids` against a real process: `SIGTERM` terminates it and the
+ /// count comes back confirmed. Discovery and the controlling-terminal
+ /// guard are covered in-process by the `test_remove_reap_kills_process`
+ /// integration test (which calls `processes_under` / `collect_reapable`
+ /// directly), so this focuses on the signalling half.
+ #[test]
+ fn reap_pids_terminates_a_process() {
+ use std::process::Command;
+
+ let mut child = Command::new("sleep").arg("30").spawn().unwrap();
+ let pid = child.id();
+
+ // Reap the zombie concurrently: `sleep` is a direct child here, so
+ // after SIGTERM it lingers as a zombie (still "alive" to `kill(pid,0)`)
+ // until `wait()`. Real reap targets are detached, not `wt`'s children,
+ // so `escalate_terminate` sees them vanish. A thread already blocked in
+ // `wait()` reaps the zombie the instant it exits, letting the alive
+ // check flip within a poll cycle.
+ let reaper = std::thread::spawn(move || child.wait().unwrap());
+ let gone = reap_pids(&[pid]);
+ let status = reaper.join().unwrap();
+
+ assert_eq!(gone, 1, "child {pid} was not confirmed terminated");
+ use std::os::unix::process::ExitStatusExt;
+ assert_eq!(
+ status.signal(),
+ Some(nix::sys::signal::Signal::SIGTERM as i32)
+ );
+ }
+}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index e1b9ede67..748077fd1 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -36,6 +36,105 @@ fn test_remove_from_worktree(mut repo: TestRepo) {
));
}
+// `--reap` (experimental) with no processes running under the worktree: the
+// reap phase reports it found nothing, then removal proceeds normally. A fresh
+// worktree has no processes with a cwd under it, so this is deterministic
+// (and identical whether or not `lsof` is installed on the runner).
+#[cfg(unix)]
+#[rstest]
+fn test_remove_reap_no_processes(mut repo: TestRepo) {
+ repo.add_worktree("feature-reap");
+
+ // Remove by name from the primary worktree so the reap scans the removed
+ // worktree's path, not the current one.
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--reap", "feature-reap"],
+ None
+ ));
+}
+
+// `--reap` (experimental) with a real process running under the worktree: the
+// detached child is discovered and terminated before removal. Whether the
+// controlling-terminal guard reaps it depends on the test's own terminal
+// (none in CI → reaped; a TTY on a dev box → spared), so the assertion is
+// driven off the guard's verdict rather than assuming either — keeping the
+// found-processes path exercised in CI without becoming host-dependent.
+#[cfg(unix)]
+#[rstest]
+fn test_remove_reap_kills_process(mut repo: TestRepo) {
+ use std::os::unix::process::CommandExt;
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+ use worktrunk::git::reap;
+
+ let worktree_path = repo.add_worktree("feature-reapkill");
+ let canonical = std::fs::canonicalize(&worktree_path).unwrap();
+
+ // A detached child whose cwd is the worktree — the shape `--reap` targets.
+ let mut child = Command::new("sleep")
+ .arg("60")
+ .current_dir(&canonical)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .process_group(0)
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+
+ // Wait until lsof reports the child's cwd (fast, but not instant).
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while !reap::processes_under(&canonical)
+ .iter()
+ .any(|p| p.pid == pid)
+ {
+ assert!(Instant::now() < deadline, "child {pid} never discovered");
+ std::thread::sleep(Duration::from_millis(50));
+ }
+
+ // The guard reaps the child iff it holds no controlling terminal.
+ let will_reap = reap::collect_reapable(&canonical)
+ .iter()
+ .any(|p| p.pid == pid);
+
+ let run_remove = |repo: &TestRepo| {
+ let output = repo
+ .wt_command()
+ .args(["remove", "--reap", "feature-reapkill"])
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&output.stderr).into_owned()
+ };
+
+ if will_reap {
+ // `sleep` is a child of *this* test process, so once `wt` signals it,
+ // its parent (us) must `wait()` to reap the zombie — otherwise it
+ // lingers and `wt`'s liveness check (`kill(pid, 0)`) still sees it.
+ // Real reap targets aren't `wt`'s children, so they simply vanish. A
+ // thread already blocked in `wait()` reaps it the instant it exits.
+ let reaper = std::thread::spawn(move || child.wait().unwrap());
+ let stderr = run_remove(&repo);
+ let status = reaper.join().unwrap();
+
+ assert!(
+ stderr.contains("Reaping 1 process under") && stderr.contains("Reaped 1 process"),
+ "expected reap output, got:\n{stderr}"
+ );
+ // Terminated by a signal (SIGTERM, or SIGKILL if it ignored SIGTERM).
+ assert!(!status.success());
+ } else {
+ let stderr = run_remove(&repo);
+ assert!(
+ stderr.contains("No processes to reap"),
+ "expected no-reap output, got:\n{stderr}"
+ );
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+}
+
#[rstest]
fn test_remove_internal_mode(mut repo: TestRepo) {
let worktree_path = repo.add_worktree("feature-internal");
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index 465f3f56c..37b3200d1 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -52,6 +52,11 @@ Usage: wt remove [OPTIONS] [BRANCHES]...
--foreground
Run removal in foreground (block until complete)
+ --reap
+ Kill processes started in the worktree [experimental]
+
+ Before removal, terminate processes whose working directory is under the worktree — dev servers, watchers, language servers. Processes holding a controlling terminal (interactive shells, terminal editors) are left alone. Unix only.
+
-f, --force
Force worktree removal
@@ -152,6 +157,24 @@ Removal runs in the background by default — the command returns immediately. T
After each wt remove, entries in .git/wt/trash/ older than 24 hours are swept by a detached rm -rf — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+Reaping processes [experimental]
+
+--reap terminates processes left running in the worktree before it is removed — a post-start dev server, a file watcher, a language server — freeing the ports and file handles they hold. Processes are discovered by working directory: any process whose current directory is at or under the worktree path (SIGTERM, then SIGKILL for survivors).
+
+  wt remove --reap feature
+  ◎ Reaping 2 processes under feature worktree
+   ┃ 51234 node
+   ┃ 51240 esbuild
+  ✓ Reaped 2 processes
+  ◎ Removing feature worktree & branch in background (same commit as main, _)
+
+To avoid killing work the user did not mean to kill, two guards keep --reap conservative:
+
+- Interactive processes are spared. A process holding a controlling terminal — an interactive shell, or a terminal editor such as vim with unsaved buffers — is never reaped. Only detached processes remain candidates.
+- Discovery is by working directory only. A process that started in the worktree and later changed directory, or a daemon that reparented to init, no longer reports a directory under the worktree and is not found. To reliably reap those, launch them with wt step tether, which kills the whole process group when the worktree is removed.
+
+Reaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the --force flag. Unix only; on Windows --reap is rejected.
+
Hooks
pre-remove hooks run before the worktree is deleted (with access to worktree files). post-remove hooks run after removal. See wt hook for configuration.
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
index fd8137d97..dc6a8b61a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
@@ -43,6 +43,7 @@ Usage: wt remove [OPTIONS] [BRANCHES]...
--no-delete-branch Keep branch after removal
-D, --force-delete Delete unmerged branches
--foreground Run removal in foreground (block until complete)
+ --reap Kill processes started in the worktree [experimental]
-f, --force Force worktree removal
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_reap_no_processes.snap b/tests/snapshots/integration__integration_tests__remove__remove_reap_no_processes.snap
new file mode 100644
index 000000000..44f13162f
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_reap_no_processes.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--reap"
+ - feature-reap
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ No processes to reap under feature-reap worktree
+◎ Removing feature-reap worktree & branch in background (same commit as main, _)