Skip to content

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

Add post-remove hook type (#757)

Maximilian Roos677928d008d5
diff --git a/.claude-plugin/skills/worktrunk/reference/hook.md b/.claude-plugin/skills/worktrunk/reference/hook.md
index 19c8baf4e..9c8f48c66 100644
--- a/.claude-plugin/skills/worktrunk/reference/hook.md
+++ b/.claude-plugin/skills/worktrunk/reference/hook.md
@@ -15,6 +15,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| `pre-merge` | Before merging to target | Yes | Yes |
| `post-merge` | After successful merge | Yes | No |
| `pre-remove` | Before worktree removed | Yes | Yes |
+| `post-remove` | After worktree removed | No (background) | No |
**Blocking**: Command waits for hook to complete before continuing.
**Fail-fast**: First failure aborts the operation.
@@ -80,14 +81,24 @@ post-merge = "cargo install --path ."
### pre-remove
-Cleanup tasks, saving state, notifying external systems.
+Cleanup tasks before worktree is deleted, saving test artifacts, backing up state. Runs in the worktree being removed, with access to worktree files.
```toml
[pre-remove]
-cleanup = "rm -rf /tmp/cache/{{ branch }}"
+archive = "tar -czf ~/.wt-logs/{{ branch }}.tar.gz test-results/ logs/ 2>/dev/null || true"
```
-During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-merge. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
+### post-remove
+
+Cleanup tasks after worktree removal: stopping dev servers, removing containers, notifying external systems. All template variables reference the removed worktree, so cleanup scripts can identify resources to clean up. Output logged to `.git/wt-logs/{branch}-{source}-post-remove-{name}.log`.
+
+```toml
+[post-remove]
+kill-server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
+remove-db = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
+```
+
+During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-remove → post-merge. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.
## Security
@@ -290,7 +301,7 @@ Both run when creating a worktree. The difference:
Many tasks work well in `post-start` — they'll likely be ready by the time they're needed, especially when the fallback is recompiling. If unsure, prefer `post-start` for faster worktree creation.
-Background processes spawned by `post-start` outlive the worktree — pair them with `pre-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
+Background processes spawned by `post-start` outlive the worktree — pair them with `post-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
### Copying untracked files
@@ -311,7 +322,7 @@ Run a dev server per worktree on a deterministic port using `hash_port`:
[post-start]
server = "npm run dev -- --port {{ branch | hash_port }}"
-[pre-remove]
+[post-remove]
server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
```
@@ -344,7 +355,7 @@ docker run -d --rm \
postgres:16
"""
-[pre-remove]
+[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
@@ -417,6 +428,7 @@ Usage: <b><span class=c>wt hook</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>pre-merge</span></b> Run pre-merge hooks
<b><span class=c>post-merge</span></b> Run post-merge hooks
<b><span class=c>pre-remove</span></b> Run pre-remove hooks
+ <b><span class=c>post-remove</span></b> Run post-remove hooks
<b><span class=c>approvals</span></b> Manage command approvals
<b><span class=g>Options:</span></b>
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 5a31c83ab..982bec6d8 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -23,6 +23,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| `pre-merge` | Before merging to target | Yes | Yes |
| `post-merge` | After successful merge | Yes | No |
| `pre-remove` | Before worktree removed | Yes | Yes |
+| `post-remove` | After worktree removed | No (background) | No |
**Blocking**: Command waits for hook to complete before continuing.
**Fail-fast**: First failure aborts the operation.
@@ -88,14 +89,24 @@ post-merge = "cargo install --path ."
### pre-remove
-Cleanup tasks, saving state, notifying external systems.
+Cleanup tasks before worktree is deleted, saving test artifacts, backing up state. Runs in the worktree being removed, with access to worktree files.
```toml
[pre-remove]
-cleanup = "rm -rf /tmp/cache/{{ branch }}"
+archive = "tar -czf ~/.wt-logs/{{ branch }}.tar.gz test-results/ logs/ 2>/dev/null || true"
```
-During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-merge. See [`wt merge`](@/merge.md#pipeline) for the complete pipeline.
+### post-remove
+
+Cleanup tasks after worktree removal: stopping dev servers, removing containers, notifying external systems. All template variables reference the removed worktree, so cleanup scripts can identify resources to clean up. Output logged to `.git/wt-logs/{branch}-{source}-post-remove-{name}.log`.
+
+```toml
+[post-remove]
+kill-server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
+remove-db = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
+```
+
+During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-remove → post-merge. See [`wt merge`](@/merge.md#pipeline) for the complete pipeline.
## Security
@@ -298,7 +309,7 @@ Both run when creating a worktree. The difference:
Many tasks work well in `post-start` — they'll likely be ready by the time they're needed, especially when the fallback is recompiling. If unsure, prefer `post-start` for faster worktree creation.
-Background processes spawned by `post-start` outlive the worktree — pair them with `pre-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
+Background processes spawned by `post-start` outlive the worktree — pair them with `post-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
### Copying untracked files
@@ -319,7 +330,7 @@ Run a dev server per worktree on a deterministic port using `hash_port`:
[post-start]
server = "npm run dev -- --port {{ branch | hash_port }}"
-[pre-remove]
+[post-remove]
server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
```
@@ -352,7 +363,7 @@ docker run -d --rm \
postgres:16
"""
-[pre-remove]
+[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
@@ -432,6 +443,7 @@ Usage: <b><span class=c>wt hook</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>pre-merge</span></b> Run pre-merge hooks
<b><span class=c>post-merge</span></b> Run post-merge hooks
<b><span class=c>pre-remove</span></b> Run pre-remove hooks
+ <b><span class=c>post-remove</span></b> Run post-remove hooks
<b><span class=c>approvals</span></b> Manage command approvals
<b><span class=g>Options:</span></b>
diff --git a/src/cli/hook.rs b/src/cli/hook.rs
index fe66f8fe6..6368db065 100644
--- a/src/cli/hook.rs
+++ b/src/cli/hook.rs
@@ -10,7 +10,7 @@ pub enum HookCommand {
/// Lists user and project hooks. Project hooks show approval status (❓ = needs approval).
Show {
/// Hook type to show (default: all)
- #[arg(value_parser = ["post-create", "post-start", "post-switch", "pre-commit", "pre-merge", "post-merge", "pre-remove"])]
+ #[arg(value_parser = ["post-create", "post-start", "post-switch", "pre-commit", "pre-merge", "post-merge", "pre-remove", "post-remove"])]
hook_type: Option<String>,
/// Show expanded commands with current variables
@@ -166,6 +166,30 @@ pub enum HookCommand {
vars: Vec<(String, String)>,
},
+ /// Run post-remove hooks
+ ///
+ /// Background by default. Use `--foreground` to run in foreground for debugging.
+ PostRemove {
+ /// Filter by command name
+ ///
+ /// Supports `user:name` or `project:name` to filter by source.
+ /// `user:` alone runs all user hooks; `project:` alone runs all project hooks.
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
+ /// Skip approval prompts
+ #[arg(short, long)]
+ yes: bool,
+
+ /// Run in foreground (block until complete)
+ #[arg(long)]
+ foreground: bool,
+
+ /// Override built-in template variable (KEY=VALUE)
+ #[arg(long = "var", value_name = "KEY=VALUE", value_parser = super::parse_key_val, action = clap::ArgAction::Append)]
+ vars: Vec<(String, String)>,
+ },
+
/// Manage command approvals
#[command(
after_long_help = r#"Project hooks require approval on first run to prevent untrusted projects from running arbitrary commands.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 4d513c304..39dc6b31d 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1047,6 +1047,7 @@ wt step push
| `pre-merge` | Before merging to target | Yes | Yes |
| `post-merge` | After successful merge | Yes | No |
| `pre-remove` | Before worktree removed | Yes | Yes |
+| `post-remove` | After worktree removed | No (background) | No |
**Blocking**: Command waits for hook to complete before continuing.
**Fail-fast**: First failure aborts the operation.
@@ -1112,14 +1113,24 @@ post-merge = "cargo install --path ."
### pre-remove
-Cleanup tasks, saving state, notifying external systems.
+Cleanup tasks before worktree is deleted, saving test artifacts, backing up state. Runs in the worktree being removed, with access to worktree files.
```toml
[pre-remove]
-cleanup = "rm -rf /tmp/cache/{{ branch }}"
+archive = "tar -czf ~/.wt-logs/{{ branch }}.tar.gz test-results/ logs/ 2>/dev/null || true"
```
-During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-merge. See [`wt merge`](@/merge.md#pipeline) for the complete pipeline.
+### post-remove
+
+Cleanup tasks after worktree removal: stopping dev servers, removing containers, notifying external systems. All template variables reference the removed worktree, so cleanup scripts can identify resources to clean up. Output logged to `.git/wt-logs/{branch}-{source}-post-remove-{name}.log`.
+
+```toml
+[post-remove]
+kill-server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
+remove-db = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
+```
+
+During `wt merge`, hooks run in this order: pre-commit → pre-merge → pre-remove → post-remove → post-merge. See [`wt merge`](@/merge.md#pipeline) for the complete pipeline.
## Security
@@ -1322,7 +1333,7 @@ Both run when creating a worktree. The difference:
Many tasks work well in `post-start` — they'll likely be ready by the time they're needed, especially when the fallback is recompiling. If unsure, prefer `post-start` for faster worktree creation.
-Background processes spawned by `post-start` outlive the worktree — pair them with `pre-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
+Background processes spawned by `post-start` outlive the worktree — pair them with `post-remove` hooks to clean up. See [Dev servers](#dev-servers) and [Databases](#databases) for examples.
### Copying untracked files
@@ -1343,7 +1354,7 @@ Run a dev server per worktree on a deterministic port using `hash_port`:
[post-start]
server = "npm run dev -- --port {{ branch | hash_port }}"
-[pre-remove]
+[post-remove]
server = "lsof -ti :{{ branch | hash_port }} | xargs kill 2>/dev/null || true"
```
@@ -1376,7 +1387,7 @@ docker run -d --rm \
postgres:16
"""
-[pre-remove]
+[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 57a0a6307..340a85365 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -249,6 +249,45 @@ pub fn run_hook(
&custom_vars_refs,
)
}
+ HookType::PostRemove => {
+ let user_config = ctx.config.hooks.post_remove.as_ref();
+ let project_config = project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_remove.as_ref());
+ require_hooks(user_config, project_config, hook_type)?;
+
+ // Default to background (matching normal behavior during remove)
+ // Use --foreground to run in foreground for debugging
+ if !foreground.unwrap_or(false) {
+ let commands = prepare_hook_commands(
+ &ctx,
+ user_config,
+ project_config,
+ hook_type,
+ &custom_vars_refs,
+ name_filter,
+ None,
+ )?;
+ check_name_filter_matched(
+ name_filter,
+ commands.len(),
+ user_config,
+ project_config,
+ )?;
+ spawn_hook_commands_background(&ctx, commands, hook_type)
+ } else {
+ run_hook_with_filter(
+ &ctx,
+ user_config,
+ project_config,
+ hook_type,
+ &custom_vars_refs,
+ HookFailureStrategy::Warn,
+ name_filter,
+ crate::output::pre_hook_display_path(ctx.worktree_path),
+ )
+ }
+ }
}
}
@@ -402,6 +441,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
"pre-merge" => HookType::PreMerge,
"post-merge" => HookType::PostMerge,
"pre-remove" => HookType::PreRemove,
+ "post-remove" => HookType::PostRemove,
_ => unreachable!("clap validates hook type"),
});
@@ -472,6 +512,7 @@ fn render_user_hooks(
(HookType::PreMerge, &config.hooks.pre_merge),
(HookType::PostMerge, &config.hooks.post_merge),
(HookType::PreRemove, &config.hooks.pre_remove),
+ (HookType::PostRemove, &config.hooks.post_remove),
];
let mut has_any = false;
@@ -532,6 +573,7 @@ fn render_project_hooks(
(HookType::PreMerge, &config.hooks.pre_merge),
(HookType::PostMerge, &config.hooks.post_merge),
(HookType::PreRemove, &config.hooks.pre_remove),
+ (HookType::PostRemove, &config.hooks.post_remove),
];
let mut has_any = false;
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 44e9a35b3..933f98d32 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -64,6 +64,7 @@ fn collect_merge_commands(
hooks.push(HookType::PostMerge);
if will_remove {
hooks.push(HookType::PreRemove);
+ hooks.push(HookType::PostRemove);
hooks.push(HookType::PostSwitch);
}
}
@@ -249,6 +250,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let (_, integration_reason) = repo.integration_reason(&current_branch, &target_branch)?;
// Compute expected_path for path mismatch detection
let expected_path = get_path_mismatch(repo, &current_branch, &worktree_root, config);
+ // Capture commit SHA before removal for post-remove hook template variables
+ let removed_commit = current_wt
+ .run_command(&["rev-parse", "HEAD"])
+ .ok()
+ .map(|s| s.trim().to_string());
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
@@ -261,6 +267,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// commit, removal will fail and user can run `wt remove --force`
force_worktree: false,
expected_path,
+ removed_commit,
};
// Run hooks during merge removal (pass through verify flag)
// Approval was handled at the gate (collect_merge_commands)
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 9cf4fd9ca..624c31f48 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -201,6 +201,13 @@ impl RepositoryCliExt for Repository {
.as_ref()
.and_then(|branch| get_path_mismatch(self, branch, &worktree_path, config));
+ // Capture commit SHA before removal for post-remove hook template variables.
+ // This ensures {{ commit }} references the removed worktree's state.
+ let removed_commit = target_wt
+ .run_command(&["rev-parse", "HEAD"])
+ .ok()
+ .map(|s| s.trim().to_string());
+
Ok(RemoveResult::RemovedWorktree {
main_path,
worktree_path,
@@ -211,6 +218,7 @@ impl RepositoryCliExt for Repository {
integration_reason,
force_worktree,
expected_path,
+ removed_commit,
})
}
diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rs
index 50279cd29..f07c7e9d1 100644
--- a/src/commands/worktree/hooks.rs
+++ b/src/commands/worktree/hooks.rs
@@ -1,8 +1,11 @@
//! Hook execution for worktree operations.
//!
-//! CommandContext implementations for post-create, post-start, and post-switch hooks.
+//! CommandContext implementations for post-create, post-start, post-switch, and post-remove hooks.
+
+use std::path::Path;
use worktrunk::HookType;
+use worktrunk::path::to_posix_path;
use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
@@ -88,4 +91,64 @@ impl<'a> CommandContext<'a> {
spawn_hook_commands_background(self, commands, HookType::PostSwitch)
}
+
+ /// Spawn post-remove commands in parallel as background processes (non-blocking)
+ ///
+ /// Runs after worktree removal. Commands execute from the invoking worktree (where
+ /// the user ends up after removal), but template variables reflect the removed
+ /// worktree so hooks can reference paths and names correctly.
+ ///
+ /// `removed_branch`: The branch that was removed (for `{{ branch }}`).
+ /// `removed_worktree_path`: The removed worktree's path (for `{{ worktree_path }}`, etc.).
+ /// `removed_commit`: The commit SHA of the removed worktree's HEAD (for `{{ commit }}`).
+ /// `display_path`: When `Some`, shows the path in hook announcements.
+ pub fn spawn_post_remove_commands(
+ &self,
+ removed_branch: &str,
+ removed_worktree_path: &Path,
+ removed_commit: Option<&str>,
+ display_path: Option<&Path>,
+ ) -> anyhow::Result<()> {
+ let project_config = self.repo.load_project_config()?;
+
+ // Template variables should reflect the removed worktree, not where we run from.
+ // The removed worktree path no longer exists, but hooks may need to reference it
+ // (e.g., for cleanup scripts that use the path in container names).
+ let worktree_path_str = to_posix_path(&removed_worktree_path.to_string_lossy());
+ let worktree_name = removed_worktree_path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("unknown");
+
+ // Build extra_vars with all removed worktree context.
+ // Commit is captured before removal to ensure it reflects the removed worktree's state.
+ let commit = removed_commit.unwrap_or("");
+ let short_commit = if commit.len() >= 7 {
+ &commit[..7]
+ } else {
+ commit
+ };
+ let extra_vars: Vec<(&str, &str)> = vec![
+ ("branch", removed_branch),
+ ("worktree_path", &worktree_path_str),
+ ("worktree", &worktree_path_str), // deprecated alias
+ ("worktree_name", worktree_name),
+ ("commit", commit),
+ ("short_commit", short_commit),
+ ];
+
+ let commands = prepare_hook_commands(
+ self,
+ self.config.hooks.post_remove.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_remove.as_ref()),
+ HookType::PostRemove,
+ &extra_vars,
+ None,
+ display_path,
+ )?;
+
+ spawn_hook_commands_background(self, commands, HookType::PostRemove)
+ }
}
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index e0919e57f..6f81b908a 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -196,6 +196,10 @@ pub enum RemoveResult {
/// Expected path based on config template. `Some` when actual path differs
/// from expected (path mismatch), `None` when path matches template.
expected_path: Option<PathBuf>,
+ /// Commit SHA of the removed worktree's HEAD, captured before removal.
+ /// Used for post-remove hook template variables so they reference the
+ /// removed worktree's state, not the execution context.
+ removed_commit: Option<String>,
},
/// Branch exists but has no worktree - attempt branch deletion only.
///
@@ -329,6 +333,7 @@ mod tests {
integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),
force_worktree: false,
expected_path: None,
+ removed_commit: Some("abc1234567890".to_string()),
};
match result {
RemoveResult::RemovedWorktree {
@@ -341,6 +346,7 @@ mod tests {
integration_reason,
force_worktree,
expected_path,
+ removed_commit,
} => {
assert_eq!(main_path.to_str().unwrap(), "/main");
assert_eq!(worktree_path.to_str().unwrap(), "/worktree");
@@ -352,6 +358,7 @@ mod tests {
assert!(integration_reason.is_some());
assert!(!force_worktree);
assert!(expected_path.is_none());
+ assert_eq!(removed_commit.as_deref(), Some("abc1234567890"));
}
_ => panic!("Expected RemovedWorktree variant"),
}
@@ -412,6 +419,7 @@ mod tests {
integration_reason: None, // Force delete skips integration check
force_worktree: true,
expected_path: None,
+ removed_commit: None, // Detached HEAD may not have meaningful commit
};
match result {
RemoveResult::RemovedWorktree {
diff --git a/src/config/hooks.rs b/src/config/hooks.rs
index 8251c3631..8627949a0 100644
--- a/src/config/hooks.rs
+++ b/src/config/hooks.rs
@@ -58,6 +58,14 @@ pub struct HooksConfig {
skip_serializing_if = "Option::is_none"
)]
pub pre_remove: Option<CommandConfig>,
+
+ /// Commands to execute after worktree removal (background)
+ #[serde(
+ default,
+ rename = "post-remove",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_remove: Option<CommandConfig>,
}
impl HooksConfig {
@@ -70,6 +78,7 @@ impl HooksConfig {
HookType::PreMerge => self.pre_merge.as_ref(),
HookType::PostMerge => self.post_merge.as_ref(),
HookType::PreRemove => self.pre_remove.as_ref(),
+ HookType::PostRemove => self.post_remove.as_ref(),
}
}
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index a96c8702d..8b8a05fa1 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -326,6 +326,7 @@ pub enum HookType {
PreMerge,
PostMerge,
PreRemove,
+ PostRemove,
}
/// Reference to a branch for parallel task execution.
diff --git a/src/main.rs b/src/main.rs
index 524a90b31..f05f0b4b8 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -604,6 +604,18 @@ fn main() {
HookCommand::PreRemove { name, yes, vars } => {
run_hook(HookType::PreRemove, yes, None, name.as_deref(), &vars)
}
+ HookCommand::PostRemove {
+ name,
+ yes,
+ foreground,
+ vars,
+ } => run_hook(
+ HookType::PostRemove,
+ yes,
+ Some(foreground),
+ name.as_deref(),
+ &vars,
+ ),
HookCommand::Approvals { action } => match action {
ApprovalsCommand::Add { all } => add_approvals(all),
ApprovalsCommand::Clear { global } => clear_approvals(global),
@@ -902,8 +914,14 @@ fn main() {
use commands::context::CommandEnv;
let env = CommandEnv::for_action_branchless()?;
let ctx = env.context(yes);
- let approved =
- approve_hooks(&ctx, &[HookType::PreRemove, HookType::PostSwitch])?;
+ let approved = approve_hooks(
+ &ctx,
+ &[
+ HookType::PreRemove,
+ HookType::PostRemove,
+ HookType::PostSwitch,
+ ],
+ )?;
if !approved {
crate::output::print(info_message(
"Commands declined, continuing removal",
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index f9b3feae5..49f53bfbe 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -476,6 +476,7 @@ pub fn handle_remove_output(
integration_reason,
force_worktree,
expected_path,
+ removed_commit,
} => handle_removed_worktree_output(
main_path,
worktree_path,
@@ -486,6 +487,7 @@ pub fn handle_remove_output(
*integration_reason,
*force_worktree,
expected_path.as_ref(),
+ removed_commit.as_deref(),
background,
verify,
),
@@ -550,6 +552,45 @@ fn handle_branch_only_output(
Ok(())
}
+/// Spawn post-remove hooks after worktree removal.
+///
+/// Runs after the worktree is removed. Template variables reflect the removed
+/// worktree (branch, worktree_path, worktree_name, commit), but commands execute from
+/// `run_from_path` since the removed worktree no longer exists.
+///
+/// Only runs if `verify` is true (hooks approved).
+fn spawn_post_remove_hooks(
+ run_from_path: &std::path::Path,
+ removed_worktree_path: &std::path::Path,
+ removed_branch: &str,
+ removed_commit: Option<&str>,
+ verify: bool,
+) -> anyhow::Result<()> {
+ if !verify {
+ return Ok(());
+ }
+ let Ok(config) = UserConfig::load() else {
+ return Ok(());
+ };
+ // Use run_from_path for discovery since the original worktree is removed
+ let repo = Repository::at(run_from_path)?;
+ // Context uses run_from_path for execution, but we pass removed worktree
+ // info as extra_vars so template variables reflect the removed worktree
+ let ctx = CommandContext::new(
+ &repo,
+ &config,
+ Some(removed_branch),
+ run_from_path,
+ false, // yes=false for CommandContext
+ );
+ ctx.spawn_post_remove_commands(
+ removed_branch,
+ removed_worktree_path,
+ removed_commit,
+ super::post_hook_display_path(run_from_path),
+ )
+}
+
/// Spawn post-switch hooks in the destination worktree after a directory change.
///
/// Called when removing a worktree causes a cd to the main worktree.
@@ -574,7 +615,7 @@ fn spawn_post_switch_after_remove(
&config,
dest_branch.as_deref(),
main_path,
- false, // force=false for CommandContext
+ false, // yes=false for CommandContext
);
// No base context for remove-triggered switch (we're returning to main, not creating)
ctx.spawn_post_switch_commands(&[], super::post_hook_display_path(main_path))
@@ -778,6 +819,7 @@ fn handle_removed_worktree_output(
pre_computed_integration: Option<IntegrationReason>,
force_worktree: bool,
expected_path: Option<&PathBuf>,
+ removed_commit: Option<&str>,
background: bool,
verify: bool,
) -> anyhow::Result<()> {
@@ -795,7 +837,7 @@ fn handle_removed_worktree_output(
&config,
branch_name,
worktree_path,
- false, // force=false for CommandContext (not approval-related)
+ false, // yes=false for CommandContext (not approval-related)
);
// Show path when removing a different worktree (user is elsewhere)
let display_path = if changed_directory {
@@ -848,6 +890,8 @@ fn handle_removed_worktree_output(
"Removed worktree (detached HEAD, no branch to delete)",
))?;
}
+ // Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
+ spawn_post_remove_hooks(main_path, worktree_path, "HEAD", removed_commit, verify)?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
super::flush()?;
return Ok(());
@@ -888,6 +932,13 @@ fn handle_removed_worktree_output(
None,
)?;
+ spawn_post_remove_hooks(
+ main_path,
+ worktree_path,
+ branch_name,
+ removed_commit,
+ verify,
+ )?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
super::flush()?;
Ok(())
@@ -932,6 +983,13 @@ fn handle_removed_worktree_output(
display_info.print_hints(branch_name, deletion_mode, pre_computed_integration)?;
print_switch_message_if_changed(changed_directory, main_path)?;
+ spawn_post_remove_hooks(
+ main_path,
+ worktree_path,
+ branch_name,
+ removed_commit,
+ verify,
+ )?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
super::flush()?;
Ok(())
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 2a8c7b782..d79acd00f 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -617,11 +617,12 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"pre-merge"), "Missing pre-merge");
assert!(subcommands.contains(&"post-merge"), "Missing post-merge");
assert!(subcommands.contains(&"pre-remove"), "Missing pre-remove");
+ assert!(subcommands.contains(&"post-remove"), "Missing post-remove");
assert!(subcommands.contains(&"approvals"), "Missing approvals");
assert_eq!(
subcommands.len(),
- 9,
- "Should have exactly 9 hook subcommands"
+ 10,
+ "Should have exactly 10 hook subcommands"
);
// Test 2: Partial input "po" - filters to post-* subcommands
@@ -633,6 +634,7 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"post-start"));
assert!(subcommands.contains(&"post-switch"));
assert!(subcommands.contains(&"post-merge"));
+ assert!(subcommands.contains(&"post-remove"));
assert!(!subcommands.contains(&"pre-commit"));
assert!(!subcommands.contains(&"pre-merge"));
}
diff --git a/tests/integration_tests/hook_show.rs b/tests/integration_tests/hook_show.rs
index c2561e545..a56395912 100644
--- a/tests/integration_tests/hook_show.rs
+++ b/tests/integration_tests/hook_show.rs
@@ -70,9 +70,8 @@ fn test_hook_show_no_hooks(repo: TestRepo, temp_home: TempDir) {
});
}
-#[rstest]
-fn test_hook_show_filter_by_type(repo: TestRepo, temp_home: TempDir) {
- // Create user config without hooks
+/// Helper to set up a repo with all hook types configured for filter tests
+fn setup_all_hook_types(repo: &TestRepo, temp_home: &TempDir) {
let global_config_dir = temp_home.path().join(".config").join("worktrunk");
fs::create_dir_all(&global_config_dir).unwrap();
fs::write(
@@ -82,7 +81,6 @@ fn test_hook_show_filter_by_type(repo: TestRepo, temp_home: TempDir) {
)
.unwrap();
- // Create project config with multiple hook types
repo.write_project_config(
r#"[post-start]
deps = "npm install"
@@ -93,9 +91,20 @@ test = "cargo test"
[post-merge]
deploy = "scripts/deploy.sh"
+
+[pre-remove]
+cleanup = "echo cleanup"
+
+[post-remove]
+notify = "echo removed"
"#,
);
repo.commit("Add project config");
+}
+
+#[rstest]
+fn test_hook_show_filter_by_type(repo: TestRepo, temp_home: TempDir) {
+ setup_all_hook_types(&repo, &temp_home);
let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
settings.bind(|| {
@@ -111,6 +120,60 @@ deploy = "scripts/deploy.sh"
});
}
+#[rstest]
+fn test_hook_show_filter_post_merge(repo: TestRepo, temp_home: TempDir) {
+ setup_all_hook_types(&repo, &temp_home);
+
+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.arg("hook")
+ .arg("show")
+ .arg("post-merge")
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+#[rstest]
+fn test_hook_show_filter_pre_remove(repo: TestRepo, temp_home: TempDir) {
+ setup_all_hook_types(&repo, &temp_home);
+
+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.arg("hook")
+ .arg("show")
+ .arg("pre-remove")
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+#[rstest]
+fn test_hook_show_filter_post_remove(repo: TestRepo, temp_home: TempDir) {
+ setup_all_hook_types(&repo, &temp_home);
+
+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.arg("hook")
+ .arg("show")
+ .arg("post-remove")
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
#[rstest]
fn test_hook_show_approval_status(repo: TestRepo, temp_home: TempDir) {
// Remove origin so project_identifier uses full canonical path
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 1ce2d5029..2a5b9e046 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -572,6 +572,273 @@ block = "exit 1"
);
}
+// ============================================================================
+// User Post-Remove Hook Tests
+// ============================================================================
+
+#[rstest]
+fn test_user_post_remove_hook_executes(mut repo: TestRepo) {
+ // Create a worktree to remove
+ let _feature_wt = repo.add_worktree("feature");
+
+ // Write user config with post-remove hook
+ // Hook writes to parent dir (temp dir) since the worktree itself is removed
+ repo.write_test_config(
+ r#"[post-remove]
+cleanup = "echo 'USER_POST_REMOVE_RAN' > ../user_postremove_marker.txt"
+"#,
+ );
+
+ snapshot_remove(
+ "user_post_remove_executes",
+ &repo,
+ &["feature", "--force-delete"],
+ Some(repo.root_path()),
+ );
+
+ // Wait for background hook to complete
+ let marker_file = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("user_postremove_marker.txt");
+ crate::common::wait_for_file(&marker_file);
+ assert!(
+ marker_file.exists(),
+ "User post-remove hook should have run"
+ );
+}
+
+/// Verify that post-remove hook template variables reference the removed worktree,
+/// not the worktree where the hook executes from.
+#[rstest]
+fn test_user_post_remove_template_vars_reference_removed_worktree(mut repo: TestRepo) {
+ // Create a worktree with a unique commit to verify commit capture
+ let feature_wt_path =
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");
+
+ // Get the commit SHA of the feature worktree BEFORE removal
+ let feature_commit = repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .current_dir(&feature_wt_path)
+ .output()
+ .unwrap();
+ let feature_commit = String::from_utf8_lossy(&feature_commit.stdout);
+ let feature_commit = feature_commit.trim();
+ let feature_short_commit = &feature_commit[..7];
+
+ // Write user config that captures template variables to a file
+ // Hook writes to parent dir (temp dir) since the worktree itself is removed
+ repo.write_test_config(
+ r#"[post-remove]
+capture = "echo 'branch={{ branch }} worktree_path={{ worktree_path }} worktree_name={{ worktree_name }} commit={{ commit }} short_commit={{ short_commit }}' > ../postremove_vars.txt"
+"#,
+ );
+
+ // Run from main worktree, remove the feature worktree
+ repo.wt_command()
+ .args(["remove", "feature", "--force-delete", "--yes"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Wait for background hook to complete
+ let vars_file = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("postremove_vars.txt");
+ crate::common::wait_for_file(&vars_file);
+
+ let content = std::fs::read_to_string(&vars_file).unwrap();
+
+ // Verify branch is the removed branch
+ assert!(
+ content.contains("branch=feature"),
+ "branch should be the removed branch 'feature', got: {content}"
+ );
+
+ // Extract worktree name for cross-platform comparison.
+ // Hooks run in Git Bash on Windows, which converts paths to MSYS2 format
+ // (/c/Users/... instead of C:\Users\... or C:/Users/...). Instead of trying
+ // to match exact path formats, verify the path ends with the worktree name.
+ let feature_wt_name = feature_wt_path
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .to_string();
+
+ // Verify worktree_path is the removed worktree's path (not the main worktree)
+ // The worktree_path in hook output should end with the worktree directory name
+ assert!(
+ content.contains(&format!("/{feature_wt_name} "))
+ || content.contains(&format!("\\{feature_wt_name} ")),
+ "worktree_path should end with the removed worktree's name '{feature_wt_name}', got: {content}"
+ );
+
+ // Verify worktree_name is the removed worktree's directory name
+ assert!(
+ content.contains(&format!("worktree_name={feature_wt_name}")),
+ "worktree_name should be the removed worktree's name '{feature_wt_name}', got: {content}"
+ );
+
+ // Verify commit is the removed worktree's commit (not main worktree's commit)
+ assert!(
+ content.contains(&format!("commit={feature_commit}")),
+ "commit should be the removed worktree's commit '{feature_commit}', got: {content}"
+ );
+
+ // Verify short_commit is the first 7 chars of the removed worktree's commit
+ assert!(
+ content.contains(&format!("short_commit={feature_short_commit}")),
+ "short_commit should be '{feature_short_commit}', got: {content}"
+ );
+}
+
+#[rstest]
+fn test_user_post_remove_skipped_with_no_verify(mut repo: TestRepo) {
+ // Create a worktree to remove
+ let feature_wt = repo.add_worktree("feature");
+
+ // Write user config with post-remove hook that creates a marker
+ repo.write_test_config(
+ r#"[post-remove]
+marker = "echo 'SHOULD_NOT_RUN' > ../no_verify_postremove.txt"
+"#,
+ );
+
+ snapshot_remove(
+ "user_post_remove_no_verify",
+ &repo,
+ &["feature", "--force-delete", "--no-verify"],
+ Some(repo.root_path()),
+ );
+
+ // Worktree should be removed
+ let timeout = Duration::from_secs(5);
+ let poll_interval = Duration::from_millis(50);
+ let start = std::time::Instant::now();
+ while feature_wt.exists() && start.elapsed() < timeout {
+ thread::sleep(poll_interval);
+ }
+ assert!(
+ !feature_wt.exists(),
+ "Worktree should be removed with --no-verify"
+ );
+
+ // Post-remove hook should NOT have run
+ let marker_file = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("no_verify_postremove.txt");
+ thread::sleep(Duration::from_millis(500)); // Wait to ensure hook would have run if enabled
+ assert!(
+ !marker_file.exists(),
+ "Post-remove hook should be skipped when --no-verify is used"
+ );
+}
+
+/// Verify that post-remove hooks run during `wt merge` (which removes the worktree).
+/// This tests the main production use case for post-remove hooks.
+#[rstest]
+fn test_user_post_remove_hook_runs_during_merge(mut repo: TestRepo) {
+ // Create feature worktree with a commit
+ let feature_wt =
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");
+
+ // Write user config with post-remove hook
+ // Hook writes to temp dir (parent of repo) since worktree is removed
+ repo.write_test_config(
+ r#"[post-remove]
+cleanup = "echo 'POST_REMOVE_DURING_MERGE' > ../merge_postremove_marker.txt"
+"#,
+ );
+
+ // Run merge from feature worktree - this should trigger post-remove hooks
+ repo.wt_command()
+ .args(["merge", "main", "--yes"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+
+ // Wait for background hook to complete
+ let marker_file = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("merge_postremove_marker.txt");
+ crate::common::wait_for_file(&marker_file);
+
+ assert!(
+ marker_file.exists(),
+ "Post-remove hook should run during wt merge"
+ );
+ let contents = fs::read_to_string(&marker_file).unwrap();
+ assert!(
+ contents.contains("POST_REMOVE_DURING_MERGE"),
+ "Marker file should contain expected content"
+ );
+}
+
+// Note: The `return Ok(())` path in spawn_post_remove_hooks when UserConfig::load()
+// fails (handlers.rs line 556) is defensive code for an extremely rare race condition
+// where config becomes invalid between command startup and hook execution. This is
+// not easily testable without complex timing manipulation and matches the existing
+// pattern in spawn_post_switch_after_remove (line 584).
+
+#[rstest]
+fn test_standalone_hook_post_remove_invalid_template(repo: TestRepo) {
+ // Write project config with invalid template syntax (unclosed braces)
+ repo.write_project_config(r#"post-remove = "echo {{ invalid""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-remove", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt hook post-remove should fail with invalid template"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Failed to expand command template"),
+ "Error should mention template expansion failure, got: {stderr}"
+ );
+}
+
+#[rstest]
+fn test_standalone_hook_post_remove_name_filter_no_match(repo: TestRepo) {
+ // Write project config with a named hook
+ repo.write_project_config(
+ r#"[post-remove]
+cleanup = "echo cleanup"
+"#,
+ );
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ // Use a name filter that doesn't match any configured hook
+ cmd.args(["hook", "post-remove", "nonexistent", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt hook post-remove should fail when name filter doesn't match"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No hook named") || stderr.contains("nonexistent"),
+ "Error should mention the unmatched filter, got: {stderr}"
+ );
+}
+
// ============================================================================
// User Pre-Commit Hook Tests
// ============================================================================
@@ -908,6 +1175,52 @@ fn test_standalone_hook_pre_remove(repo: TestRepo) {
assert!(content.contains("STANDALONE_PRE_REMOVE"));
}
+#[rstest]
+fn test_standalone_hook_post_remove(repo: TestRepo) {
+ // Write project config with post-remove hook
+ repo.write_project_config(r#"post-remove = "echo 'STANDALONE_POST_REMOVE' > hook_ran.txt""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-remove", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt hook post-remove should succeed (spawns in background)"
+ );
+
+ // Wait for background hook to complete
+ let marker = repo.root_path().join("hook_ran.txt");
+ crate::common::wait_for_file(&marker);
+ let content = fs::read_to_string(&marker).unwrap();
+ assert!(content.contains("STANDALONE_POST_REMOVE"));
+}
+
+#[rstest]
+fn test_standalone_hook_post_remove_foreground(repo: TestRepo) {
+ // Write project config with post-remove hook
+ repo.write_project_config(r#"post-remove = "echo 'FOREGROUND_POST_REMOVE' > hook_ran.txt""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-remove", "--yes", "--foreground"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt hook post-remove --foreground should succeed"
+ );
+
+ // Hook runs in foreground, so marker should exist immediately
+ let marker = repo.root_path().join("hook_ran.txt");
+ assert!(marker.exists(), "post-remove hook should have run");
+ let content = fs::read_to_string(&marker).unwrap();
+ assert!(content.contains("FOREGROUND_POST_REMOVE"));
+}
+
#[rstest]
fn test_standalone_hook_no_hooks_configured(repo: TestRepo) {
// No project config, no user config with hooks
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_merge.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_merge.snap
new file mode 100644
index 000000000..c4985a8d2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_merge.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/hook_show.rs
+info:
+ program: wt
+ args:
+ - hook
+ - show
+ - post-merge
+ 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]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+USER HOOKS [TEST_CONFIG]
+↳ (none configured)
+
+PROJECT HOOKS _REPO_/.config/wt.toml
+❯ post-merge deploy: (requires approval)
+  scripts/deploy.sh
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_remove.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_remove.snap
new file mode 100644
index 000000000..b074bb2cc
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_post_remove.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/hook_show.rs
+info:
+ program: wt
+ args:
+ - hook
+ - show
+ - post-remove
+ 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]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+USER HOOKS [TEST_CONFIG]
+↳ (none configured)
+
+PROJECT HOOKS _REPO_/.config/wt.toml
+❯ post-remove notify: (requires approval)
+  echo removed
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_pre_remove.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_pre_remove.snap
new file mode 100644
index 000000000..03c05ac20
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_filter_pre_remove.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/hook_show.rs
+info:
+ program: wt
+ args:
+ - hook
+ - show
+ - pre-remove
+ 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]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+USER HOOKS [TEST_CONFIG]
+↳ (none configured)
+
+PROJECT HOOKS _REPO_/.config/wt.toml
+❯ pre-remove cleanup: (requires approval)
+  echo cleanup
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_executes.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_executes.snap
new file mode 100644
index 000000000..0886f2bfb
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_executes.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature
+ - "--force-delete"
+ 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]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature worktree & branch in background (--force-delete)
+◎ Running post-remove hooks: user:cleanup
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_no_verify.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_no_verify.snap
new file mode 100644
index 000000000..651555012
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_no_verify.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature
+ - "--force-delete"
+ - "--no-verify"
+ 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]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature worktree & branch in background (--force-delete)