Skip to content

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

hooks: combine background hook announces per command (#2457)

Maximilian Roos091a3d6ed6f0
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 0aae01dda..657a4e8ab 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -4,7 +4,8 @@ use std::path::{Path, PathBuf};
use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
-use worktrunk::config::{CommandConfig, format_hook_variables};
+use worktrunk::config::{CommandConfig, UserConfig, format_hook_variables};
+use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
eprintln, format_with_gutter, info_message, progress_message, verbosity, warning_message,
@@ -260,23 +261,139 @@ fn format_pipeline_summary(steps: &[SourcedStep]) -> String {
)
}
+/// Coordinates background hook announcements within a single `wt` command.
+///
+/// The principle: one `◎ Running …` line per command. Sites that would have
+/// individually spawned background hooks instead `register` their pipelines
+/// here, and the command `flush`es once after all phases have been resolved.
+/// All registered hook types end up on a single combined line, joined by `;`.
+///
+/// Just-in-time honesty: registration happens at each phase's normal moment,
+/// so if an earlier phase fails (e.g. pre-merge errors before post-merge is
+/// queued), the announce only describes hooks that actually ran. The line is
+/// emitted at `flush`, not at the first registration.
+pub struct HookAnnouncer<'a> {
+ pending: Vec<PendingPipeline>,
+ repo: &'a Repository,
+ /// Shared config used to rebuild `CommandContext`s at flush time.
+ config: &'a UserConfig,
+ show_branch: bool,
+}
+
+/// Owned spawn data for a registered pipeline. Stores enough to rebuild a
+/// `CommandContext` at flush time so the announcer can outlive any short-lived
+/// contexts at the registration site.
+struct PendingPipeline {
+ worktree_path: PathBuf,
+ branch: Option<String>,
+ steps: Vec<SourcedStep>,
+}
+
+impl<'a> HookAnnouncer<'a> {
+ /// `show_branch=true` includes the branch name for disambiguation in batch
+ /// contexts (e.g., prune removing multiple worktrees):
+ /// `Running post-remove for feature: docs; post-switch for feature: zellij-tab`
+ pub fn new(repo: &'a Repository, config: &'a UserConfig, show_branch: bool) -> Self {
+ Self {
+ pending: Vec::new(),
+ repo,
+ config,
+ show_branch,
+ }
+ }
+
+ /// Add prepared pipelines to the announcer.
+ ///
+ /// Pipelines come from `prepare_background_hooks` / its callers, which
+ /// already filter out empty source groups — empty `steps` is unreachable.
+ pub fn extend<'b, I>(&mut self, pipelines: I)
+ where
+ I: IntoIterator<Item = (CommandContext<'b>, Vec<SourcedStep>)>,
+ {
+ for (ctx, steps) in pipelines {
+ self.pending.push(PendingPipeline {
+ worktree_path: ctx.worktree_path.to_path_buf(),
+ branch: ctx.branch.map(String::from),
+ steps,
+ });
+ }
+ }
+
+ /// Prepare and add user+project pipelines for a single hook type.
+ pub fn register(
+ &mut self,
+ ctx: &CommandContext<'_>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ display_path: Option<&Path>,
+ ) -> anyhow::Result<()> {
+ let groups = prepare_background_hooks(ctx, hook_type, extra_vars, display_path)?;
+ self.extend(groups.into_iter().map(|g| (*ctx, g)));
+ Ok(())
+ }
+
+ /// 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).
+ pub fn flush(&mut self) -> anyhow::Result<()> {
+ let mut pending = std::mem::take(&mut self.pending);
+ if pending.is_empty() {
+ return Ok(());
+ }
+
+ // Borrow `worktree_path` / `branch` from each `pending` slot for
+ // CommandContext while moving `steps` out via `mem::take`. `pending`
+ // outlives `pipelines`, so the borrow checker is satisfied.
+ let pipelines: Vec<_> = pending
+ .iter_mut()
+ .map(|p| {
+ (
+ CommandContext::new(
+ self.repo,
+ self.config,
+ p.branch.as_deref(),
+ &p.worktree_path,
+ false,
+ ),
+ std::mem::take(&mut p.steps),
+ )
+ })
+ .collect();
+
+ announce_and_spawn_pipelines(pipelines, self.show_branch)
+ }
+}
+
+impl<'a> Drop for HookAnnouncer<'a> {
+ /// Best-effort flush on drop so hooks registered before an early-return
+ /// error still spawn. Without this, a `register` error in a later phase
+ /// would silently swallow earlier-registered pipelines — a regression
+ /// from the prior fire-and-forget pattern. On the success path,
+ /// `flush()` runs explicitly first and `pending` is empty here.
+ fn drop(&mut self) {
+ if self.pending.is_empty() {
+ return;
+ }
+ if let Err(err) = self.flush() {
+ eprintln!(
+ "{}",
+ warning_message(format!("Failed to spawn pending hooks: {err:#}"))
+ );
+ }
+ }
+}
+
/// Announce and spawn background hooks for one or more hook types.
///
-/// Displays a single combined summary line covering all hook types, then
-/// spawns each source group as an independent pipeline. For a single hook
-/// type, prefer `spawn_background_hooks` — it wraps the prepare+announce
-/// step. Use this directly when multiple hook types fire together (e.g.,
-/// post-switch + post-start on create).
+/// Convenience wrapper around `HookAnnouncer` for sites that produce all
+/// pipelines in one place (e.g., post-switch + post-start on create). For
+/// commands that fire hooks at multiple moments, use `HookAnnouncer` directly
+/// so the whole command shares one announce line.
///
/// Each pipeline carries its own `CommandContext` so that different hook types
/// can use different contexts (e.g., post-remove uses the removed branch while
/// post-switch uses the destination branch).
-///
-/// When `show_branch` is true, includes the branch name for disambiguation in batch
-/// contexts (e.g., prune removing multiple worktrees):
-/// `Running post-remove for feature: docs; post-switch for feature: zellij-tab`
-///
-/// Without `show_branch`: `Running post-switch: zellij-tab; post-start: deps, assets, docs`
pub fn announce_and_spawn_background_hooks(
pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,
show_branch: bool,
@@ -288,10 +405,19 @@ pub fn announce_and_spawn_background_hooks(
if non_empty.is_empty() {
return Ok(());
}
+ announce_and_spawn_pipelines(non_empty, show_branch)
+}
+/// Format the combined `Running …` line for `pipelines`, print it, and spawn
+/// each source group as an independent pipeline. Caller is responsible for
+/// filtering out empty groups before calling.
+fn announce_and_spawn_pipelines(
+ pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,
+ show_branch: bool,
+) -> anyhow::Result<()> {
// Build combined summary, merging groups with the same hook type:
// "post-switch: zellij-tab; post-start: deps, assets, docs"
- let display_path = non_empty
+ let display_path = pipelines
.iter()
.flat_map(|(_, g)| g.iter())
.find_map(|s| s.display_path.as_ref());
@@ -299,7 +425,7 @@ pub fn announce_and_spawn_background_hooks(
// Merge summaries by hook type so user+project for the same type
// shows "post-start: user_bg, project" not "post-start: user_bg; post-start: project".
let mut type_summaries: Vec<(HookType, Vec<String>)> = Vec::new();
- for (_, group) in &non_empty {
+ for (_, group) in &pipelines {
let hook_type = group[0].hook_type;
let summary = format_pipeline_summary(group);
if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| *ht == hook_type) {
@@ -313,7 +439,7 @@ pub fn announce_and_spawn_background_hooks(
// This is the removed branch — it identifies the triggering event even for
// post-switch hooks that fire as a consequence of the removal.
let branch_suffix = if show_branch {
- non_empty
+ pipelines
.first()
.and_then(|(ctx, _)| ctx.branch)
.map(|b| cformat!(" for <bold>{b}</>"))
@@ -337,11 +463,11 @@ pub fn announce_and_spawn_background_hooks(
None => format!("Running {combined}"),
};
if verbosity() >= 1 {
- print_background_variable_tables(&non_empty);
+ print_background_variable_tables(&pipelines);
}
eprintln!("{}", progress_message(message));
- for (ctx, group) in non_empty {
+ for (ctx, group) in pipelines {
spawn_hook_pipeline_quiet(&ctx, group)?;
}
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 56e5e39e6..2a5970f44 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -9,7 +9,7 @@ use super::command_executor::CommandContext;
use super::command_executor::FailureStrategy;
use super::commit::CommitOptions;
use super::context::CommandEnv;
-use super::hooks::{execute_hook, spawn_background_hooks};
+use super::hooks::{HookAnnouncer, execute_hook};
use super::project_config::{ApprovableCommand, collect_commands_for_hooks};
use super::repository_ext::{
RepositoryCliExt, check_not_default_branch, compute_integration_reason, is_primary_worktree,
@@ -284,6 +284,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
.filter(|c| c.len() >= 7)
.map(|c| c[..7].to_string());
+ // One announcer for the whole command's background hooks: post-remove +
+ // post-switch (from worktree removal) and post-merge share a single
+ // `◎ Running …` line, flushed at the end.
+ let mut announcer = HookAnnouncer::new(repo, config, false);
+
// Finish worktree unless removal is disabled or blocked.
// Guards are shared with `wt remove`: is_primary_worktree (Phase 2) and
// check_not_default_branch (Phase 3) are the same helpers both paths use.
@@ -327,7 +332,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
expected_path,
removed_commit: feature_commit.clone(),
};
- crate::output::handle_remove_output(&remove_result, false, verify, false, false)?;
+ crate::output::handle_remove_output(
+ &remove_result,
+ false,
+ verify,
+ false,
+ false,
+ Some(&mut announcer),
+ )?;
true
};
@@ -358,9 +370,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
extra.push(("short_commit", sc));
}
- spawn_background_hooks(&ctx, HookType::PostMerge, &extra, display_path)?;
+ announcer.register(&ctx, HookType::PostMerge, &extra, display_path)?;
}
+ announcer.flush()?;
+
if json_mode {
let output = serde_json::json!({
"branch": current_branch,
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index fb8cc5e2c..2805d2ae6 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1447,7 +1447,7 @@ pub fn step_prune(
return Ok(false);
}
};
- handle_remove_output(&plan, foreground, run_hooks, true, true)?;
+ handle_remove_output(&plan, foreground, run_hooks, true, true, None)?;
Ok(true)
}
diff --git a/src/main.rs b/src/main.rs
index a697b4cd7..a506ec44c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -807,7 +807,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
// "Approve at the Gate": approval happens AFTER validation passes
let run_hooks = verify && approve_remove(yes)?;
- handle_remove_output(&result, args.foreground, run_hooks, false, false)?;
+ handle_remove_output(&result, args.foreground, run_hooks, false, false, None)?;
if json_mode {
let json = serde_json::json!([result.to_json()]);
println!("{}", serde_json::to_string_pretty(&json)?);
@@ -846,13 +846,34 @@ 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;
for result in &plans.others {
- handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
+ handle_remove_output(
+ result,
+ args.foreground,
+ run_hooks,
+ false,
+ show_branch,
+ None,
+ )?;
}
for result in &plans.branch_only {
- handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
+ handle_remove_output(
+ result,
+ args.foreground,
+ run_hooks,
+ false,
+ show_branch,
+ None,
+ )?;
}
if let Some(ref result) = plans.current {
- handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
+ handle_remove_output(
+ result,
+ args.foreground,
+ run_hooks,
+ false,
+ show_branch,
+ None,
+ )?;
}
if json_mode {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 329c96bf8..2cdc91c1b 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -12,7 +12,7 @@ use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
use crate::commands::command_executor::CommandContext;
use crate::commands::command_executor::FailureStrategy;
use crate::commands::hooks::{
- announce_and_spawn_background_hooks, execute_hook, prepare_background_hooks,
+ HookAnnouncer, announce_and_spawn_background_hooks, execute_hook, prepare_background_hooks,
};
use crate::commands::process::{
HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,
@@ -736,6 +736,7 @@ pub fn handle_remove_output(
verify: bool,
quiet: bool,
show_branch_in_hooks: bool,
+ announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<()> {
match result {
RemoveResult::RemovedWorktree {
@@ -749,21 +750,24 @@ pub fn handle_remove_output(
force_worktree,
expected_path,
removed_commit,
- } => handle_removed_worktree_output(RemovedWorktreeOutputContext {
- main_path,
- worktree_path,
- changed_directory: *changed_directory,
- branch_name: branch_name.as_deref(),
- deletion_mode: *deletion_mode,
- target_branch: target_branch.as_deref(),
- pre_computed_integration: *integration_reason,
- force_worktree: *force_worktree,
- expected_path: expected_path.as_deref(),
- removed_commit: removed_commit.as_deref(),
- foreground,
- verify,
- show_branch_in_hooks,
- }),
+ } => handle_removed_worktree_output(
+ RemovedWorktreeOutputContext {
+ main_path,
+ worktree_path,
+ changed_directory: *changed_directory,
+ branch_name: branch_name.as_deref(),
+ deletion_mode: *deletion_mode,
+ target_branch: target_branch.as_deref(),
+ pre_computed_integration: *integration_reason,
+ force_worktree: *force_worktree,
+ expected_path: expected_path.as_deref(),
+ removed_commit: removed_commit.as_deref(),
+ foreground,
+ verify,
+ show_branch_in_hooks,
+ },
+ announcer,
+ ),
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
@@ -874,10 +878,12 @@ fn handle_branch_only_output(
Ok(())
}
-/// Spawn post-remove and post-switch hooks as a single batch after worktree removal.
+/// Register or spawn post-remove and post-switch hooks after worktree removal.
///
-/// Combines both hook types into one output line for consistency with how
-/// post-switch and post-start are combined during worktree creation.
+/// When `ctx.announcer` is `Some`, pipelines are registered on the caller's
+/// announcer so they can share an announce line with later hooks (e.g.
+/// post-merge in `wt merge`). When `None`, this self-announces and spawns —
+/// the standalone `wt remove` path.
///
/// Post-remove template variables reflect the removed worktree (branch, path, commit).
/// Post-switch hooks only run when `changed_directory` is true (user cd'd to main).
@@ -887,6 +893,7 @@ fn spawn_hooks_after_remove(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
removed_branch: &str,
+ announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<()> {
if !ctx.verify {
return Ok(());
@@ -950,7 +957,11 @@ fn spawn_hooks_after_remove(
);
}
- announce_and_spawn_background_hooks(pipelines, ctx.show_branch_in_hooks)?;
+ if let Some(announcer) = announcer {
+ announcer.extend(pipelines);
+ } else {
+ announce_and_spawn_background_hooks(pipelines, ctx.show_branch_in_hooks)?;
+ }
Ok(())
}
@@ -1247,6 +1258,7 @@ fn prepare_remove_directory_change(
fn handle_detached_removed_worktree_output(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
+ announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<()> {
if ctx.foreground {
eprintln!(
@@ -1307,7 +1319,7 @@ fn handle_detached_removed_worktree_output(
}
// Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
- spawn_hooks_after_remove(repo, ctx, "HEAD")?;
+ spawn_hooks_after_remove(repo, ctx, "HEAD", announcer)?;
stderr().flush()?;
Ok(())
}
@@ -1316,6 +1328,7 @@ fn handle_named_removed_worktree_foreground(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
branch_name: &str,
+ announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<()> {
eprintln!(
"{}",
@@ -1363,7 +1376,7 @@ fn handle_named_removed_worktree_foreground(
display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
- spawn_hooks_after_remove(repo, ctx, branch_name)?;
+ spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;
stderr().flush()?;
Ok(())
}
@@ -1372,6 +1385,7 @@ fn handle_named_removed_worktree_background(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
branch_name: &str,
+ announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<()> {
if let Some(expected) = ctx.expected_path {
eprintln!(
@@ -1401,13 +1415,16 @@ fn handle_named_removed_worktree_background(
ctx.changed_directory,
)?;
- spawn_hooks_after_remove(repo, ctx, branch_name)?;
+ spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;
stderr().flush()?;
Ok(())
}
/// Handle output for RemovedWorktree removal
-fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhow::Result<()> {
+fn handle_removed_worktree_output(
+ ctx: RemovedWorktreeOutputContext<'_>,
+ announcer: Option<&mut HookAnnouncer<'_>>,
+) -> anyhow::Result<()> {
// Use main_path for discovery - the worktree being removed might be cwd,
// and git operations after removal need a valid working directory.
let repo = worktrunk::git::Repository::at(ctx.main_path)?;
@@ -1417,13 +1434,13 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh
// Handle detached HEAD case (no branch known)
let Some(branch_name) = ctx.branch_name else {
- return handle_detached_removed_worktree_output(&repo, &ctx);
+ return handle_detached_removed_worktree_output(&repo, &ctx, announcer);
};
if ctx.foreground {
- handle_named_removed_worktree_foreground(&repo, &ctx, branch_name)
+ handle_named_removed_worktree_foreground(&repo, &ctx, branch_name, announcer)
} else {
- handle_named_removed_worktree_background(&repo, &ctx, branch_name)
+ handle_named_removed_worktree_background(&repo, &ctx, branch_name, announcer)
}
}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 72fd5189d..83a524ed4 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -11,6 +11,7 @@ use crate::common::{
setup_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_file_count,
};
use insta_cmd::assert_cmd_snapshot;
+use path_slash::PathExt as _;
use rstest::rstest;
use std::fs;
use std::thread;
@@ -926,6 +927,92 @@ cleanup = "echo 'POST_REMOVE_DURING_MERGE' > ../merge_postremove_marker.txt"
);
}
+/// `wt merge` with removal fires post-remove, post-switch, and post-merge in
+/// sequence. They should share one `Running …` announce line so the user sees
+/// a single status line for the whole command, not three.
+#[rstest]
+fn test_merge_combines_post_remove_post_switch_post_merge(mut repo: TestRepo) {
+ let feature_wt =
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature", "Add feature");
+
+ repo.write_test_config(
+ r#"[post-remove]
+cleanup = "echo removed"
+
+[post-switch]
+notify = "echo switched"
+
+[post-merge]
+sync = "echo merged"
+"#,
+ );
+
+ snapshot_merge(
+ "merge_combines_post_remove_post_switch_post_merge",
+ &repo,
+ &["main", "--yes"],
+ Some(&feature_wt),
+ );
+}
+
+/// 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
+/// which earlier hooks couldn't be lost by a later failure.
+#[rstest]
+fn test_merge_drops_pending_hooks_when_post_merge_fails(mut repo: TestRepo) {
+ let feature_wt =
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature", "Add feature");
+
+ let temp_root = repo.root_path().parent().unwrap();
+ let post_remove_marker = temp_root.join("drop_postremove_marker.txt");
+ let post_merge_marker = temp_root.join("drop_postmerge_marker.txt");
+
+ // post-merge references an undefined variable, so `register` errors after
+ // post-remove + post-switch are already pending in the announcer.
+ // Convert to forward slashes so the rendered shell command parses the same
+ // way under Windows Git Bash (where backslashes in unquoted paths get
+ // eaten as escape-of-next-char).
+ repo.write_test_config(&format!(
+ r#"[post-remove]
+cleanup = "echo POST_REMOVE_RAN > {}"
+
+[post-switch]
+notify = "echo switched"
+
+[post-merge]
+sync = "echo POST_MERGE_RAN > {} {{{{ does_not_exist }}}}"
+"#,
+ post_remove_marker.to_slash_lossy(),
+ post_merge_marker.to_slash_lossy(),
+ ));
+
+ let output = repo
+ .wt_command()
+ .args(["merge", "main", "--yes"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ !output.status.success(),
+ "merge should fail when post-merge template references undefined variable"
+ );
+
+ // Drop flushed the pending pipelines: post-remove ran despite the failure.
+ crate::common::wait_for_file_content(&post_remove_marker);
+ let contents = fs::read_to_string(&post_remove_marker).unwrap();
+ assert!(
+ contents.contains("POST_REMOVE_RAN"),
+ "post-remove should have spawned via Drop: {contents}"
+ );
+
+ // post-merge never registered (template prep failed), so its marker stays absent.
+ assert!(
+ !post_merge_marker.exists(),
+ "post-merge marker should not exist (template prep failed before spawn)"
+ );
+}
+
/// When removing the current worktree (cd back to main), both post-remove and
/// post-switch hooks fire. They should appear on a single combined announcement line.
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_combines_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_combines_post_remove_post_switch_post_merge.snap
new file mode 100644
index 000000000..c058f2d7a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_combines_post_remove_post_switch_post_merge.snap
@@ -0,0 +1,56 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ 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_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
+  * [HASH] Add feature
+  feature.txt | 1 +
+  1 file changed, 1 insertion(+)
+✓ Merged to main (1 commit, 1 file, +1)
+◎ 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-remove: user:cleanup; post-switch: user:notify; post-merge: user:sync @ _REPO_