Skip to content

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

Drop post-commit when the merge removed the worktree it runs in (#4049)

Maximilian Roos28ebf2450535
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c2a1e47b0..f3aa3d576 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@
### Fixed
+- **`wt merge` no longer runs `post-commit` in a worktree the user never chose**: the merge removes the worktree that hook is anchored on before the hook starts, so the pipeline was spawned into an emptied path. Where the worktree sat inside the repository, git discovery walked up from there and the hook's commands ran in the primary worktree; anywhere else they didn't run at all, and the only record was a log file nothing reads. The merge now prints `▲ Skipped post-commit: …` naming that worktree, and points at `pre-remove` for work that must finish there. `--no-remove`, merging on the target branch, `wt step commit`, and `wt step squash` still run it. ([#4049](https://github.com/max-sixty/worktrunk/pull/4049))
+
- **`wt config plugins claude uninstall` / `codex uninstall` no longer report success over a marketplace that is still there**: to tell an already-removed marketplace from a removal that failed, uninstall used to read the harness's own config file. A file or key the harness renamed reads as an absence there, so every failed removal would have printed `Plugin & marketplace removed` and exited 0. It now asks `claude` / `codex plugin marketplace list --json`, and an answer it cannot read leaves the harness's error standing. ([#4048](https://github.com/max-sixty/worktrunk/pull/4048))
## 0.77.0
diff --git a/CLAUDE.md b/CLAUDE.md
index d3249296a..a72067596 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -152,7 +152,7 @@ Why: wt installs a `signal_hook` SIGINT/SIGTERM handler so it can forward signal
### Background Hook Pipelines Run Concurrently, Per Source
-A `post-*` batch spawns one detached pipeline per source, and they run at once. Don't serialize them: `post-start` is documented for dev servers and `wt step tether`, so a user hook that never exits would block the project's forever, and `wt merge`'s batch spans two worktrees (`post-commit` anchors on the invoking worktree, the rest on the destination) so chaining also drops hooks behind a head whose worktree is already removed. The cost is that two hooks touching one worktree's git state can collide — two `git pull`s there append to each other's `FETCH_HEAD` and both fail — which `wt hook --help` tells users to avoid by keeping dependent commands in one source.
+A `post-*` batch spawns one detached pipeline per source, and they run at once. Don't serialize them: `post-start` is documented for dev servers and `wt step tether`, so a user hook that never exits would block the project's forever, and `wt merge`'s batch spans two worktrees (`post-commit` anchors on the invoking worktree, the rest on the destination) so chaining also drops hooks behind a head whose worktree is already removed. That span is also why the flush can reach a pipeline whose anchor is gone: the merge removes `post-commit`'s worktree first, so the removal reports it through `HookAnnouncer::mark_worktree_removed` and the flush drops that pipeline rather than spawning it into a path whose git discovery would resolve to the primary worktree. The removal is what knows — where its fast rename into `.git/wt/trash/` fails, the fallback `git worktree remove` runs detached and the anchor is still on disk at the flush, so a filesystem probe would answer differently on the two paths. The cost is that two hooks touching one worktree's git state can collide — two `git pull`s there append to each other's `FETCH_HEAD` and both fail — which `wt hook --help` tells users to avoid by keeping dependent commands in one source.
## Hook Output Logs
diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.md
index 6f4468501..018710730 100644
--- a/docs/src/content/docs/hook.md
+++ b/docs/src/content/docs/hook.md
@@ -37,7 +37,7 @@ The most common creation hook is `post-start` — it runs background tasks (dev
| `pre-remove` | Cleanup before worktree deletion: saving test artifacts, backing up state. Runs in the worktree being removed |
| `post-remove` | Stopping dev servers, removing containers, notifying external systems. Template variables reference the removed worktree |
-During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. So `post-commit` can't be relied on for a merge that removes that worktree — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](/merge/#pipeline) for the complete pipeline.
+During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. A merge that removes that worktree reports `post-commit` as skipped instead of running it — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](/merge/#pipeline) for the complete pipeline.
# Security
diff --git a/docs/src/content/docs/merge.md b/docs/src/content/docs/merge.md
index efb9b0fdd..5ba802035 100644
--- a/docs/src/content/docs/merge.md
+++ b/docs/src/content/docs/merge.md
@@ -76,7 +76,7 @@ $ wt merge --no-commit --no-rebase
`wt merge` runs these steps:
-1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
+1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. Working-tree changes swept into the squash are backed up first to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.
3. **Rebase** — Rebases onto target, skipping when nothing needs replaying ([`wt step rebase`](/step/#wt-step-rebase) gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.md
index 738d2f7ed..030576166 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/hook.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md
@@ -31,7 +31,7 @@ The most common creation hook is `post-start` — it runs background tasks (dev
| `pre-remove` | Cleanup before worktree deletion: saving test artifacts, backing up state. Runs in the worktree being removed |
| `post-remove` | Stopping dev servers, removing containers, notifying external systems. Template variables reference the removed worktree |
-During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. So `post-commit` can't be relied on for a merge that removes that worktree — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
+During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. A merge that removes that worktree reports `post-commit` as skipped instead of running it — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
# Security
diff --git a/plugins/worktrunk/skills/worktrunk/reference/merge.md b/plugins/worktrunk/skills/worktrunk/reference/merge.md
index ac18a7e17..38320323a 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/merge.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/merge.md
@@ -63,7 +63,7 @@ $ wt merge --no-commit --no-rebase
`wt merge` runs these steps:
-1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
+1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. Working-tree changes swept into the squash are backed up first to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.
3. **Rebase** — Rebases onto target, skipping when nothing needs replaying ([`wt step rebase`](https://worktrunk.dev/step/#wt-step-rebase) gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 738d2f7ed..030576166 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -31,7 +31,7 @@ The most common creation hook is `post-start` — it runs background tasks (dev
| `pre-remove` | Cleanup before worktree deletion: saving test artifacts, backing up state. Runs in the worktree being removed |
| `post-remove` | Stopping dev servers, removing containers, notifying external systems. Template variables reference the removed worktree |
-During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. So `post-commit` can't be relied on for a merge that removes that worktree — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
+During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. A merge that removes that worktree reports `post-commit` as skipped instead of running it — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
# Security
diff --git a/skills/worktrunk/reference/merge.md b/skills/worktrunk/reference/merge.md
index ac18a7e17..38320323a 100644
--- a/skills/worktrunk/reference/merge.md
+++ b/skills/worktrunk/reference/merge.md
@@ -63,7 +63,7 @@ $ wt merge --no-commit --no-rebase
`wt merge` runs these steps:
-1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
+1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. Working-tree changes swept into the squash are backed up first to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.
3. **Rebase** — Rebases onto target, skipping when nothing needs replaying ([`wt step rebase`](https://worktrunk.dev/step/#wt-step-rebase) gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 604c6f6fa..1677cb0a2 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1487,7 +1487,7 @@ $ wt merge --no-commit --no-rebase
`wt merge` runs these steps:
-1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
+1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. Working-tree changes swept into the squash are backed up first to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.
3. **Rebase** — Rebases onto target, skipping when nothing needs replaying ([`wt step rebase`](/step/#wt-step-rebase) gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
@@ -1634,7 +1634,7 @@ The most common creation hook is `post-start` — it runs background tasks (dev
| `pre-remove` | Cleanup before worktree deletion: saving test artifacts, backing up state. Runs in the worktree being removed |
| `post-remove` | Stopping dev servers, removing containers, notifying external systems. Template variables reference the removed worktree |
-During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. So `post-commit` can't be relied on for a merge that removes that worktree — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](/merge/#pipeline) for the complete pipeline.
+During `wt merge`, the blocking hooks run in this order: pre-commit → pre-merge → pre-remove. The `post-*` hooks all start together once the merge finishes, each in the worktree it is anchored on — post-merge, post-switch and post-remove in the destination, post-commit in the worktree the commit was made in. A merge that removes that worktree reports `post-commit` as skipped instead of running it — the worktree is gone by the time the hook would start. Use `pre-remove` for work that must finish there, or `--no-remove` to keep the worktree. See [`wt merge`](/merge/#pipeline) for the complete pipeline.
# Security
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 03e9b3afc..c5613ae5c 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -35,7 +35,11 @@
//!
//! "Runs in" is the *anchor* — the executor's plan lookup key and render root,
//! not a config source. A `pre-start`'s new worktree need not exist when the
-//! gate runs; the config came from the invoking worktree regardless.
+//! gate runs; the config came from the invoking worktree regardless. A
+//! background pipeline anchored on a worktree the command removed is dropped
+//! and reported rather than spawned (see [`report_dropped_pipelines`]); only
+//! `wt merge` reaches that, since it removes `post-commit`'s anchor before the
+//! flush.
//!
//! **Invocation-resolved (no gate→exec mutation):** `pre-commit`,
//! `post-commit`, `pre-switch`, `wt hook <type>`, aliases. They resolve config
@@ -71,7 +75,8 @@ use worktrunk::config::{CommandConfig, format_hook_variables};
use worktrunk::git::{Repository, add_hook_skip_hint};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- eprintln, format_with_gutter, info_message, progress_message, verbosity, warning_message,
+ eprintln, format_with_gutter, hint_message, info_message, progress_message, verbosity,
+ warning_message,
};
use super::command_executor::{
@@ -278,6 +283,7 @@ fn no_matching_commands_error(
/// emitted at `flush`, not at registration time.
pub struct HookAnnouncer<'a> {
pending: Vec<PendingPipeline>,
+ removed_worktrees: Vec<PathBuf>,
repo: &'a Repository,
show_branch: bool,
}
@@ -302,6 +308,7 @@ impl<'a> HookAnnouncer<'a> {
pub fn new(repo: &'a Repository, show_branch: bool) -> Self {
Self {
pending: Vec::new(),
+ removed_worktrees: Vec::new(),
repo,
show_branch,
}
@@ -363,16 +370,36 @@ impl<'a> HookAnnouncer<'a> {
Ok(())
}
+ /// Record that this command removed the worktree at `path`, so a pipeline
+ /// anchored there is dropped at [`flush`](Self::flush) rather than spawned
+ /// into it — see [`report_dropped_pipelines`].
+ ///
+ /// The removal is the only thing that knows: on the fast path the worktree
+ /// is already renamed into `.git/wt/trash/` by the time `flush` runs, but
+ /// where that rename fails (cross-filesystem, permissions, Windows file
+ /// locks) the fallback `git worktree remove` runs detached and the anchor
+ /// is still on disk, intact, at the flush. Probing the filesystem would
+ /// answer differently in those two cases; the removal's own report doesn't.
+ pub fn mark_worktree_removed(&mut self, path: &Path) {
+ self.removed_worktrees.push(path.to_path_buf());
+ }
+
/// Emit the combined announce line and spawn all registered pipelines.
///
/// No-op when nothing was registered. Drains `pending` so the announcer
- /// can be reused (though one-per-command is the intended pattern).
+ /// can be reused (though one-per-command is the intended pattern); the
+ /// removed-worktree marks persist, since a removed worktree stays removed.
pub fn flush(&mut self) -> anyhow::Result<()> {
let pending = std::mem::take(&mut self.pending);
if pending.is_empty() {
return Ok(());
}
- run_hooks_background(self.repo, pending, self.show_branch)
+ run_hooks_background(
+ self.repo,
+ pending,
+ &self.removed_worktrees,
+ self.show_branch,
+ )
}
}
@@ -411,11 +438,23 @@ impl Drop for HookAnnouncer<'_> {
/// When `show_branch` is true, the announce includes the branch name for
/// disambiguation in batch contexts (e.g., prune removing multiple worktrees):
/// `Running post-remove for feature: docs (user)`.
+///
+/// Pipelines anchored on one of `removed_worktrees` are dropped first, so the
+/// announce describes only what starts — see [`report_dropped_pipelines`].
fn run_hooks_background(
repo: &Repository,
pipelines: Vec<PendingPipeline>,
+ removed_worktrees: &[PathBuf],
show_branch: bool,
) -> anyhow::Result<()> {
+ let (pipelines, dropped): (Vec<_>, Vec<_>) = pipelines
+ .into_iter()
+ .partition(|p| !removed_worktrees.contains(&p.worktree_path));
+ report_dropped_pipelines(&dropped);
+ if pipelines.is_empty() {
+ return Ok(());
+ }
+
// Merge per-source summaries by hook type so user+project for the same
// type render as one clause: `post-merge: sync, push (user); build (project)`.
// Pull `display_path` off the first pipeline that has one — every hook
@@ -476,6 +515,43 @@ fn run_hooks_background(
Ok(())
}
+/// Report background hook pipelines dropped because this command removed the
+/// worktree they are anchored on.
+///
+/// A pipeline runs with its anchor as cwd, and the runner
+/// ([`run_pipeline`](super::run_pipeline::run_pipeline)) opens the repository
+/// by discovery from there. Discovery walks up, so once the anchor is emptied
+/// a worktree nested inside its repository resolves to the *primary* worktree
+/// and the steps — arbitrary project code — run in a worktree the user never
+/// chose. A worktree outside the repository has nothing to walk up to, and the
+/// runner writes `failed to open repository for pipeline` to a log nothing
+/// reads back. Both are silent, so the drop is reported here instead.
+///
+/// Only `wt merge` reaches this. `post-commit` is anchored on the feature
+/// worktree the merge then removes; every other background hook anchors on a
+/// worktree its command keeps.
+fn report_dropped_pipelines(dropped: &[PendingPipeline]) {
+ for pipeline in dropped {
+ let hook_type = pipeline.hook_type;
+ let summary = format_pipeline_summary(&pipeline.steps);
+ let path = format_path_for_display(&pipeline.worktree_path);
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Skipped {hook_type}: {summary} — worktree removed @ <bold>{path}</>"
+ ))
+ );
+ }
+ if !dropped.is_empty() {
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To run commands in a worktree before it is removed, use <underline>pre-remove</>"
+ ))
+ );
+ }
+}
+
/// Group sourced steps into one Vec per source, preserving insertion order.
///
/// Used by background callers that want one pipeline per source (the canonical
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 735d450a9..748fe6859 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -325,24 +325,17 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
//
// Every background hook runs in the worktree it is anchored on, and only
// post-commit is anchored on the feature worktree (the other three anchor
- // on the destination). Flushing after `finish_after_merge` therefore spawns
- // post-commit into a path the removal has already emptied — the fast path
- // renames the worktree into `.git/wt/trash/` and leaves an empty
- // placeholder there (torn down by the detached `sleep 1 && rmdir`). Where
- // nothing above that placeholder is a git repository, the runner logs
- // `failed to open repository for pipeline` to
- // `.git/wt/logs/<branch>/user|project/post-commit/runner.log`, which
- // nothing reads back; where the worktree is nested inside the repo,
- // discovery walks up to the primary worktree instead and the steps run
- // there, in a directory about to vanish. Either way the
- // `◎ Running post-commit` line is the only trace.
- // Accepted rather than fixed: the commit it would fire on is squashed and
- // rebased before the merge lands, `pre-remove` already covers work that
- // must finish in the feature worktree, and spawning early only narrows the
- // window (removal succeeds against a live cwd). post-commit still runs where
- // the worktree survives — `--no-remove`, merging on the target branch,
- // merging from the primary worktree — and on `wt step commit` /
- // `wt step squash`.
+ // on the destination). A merge that removes that worktree therefore
+ // reaches the flush with post-commit's anchor gone, so the removal reports
+ // it via `HookAnnouncer::mark_worktree_removed` and the flush drops that
+ // pipeline rather than spawning it into a path whose git discovery would
+ // walk up to the primary worktree.
+ //
+ // There is no earlier moment to spawn it. Between the commit and the
+ // removal the worktree is rebased and runs `pre-merge`, and a background
+ // pipeline there would race both. post-commit still runs where the
+ // worktree survives — `--no-remove`, merging on the target branch, merging
+ // from the primary worktree — and on `wt step commit` / `wt step squash`.
let mut announcer = HookAnnouncer::new(repo, false);
// The project commit-append is gated independently of hook approval:
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index e6925029a..3fe637381 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1388,13 +1388,22 @@ fn handle_branch_only_output(
/// flushes — multi-phase callers (e.g. `wt merge`) batch with later phases,
/// standalone callers (e.g. `wt remove`) flush immediately after.
///
-/// Only runs if `ctx.verify` is true (hooks approved).
+/// Hook selection is the frozen `ctx.hook_plan`, so an empty plan
+/// (`--no-hooks`, declined approval, or no project config) registers nothing.
+/// The removed-worktree mark below is not part of that: it records what the
+/// removal did, which no approval decision changes.
fn spawn_hooks_after_remove(
repo: &Repository,
ctx: &WorktreeRemovalContext<'_>,
removed_branch: Option<&str>,
announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
+ // The worktree is gone (or, on the fallback path, being deleted by the
+ // detached `git worktree remove` this call follows), so a pipeline anchored
+ // on it must not be spawned into it. Recorded before the config load, which
+ // returns early on an unreadable user config.
+ announcer.mark_worktree_removed(ctx.worktree_path);
+
let Ok(config) = UserConfig::load() else {
return Ok(());
};
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index b3d09f353..603683113 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1047,15 +1047,14 @@ sync = "echo merged"
/// `CommitOptions::commit`, which threads the merge announcer through. The
/// post-commit phase should join post-remove + post-switch + post-merge on
/// one combined announce line — the non-squash sibling of
-/// [`test_merge_squash_combines_post_commit_post_remove_post_switch_post_merge`].
+/// [`test_merge_squash_combines_post_remove_post_switch_post_merge`].
///
-/// The announce line is all this pins. post-commit is announced but can't be
-/// relied on to run on a merge that removes the worktree, which
-/// `handle_merge`'s announcer comment covers.
+/// The announce line is all this pins. The merge removes the worktree
+/// post-commit is anchored on, so that clause is a `Skipped post-commit` line
+/// instead — see
+/// [`test_merge_post_commit_runs_only_when_its_worktree_survives`].
#[rstest]
-fn test_merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge(
- mut repo: TestRepo,
-) {
+fn test_merge_auto_commit_combines_post_remove_post_switch_post_merge(mut repo: TestRepo) {
let feature_wt =
repo.add_worktree_with_commit("feature", "feature.txt", "feature", "Add feature");
// Leave an uncommitted change so the merge auto-commits via
@@ -1078,23 +1077,23 @@ sync = "echo merged"
);
snapshot_merge(
- "merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge",
+ "merge_auto_commit_combines_post_remove_post_switch_post_merge",
&repo,
&["main", "--yes", "--no-squash"],
Some(&feature_wt),
);
}
-/// `wt merge --squash` announces post-commit (from the squash phase),
-/// post-remove, post-switch (from worktree removal), and post-merge. All four
-/// should share one `Running …` announce line so the user sees a single status
-/// line for the whole command, not four.
+/// `wt merge --squash` registers post-commit (from the squash phase),
+/// post-remove, post-switch (from worktree removal), and post-merge. The three
+/// that still have a worktree share one `Running …` announce line so the user
+/// sees a single status line for the whole command, not three.
///
-/// That line is all this pins. post-commit is announced but can't be relied on
-/// to run on a merge that removes the worktree, which `handle_merge`'s
-/// announcer comment covers.
+/// That line is all this pins. The merge removes the worktree post-commit is
+/// anchored on, so that clause is a `Skipped post-commit` line instead — see
+/// [`test_merge_post_commit_runs_only_when_its_worktree_survives`].
#[rstest]
-fn test_merge_squash_combines_post_commit_post_remove_post_switch_post_merge(mut repo: TestRepo) {
+fn test_merge_squash_combines_post_remove_post_switch_post_merge(mut repo: TestRepo) {
// Squash needs >1 commit ahead of main to actually run.
let feature_wt = repo.add_worktree_with_commit("feature", "feature1.txt", "one", "feat: one");
repo.commit_in_worktree(&feature_wt, "feature2.txt", "two", "feat: two");
@@ -1115,13 +1114,77 @@ sync = "echo merged"
);
snapshot_merge(
- "merge_squash_combines_post_commit_post_remove_post_switch_post_merge",
+ "merge_squash_combines_post_remove_post_switch_post_merge",
&repo,
&["main", "--yes", "--squash"],
Some(&feature_wt),
);
}
+/// `post-commit` is anchored on the worktree the commit was made in, and a
+/// `wt merge` that removes that worktree reaches the announcer's flush with
+/// the anchor already renamed into `.git/wt/trash/`. `run_hooks_background`
+/// drops such a pipeline rather than spawn it: the runner would open the
+/// repository by discovery from an emptied path, which for a worktree nested
+/// inside its repository resolves to the **primary** worktree and runs the
+/// project's commands there.
+///
+/// The worktree is nested here so that a regression executes rather than
+/// merely fails — `git rev-parse --show-toplevel` would answer with the
+/// primary worktree and write the marker. `--no-remove` is the control: the
+/// same hook, config, and marker path, with the worktree kept.
+#[rstest]
+#[case::removed("removed", &["main", "--yes"], false)]
+#[case::kept("kept", &["main", "--yes", "--no-remove"], true)]
+fn test_merge_post_commit_runs_only_when_its_worktree_survives(
+ repo: TestRepo,
+ #[case] label: &str,
+ #[case] args: &[&str],
+ #[case] expect_ran: bool,
+) {
+ // A worktree inside the repository, so a pipeline spawned into its emptied
+ // path would find the primary worktree one level up.
+ let nested = repo.path().join(".worktrees").join("feature");
+ repo.run_git(&["worktree", "add", "-b", "feature", &nested.to_slash_lossy()]);
+ fs::write(nested.join("feature.txt"), "feature").unwrap();
+ repo.run_git_in(&nested, &["add", "feature.txt"]);
+ repo.run_git_in(&nested, &["commit", "-m", "Add feature"]);
+ // Uncommitted work so the merge squashes, which is what fires post-commit.
+ fs::write(nested.join("dirty.txt"), "uncommitted").unwrap();
+
+ // The marker lives in the primary worktree so it outlives the feature
+ // worktree, and records which worktree the hook resolved to.
+ repo.write_test_config(
+ r#"[post-commit]
+mark = "git rev-parse --show-toplevel > {{ repo_path }}/post-commit-toplevel.txt"
+"#,
+ );
+
+ let marker = repo.path().join("post-commit-toplevel.txt");
+ snapshot_merge(
+ &format!("merge_post_commit_worktree_{label}"),
+ &repo,
+ args,
+ Some(&nested),
+ );
+
+ if expect_ran {
+ wait_for_file_content(&marker);
+ let toplevel = fs::read_to_string(&marker).unwrap();
+ assert!(
+ toplevel.trim().ends_with(".worktrees/feature"),
+ "post-commit should resolve to the feature worktree, got: {toplevel}"
+ );
+ } else {
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
+ assert!(
+ !marker.exists(),
+ "post-commit ran with its worktree removed, resolving to {:?}",
+ fs::read_to_string(&marker).ok()
+ );
+ }
+}
+
/// When post-merge template prep errors after post-remove + post-switch are
/// already registered, the announcer's `Drop` impl flushes the pending hooks
/// so they still spawn — preserving the prior fire-and-forget behavior in
diff --git a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
index 701ddeee5..96d1c9f0e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
@@ -172,7 +172,7 @@ $ wt merge --no-commit --no-rebase
`wt merge` runs these steps:
-1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
+1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.
2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. Working-tree changes swept into the squash are backed up first to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.
3. **Rebase** — Rebases onto target, skipping when nothing needs replaying ([`wt step rebase`](/step/#wt-step-rebase) gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
index bcf2c639b..0cdb1d264 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
@@ -156,7 +156,7 @@ Preserve the exact clean commit graph and tip:
wt merge runs these steps:
-1. Commit — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background, and can't be relied on when step 7 removes the worktree they are anchored on. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With --no-squash, this is the only commit step.
+1. Commit — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in the background; when step 7 removes the worktree they are anchored on, the merge reports them rather than running them. This step is skipped when squashing (the default) — changes are staged during the squash step instead. With --no-squash, this is the only commit step.
2. Squash — Combines all commits since target into one (like GitHub's "Squash and merge"). Use --stage to control what gets staged: all (default), tracked, or none. Working-tree changes swept into the squash are backed up first to refs/wt-backup/<branch>. With --no-squash, individual commits are preserved.
3. Rebase — Rebases onto target, skipping when nothing needs replaying (wt step rebase gives the conditions). A conflict stops the merge with the rebase left open in the worktree, to resolve or abort. With --no-rebase, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.
4. Pre-merge hooks — Hooks run after rebase, before merge. Failures abort. See wt hook.
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_remove_post_switch_post_merge.snap
similarity index 89%
rename from tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap
rename to tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_remove_post_switch_post_merge.snap
index 9425829ef..61c18e8e2 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_remove_post_switch_post_merge.snap
@@ -77,4 +77,6 @@ exit_code: 0
◎ Removing feature worktree & branch in background (same commit as main, _)
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-◎ Running post-commit: mark (user); post-remove: cleanup (user); post-switch: notify (user); post-merge: sync (user) @ _REPO_
+▲ Skipped post-commit: mark (user) — worktree removed @ _REPO_.feature
+↳ To run commands in a worktree before it is removed, use pre-remove
+◎ Running post-remove: cleanup (user); post-switch: notify (user); post-merge: sync (user) @ _REPO_
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_kept.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_kept.snap
new file mode 100644
index 000000000..0bb410ae4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_kept.snap
@@ -0,0 +1,82 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--yes"
+ - "--no-remove"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ 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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ 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 -----
+▲ Auto-staging 1 untracked path:
+  dirty.txt
+◎ Squashing 1 commit & working tree changes into a single commit (2 files, +2)...
+↳ Backup created @ c866be4
+◎ Generating squash commit message...
+↳ Using fallback commit message. For LLM setup guide, run wt config --help
+  Squash commits from feature
+ 
+  Combined commits:
+  - Add feature
+✓ Squashed @ [HASH]
+◎ Merging 1 commit to main @ [HASH] (no rebase needed)
+  * [HASH] Squash commits from feature
+  dirty.txt | 1 +
+  feature.txt | 1 +
+  2 files changed, 2 insertions(+)
+✓ Merged to main (1 commit, 2 files, +2)
+○ Worktree preserved (--no-remove)
+◎ Running post-commit: mark (user)
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_removed.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_removed.snap
new file mode 100644
index 000000000..7408c15dc
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_post_commit_worktree_removed.snap
@@ -0,0 +1,84 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ 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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ 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 -----
+▲ Auto-staging 1 untracked path:
+  dirty.txt
+◎ Squashing 1 commit & working tree changes into a single commit (2 files, +2)...
+↳ Backup created @ c866be4
+◎ Generating squash commit message...
+↳ Using fallback commit message. For LLM setup guide, run wt config --help
+  Squash commits from feature
+ 
+  Combined commits:
+  - Add feature
+✓ Squashed @ [HASH]
+◎ Merging 1 commit to main @ [HASH] (no rebase needed)
+  * [HASH] Squash commits from feature
+  dirty.txt | 1 +
+  feature.txt | 1 +
+  2 files changed, 2 insertions(+)
+✓ Merged to main (1 commit, 2 files, +2)
+◎ Removing feature worktree & branch in background (same commit as main, _)
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+▲ Skipped post-commit: mark (user) — worktree removed @ _REPO_/.worktrees/feature
+↳ To run commands in a worktree before it is removed, use pre-remove
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_remove_post_switch_post_merge.snap
similarity index 89%
rename from tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snap
rename to tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_remove_post_switch_post_merge.snap
index cf775849a..328f3adc2 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_remove_post_switch_post_merge.snap
@@ -79,4 +79,6 @@ exit_code: 0
◎ Removing feature worktree & branch in background (same commit as main, _)
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
-◎ Running post-commit: mark (user); post-remove: cleanup (user); post-switch: notify (user); post-merge: sync (user) @ _REPO_
+▲ Skipped post-commit: mark (user) — worktree removed @ _REPO_.feature
+↳ To run commands in a worktree before it is removed, use pre-remove
+◎ Running post-remove: cleanup (user); post-switch: notify (user); post-merge: sync (user) @ _REPO_