Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add pre-remove hook for cleanup before worktree removal (#107)
Maximilian Roos22698cf182e6
diff --git a/docs/content/hooks.md b/docs/content/hooks.mdindex e23311a1a..117fefd9c 100644--- a/docs/content/hooks.md+++ b/docs/content/hooks.md@@ -6,7 +6,7 @@ weight = 21group = "Reference"+++-Hooks automate setup and validation at worktree lifecycle events. They're defined in `.config/wt.toml` (project config) and run automatically during `wt switch --create` and `wt merge`.+Hooks automate setup and validation at worktree lifecycle events. They're defined in `.config/wt.toml` (project config) and run automatically during `wt switch --create`, `wt merge`, and `wt remove`.## Hook types@@ -17,6 +17,7 @@ Hooks automate setup and validation at worktree lifecycle events. They're define| **pre-commit** | Before commit during merge | Yes | Yes | Sequential || **pre-merge** | Before merging to target | Yes | Yes | Sequential || **post-merge** | After successful merge | Yes | No | Sequential |+| **pre-remove** | Before worktree removed | Yes | Yes | Sequential |**Blocking**: Command waits for hook to complete before continuing.**Fail-fast**: First failure aborts the operation.@@ -176,10 +177,30 @@ post-merge = "cargo install --path ."- Runs after cleanup completes- Failures show errors but don't affect the completed merge+### pre-remove++Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit with code 0 for the removal to proceed.++**Use cases**: Cleanup tasks, saving state, notifying external systems — validation before removal.++```toml+[pre-remove]+cleanup = "rm -rf /tmp/cache/{{ branch }}"+notify = "echo 'Removing {{ branch }}' >> ~/worktree-log.txt"+```++**Behavior**:+- Commands run sequentially in the **worktree being removed**+- First failure aborts the removal (worktree preserved)+- Runs for both foreground and background removal modes+- Does **not** run for branch-only removal (no worktree)+- Use `--no-verify` to skip+## When hooks run during merge- **pre-commit** — After staging, before squash commit- **pre-merge** — After rebase, before merge to target+- **pre-remove** — Before removing worktree during cleanup (failures abort)- **post-merge** — After cleanup completesSee [wt merge](@/merge.md#pipeline) for the complete pipeline.@@ -226,6 +247,7 @@ Use `--no-verify` to skip all project hooks:```bashwt switch --create temp --no-verify # Skip post-create and post-startwt merge --no-verify # Skip pre-commit, pre-merge, post-merge+wt remove feature --no-verify # Skip pre-remove```## Logging@@ -247,6 +269,7 @@ Use `wt step` to run individual hooks:wt step post-create # Run post-create hookswt step pre-merge # Run pre-merge hookswt step post-merge # Run post-merge hooks+wt step pre-remove # Run pre-remove hooks```## Example configurationsdiff --git a/docs/content/merge.md b/docs/content/merge.mdindex fc680d055..9313dd18f 100644--- a/docs/content/merge.md+++ b/docs/content/merge.md@@ -52,8 +52,9 @@ wt merge --no-commit2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.3. **Pre-merge hooks** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.-5. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.-6. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.+5. **Pre-remove hooks** — Project commands run before removing worktree. Failures abort.+6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.+7. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.Use `--no-commit` to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with `wt step`. Requires a clean working tree.diff --git a/docs/content/remove.md b/docs/content/remove.mdindex 70f7d1766..50f9510b8 100644--- a/docs/content/remove.md+++ b/docs/content/remove.md@@ -86,6 +86,9 @@ Options:--no-backgroundRun removal in foreground+ --no-verify+ Skip pre-remove hooks+-h, --helpPrint help (see a summary with '-h')diff --git a/docs/content/step.md b/docs/content/step.mdindex 2978f7ea8..c1ebc7172 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -75,6 +75,7 @@ Commands:pre-commit Run pre-commit hookpre-merge Run pre-merge hookpost-merge Run post-merge hook+ pre-remove Run pre-remove hookOptions:-h, --helpdiff --git a/src/cli.rs b/src/cli.rsindex 619cf3e19..bd9e81ce4 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -637,6 +637,13 @@ pub enum StepCommand {#[arg(short, long)]force: bool,},++ /// Run pre-remove hook+ PreRemove {+ /// Skip approval prompts+ #[arg(short, long)]+ force: bool,+ },}/// Subcommands for `wt list`@@ -1302,6 +1309,10 @@ Arguments resolve by path first, then branch name. [Shortcuts](@/switch.md#short/// Run removal in foreground#[arg(long = "no-background", action = clap::ArgAction::SetFalse, default_value_t = true)]background: bool,++ /// Skip pre-remove hooks+ #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]+ verify: bool,},/// Merge worktree into target branch@@ -1350,8 +1361,9 @@ wt merge --no-commit2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.3. **Pre-merge hooks** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.-5. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.-6. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.+5. **Pre-remove hooks** — Project commands run before removing worktree. Failures abort.+6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.+7. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.Use `--no-commit` to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with `wt step`. Requires a clean working tree.diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 40457e32c..5e4d9d77f 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -209,7 +209,8 @@ pub fn handle_merge(force_delete: false,target_branch: Some(target_branch.clone()),};- crate::output::handle_remove_output(&remove_result, Some(¤t_branch), true)?;+ // Run hooks during merge removal (verify=true)+ crate::output::handle_remove_output(&remove_result, Some(¤t_branch), true, true)?;} else {// Print comprehensive summary (worktree preserved)// Priority: main worktree > on target > --no-remove flag@@ -315,3 +316,33 @@ pub fn execute_post_merge_commands(HookFailureStrategy::Warn,)}++/// Execute pre-remove commands sequentially in the worktree (blocking)+///+/// Runs before a worktree is removed. Non-zero exit aborts the removal.+///+/// # Arguments+/// * `ctx` - Command context pointing to the worktree being removed+/// * `auto_trust` - When true, skip approval prompts+pub fn execute_pre_remove_commands(ctx: &CommandContext, auto_trust: bool) -> anyhow::Result<()> {+ let project_config = match ctx.repo.load_project_config()? {+ Some(cfg) => cfg,+ None => return Ok(()),+ };++ let Some(pre_remove_config) = &project_config.pre_remove else {+ return Ok(());+ };++ let pipeline = HookPipeline::new(*ctx);++ pipeline.run_sequential(+ pre_remove_config,+ CommandPhase::PreRemove,+ auto_trust,+ &[],+ "pre-remove",+ HookType::PreRemove,+ HookFailureStrategy::FailFast,+ )+}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex e10718cd2..8fdfb263d 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -24,7 +24,7 @@ pub use config::{pub use configure_shell::{ConfigAction, handle_configure_shell, handle_unconfigure_shell};pub use init::handle_init;pub use list::handle_list;-pub use merge::handle_merge;+pub use merge::{execute_pre_remove_commands, handle_merge};#[cfg(unix)]pub use select::handle_select;pub use standalone::{diff --git a/src/commands/project_config.rs b/src/commands/project_config.rsindex 97bf2993c..c66730c8d 100644--- a/src/commands/project_config.rs+++ b/src/commands/project_config.rs@@ -14,6 +14,7 @@ pub fn collect_commands_for_hooks(HookType::PreCommit => &project_config.pre_commit,HookType::PreMerge => &project_config.pre_merge,HookType::PostMerge => &project_config.post_merge,+ HookType::PreRemove => &project_config.pre_remove,};if let Some(config) = cfg {commands.extend(config.commands_with_phase(*hook));diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex a0a29f05f..3f619e0b7 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -7,7 +7,9 @@ use worktrunk::styling::format_with_gutter;use super::commit::{CommitGenerator, CommitOptions};use super::context::CommandEnv;use super::hooks::HookPipeline;-use super::merge::{execute_post_merge_commands, run_pre_merge_commands};+use super::merge::{+ execute_post_merge_commands, execute_pre_remove_commands, run_pre_merge_commands,+};use super::project_config::collect_commands_for_hooks;use super::repository_ext::RepositoryCliExt;@@ -54,6 +56,10 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::R// branch being merged into)execute_post_merge_commands(&ctx, &env.branch, false)}+ HookType::PreRemove => {+ check_hook_configured(&project_config.pre_remove, hook_type)?;+ execute_pre_remove_commands(&ctx, false)+ }}}diff --git a/src/config/project.rs b/src/config/project.rsindex c3434664a..084da2943 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -70,6 +70,14 @@ pub struct ProjectConfig {#[serde(default, rename = "post-merge")]pub post_merge: Option<CommandConfig>,+ /// Commands to execute before a worktree is removed (blocking)+ /// Supports string (single command) or table (named, sequential)+ /// Runs in the worktree before removal; non-zero exit aborts removal+ ///+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`+ #[serde(default, rename = "pre-remove")]+ pub pre_remove: Option<CommandConfig>,+/// Captures unknown fields for validation warnings#[serde(flatten, default, skip_serializing)]unknown: std::collections::HashMap<String, toml::Value>,diff --git a/src/git/mod.rs b/src/git/mod.rsindex c8743e61b..34beabc2e 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -78,6 +78,7 @@ pub enum HookType {PreCommit,PreMerge,PostMerge,+ PreRemove,}/// Worktree informationdiff --git a/src/main.rs b/src/main.rsindex c6ee4bb00..97529ab48 100644--- a/src/main.rs+++ b/src/main.rs@@ -818,6 +818,9 @@ fn main() {StepCommand::PostMerge { force } => {handle_standalone_run_hook(HookType::PostMerge, force)}+ StepCommand::PreRemove { force } => {+ handle_standalone_run_hook(HookType::PreRemove, force)+ }},#[cfg(unix)]Commands::Select => handle_select(cli.internal),@@ -929,6 +932,7 @@ fn main() {delete_branch,force_delete,background,+ verify,} => WorktrunkConfig::load().context("Failed to load config").and_then(|config| {@@ -944,7 +948,7 @@ fn main() {// No worktrees specified, remove current worktree// Uses path-based removal to handle detached HEAD statelet result = handle_remove_current(!delete_branch, force_delete, background)?;- handle_remove_output(&result, None, background)+ handle_remove_output(&result, None, background, verify)} else {use worktrunk::git::ResolvedWorktree;@@ -983,12 +987,12 @@ fn main() {force_delete,background,)?;- handle_remove_output(&result, Some(branch_name), background)?;+ handle_remove_output(&result, Some(branch_name), background, verify)?;} else {// Non-current worktree is detached - remove by path (no branch to delete)let result =handle_remove_by_path(path, None, force_delete, background)?;- handle_remove_output(&result, None, background)?;+ handle_remove_output(&result, None, background, verify)?;}}@@ -996,14 +1000,14 @@ fn main() {for branch in &branch_only {let result =handle_remove(branch, !delete_branch, force_delete, background)?;- handle_remove_output(&result, Some(branch), background)?;+ handle_remove_output(&result, Some(branch), background, verify)?;}// Remove current worktree last (if it was in the list)if let Some((_path, branch)) = current {let result =handle_remove_current(!delete_branch, force_delete, background)?;- handle_remove_output(&result, branch.as_deref(), background)?;+ handle_remove_output(&result, branch.as_deref(), background, verify)?;}Ok(())diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 408af9c9e..183bec633 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -3,8 +3,11 @@use color_print::cformat;use std::path::Path;+use crate::commands::command_executor::CommandContext;+use crate::commands::execute_pre_remove_commands;use crate::commands::process::spawn_detached;use crate::commands::worktree::{RemoveResult, SwitchResult};+use worktrunk::config::WorktrunkConfig;use worktrunk::git::GitError;use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;@@ -364,6 +367,7 @@ pub fn handle_remove_output(result: &RemoveResult,branch: Option<&str>,background: bool,+ verify: bool,) -> anyhow::Result<()> {match result {RemoveResult::RemovedWorktree {@@ -384,6 +388,7 @@ pub fn handle_remove_output(target_branch.as_deref(),branch,background,+ verify,),RemoveResult::BranchOnly {branch_name,@@ -447,6 +452,7 @@ fn handle_removed_worktree_output(target_branch: Option<&str>,branch: Option<&str>,background: bool,+ verify: bool,) -> anyhow::Result<()> {// 1. Emit cd directive if needed - shell will execute this immediatelyif changed_directory {@@ -482,6 +488,21 @@ fn handle_removed_worktree_output(return Ok(());};+ // Execute pre-remove hooks in the worktree being removed+ // Non-zero exit aborts removal (FailFast strategy)+ if verify && let Ok(config) = WorktrunkConfig::load() {+ let target_repo = Repository::at(worktree_path);+ let ctx = CommandContext::new(+ &target_repo,+ &config,+ branch_name,+ worktree_path,+ main_path,+ false, // force=false, prompt for approval+ );+ execute_pre_remove_commands(&ctx, false)?;+ }+if background {// Background mode: spawn detached process@@ -589,6 +610,7 @@ fn handle_removed_worktree_output(integration_reason,target_branch,))?;+super::flush()?;Ok(())}diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex e2fd116a8..fba5d8dc0 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -707,10 +707,11 @@ fn test_complete_step_subcommands() {assert!(subcommands.contains(&"pre-commit"), "Missing pre-commit");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_eq!(subcommands.len(),- 9,- "Should have exactly 9 step subcommands"+ 10,+ "Should have exactly 10 step subcommands");// Test 2: Partial input "po" - filters to post-* subcommandsdiff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 53780ae9b..18249f6b9 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -5,6 +5,7 @@ use crate::common::{use insta_cmd::assert_cmd_snapshot;use std::path::PathBuf;use std::process::Command;+use std::time::Duration;use tempfile::TempDir;/// Helper to create snapshot with normalized paths@@ -715,3 +716,272 @@ fn test_remove_squash_merged_then_main_advanced() {None,);}++// ============================================================================+// Pre-Remove Hook Tests+// ============================================================================++/// Test pre-remove hook executes before worktree removal.+#[test]+fn test_pre_remove_hook_executes() {+ // Use simple repo without remote for predictable project ID+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with pre-remove hook+ repo.write_project_config(r#"pre-remove = "echo 'About to remove worktree'""#);+ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = ["echo 'About to remove worktree'"]+"#,+ );++ // Create a worktree to remove+ let _worktree_path = repo.add_worktree("feature-hook");++ // Remove with --no-background to ensure synchronous execution+ snapshot_remove(+ "pre_remove_hook_executes",+ &repo,+ &["--no-background", "feature-hook"],+ None,+ );+}++/// Test pre-remove hook has access to template variables.+#[test]+fn test_pre_remove_hook_template_variables() {+ // Use simple repo without remote for predictable project ID+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with template variables+ repo.write_project_config(+ r#"[pre-remove]+branch = "echo 'Branch: {{ branch }}'"+worktree = "echo 'Worktree: {{ worktree }}'"+worktree_name = "echo 'Name: {{ worktree_name }}'"+"#,+ );+ repo.commit("Add config with templates");++ // Pre-approve the commands (use expanded forms for approval)+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = [+ "echo 'Branch: {{ branch }}'",+ "echo 'Worktree: {{ worktree }}'",+ "echo 'Name: {{ worktree_name }}'",+]+"#,+ );++ // Create a worktree to remove+ let _worktree_path = repo.add_worktree("feature-templates");++ // Remove with --no-background+ snapshot_remove(+ "pre_remove_hook_template_variables",+ &repo,+ &["--no-background", "feature-templates"],+ None,+ );+}++/// Test pre-remove hook runs even in background mode (before spawning background process).+#[test]+fn test_pre_remove_hook_runs_in_background_mode() {+ use crate::common::wait_for_file;++ // Use simple repo without remote for predictable project ID+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a marker file that the hook will create+ let marker_file = repo.root_path().join("hook-ran.txt");++ // Create project config with hook that creates a file+ repo.write_project_config(&format!(+ r#"pre-remove = "echo 'hook ran' > {}""#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));+ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(&format!(+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"++[projects."repo"]+approved-commands = ["echo 'hook ran' > {}"]+"#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));++ // Create a worktree to remove+ let _worktree_path = repo.add_worktree("feature-bg");++ // Remove in background mode (default)+ let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));+ repo.clean_cli_env(&mut cmd);+ cmd.current_dir(repo.root_path())+ .args(["remove", "feature-bg"])+ .output()+ .unwrap();++ // Wait for the hook to create the marker file+ wait_for_file(&marker_file, Duration::from_secs(5));++ // Marker file SHOULD exist - pre-remove hooks run before background removal starts+ assert!(+ marker_file.exists(),+ "Pre-remove hook should run even in background mode"+ );+}++/// Test pre-remove hook failure aborts removal (FailFast strategy).+#[test]+fn test_pre_remove_hook_failure_aborts() {+ // Use simple repo without remote for predictable project ID+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with failing hook+ repo.write_project_config(r#"pre-remove = "exit 1""#);+ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = ["exit 1"]+"#,+ );++ // Create a worktree to remove+ let worktree_path = repo.add_worktree("feature-fail");++ // Remove - should FAIL due to hook failure+ snapshot_remove(+ "pre_remove_hook_failure_aborts",+ &repo,+ &["--no-background", "feature-fail"],+ None,+ );++ // Verify worktree was NOT removed (hook failure aborted removal)+ assert!(+ worktree_path.exists(),+ "Worktree should NOT be removed when hook fails"+ );+}++/// Test pre-remove hook does NOT run for branch-only removal (no worktree).+#[test]+fn test_pre_remove_hook_not_for_branch_only() {+ // Use simple repo without remote for predictable project ID+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a marker file that the hook would create+ let marker_file = repo.root_path().join("branch-only-hook.txt");++ // Create project config with hook+ repo.write_project_config(&format!(+ r#"pre-remove = "echo 'hook ran' > {}""#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));+ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(&format!(+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"++[projects."repo"]+approved-commands = ["echo 'hook ran' > {}"]+"#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));++ // Create a branch without a worktree+ repo.git_command(&["branch", "branch-only"])+ .output()+ .unwrap();++ // Remove the branch (no worktree)+ let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));+ repo.clean_cli_env(&mut cmd);+ cmd.current_dir(repo.root_path())+ .args(["remove", "branch-only"])+ .output()+ .unwrap();++ // Marker file should NOT exist - pre-remove hooks only run for worktree removal+ assert!(+ !marker_file.exists(),+ "Pre-remove hook should NOT run for branch-only removal"+ );+}++/// Test --no-verify flag skips pre-remove hooks.+#[test]+fn test_pre_remove_hook_skipped_with_no_verify() {+ use std::thread;++ // Use simple repo without remote for predictable project ID+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a marker file that the hook would create+ let marker_file = repo.root_path().join("should-not-exist.txt");++ // Create project config with hook that creates a file+ repo.write_project_config(&format!(+ r#"pre-remove = "echo 'hook ran' > {}""#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));+ repo.commit("Add config");++ // Pre-approve the command (even though it shouldn't run)+ repo.write_test_config(&format!(+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"++[projects."repo"]+approved-commands = ["echo 'hook ran' > {}"]+"#,+ marker_file.to_string_lossy().replace('\\', "/")+ ));++ // Create a worktree to remove+ let worktree_path = repo.add_worktree("feature-skip");++ // Remove with --no-verify to skip hooks+ snapshot_remove(+ "pre_remove_hook_skipped_with_no_verify",+ &repo,+ &["--no-background", "--no-verify", "feature-skip"],+ None,+ );++ // Wait a bit for any potential hook execution+ thread::sleep(Duration::from_millis(100));++ // Marker file should NOT exist - --no-verify skips the hook+ assert!(+ !marker_file.exists(),+ "Pre-remove hook should NOT run with --no-verify"+ );++ // Worktree should be removed (removal itself succeeds)+ assert!(+ !worktree_path.exists(),+ "Worktree should be removed even with --no-verify"+ );+}diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snapindex 74a21f3c3..4b1242471 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap@@ -97,8 +97,9 @@ Skip git operations, only run hooks and push:2. [1mRebase[0m — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.3. [1mPre-merge hooks[0m — Project commands run after rebase, before merge. Failures abort. See Hooks.4. [1mMerge[0m — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.-5. [1mCleanup[0m — Removes the worktree and branch. Use [2m--no-remove[0m to keep the worktree.-6. [1mPost-merge hooks[0m — Project commands run after cleanup. Failures are logged but don't abort.+5. [1mPre-remove hooks[0m — Project commands run before removing worktree. Failures abort.+6. [1mCleanup[0m — Removes the worktree and branch. Use [2m--no-remove[0m to keep the worktree.+7. [1mPost-merge hooks[0m — Project commands run after cleanup. Failures are logged but don't abort.Use [2m--no-commit[0m to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with [2mwt step[0m. Requires a clean working tree.diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snapindex 97cb599fd..c5bd9dcdc 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap@@ -34,6 +34,9 @@ Usage: [1m[36mwt remove[0m [36m[OPTIONS][0m [36m[WORKTREES]...[0m[1m[36m--no-background[0mRun removal in foreground+ [1m[36m--no-verify[0m+ Skip pre-remove hooks+[1m[36m-h[0m, [1m[36m--help[0mPrint help (see a summary with '-h')diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap b/tests/snapshots/integration__integration_tests__help__help_remove_short.snapindex 20686b04f..96530694b 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap@@ -27,6 +27,7 @@ Usage: [1m[36mwt remove[0m [36m[OPTIONS][0m [36m[WORKTREES]...[0m[1m[36m--no-delete-branch[0m Keep branch after removal[1m[36m-D[0m, [1m[36m--force-delete[0m Delete unmerged branches[1m[36m--no-background[0m Run removal in foreground+ [1m[36m--no-verify[0m Skip pre-remove hooks[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')[1m[32mGlobal Options:[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snapindex 03dd97663..6e719ee0f 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap@@ -30,6 +30,7 @@ Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m[1m[36mpre-commit[0m Run pre-commit hook[1m[36mpre-merge[0m Run pre-merge hook[1m[36mpost-merge[0m Run post-merge hook+ [1m[36mpre-remove[0m Run pre-remove hook[1m[32mOptions:[0m[1m[36m-h[0m, [1m[36m--help[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snapindex 387b80c86..730b2db10 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap@@ -30,6 +30,7 @@ Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m[1m[36mpre-commit[0m Run pre-commit hook[1m[36mpre-merge[0m Run pre-merge hook[1m[36mpost-merge[0m Run post-merge hook+ [1m[36mpre-remove[0m Run pre-remove hook[1m[32mOptions:[0m[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snapnew file mode 100644index 000000000..1269aa611--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap@@ -0,0 +1,31 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--no-background"+ - feature-hook+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+🔄 [36mRemoving worktree for [1mfeature-hook[22m...[39m+🔄 [36mRunning pre-remove:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'About to remove worktree'[0m[2m[0m+[0mAbout to remove worktree+✅ [32mRemoved [1mfeature-hook[22m worktree & branch (already in main)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snapnew file mode 100644index 000000000..fdebf022b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--no-background"+ - feature-fail+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+🔄 [36mRemoving worktree for [1mfeature-fail[22m...[39m+🔄 [36mRunning pre-remove:[39m+[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m+[0m❌ [31mpre-remove command failed: exit status: 1[39m++💡 [2mUse [90m--no-verify[39m to skip pre-remove commands[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snapnew file mode 100644index 000000000..2d77e1f7c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snap@@ -0,0 +1,29 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--no-background"+ - "--no-verify"+ - feature-skip+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+🔄 [36mRemoving worktree for [1mfeature-skip[22m...[39m+✅ [32mRemoved [1mfeature-skip[22m worktree & branch (already in main)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snapnew file mode 100644index 000000000..e6d78e2fd--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--no-background"+ - feature-templates+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+🔄 [36mRemoving worktree for [1mfeature-templates[22m...[39m+🔄 [36mRunning pre-remove [1mbranch[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Branch: feature-templates'[0m[2m[0m+[0mBranch: feature-templates+🔄 [36mRunning pre-remove [1mworktree[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Worktree: [REPO].feature-templates'[0m[2m[0m+[0mWorktree: [REPO].feature-templates+🔄 [36mRunning pre-remove [1mworktree_name[22m:[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Name: repo.feature-templates'[0m[2m[0m+[0mName: repo.feature-templates+✅ [32mRemoved [1mfeature-templates[22m worktree & branch (already in main)[39m