Skip to content

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

Add `wt step tether`: kill a command's process group when its worktree is removed

Maximilian Roos408f4f5bee23
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 8bc0fdb19..76858f787 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -317,7 +317,7 @@ The long form `--var KEY=VALUE` is deprecated but still supported. It force-bind
# Recipes
- [Eliminate cold starts](@/tips-patterns.md#eliminate-cold-starts): `wt step copy-ignored` in `post-start` shares build caches and dependencies; use a `[[post-start]]` pipeline when a later hook depends on the copy
-- [Dev server per worktree](@/tips-patterns.md#dev-server-per-worktree): `hash_port` in `post-start` for launch and `post-remove` for cleanup, with optional subdomain routing
+- [Dev server per worktree](@/tips-patterns.md#dev-server-per-worktree): `wt step tether` in `post-start` runs the dev server and kills its whole process group when the worktree is removed, with optional subdomain routing
- [Database per worktree](@/tips-patterns.md#database-per-worktree): a `post-start` pipeline stores container name, port, and connection string as [per-branch vars](@/config.md#wt-config-state-vars) that later hooks reference
- [Progressive validation](@/tips-patterns.md#progressive-validation): quick lint/typecheck in `pre-commit`, expensive tests and builds in `pre-merge`
- [Target-specific hooks](@/tips-patterns.md#target-specific-hooks): branch on `{{ target }}` in `post-merge` for per-environment deploys
diff --git a/docs/content/step.md b/docs/content/step.md
index 9f6f359ad..e7567dee0 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -38,6 +38,7 @@ Manual merge workflow with review between steps:
- [`promote`](#wt-step-promote) — <span class="badge-experimental"></span> Swap a branch into the main worktree
- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch
- [`relocate`](#wt-step-relocate) — <span class="badge-experimental"></span> Move worktrees to expected paths
+- [`tether`](#wt-step-tether) — <span class="badge-experimental"></span> Run a command; kill its whole process tree when its worktree is removed
- [`<alias>`](@/extending.md#aliases) — Run a configured command alias
## See also
@@ -67,6 +68,8 @@ Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>promote</span></b> [experimental] Swap a branch into the main worktree
<b><span class=c>prune</span></b> [experimental] Remove worktrees merged into the default branch
<b><span class=c>relocate</span></b> [experimental] Move worktrees to expected paths
+ <b><span class=c>tether</span></b> [experimental] Run a command; kill its whole process tree when its worktree is
+ removed
<b><span class=g>Options:</span></b>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
@@ -895,4 +898,75 @@ Usage: <b><span class=c>wt step relocate</span></b> <span class=c>[OPTIONS]</spa
Skip approval prompts
{% end %}
+## wt step tether
+
+<span class="badge-experimental"></span>
+
+Run a command; kill its whole process tree when its worktree is removed. Teardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.
+
+### Why
+
+A `post-start` hook to start a long-lived process and a `pre-remove` hook to
+stop it is usually enough. But `pre-remove` only runs when worktrunk removes
+the worktree, so a `git worktree remove`, an `rm -rf`, or a crashed hook skips
+it. Across enough worktree churn some process is bound to outlive its worktree,
+and with no cleanup these leaks accumulate (on macOS they eventually saturate
+`fseventsd`). `tether` removes the need for a `pre-remove`: it ties the
+command's lifetime to the worktree and kills the whole process group once the
+worktree is gone.
+
+### Arguments
+
+Arguments after `--` are the program and its arguments, run directly, no shell.
+
+{{ terminal(cmd="wt step tether -- npm run dev") }}
+
+For pipes, redirects, variables, or globs, wrap in `sh -c`:
+
+{{ terminal(cmd="wt step tether -- sh -c 'PORT=$P npm run dev | tee dev.log'") }}
+
+### Examples
+
+Run a dev server, torn down automatically when the worktree goes away:
+
+```toml
+# .config/wt.toml
+[post-start]
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
+```
+
+Note: This command is experimental and may change in future versions.
+
+### Command reference
+
+{% terminal() %}
+wt step tether - [experimental] Run a command; kill its whole process tree when its worktree is removed
+
+Teardown is automatic and needs no <b>pre-remove</b> hook; the group gets <b>SIGTERM</b> then <b>SIGKILL</b>.
+
+Usage: <b><span class=c>wt step tether</span></b> <span class=c>[OPTIONS]</span> <b><span class=c>--</span></b> <span class=c>&lt;COMMAND&gt;...</span>
+
+<b><span class=g>Arguments:</span></b>
+ <span class=c>&lt;COMMAND&gt;...</span>
+ Command to run (after <b>--</b>, run directly, no shell)
+
+<b><span class=g>Options:</span></b>
+ <b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
+ Print help (see a summary with &#39;-h&#39;)
+
+<b><span class=g>Global Options:</span></b>
+ <b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
+ Working directory for this command
+
+ <b><span class=c>--config</span></b><span class=c> &lt;path&gt;</span>
+ User config file path
+
+ <b><span class=c>-v</span></b>, <b><span class=c>--verbose</span></b><span class=c>...</span>
+ Verbose output (-v: info logs + hook/alias template variable &amp; output; -vv: debug logs +
+ diagnostic report + trace.log/output.log under .git/wt/logs/)
+
+ <b><span class=c>-y</span></b>, <b><span class=c>--yes</span></b>
+ Skip approval prompts
+{% end %}
+
<!-- END AUTO-GENERATED -->
diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.md
index 32b363ced..b2f28a064 100644
--- a/docs/content/tips-patterns.md
+++ b/docs/content/tips-patterns.md
@@ -48,15 +48,14 @@ Each worktree runs its own dev server on a deterministic port. The `hash_port` f
```toml
# .config/wt.toml
[post-start]
-server = "npm run dev -- --port {{ branch | hash_port }}"
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
[list]
url = "http://localhost:{{ branch | hash_port }}"
-
-[pre-remove]
-server = "lsof -ti :{{ branch | hash_port }} -sTCP:LISTEN | xargs kill 2>/dev/null || true"
```
+[`wt step tether`](@/step.md#wt-step-tether) runs the server in its own process group and tears the whole group down when the worktree is removed, so no `pre-remove` hook is needed. This matters because `npm run dev` spawns an esbuild process that does not listen on the dev-server port and reparents away when the top process exits, so a port- or parent-based kill leaks it; across enough worktree churn those leaks accumulate. See the [`wt step tether`](@/step.md#wt-step-tether) docs for the full rationale and platform behavior.
+
The URL column in `wt list` shows each worktree's dev server:
<!-- ⚠️ AUTO-GENERATED from tests/snapshots/integration__integration_tests__list__tips_dev_server_workflow.snap — edit source to update -->
@@ -74,7 +73,7 @@ The URL column in `wt list` shows each worktree's dev server:
<!-- END AUTO-GENERATED -->
-Ports are deterministic — `fix-auth` always gets port 16460, regardless of which machine or when. The URL dims if the server isn't running.
+Ports are deterministic: `fix-auth` always gets port 16460, regardless of which machine or when. The URL dims if the server isn't running.
## Database per worktree
@@ -345,7 +344,7 @@ Clean URLs like `http://feature-auth.myproject.localhost` without port numbers.
```toml
# .config/wt.toml
[post-start]
-server = "npm run dev -- --port {{ branch | hash_port }}"
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
proxy = """
curl -sf --max-time 0.5 http://localhost:2019/config/ || caddy start
curl -sf http://localhost:2019/config/apps/http/servers/wt || \
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 07ba8454e..9e11c902a 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -320,7 +320,7 @@ The long form `--var KEY=VALUE` is deprecated but still supported. It force-bind
# Recipes
- [Eliminate cold starts](https://worktrunk.dev/tips-patterns/#eliminate-cold-starts): `wt step copy-ignored` in `post-start` shares build caches and dependencies; use a `[[post-start]]` pipeline when a later hook depends on the copy
-- [Dev server per worktree](https://worktrunk.dev/tips-patterns/#dev-server-per-worktree): `hash_port` in `post-start` for launch and `post-remove` for cleanup, with optional subdomain routing
+- [Dev server per worktree](https://worktrunk.dev/tips-patterns/#dev-server-per-worktree): `wt step tether` in `post-start` runs the dev server and kills its whole process group when the worktree is removed, with optional subdomain routing
- [Database per worktree](https://worktrunk.dev/tips-patterns/#database-per-worktree): a `post-start` pipeline stores container name, port, and connection string as [per-branch vars](https://worktrunk.dev/config/#wt-config-state-vars) that later hooks reference
- [Progressive validation](https://worktrunk.dev/tips-patterns/#progressive-validation): quick lint/typecheck in `pre-commit`, expensive tests and builds in `pre-merge`
- [Target-specific hooks](https://worktrunk.dev/tips-patterns/#target-specific-hooks): branch on `{{ target }}` in `post-merge` for per-environment deploys
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index a7bf89bf7..d945e5a83 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -35,6 +35,7 @@ $ wt step push
- [`promote`](#wt-step-promote) — [experimental] Swap a branch into the main worktree
- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch
- [`relocate`](#wt-step-relocate) — [experimental] Move worktrees to expected paths
+- [`tether`](#wt-step-tether) — [experimental] Run a command; kill its whole process tree when its worktree is removed
- [`<alias>`](https://worktrunk.dev/extending/#aliases) — Run a configured command alias
## Command reference
@@ -58,6 +59,8 @@ Commands:
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is
+ removed
Options:
-h, --help
@@ -937,3 +940,78 @@ Global Options:
-y, --yes
Skip approval prompts
```
+
+## wt step tether
+
+[experimental]
+
+Run a command; kill its whole process tree when its worktree is removed. Teardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.
+
+### Why
+
+A `post-start` hook to start a long-lived process and a `pre-remove` hook to
+stop it is usually enough. But `pre-remove` only runs when worktrunk removes
+the worktree, so a `git worktree remove`, an `rm -rf`, or a crashed hook skips
+it. Across enough worktree churn some process is bound to outlive its worktree,
+and with no cleanup these leaks accumulate (on macOS they eventually saturate
+`fseventsd`). `tether` removes the need for a `pre-remove`: it ties the
+command's lifetime to the worktree and kills the whole process group once the
+worktree is gone.
+
+### Arguments
+
+Arguments after `--` are the program and its arguments, run directly, no shell.
+
+```bash
+$ wt step tether -- npm run dev
+```
+
+For pipes, redirects, variables, or globs, wrap in `sh -c`:
+
+```bash
+$ wt step tether -- sh -c 'PORT=$P npm run dev | tee dev.log'
+```
+
+### Examples
+
+Run a dev server, torn down automatically when the worktree goes away:
+
+```toml
+# .config/wt.toml
+[post-start]
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
+```
+
+Note: This command is experimental and may change in future versions.
+
+### Command reference
+
+```
+wt step tether - [experimental] Run a command; kill its whole process tree when its worktree is removed
+
+Teardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.
+
+Usage: wt step tether [OPTIONS] -- <COMMAND>...
+
+Arguments:
+ <COMMAND>...
+ Command to run (after --, run directly, no shell)
+
+Options:
+ -h, --help
+ Print help (see a summary with '-h')
+
+Global Options:
+ -C <path>
+ Working directory for this command
+
+ --config <path>
+ User config file path
+
+ -v, --verbose...
+ Verbose output (-v: info logs + hook/alias template variable & output; -vv: debug logs +
+ diagnostic report + trace.log/output.log under .git/wt/logs/)
+
+ -y, --yes
+ Skip approval prompts
+```
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index e5c846819..e7db4ff97 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -45,15 +45,14 @@ Each worktree runs its own dev server on a deterministic port. The `hash_port` f
```toml
# .config/wt.toml
[post-start]
-server = "npm run dev -- --port {{ branch | hash_port }}"
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
[list]
url = "http://localhost:{{ branch | hash_port }}"
-
-[pre-remove]
-server = "lsof -ti :{{ branch | hash_port }} -sTCP:LISTEN | xargs kill 2>/dev/null || true"
```
+[`wt step tether`](https://worktrunk.dev/step/#wt-step-tether) runs the server in its own process group and tears the whole group down when the worktree is removed, so no `pre-remove` hook is needed. This matters because `npm run dev` spawns an esbuild process that does not listen on the dev-server port and reparents away when the top process exits, so a port- or parent-based kill leaks it; across enough worktree churn those leaks accumulate. See the [`wt step tether`](https://worktrunk.dev/step/#wt-step-tether) docs for the full rationale and platform behavior.
+
The URL column in `wt list` shows each worktree's dev server:
```bash
@@ -67,7 +66,7 @@ $ wt list
<span class=d>○</span> <span class=d>Showing 4 worktrees, 2 with changes, 2 ahead, 2 columns hidden</span>
```
-Ports are deterministic — `fix-auth` always gets port 16460, regardless of which machine or when. The URL dims if the server isn't running.
+Ports are deterministic: `fix-auth` always gets port 16460, regardless of which machine or when. The URL dims if the server isn't running.
## Database per worktree
@@ -362,7 +361,7 @@ Clean URLs like `http://feature-auth.myproject.localhost` without port numbers.
```toml
# .config/wt.toml
[post-start]
-server = "npm run dev -- --port {{ branch | hash_port }}"
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
proxy = """
curl -sf --max-time 0.5 http://localhost:2019/config/ || caddy start
curl -sf http://localhost:2019/config/apps/http/servers/wt || \
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index bd8a9e852..4705eddb0 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1175,6 +1175,7 @@ $ wt step push
- [`promote`](#wt-step-promote) — [experimental] Swap a branch into the main worktree
- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch
- [`relocate`](#wt-step-relocate) — [experimental] Move worktrees to expected paths
+- [`tether`](#wt-step-tether) — [experimental] Run a command; kill its whole process tree when its worktree is removed
- [`<alias>`](@/extending.md#aliases) — Run a configured command alias
## See also
@@ -1190,7 +1191,8 @@ $ wt step push
<!-- subdoc: for-each -->
<!-- subdoc: promote -->
<!-- subdoc: prune -->
-<!-- subdoc: relocate -->"#
+<!-- subdoc: relocate -->
+<!-- subdoc: tether -->"#
)]
Step {
#[command(subcommand)]
@@ -1519,7 +1521,7 @@ The long form `--var KEY=VALUE` is deprecated but still supported. It force-bind
# Recipes
- [Eliminate cold starts](@/tips-patterns.md#eliminate-cold-starts): `wt step copy-ignored` in `post-start` shares build caches and dependencies; use a `[[post-start]]` pipeline when a later hook depends on the copy
-- [Dev server per worktree](@/tips-patterns.md#dev-server-per-worktree): `hash_port` in `post-start` for launch and `post-remove` for cleanup, with optional subdomain routing
+- [Dev server per worktree](@/tips-patterns.md#dev-server-per-worktree): `wt step tether` in `post-start` runs the dev server and kills its whole process group when the worktree is removed, with optional subdomain routing
- [Database per worktree](@/tips-patterns.md#database-per-worktree): a `post-start` pipeline stores container name, port, and connection string as [per-branch vars](@/config.md#wt-config-state-vars) that later hooks reference
- [Progressive validation](@/tips-patterns.md#progressive-validation): quick lint/typecheck in `pre-commit`, expensive tests and builds in `pre-merge`
- [Target-specific hooks](@/tips-patterns.md#target-specific-hooks): branch on `{{ target }}` in `post-merge` for per-environment deploys
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 012ee6caf..ff64926ac 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -70,8 +70,8 @@ pub struct SquashArgs {
// Ordering: `wt merge` pipeline steps first (commit → squash → rebase → push),
// then standalone utilities (diff, copy-ignored), then experimentals
-// (alphabetical: eval, for-each, promote, prune, relocate). Keep this enum,
-// the `## Operations` bullet list in `src/cli/mod.rs`, and the
+// (alphabetical: eval, for-each, promote, prune, relocate, tether). Keep this
+// enum, the `## Operations` bullet list in `src/cli/mod.rs`, and the
// `<!-- subdoc: -->` markers in the same relative order.
/// Run individual operations
#[derive(Subcommand)]
@@ -684,6 +684,52 @@ Note: This command is experimental and may change in future versions.
format: crate::cli::SwitchFormat,
},
+ /// \[experimental\] Run a command; kill its whole process tree when its worktree is removed
+ ///
+ /// Teardown is automatic and needs no `pre-remove` hook; the group gets `SIGTERM` then `SIGKILL`.
+ #[command(after_long_help = r#"## Why
+
+A `post-start` hook to start a long-lived process and a `pre-remove` hook to
+stop it is usually enough. But `pre-remove` only runs when worktrunk removes
+the worktree, so a `git worktree remove`, an `rm -rf`, or a crashed hook skips
+it. Across enough worktree churn some process is bound to outlive its worktree,
+and with no cleanup these leaks accumulate (on macOS they eventually saturate
+`fseventsd`). `tether` removes the need for a `pre-remove`: it ties the
+command's lifetime to the worktree and kills the whole process group once the
+worktree is gone.
+
+## Arguments
+
+Arguments after `--` are the program and its arguments, run directly, no shell.
+
+```console
+$ wt step tether -- npm run dev
+```
+
+For pipes, redirects, variables, or globs, wrap in `sh -c`:
+
+```console
+$ wt step tether -- sh -c 'PORT=$P npm run dev | tee dev.log'
+```
+
+## Examples
+
+Run a dev server, torn down automatically when the worktree goes away:
+
+```toml
+# .config/wt.toml
+[post-start]
+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
+```
+
+Note: This command is experimental and may change in future versions.
+"#)]
+ Tether {
+ /// Command to run (after `--`, run directly, no shell)
+ #[arg(required = true, last = true, num_args = 1..)]
+ command: Vec<String>,
+ },
+
/// Catch-all for alias lookup
#[command(external_subcommand)]
External(Vec<String>),
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 9f0c88c29..1a46acc0c 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -78,6 +78,7 @@ const BUILTIN_STEP_COMMANDS: &[&str] = &[
"rebase",
"relocate",
"squash",
+ "tether",
];
/// Built-in top-level `wt` subcommand names — visible and hidden. Aliases
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 4a2e728f9..b5795b62c 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -58,7 +58,7 @@ pub(crate) use run_pipeline::run_pipeline;
pub(crate) use step::{
PreApprovedGuidance, PromoteResult, RebaseResult, SquashResult, handle_promote, handle_rebase,
handle_squash, step_commit, step_copy_ignored, step_diff, step_dry_run_squash, step_prune,
- step_relocate, step_show_squash_prompt,
+ step_relocate, step_show_squash_prompt, step_tether,
};
pub(crate) use worktree::{
OperationMode, SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,
diff --git a/src/commands/step/mod.rs b/src/commands/step/mod.rs
index 3b276dd63..88a370af2 100644
--- a/src/commands/step/mod.rs
+++ b/src/commands/step/mod.rs
@@ -12,6 +12,8 @@
//! - `promote::handle_promote` - Swap a branch into the main worktree
//! - `prune::step_prune` - Remove worktrees merged into the default branch
//! - `relocate::step_relocate` - Move worktrees to expected paths
+//! - `tether::step_tether` - Supervise a command and kill its whole process
+//! group when the command exits or its worktree is removed
pub(crate) mod commit;
pub(crate) mod copy_ignored;
@@ -22,6 +24,7 @@ pub(crate) mod rebase;
pub(crate) mod relocate;
mod shared;
pub(crate) mod squash;
+pub(crate) mod tether;
pub(crate) use commit::step_commit;
pub(crate) use copy_ignored::step_copy_ignored;
@@ -33,3 +36,4 @@ pub(crate) use relocate::step_relocate;
pub(crate) use squash::{
PreApprovedGuidance, SquashResult, handle_squash, step_dry_run_squash, step_show_squash_prompt,
};
+pub(crate) use tether::step_tether;
diff --git a/src/commands/step/tether.rs b/src/commands/step/tether.rs
new file mode 100644
index 000000000..a9dfe994a
--- /dev/null
+++ b/src/commands/step/tether.rs
@@ -0,0 +1,139 @@
+//! `wt step tether` — run a command and guarantee its whole process tree dies.
+//!
+//! `tether -- CMD…` starts CMD in a new process group and supervises it. The
+//! whole tree is torn down when CMD exits on its own, or the worktree the
+//! command runs in is removed.
+//!
+//! The process group is the point. `npm run dev` spawns an esbuild
+//! `--service` sidecar that does not listen on the dev-server port; a port- or
+//! parent-based kill misses it. Putting CMD in its own group at spawn keeps
+//! every descendant reachable for one teardown call.
+//!
+//! Removal detection is a poll, not a kqueue/inotify watch: a `symlink_metadata`
+//! of one path is portable, has no arm-time race, behaves identically on every
+//! platform, and registers no filesystem watcher — the proliferation of which
+//! is the very problem this command exists to avoid. The 250ms interval bounds
+//! teardown latency for an already-orphaned server, which no one observes.
+//!
+//! Fire and forget: no stop command, no rendezvous file, no `pre-remove` hook.
+//! State lives only in this supervisor process, which dies with CMD.
+//!
+//! Platform teardown differs. Unix sweeps the process group with a bounded
+//! `SIGTERM` → `SIGKILL` escalation (`killpg`), which still reaches a child
+//! that reparented to PID 1 after CMD exited. Windows has no killable process
+//! group, so `taskkill /T /F` terminates CMD's process tree; it reaches every
+//! descendant while CMD is alive (the dominant "worktree removed while the
+//! server runs" case), but a child that detaches *after* CMD self-exits can
+//! outlive it — Windows neither reparents to a single init nor offers a pgid.
+
+use std::path::Path;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+
+/// How often the reaper re-checks whether the worktree still exists. Teardown
+/// of an already-orphaned server within this bound is imperceptible next to a
+/// dev server's own startup.
+const POLL_INTERVAL: Duration = Duration::from_millis(250);
+
+/// Run `command` supervised; tear its whole process tree down when the command
+/// exits or its worktree is removed.
+pub(crate) fn step_tether(command: &[String]) -> Result<()> {
+ // post-start hooks run with cwd at the worktree root; capture it now so
+ // the reaper can notice the worktree being removed. `None` (cwd
+ // unavailable) degrades to "tear down only on the command's own exit",
+ // never a false teardown.
+ let worktree = std::env::current_dir().ok();
+
+ let mut cmd = std::process::Command::new(&command[0]);
+ cmd.args(&command[1..]);
+ // Direct exec, no implicit shell, same as `wt step for-each`; scrub the
+ // directive env vars so a long-lived child can't write to the parent
+ // shell's cd/exec directive files.
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ set_new_process_group(&mut cmd);
+ let mut child = cmd
+ .spawn()
+ .with_context(|| format!("spawn tethered command: {}", command[0]))?;
+ let id = child.id();
+
+ // Reaper: polls until the worktree is gone, then kills the tree so the
+ // supervised child exits and `wait` returns. Only spawned when there is a
+ // worktree to watch; otherwise teardown relies solely on the command's
+ // own exit.
+ if let Some(dir) = worktree {
+ std::thread::spawn(move || {
+ while !worktree_gone(&dir) {
+ std::thread::sleep(POLL_INTERVAL);
+ }
+ kill_process_tree(id);
+ });
+ }
+
+ // Block until the child exits — killed by the reaper, or on its own.
+ let _ = child.wait();
+
+ // Final sweep: on a self-exit, descendants may still be running (Unix:
+ // reparented but in this pgid; Windows: while the tree is intact). On a
+ // reaper-driven teardown the tree is already gone and this is a no-op.
+ kill_process_tree(id);
+
+ // A reaper still sleeping between polls (the command self-exited) dies
+ // with this process when it returns.
+ Ok(())
+}
+
+/// The worktree path no longer resolves. Only `NotFound` counts as gone; a
+/// transient stat error (`EACCES`, `EIO`) is not a removal, so the reaper
+/// keeps waiting rather than tearing down a live server.
+fn worktree_gone(worktree: &Path) -> bool {
+ matches!(
+ std::fs::symlink_metadata(worktree),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound
+ )
+}
+
+/// Put the child at the head of a new process group so a single teardown call
+/// reaches every descendant, including ones that reparent away.
+#[cfg(unix)]
+fn set_new_process_group(cmd: &mut std::process::Command) {
+ use std::os::unix::process::CommandExt;
+
+ // POSIX `setpgid(0, 0)`: the child's pid is the new group's id, so
+ // `child.id()` is the pgid. Children that do not re-`setpgid` (node,
+ // Vite, the esbuild sidecar) stay in the group. Same invariant the
+ // foreground runner relies on (`shell_exec.rs`).
+ cmd.process_group(0);
+}
+
+#[cfg(windows)]
+fn set_new_process_group(cmd: &mut std::process::Command) {
+ use std::os::windows::process::CommandExt;
+
+ // CREATE_NEW_PROCESS_GROUP (0x00000200): the child leads a new process
+ // group. Windows has no killable group like a Unix pgid, but the new
+ // group still detaches CMD from the parent's console so its tree can be
+ // terminated as a unit. Same flag `commands/process.rs` uses.
+ cmd.creation_flags(0x0000_0200);
+}
+
+/// Tear down the whole tree rooted at the supervised child.
+#[cfg(unix)]
+fn kill_process_tree(pid: u32) {
+ // `process_group(0)` made the child its own group leader, so the pid is
+ // the pgid. The bounded TERM → KILL escalation reaches every member,
+ // including a child that reparented to PID 1 after the leader exited.
+ worktrunk::shell_exec::forward_signal_with_escalation(pid as i32, signal_hook::consts::SIGTERM);
+}
+
+#[cfg(windows)]
+fn kill_process_tree(pid: u32) {
+ // No killable process group on Windows; `taskkill /T` terminates the
+ // process and its child tree, `/F` forces. Best-effort: the pid may
+ // already be gone (self-exit) or have left detached children.
+ let _ = std::process::Command::new("taskkill")
+ .args(["/T", "/F", "/PID", &pid.to_string()])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status();
+}
diff --git a/src/main.rs b/src/main.rs
index 5789e426e..4af402bf5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -60,7 +60,7 @@ use commands::{
handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
handle_state_show, handle_unconfigure_shell, handle_vars_clear, handle_vars_get,
handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch, step_commit,
- step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate,
+ step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate, step_tether,
};
use output::handle_remove_output;
use worktrunk::git::BranchDeletionMode;
@@ -411,6 +411,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
clobber,
format,
} => step_relocate(branches, dry_run, commit, clobber, format),
+ StepCommand::Tether { command } => step_tether(&command),
StepCommand::External(args) => commands::step_alias(args, yes),
}
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 4505df1f1..099de6ff3 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -782,10 +782,11 @@ fn test_complete_step_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"promote"), "Missing promote");
assert!(subcommands.contains(&"prune"), "Missing prune");
assert!(subcommands.contains(&"relocate"), "Missing relocate");
+ assert!(subcommands.contains(&"tether"), "Missing tether");
assert_eq!(
subcommands.len(),
- 11,
- "Should have exactly 11 step subcommands"
+ 12,
+ "Should have exactly 12 step subcommands"
);
}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 05d66b9a8..50cfb46f3 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -61,6 +61,7 @@ pub mod step_diff;
pub mod step_promote;
pub mod step_prune;
pub mod step_relocate;
+pub mod step_tether;
pub mod switch;
pub mod switch_picker;
pub mod switch_picker_dry_run;
diff --git a/tests/integration_tests/step_tether.rs b/tests/integration_tests/step_tether.rs
new file mode 100644
index 000000000..bb5cf4319
--- /dev/null
+++ b/tests/integration_tests/step_tether.rs
@@ -0,0 +1,134 @@
+//! Integration tests for `wt step tether`.
+//!
+//! `tether` runs a command in its own process group and tears the whole group
+//! down (a) when its worktree is removed and (b) when the command exits on its
+//! own. The supervised snippet records its process-group id (the leader's pid,
+//! since `tether` puts the child in a new group) and backgrounds a second
+//! sleep, so the assertions prove the whole group dies, including the
+//! reparented sidecar a parent-walk would miss.
+#![cfg(unix)]
+
+use std::path::Path;
+use std::process::{Child, Stdio};
+use std::time::{Duration, Instant};
+
+use crate::common::{TestRepo, repo, wait_for_file_content};
+use nix::errno::Errno;
+use nix::sys::signal::kill;
+use nix::unistd::Pid;
+use rstest::rstest;
+
+/// True while any process in group `pgid` still exists. `kill(-pgid, 0)` is the
+/// portable group-liveness probe: `ESRCH` once the group is empty.
+fn group_alive(pgid: i32) -> bool {
+ !matches!(kill(Pid::from_raw(-pgid), None), Err(Errno::ESRCH))
+}
+
+/// Poll `cond` with a generous cap and fast interval (per tests/CLAUDE.md:
+/// long timeout for slow CI, fast polling so it returns immediately when the
+/// event has happened).
+fn wait_until(mut cond: impl FnMut() -> bool) -> bool {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while Instant::now() < deadline {
+ if cond() {
+ return true;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ cond()
+}
+
+/// Spawn `wt step tether` supervising a snippet that records its pgid to
+/// `pidfile`, backgrounds a sidecar sleep, then blocks. Returns the child
+/// handle and the pgid once recorded.
+fn spawn_tether(repo: &TestRepo, cwd: &Path, pidfile: &Path, tail: &str) -> (Child, i32) {
+ let snippet = format!(
+ "printf %s \"$$\" > \"{}\"; sleep 600 & {tail}",
+ pidfile.display()
+ );
+ let child = repo
+ .wt_command()
+ .args(["step", "tether", "--", "sh", "-c", &snippet])
+ .current_dir(cwd)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn wt step tether");
+
+ wait_for_file_content(pidfile);
+ let pgid: i32 = std::fs::read_to_string(pidfile)
+ .unwrap()
+ .trim()
+ .parse()
+ .expect("pgid in pidfile");
+ (child, pgid)
+}
+
+/// Both ways a worktree disappears tear the whole group down: outright
+/// deletion (`rm -rf` / `git worktree remove`, `NOTE_DELETE`/`IN_DELETE_SELF`)
+/// and rename into trash (worktrunk's own removal, `NOTE_RENAME`/
+/// `IN_MOVE_SELF`).
+#[rstest]
+fn test_tether_kills_process_group_when_worktree_removed(mut repo: TestRepo) {
+ for mechanism in ["delete", "rename"] {
+ let worktree = repo.add_worktree(&format!("server-{mechanism}"));
+ let pidfile = repo.home_path().join(format!("tether-{mechanism}.pgid"));
+
+ let (mut child, pgid) = spawn_tether(&repo, &worktree, &pidfile, "exec sleep 600");
+ assert!(
+ group_alive(pgid),
+ "[{mechanism}] supervised group should be alive before removal"
+ );
+
+ match mechanism {
+ "delete" => std::fs::remove_dir_all(&worktree).unwrap(),
+ "rename" => std::fs::rename(&worktree, repo.home_path().join("trash")).unwrap(),
+ _ => unreachable!(),
+ }
+
+ let group_gone = wait_until(|| !group_alive(pgid));
+ let supervisor_exited = wait_until(|| child.try_wait().unwrap().is_some());
+
+ // Clean up before asserting so a failure can't leak the sleeps.
+ let _ = kill(Pid::from_raw(-pgid), nix::sys::signal::Signal::SIGKILL);
+ let _ = child.kill();
+ let _ = child.wait();
+ let _ = std::fs::remove_dir_all(repo.home_path().join("trash"));
+
+ assert!(
+ group_gone,
+ "[{mechanism}] removing the worktree must kill the whole process group"
+ );
+ assert!(
+ supervisor_exited,
+ "[{mechanism}] the tether supervisor must exit after teardown"
+ );
+ }
+}
+
+/// When the supervised command exits on its own, the supervisor sweeps the
+/// group (so the backgrounded sidecar dies too) and then exits.
+#[rstest]
+fn test_tether_kills_process_group_when_command_exits(repo: TestRepo) {
+ let pidfile = repo.home_path().join("tether-selfexit.pgid");
+ // Foreground `true` exits immediately; the sidecar `sleep 600` would
+ // outlive it without the group sweep.
+ let (mut child, pgid) = spawn_tether(&repo, repo.path(), &pidfile, "true");
+
+ let group_gone = wait_until(|| !group_alive(pgid));
+ let supervisor_exited = wait_until(|| child.try_wait().unwrap().is_some());
+
+ let _ = kill(Pid::from_raw(-pgid), nix::sys::signal::Signal::SIGKILL);
+ let _ = child.kill();
+ let _ = child.wait();
+
+ assert!(
+ group_gone,
+ "command self-exit must sweep the whole group, including the sidecar"
+ );
+ assert!(
+ supervisor_exited,
+ "the tether supervisor must exit after the command exits"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index a8eff5c95..84667ee85 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
@@ -11,6 +11,7 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: /var/folders/v3/8k5q0_6j3_q6gl4h8czr66sh0000gn/T/wt-test-profraw/cov-%m_%p.profraw
NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
@@ -19,13 +20,17 @@ info:
WORKTRUNK_APPROVALS_PATH: /nonexistent/wt/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/wt/config.toml
WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_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"
---
success: true
exit_code: 0
@@ -48,6 +53,7 @@ Usage: wt step [OPTIONS] <COMMAND>
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is removed
Options:
-h, --help
@@ -95,6 +101,7 @@ Manual merge workflow with review between steps:
- promote — [experimental] Swap a branch into the main worktree
- prune — Remove worktrees and branches merged into the default branch
- relocate — [experimental] Move worktrees to expected paths
+- tether — [experimental] Run a command; kill its whole process tree when its worktree is removed
- <alias> — Run a configured command alias
See also
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index 8e4176637..9a500c524 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
@@ -11,6 +11,7 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: /var/folders/v3/8k5q0_6j3_q6gl4h8czr66sh0000gn/T/wt-test-profraw/cov-%m_%p.profraw
NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
@@ -19,13 +20,17 @@ info:
WORKTRUNK_APPROVALS_PATH: /nonexistent/wt/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/wt/config.toml
WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_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"
---
success: true
exit_code: 0
@@ -46,6 +51,7 @@ Usage: wt step [OPTIONS] <COMMAND>
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is removed
Options:
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap
index f3bdb0f00..66b6ac085 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap
@@ -23,6 +23,7 @@ info:
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
NO_COLOR: ""
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
@@ -67,6 +68,7 @@ Usage: wt step [OPTIONS] <COMMAND>
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is removed
Aliases:
deploy
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
index b22f12352..bbff22ded 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
@@ -10,13 +10,19 @@ info:
COLUMNS: "500"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMON_DIR: ""
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
NO_COLOR: ""
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
@@ -29,13 +35,17 @@ info:
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_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_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
@@ -57,6 +67,7 @@ Usage: wt step [OPTIONS] <COMMAND>
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is removed
Options:
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
index aed41c869..f3f9cb4ad 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
@@ -22,6 +22,7 @@ info:
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
NO_COLOR: ""
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
@@ -66,6 +67,7 @@ Usage: wt step [OPTIONS] <COMMAND>
promote [experimental] Swap a branch into the main worktree
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
+ tether [experimental] Run a command; kill its whole process tree when its worktree is removed
Aliases:
deploy, port, squash (shadowed by built-in)