Skip to content

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

feat: add `pre-switch` hook (#1094)

Maximilian Roosd9e1d53bf158
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 1c57b3121..ad00945e4 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -16,6 +16,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| Hook | When | Blocking | Fail-fast |
|------|------|----------|-----------|
+| `pre-switch` | Before every switch | Yes | Yes |
| `post-start` | After worktree created | No (background) | No |
| `post-create` | After worktree created | Yes | No |
| `post-switch` | After every switch | No (background) | No |
@@ -30,6 +31,23 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
Background hooks show a single-line summary by default. Use `-v` to see expanded command details.
+The most common starting point is `post-start` — it runs background tasks (dev servers, file copying, builds) when creating a worktree.
+
+### pre-switch
+
+Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (where you're switching from), not the destination. Failure aborts the switch.
+
+```toml
+[pre-switch]
+# Fetch if last fetch was more than 6 hours ago
+fetch = """
+FETCH_HEAD="$(git rev-parse --git-common-dir)/FETCH_HEAD"
+if [ "$(find "$FETCH_HEAD" -mmin +360 2>/dev/null)" ] || [ ! -f "$FETCH_HEAD" ]; then
+ git fetch
+fi
+"""
+```
+
### post-start
Dev servers, long builds, file watchers, copying caches. Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log`.
@@ -423,6 +441,7 @@ Usage: <b><span class=c>wt hook</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=g>Commands:</span></b>
<b><span class=c>show</span></b> Show configured hooks
+ <b><span class=c>pre-switch</span></b> Run pre-switch hooks
<b><span class=c>post-create</span></b> Run post-create hooks
<b><span class=c>post-start</span></b> Run post-start hooks
<b><span class=c>post-switch</span></b> Run post-switch hooks
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 34d716318..2ff952acf 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -8,6 +8,7 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
| Hook | When | Blocking | Fail-fast |
|------|------|----------|-----------|
+| `pre-switch` | Before every switch | Yes | Yes |
| `post-start` | After worktree created | No (background) | No |
| `post-create` | After worktree created | Yes | No |
| `post-switch` | After every switch | No (background) | No |
@@ -22,6 +23,23 @@ Hooks are shell commands that run at key points in the worktree lifecycle — au
Background hooks show a single-line summary by default. Use `-v` to see expanded command details.
+The most common starting point is `post-start` — it runs background tasks (dev servers, file copying, builds) when creating a worktree.
+
+### pre-switch
+
+Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (where you're switching from), not the destination. Failure aborts the switch.
+
+```toml
+[pre-switch]
+# Fetch if last fetch was more than 6 hours ago
+fetch = """
+FETCH_HEAD="$(git rev-parse --git-common-dir)/FETCH_HEAD"
+if [ "$(find "$FETCH_HEAD" -mmin +360 2>/dev/null)" ] || [ ! -f "$FETCH_HEAD" ]; then
+ git fetch
+fi
+"""
+```
+
### post-start
Dev servers, long builds, file watchers, copying caches. Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log`.
@@ -407,6 +425,7 @@ Usage: <b><span class=c>wt hook</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=g>Commands:</span></b>
<b><span class=c>show</span></b> Show configured hooks
+ <b><span class=c>pre-switch</span></b> Run pre-switch hooks
<b><span class=c>post-create</span></b> Run post-create hooks
<b><span class=c>post-start</span></b> Run post-start hooks
<b><span class=c>post-switch</span></b> Run post-switch hooks
diff --git a/src/cli/hook.rs b/src/cli/hook.rs
index dd24b823e..864ce7faa 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", "post-remove"])]
+ #[arg(value_parser = ["pre-switch", "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
@@ -18,6 +18,26 @@ pub enum HookCommand {
expanded: bool,
},
+ /// Run pre-switch hooks
+ ///
+ /// Blocking — waits for completion before continuing.
+ PreSwitch {
+ /// 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,
+
+ /// 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)>,
+ },
+
/// Run post-create hooks
///
/// Blocking — waits for completion before continuing.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 7a0bc59ea..04a0801bb 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1043,6 +1043,7 @@ wt step push
| Hook | When | Blocking | Fail-fast |
|------|------|----------|-----------|
+| `pre-switch` | Before every switch | Yes | Yes |
| `post-start` | After worktree created | No (background) | No |
| `post-create` | After worktree created | Yes | No |
| `post-switch` | After every switch | No (background) | No |
@@ -1057,6 +1058,23 @@ wt step push
Background hooks show a single-line summary by default. Use `-v` to see expanded command details.
+The most common starting point is `post-start` — it runs background tasks (dev servers, file copying, builds) when creating a worktree.
+
+### pre-switch
+
+Runs before every `wt switch` — before branch validation or worktree creation. Useful for ensuring the repository is up to date before switching. Template variables reflect the current worktree (where you're switching from), not the destination. Failure aborts the switch.
+
+```toml
+[pre-switch]
+# Fetch if last fetch was more than 6 hours ago
+fetch = """
+FETCH_HEAD="$(git rev-parse --git-common-dir)/FETCH_HEAD"
+if [ "$(find "$FETCH_HEAD" -mmin +360 2>/dev/null)" ] || [ ! -f "$FETCH_HEAD" ]; then
+ git fetch
+fi
+"""
+```
+
### post-start
Dev servers, long builds, file watchers, copying caches. Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log`.
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 427e86431..080ab0e64 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -11,6 +11,7 @@ use worktrunk::styling::{eprintln, info_message};
use super::command_approval::approve_hooks;
use super::command_executor::{CommandContext, build_hook_context};
+use super::hooks::{HookFailureStrategy, execute_hook};
use super::worktree::{
SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, get_path_mismatch, plan_switch,
};
@@ -33,6 +34,35 @@ pub struct SwitchOptions<'a> {
pub verify: bool,
}
+/// Run pre-switch hooks before branch validation or worktree creation.
+///
+/// Uses current worktree context since the destination is unknown at this point.
+pub(crate) fn run_pre_switch_hooks(
+ repo: &Repository,
+ config: &UserConfig,
+ yes: bool,
+) -> anyhow::Result<()> {
+ let current_branch = repo
+ .current_worktree()
+ .branch()
+ .context("Failed to determine current branch")?;
+ let current_path = repo.current_worktree().path().to_path_buf();
+ let pre_ctx = CommandContext::new(repo, config, current_branch.as_deref(), &current_path, yes);
+
+ let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;
+ if pre_switch_approved {
+ execute_hook(
+ &pre_ctx,
+ HookType::PreSwitch,
+ &[],
+ HookFailureStrategy::FailFast,
+ None,
+ crate::output::pre_hook_display_path(pre_ctx.worktree_path),
+ )?;
+ }
+ Ok(())
+}
+
/// Approve switch hooks upfront and show "Commands declined" if needed.
///
/// Returns `true` if hooks are approved to run.
@@ -147,6 +177,11 @@ pub fn handle_switch(
let repo = Repository::current().context("Failed to switch worktree")?;
+ // Run pre-switch hooks before anything else (before branch validation, planning, etc.)
+ if verify {
+ run_pre_switch_hooks(&repo, config, yes)?;
+ }
+
// Build switch suggestion context for enriching error hints with --execute/trailing args.
// Without this, errors like "branch already exists" would suggest `wt switch <branch>`
// instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 3239bf14e..09f370626 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -97,6 +97,24 @@ pub fn run_hook(
// Execute the hook based on type
match hook_type {
+ HookType::PreSwitch => {
+ let user_config = user_hooks.pre_switch.as_ref();
+ let project_config = project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_switch.as_ref());
+ require_hooks(user_config, project_config, hook_type)?;
+ // Manual wt hook: user stays at cwd (no cd happens)
+ run_hook_with_filter(
+ &ctx,
+ user_config,
+ project_config,
+ hook_type,
+ &custom_vars_refs,
+ HookFailureStrategy::FailFast,
+ name_filter,
+ crate::output::pre_hook_display_path(ctx.worktree_path),
+ )
+ }
HookType::PostCreate => {
let user_config = user_hooks.post_create.as_ref();
let project_config = project_config
@@ -453,6 +471,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
// Parse hook type filter if provided
let filter: Option<HookType> = hook_type_filter.map(|s| match s {
+ "pre-switch" => HookType::PreSwitch,
"post-create" => HookType::PostCreate,
"post-start" => HookType::PostStart,
"post-switch" => HookType::PostSwitch,
@@ -526,6 +545,7 @@ fn render_user_hooks(
// Note: uses overrides.hooks for display, not the merged hooks() accessor
let user_hooks = &config.configs.hooks;
let hooks = [
+ (HookType::PreSwitch, &user_hooks.pre_switch),
(HookType::PostCreate, &user_hooks.post_create),
(HookType::PostStart, &user_hooks.post_start),
(HookType::PostSwitch, &user_hooks.post_switch),
@@ -587,6 +607,7 @@ fn render_project_hooks(
// Collect all project hooks
let hooks = [
+ (HookType::PreSwitch, &config.hooks.pre_switch),
(HookType::PostCreate, &config.hooks.post_create),
(HookType::PostStart, &config.hooks.post_start),
(HookType::PostSwitch, &config.hooks.post_switch),
diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rs
index 9f310ad4e..b370dfc3a 100644
--- a/src/commands/select/mod.rs
+++ b/src/commands/select/mod.rs
@@ -17,7 +17,7 @@ use skim::prelude::*;
use worktrunk::git::Repository;
use super::handle_switch::{
- approve_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,
+ approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,
};
use super::list::collect;
use super::worktree::{
@@ -312,6 +312,9 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
let repo = Repository::current().context("Failed to switch worktree")?;
let config = repo.user_config();
+ // Run pre-switch hooks before anything else (before branch validation, planning, etc.)
+ run_pre_switch_hooks(&repo, config, true)?;
+
// Switch to existing worktree or create new one
let plan = plan_switch(&repo, &identifier, should_create, None, false, config)?;
let skip_hooks = !approve_switch_hooks(&repo, config, &plan, false, true)?;
diff --git a/src/config/hooks.rs b/src/config/hooks.rs
index f9b247539..5f4404c85 100644
--- a/src/config/hooks.rs
+++ b/src/config/hooks.rs
@@ -8,6 +8,14 @@ use super::commands::CommandConfig;
/// Shared hook configuration for user and project configs.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct HooksConfig {
+ /// Commands to execute before switch begins (blocking, fail-fast)
+ #[serde(
+ default,
+ rename = "pre-switch",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub pre_switch: Option<CommandConfig>,
+
/// Commands to execute after worktree creation (blocking)
#[serde(
default,
@@ -72,6 +80,7 @@ pub struct HooksConfig {
impl HooksConfig {
pub fn get(&self, hook: HookType) -> Option<&CommandConfig> {
match hook {
+ HookType::PreSwitch => self.pre_switch.as_ref(),
HookType::PostCreate => self.post_create.as_ref(),
HookType::PostStart => self.post_start.as_ref(),
HookType::PostSwitch => self.post_switch.as_ref(),
@@ -105,6 +114,7 @@ impl Merge for HooksConfig {
/// Both global and per-project hooks run (global first, then per-project).
fn merge_with(&self, other: &Self) -> Self {
Self {
+ pre_switch: merge_append_hooks(&self.pre_switch, &other.pre_switch),
post_create: merge_append_hooks(&self.post_create, &other.post_create),
post_start: merge_append_hooks(&self.post_start, &other.post_start),
post_switch: merge_append_hooks(&self.post_switch, &other.post_switch),
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 3d9c0ea35..03a48d977 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -326,6 +326,7 @@ pub fn branch_tracks_ref(
)]
#[strum(serialize_all = "kebab-case")]
pub enum HookType {
+ PreSwitch,
PostCreate,
PostStart,
PostSwitch,
diff --git a/src/main.rs b/src/main.rs
index 567112bc3..d5a8fe6c0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -555,6 +555,9 @@ fn main() {
hook_type,
expanded,
} => handle_hook_show(hook_type.as_deref(), expanded),
+ HookCommand::PreSwitch { name, yes, vars } => {
+ run_hook(HookType::PreSwitch, yes, None, name.as_deref(), &vars)
+ }
HookCommand::PostCreate { name, yes, vars } => {
run_hook(HookType::PostCreate, yes, None, name.as_deref(), &vars)
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 5132c1818..af4062942 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -615,6 +615,7 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"post-create"), "Missing post-create");
assert!(subcommands.contains(&"post-start"), "Missing post-start");
assert!(subcommands.contains(&"post-switch"), "Missing post-switch");
+ assert!(subcommands.contains(&"pre-switch"), "Missing pre-switch");
assert!(subcommands.contains(&"pre-commit"), "Missing pre-commit");
assert!(subcommands.contains(&"pre-merge"), "Missing pre-merge");
assert!(subcommands.contains(&"post-merge"), "Missing post-merge");
@@ -623,8 +624,8 @@ fn test_complete_hook_subcommands(repo: TestRepo) {
assert!(subcommands.contains(&"approvals"), "Missing approvals");
assert_eq!(
subcommands.len(),
- 10,
- "Should have exactly 10 hook subcommands"
+ 11,
+ "Should have exactly 11 hook subcommands"
);
// Test 2: Partial input "po" - filters to post-* subcommands
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 010d8f49a..6f4c65a70 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1752,3 +1752,103 @@ submodule = "echo '4' >> hook_order.txt"
"Hooks should execute in TOML insertion order (vscode, claude, copy, submodule)"
);
}
+
+// ============================================================================
+// User Pre-Switch Hook Tests
+// ============================================================================
+
+/// Test that a pre-switch hook executes before switching to an existing worktree
+#[rstest]
+fn test_user_pre_switch_hook_executes(mut repo: TestRepo) {
+ // Create a worktree to switch to
+ let _feature_wt = repo.add_worktree("feature");
+
+ // Write user config with pre-switch hook that creates a marker in the current worktree
+ repo.write_test_config(
+ r#"[pre-switch]
+check = "echo 'USER_PRE_SWITCH_RAN' > pre_switch_marker.txt"
+"#,
+ );
+
+ snapshot_switch("user_pre_switch_executes", &repo, &["feature"]);
+
+ // Verify user hook ran in the source worktree (main), not the destination
+ let marker_file = repo.root_path().join("pre_switch_marker.txt");
+ assert!(
+ marker_file.exists(),
+ "User pre-switch hook should have created marker in source worktree"
+ );
+
+ let contents = fs::read_to_string(&marker_file).unwrap();
+ assert!(
+ contents.contains("USER_PRE_SWITCH_RAN"),
+ "Marker file should contain expected content"
+ );
+}
+
+/// Test that a failing pre-switch hook blocks the switch (including --create)
+#[rstest]
+fn test_user_pre_switch_failure_blocks_switch(repo: TestRepo) {
+ // Write user config with failing pre-switch hook
+ repo.write_test_config(
+ r#"[pre-switch]
+block = "exit 1"
+"#,
+ );
+
+ // Failing pre-switch should prevent worktree creation
+ snapshot_switch("user_pre_switch_failure", &repo, &["--create", "feature"]);
+
+ // Worktree should NOT have been created
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ assert!(
+ !worktree_path.exists(),
+ "Worktree should not be created when pre-switch hook fails"
+ );
+}
+
+/// Test that --no-verify skips the pre-switch hook
+#[rstest]
+fn test_user_pre_switch_skipped_with_no_verify(repo: TestRepo) {
+ // Write user config with pre-switch hook that creates a marker
+ repo.write_test_config(
+ r#"[pre-switch]
+check = "echo 'SHOULD_NOT_RUN' > pre_switch_marker.txt"
+"#,
+ );
+
+ snapshot_switch(
+ "user_pre_switch_no_verify",
+ &repo,
+ &["--create", "feature", "--no-verify"],
+ );
+
+ // Pre-switch hook should NOT have run (--no-verify skips all hooks)
+ let marker_file = repo.root_path().join("pre_switch_marker.txt");
+ assert!(
+ !marker_file.exists(),
+ "Pre-switch hook should be skipped with --no-verify"
+ );
+}
+
+/// Test that `wt hook pre-switch` runs pre-switch hooks manually
+#[rstest]
+fn test_user_pre_switch_manual_hook(repo: TestRepo) {
+ repo.write_test_config(
+ r#"[pre-switch]
+check = "echo 'MANUAL_PRE_SWITCH' > pre_switch_marker.txt"
+"#,
+ );
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "hook", &["pre-switch"], None);
+ assert_cmd_snapshot!("user_pre_switch_manual", cmd);
+ });
+
+ let marker_file = repo.root_path().join("pre_switch_marker.txt");
+ assert!(
+ marker_file.exists(),
+ "Manual pre-switch hook should have created marker"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_executes.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_executes.snap
new file mode 100644
index 000000000..f0d439474
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_executes.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ 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]"
+ 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_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Running pre-switch user:check
+  echo 'USER_PRE_SWITCH_RAN' > pre_switch_marker.txt
+▲ Worktree for feature @ _REPO_.feature, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap
new file mode 100644
index 000000000..1701859f1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ 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]"
+ 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_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Running pre-switch user:block
+  exit 1
+✗ pre-switch command failed: block: exit status: 1
+↳ To skip pre-switch hooks, re-run with --no-verify
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_manual.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_manual.snap
new file mode 100644
index 000000000..a0c86dac0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_manual.snap
@@ -0,0 +1,45 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - pre-switch
+ 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]"
+ 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_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Running pre-switch user:check
+  echo 'MANUAL_PRE_SWITCH' > pre_switch_marker.txt
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_no_verify.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_no_verify.snap
new file mode 100644
index 000000000..c142d2613
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_no_verify.snap
@@ -0,0 +1,49 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ - "--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]"
+ 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_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install