Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(hooks/alias): lift hook metadata to PipelineKind, unify source enum (#2521)
Maximilian Roos2d093ffc8380
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex bdaa8eca0..3f222aff1 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -606,8 +606,6 @@ fn run_alias(sourced_steps.push(SourcedStep {step: prepared,source,- hook_type: None,- display_path: None,// Aliases have no deprecated single-table form, so concurrent// commands always run concurrently.is_pipeline: true,@@ -641,24 +639,6 @@ fn alias_prepared_command(}}-/// Where an alias came from. When the same name is defined in both configs,-/// the listing shows both entries in runtime order (user first, then project)-/// rather than merging them, so users see the real commands from each source.-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]-pub(crate) enum AliasSource {- User,- Project,-}--impl AliasSource {- pub(crate) fn label(self) -> &'static str {- match self {- AliasSource::User => "user",- AliasSource::Project => "project",- }- }-}-/// Which help page is being augmented. Controls the "shadowed by built-in"/// annotation: at the top level, only top-level built-ins shadow an alias/// (`wt list` blocks an alias named `list`). Under `wt step`, only step@@ -729,7 +709,7 @@ pub(crate) fn augment_help(help: &str, context: HelpContext) -> String {/// `context` controls the "shadowed by built-in" annotation — see/// [`HelpContext`].fn render_aliases_section(- entries: &[(String, CommandConfig, AliasSource)],+ entries: &[(String, CommandConfig, HookSource)],context: HelpContext,) -> String {use std::fmt::Write as _;@@ -763,8 +743,8 @@ fn render_aliases_section(cformat!(" <yellow>(shadowed by built-in)</>")} else if counts.get(name.as_str()).copied().unwrap_or(0) > 1 {match source {- AliasSource::User => cformat!(" <dim>(user)</>"),- AliasSource::Project => cformat!(" <dim>(project)</>"),+ HookSource::User => cformat!(" <dim>(user)</>"),+ HookSource::Project => cformat!(" <dim>(project)</>"),}} else {String::new()@@ -796,7 +776,7 @@ fn render_aliases_section(/// an execution surface, so we'd rather show the built-in commands than/// error out when a repo isn't detected or a config file is malformed./// `step_alias` surfaces those errors at execution time.-fn load_aliases_for_listing() -> Vec<(String, CommandConfig, AliasSource)> {+fn load_aliases_for_listing() -> Vec<(String, CommandConfig, HookSource)> {let repo = Repository::current().ok();let project_id = repo.as_ref().and_then(|r| r.project_identifier().ok());@@ -810,17 +790,17 @@ fn load_aliases_for_listing() -> Vec<(String, CommandConfig, AliasSource)> {.and_then(load_project_aliases_silent).unwrap_or_default();- let mut entries: Vec<(String, CommandConfig, AliasSource)> = user_aliases+ let mut entries: Vec<(String, CommandConfig, HookSource)> = user_aliases.into_iter()- .map(|(n, c)| (n, c, AliasSource::User))+ .map(|(n, c)| (n, c, HookSource::User)).chain(project_aliases.into_iter()- .map(|(n, c)| (n, c, AliasSource::Project)),+ .map(|(n, c)| (n, c, HookSource::Project)),).collect();- // Sort by name; for ties, user before project (derived Ord on AliasSource)+ // Sort by name; for ties, user before project (derived Ord on HookSource)// so duplicates display in runtime execution order.entries.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));entries@@ -1599,22 +1579,22 @@ test = "cargo test"("only-user".to_string(),cfg_from_toml(r#"cmd = "echo u""#),- AliasSource::User,+ HookSource::User,),("only-project".to_string(),cfg_from_toml(r#"cmd = "echo p""#),- AliasSource::Project,+ HookSource::Project,),("shared".to_string(),cfg_from_toml(r#"cmd = "echo from-user""#),- AliasSource::User,+ HookSource::User,),("shared".to_string(),cfg_from_toml(r#"cmd = "echo from-project""#),- AliasSource::Project,+ HookSource::Project,),];// Caller passes pre-sorted entries; mirror that here.@@ -1641,17 +1621,17 @@ test = "cargo test"("list".to_string(),cfg_from_toml(r#"cmd = "ls""#),- AliasSource::User,+ HookSource::User,),("commit".to_string(),cfg_from_toml(r#"cmd = "git commit""#),- AliasSource::User,+ HookSource::User,),("deploy".to_string(),cfg_from_toml(r#"cmd = "make deploy""#),- AliasSource::User,+ HookSource::User,),];let mut sorted = entries;diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 56c9bda8e..a1830f980 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -83,10 +83,18 @@ pub type ErrorWrapper = Box<dyn Fn(&PreparedCommand, String, Option<i32>) -> any/// Supplied at conversion time (`sourced_steps_to_foreground`) so a single/// `SourcedStep` shape can be produced by both alias and hook resolution./// Drives the per-step trust model (EXEC passthrough), announce policy,-/// stdin handling, and error wrapping.+/// stdin handling, and error wrapping. Hook-only metadata+/// (`hook_type`, `display_path`) lives on the `Hook` variant — it's+/// per-pipeline, not per-step, so the per-step shape stays neutral.+#[derive(Clone)]pub enum PipelineKind {- Hook,- Alias { name: String },+ Hook {+ hook_type: HookType,+ display_path: Option<PathBuf>,+ },+ Alias {+ name: String,+ },}/// A pipeline step ready for foreground execution, with rendering / error policy.diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 8d815ca39..c8b7cb058 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -29,12 +29,13 @@ use worktrunk::config::{use worktrunk::git::{Repository, WorktrunkError};use worktrunk::styling::{format_bash_with_gutter, info_message, println};-use crate::commands::alias::{AliasOptions, AliasSource, TOP_LEVEL_BUILTINS, load_aliases};+use crate::commands::alias::{AliasOptions, TOP_LEVEL_BUILTINS, load_aliases};use crate::commands::build_invalid_subcommand_error;use crate::commands::command_executor::{CommandContext, build_hook_context, expand_shell_template,};use crate::commands::did_you_mean;+use crate::commands::hooks::HookSource;/// Show the configured template(s) for an alias, tagged by source.///@@ -218,16 +219,16 @@ fn entries_for_name(user_config: &UserConfig,project_config: Option<&ProjectConfig>,name: &str,-) -> Vec<(CommandConfig, AliasSource)> {+) -> Vec<(CommandConfig, HookSource)> {let project_id = repo.project_identifier().ok();let mut entries = Vec::new();if let Some(cfg) = user_config.aliases(project_id.as_deref()).get(name) {- entries.push((cfg.clone(), AliasSource::User));+ entries.push((cfg.clone(), HookSource::User));}if let Some(pc) = project_config&& let Some(cfg) = pc.aliases.get(name){- entries.push((cfg.clone(), AliasSource::Project));+ entries.push((cfg.clone(), HookSource::Project));}entries}@@ -300,7 +301,7 @@ fn unknown_alias_error(fn format_entry(name: &str,cfg: &CommandConfig,- source: AliasSource,+ source: HookSource,bodies: &[String],verb: Option<&str>,) -> String {@@ -312,12 +313,11 @@ fn format_entry(fn format_entry_with_routing(name: &str,cfg: &CommandConfig,- source: AliasSource,+ source: HookSource,bodies: &[String],verb: Option<&str>,routing: Option<&str>,) -> String {- let label = source.label();let suffix = match verb {Some(v) => format!(" {v}:"),None => ":".to_string(),@@ -336,7 +336,7 @@ fn format_entry_with_routing(body.push_str(rendered);}info_message(cformat!(- "Alias <bold>{name}</> ({label}){suffix}\n{}",+ "Alias <bold>{name}</> ({source}){suffix}\n{}",format_bash_with_gutter(&body))).to_string()@@ -359,7 +359,7 @@ mod tests {fn test_format_entry_show_single() {let cfg = cfg_from_toml(r#"cmd = "echo {{ branch }}""#);let bodies: Vec<String> = cfg.commands().map(|c| c.template.clone()).collect();- let out = format_entry("greet", &cfg, AliasSource::User, &bodies, None);+ let out = format_entry("greet", &cfg, HookSource::User, &bodies, None);insta::assert_snapshot!(out.ansi_strip());}@@ -374,7 +374,7 @@ cmd = ["#,);let bodies: Vec<String> = cfg.commands().map(|c| c.template.clone()).collect();- let out = format_entry("deploy", &cfg, AliasSource::Project, &bodies, None);+ let out = format_entry("deploy", &cfg, HookSource::Project, &bodies, None);insta::assert_snapshot!(out.ansi_strip());}@@ -393,7 +393,7 @@ cmd = [let out = format_entry("deploy",&cfg,- AliasSource::Project,+ HookSource::Project,&bodies,Some("would run"),);diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 359b3d177..d3faa222f 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -98,7 +98,7 @@ fn run_post_hook(if flat.is_empty() {return Ok(());}- announcer.extend(std::iter::once((*ctx, flat)));+ announcer.extend(std::iter::once((*ctx, hook_type, None, flat)));}announcer.flush()}diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rsindex da32be5a0..ae4399744 100644--- a/src/commands/hook_filter.rs+++ b/src/commands/hook_filter.rs@@ -4,16 +4,19 @@//! and `command_approval.rs` (approval flow). Re-exported from `hooks.rs`//! for backward compatibility.-/// Distinguishes between user hooks and project hooks for command preparation.+/// Whether a hook or alias body came from user config or project config.///-/// Approval for project hooks is handled at the gate (command entry point),-/// not during hook execution.+/// Drives the per-step trust model: user-source bodies skip approval and+/// pass EXEC through (the config is the user's own); project-source bodies+/// require approval at the gate (command entry point) and scrub EXEC.#[derive(Clone,Copy,Debug,PartialEq,Eq,+ PartialOrd,+ Ord,serde::Serialize,serde::Deserialize,strum::Display,@@ -22,9 +25,11 @@#[serde(rename_all = "kebab-case")]#[strum(serialize_all = "kebab-case")]pub enum HookSource {- /// User hooks from ~/.config/worktrunk/config.toml (no approval required)+ /// User config (~/.config/worktrunk/config.toml). No approval required;+ /// EXEC directives pass through (alias steps).User,- /// Project hooks from .config/wt.toml (approval handled at gate)+ /// Project config (.config/wt.toml). Approval is handled at the gate;+ /// EXEC directives are scrubbed.Project,}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 94cd7bd34..e9ad81798 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -118,7 +118,7 @@ fn prepare_sourced_steps(hook_type,extra_vars,name_filters,- display_path,+ display_path: _,} = spec;let parsed_filters: Vec<ParsedFilter<'_>> = name_filters@@ -126,7 +126,6 @@ fn prepare_sourced_steps(.map(|f| ParsedFilter::parse(f)).collect();- let display_path = display_path.map(|p| p.to_path_buf());let mut result = Vec::new();let sources = [@@ -148,8 +147,6 @@ fn prepare_sourced_steps(result.push(SourcedStep {step: filtered,source,- hook_type: Some(hook_type),- display_path: display_path.clone(),is_pipeline,});}@@ -210,21 +207,33 @@ fn count_sourced_commands(steps: &[SourcedStep]) -> usize {/// A pipeline step with source information, for pipeline-aware execution.////// Used by both hook and alias dispatch as the source-tagged shape that feeds-/// `sourced_steps_to_foreground`. `hook_type` and `display_path` are-/// hook-only metadata; aliases leave them `None`. Pipeline kind (Hook vs-/// Alias) is supplied at conversion time, so this struct stays neutral.+/// `sourced_steps_to_foreground`. Per-pipeline metadata (`hook_type`,+/// `display_path` for hooks; `name` for aliases) lives on `PipelineKind`,+/// supplied at conversion time so this struct stays neutral. The two fields+/// here are genuinely per-step: alias flows mix steps from both sources into+/// one flat vec, and a config using `[[hook.x]]` on one side with `[hook.x]`+/// on the other can produce mixed `is_pipeline` values within a single hook+/// run.pub struct SourcedStep {pub step: PreparedStep,pub source: HookSource,- /// Hook type for hook pipelines; `None` for aliases.- pub hook_type: Option<HookType>,- pub display_path: Option<PathBuf>,/// Whether `Concurrent` steps run concurrently. For hooks: derived from/// `is_pipeline()` (deprecated single-table form runs serially). For/// aliases: always true — no deprecated form.pub is_pipeline: bool,}+/// One background hook pipeline, carrying its source group of steps with the+/// announce-time metadata (`hook_type`, `display_path`) already resolved.+/// Background flow only ever sees hooks, so the metadata is unwrapped here+/// rather than threaded through `PipelineKind`.+pub(crate) type BackgroundPipeline<'c> = (+ CommandContext<'c>,+ HookType,+ Option<PathBuf>,+ Vec<SourcedStep>,+);+/// Extract the per-step command name lists from a `CommandConfig`.////// Shared by the formatters that describe alias / hook pipelines — `Single`@@ -368,10 +377,14 @@ pub struct HookAnnouncer<'a> {/// Owned spawn data for a registered pipeline. Stores enough to rebuild a/// `CommandContext` at flush time so the announcer can outlive any short-lived-/// contexts at the registration site.+/// contexts at the registration site. Background flow only ever sees hook+/// pipelines, so `hook_type` and `display_path` live on this struct directly+/// rather than wrapped in a `PipelineKind` variant.struct PendingPipeline {worktree_path: PathBuf,branch: Option<String>,+ hook_type: HookType,+ display_path: Option<PathBuf>,steps: Vec<SourcedStep>,}@@ -392,14 +405,19 @@ impl<'a> HookAnnouncer<'a> {////// Pipelines come from `prepare_background_pipelines` / its callers, which/// already filter out empty source groups — empty `steps` is unreachable.+ /// Each pipeline's hook type and display path are passed alongside the+ /// steps; background flow doesn't need `PipelineKind` since it only ever+ /// handles hooks (aliases run in the foreground).pub fn extend<'b, I>(&mut self, pipelines: I)where- I: IntoIterator<Item = (CommandContext<'b>, Vec<SourcedStep>)>,+ I: IntoIterator<Item = BackgroundPipeline<'b>>,{- for (ctx, steps) in pipelines {+ for (ctx, hook_type, display_path, steps) in pipelines {self.pending.push(PendingPipeline {worktree_path: ctx.worktree_path.to_path_buf(),branch: ctx.branch.map(String::from),+ hook_type,+ display_path,steps,});}@@ -442,6 +460,8 @@ impl<'a> HookAnnouncer<'a> {&p.worktree_path,false,),+ p.hook_type,+ p.display_path.clone(),std::mem::take(&mut p.steps),)})@@ -487,33 +507,32 @@ impl Drop for HookAnnouncer<'_> {/// disambiguation in batch contexts (e.g., prune removing multiple worktrees):/// `Running post-remove for feature: user: docs`.fn run_hooks_background(- pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,+ pipelines: Vec<BackgroundPipeline<'_>>,show_branch: bool,) -> anyhow::Result<()> {let pipelines: Vec<_> = pipelines.into_iter()- .filter(|(_, steps)| !steps.is_empty())+ .filter(|(_, _, _, steps)| !steps.is_empty()).collect();if pipelines.is_empty() {return Ok(());}- let display_path = pipelines- .iter()- .flat_map(|(_, g)| g.iter())- .find_map(|s| s.display_path.as_ref());// Merge per-source summaries by hook type so user+project for the same// type render as one clause: `post-merge: sync, push (user); build (project)`.+ // Pull `display_path` off the first pipeline that has one — every hook+ // pipeline in this batch shares a path; the path slot is bundle-wide.+ let mut display_path: Option<&Path> = None;let mut type_summaries: Vec<(HookType, Vec<String>)> = Vec::new();- for (_, group) in &pipelines {- let hook_type = group[0]- .hook_type- .expect("background hook pipelines always set hook_type");+ for (_, hook_type, dp, group) in &pipelines {+ if display_path.is_none() {+ display_path = dp.as_deref();+ }let summary = format_pipeline_summary(group);- if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| *ht == hook_type) {+ if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| ht == hook_type) {entry.1.push(summary);} else {- type_summaries.push((hook_type, vec![summary]));+ type_summaries.push((*hook_type, vec![summary]));}}@@ -523,7 +542,7 @@ fn run_hooks_background(let branch_suffix = if show_branch {pipelines.first()- .and_then(|(ctx, _)| ctx.branch)+ .and_then(|(ctx, _, _, _)| ctx.branch).map(|b| cformat!(" for <bold>{b}</>"))} else {None@@ -549,8 +568,8 @@ fn run_hooks_background(};eprintln!("{}", progress_message(message));- for (ctx, group) in pipelines {- spawn_hook_pipeline_quiet(&ctx, group)?;+ for (ctx, hook_type, _, group) in pipelines {+ spawn_hook_pipeline_quiet(&ctx, hook_type, group)?;}Ok(())@@ -575,14 +594,14 @@ pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>/// Prepare a single hook type's background pipelines for one context.////// Looks up user/project configs, prepares + name-checks steps, and groups-/// them by source so each source spawns as an independent pipeline. The-/// returned Vec is ready to extend or pass to [`run_hooks_background`].+/// them by source so each source spawns as an independent pipeline. Each+/// group is returned with its `(hook_type, display_path)` metadata.pub(crate) fn prepare_background_pipelines<'c>(ctx: &CommandContext<'c>,hook_type: HookType,extra_vars: &[(&str, &str)],display_path: Option<&Path>,-) -> anyhow::Result<Vec<(CommandContext<'c>, Vec<SourcedStep>)>> {+) -> anyhow::Result<Vec<BackgroundPipeline<'c>>> {let project_config = ctx.repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());let (user_config, proj_config) =@@ -598,53 +617,52 @@ pub(crate) fn prepare_background_pipelines<'c>(display_path,},)?;+ let display_path_owned = display_path.map(|p| p.to_path_buf());Ok(into_source_groups(flat).into_iter()- .map(|g| (*ctx, g))+ .map(|g| (*ctx, hook_type, display_path_owned.clone(), g)).collect())}/// Emit a `template variables:` block for one hook type, using the first-/// matching step's context.+/// matching pipeline's first step context.////// Background hooks don't flow through `announce_command` (which prints the/// table in the foreground path), so this is the symmetric entry point./// Called once per hook type from `run_hooks_background`, immediately before/// that hook type's `Running ...` line, so each hook type reads as one block.-fn print_background_variable_table(- pipelines: &[(CommandContext<'_>, Vec<SourcedStep>)],- hook_type: HookType,-) {- for (_, group) in pipelines {- for sourced in group {- if sourced.hook_type != Some(hook_type) {- continue;- }- let cmd = match &sourced.step {- PreparedStep::Single(cmd) => cmd,- PreparedStep::Concurrent(cmds) => &cmds[0],- };- let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)- .expect("context_json is always serialized from a HashMap<String, String>");- eprintln!("{}", info_message("template variables:"));- eprintln!(- "{}",- format_with_gutter(&format_hook_variables(hook_type, &ctx), None)- );- return;+fn print_background_variable_table(pipelines: &[BackgroundPipeline<'_>], hook_type: HookType) {+ for (_, ht, _, group) in pipelines {+ if *ht != hook_type {+ continue;}+ // `into_source_groups` produces non-empty groups, and+ // `run_hooks_background` filters empties — `group[0]` is safe.+ let cmd = match &group[0].step {+ PreparedStep::Single(cmd) => cmd,+ PreparedStep::Concurrent(cmds) => &cmds[0],+ };+ let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)+ .expect("context_json is always serialized from a HashMap<String, String>");+ eprintln!("{}", info_message("template variables:"));+ eprintln!(+ "{}",+ format_with_gutter(&format_hook_variables(hook_type, &ctx), None)+ );+ return;}}/// Spawn a hook pipeline without displaying a summary line.////// Used by `run_hooks_background` after the combined announcement is printed.-fn spawn_hook_pipeline_quiet(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {+fn spawn_hook_pipeline_quiet(+ ctx: &CommandContext,+ hook_type: HookType,+ steps: Vec<SourcedStep>,+) -> anyhow::Result<()> {use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};- let hook_type = steps[0]- .hook_type- .expect("background hook pipelines always set hook_type");let source = steps[0].source;// Extract base context from the first command. Both call sites@@ -824,20 +842,18 @@ pub(crate) fn sourced_steps_to_foreground(_ => DirectivePassthrough::inherit_from_env(),};let (announce, pipe_stdin, redirect_stdout_to_stderr, error_wrapper) = match kind {- PipelineKind::Hook => {- let hook_type = sourced- .hook_type- .expect("hook pipelines always set hook_type");- (- AnnouncePolicy::Hook {- hook_type,- display_path: sourced.display_path,- },- true,- true,- hook_error_wrapper(hook_type),- )- }+ PipelineKind::Hook {+ hook_type,+ display_path,+ } => (+ AnnouncePolicy::Hook {+ hook_type: *hook_type,+ display_path: display_path.clone(),+ },+ true,+ true,+ hook_error_wrapper(*hook_type),+ ),PipelineKind::Alias { name } => (AnnouncePolicy::None,false,@@ -874,13 +890,17 @@ pub(crate) fn run_hooks_foreground(spec: HookCommandSpec<'_, '_, '_, '_>,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {+ let kind = PipelineKind::Hook {+ hook_type: spec.hook_type,+ display_path: spec.display_path.map(|p| p.to_path_buf()),+ };let sourced_steps = prepare_and_check(ctx, spec)?;if sourced_steps.is_empty() {return Ok(());}- let foreground_steps = sourced_steps_to_foreground(sourced_steps, &PipelineKind::Hook);+ let foreground_steps = sourced_steps_to_foreground(sourced_steps, &kind);execute_pipeline_foreground(&foreground_steps,@@ -1000,8 +1020,6 @@ mod tests {SourcedStep {step,source: HookSource::User,- hook_type: Some(worktrunk::HookType::PostStart),- display_path: None,is_pipeline: false,}}diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex f4bd6cd9e..65a5d7d5c 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1110,6 +1110,38 @@ notify = "echo switched");}+/// Verbose variant of [`test_combined_post_remove_and_post_switch_hooks`].+///+/// Under `-v`, the announcer prints a `template variables:` table for each+/// registered hook type, iterating over pipelines and skipping those whose+/// hook type doesn't match — that filter branch needs at least two hook+/// types in one batch to fire. Removing the current worktree's branch is+/// the only path that registers both `post-remove` and `post-switch`.+#[rstest]+fn test_combined_post_remove_and_post_switch_hooks_verbose(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");+ repo.write_test_config(+ r#"[post-remove]+cleanup = "echo removed"++[post-switch]+notify = "echo switched"+"#,+ );++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd_with_global_flags(+ &repo,+ "remove",+ &["feature", "--force-delete"],+ Some(&feature_wt),+ &["-v"],+ );+ assert_cmd_snapshot!("combined_post_remove_and_post_switch_verbose", cmd);+ });+}+// Note: The `return Ok(())` path in spawn_hooks_after_remove when UserConfig::load()// fails is defensive code for an extremely rare race condition where config becomes// invalid between command startup and hook execution. This is not easily testablediff --git a/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap b/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snapnew file mode 100644index 000000000..91a8f069c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__combined_post_remove_and_post_switch_verbose.snap@@ -0,0 +1,106 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - "-v"+ - 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]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m Expanding [1mworktree-path[22m+[107m [0m [2m[0m[2m[32m{{[0m[2m[0m[2m repo_path [0m[2m[32m}}[0m[2m/../[0m[2m[32m{{[0m[2m repo [0m[2m[32m}}[0m[2m.[0m[2m[32m{{[0m[2m branch [0m[2m[36m|[0m[2m [0m[2m[34msanitize[0m[2m [0m[2m[32m}}[0m[2m+[107m [0m [2m→[22m+[107m [0m [2m[0m[2m[34m_REPO_/../repo.feature[0m[2m+[36m◎[39m [36mRemoving [1mfeature[22m worktree & branch in background (--force-delete)[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[2m○[22m Expanding [1muser:cleanup[22m+[107m [0m [2m[0m[2m[34mecho[0m[2m removed+[107m [0m [2m→[22m+[107m [0m [2m[0m[2m[34mecho[0m[2m removed+[2m○[22m Expanding [1muser:notify[22m+[107m [0m [2m[0m[2m[34mecho[0m[2m switched+[107m [0m [2m→[22m+[107m [0m [2m[0m[2m[34mecho[0m[2m switched+[2m○[22m template variables:+[107m [0m branch = feature+[107m [0m worktree_path = _REPO_.feature+[107m [0m worktree_name = repo.feature+[107m [0m commit = 05a4a45d0b981dad5c27db59dca482836d59f89e+[107m [0m short_commit = 05a4a45+[107m [0m upstream = (unset)+[107m [0m target = main+[107m [0m target_worktree_path = _REPO_+[107m [0m repo = repo+[107m [0m repo_path = _REPO_+[107m [0m owner = (unset)+[107m [0m primary_worktree_path = _REPO_+[107m [0m default_branch = main+[107m [0m remote = origin+[107m [0m remote_url = ../origin.git+[107m [0m cwd = _REPO_+[107m [0m hook_type = post-remove+[107m [0m hook_name = cleanup+[2m○[22m template variables:+[107m [0m branch = main+[107m [0m worktree_path = _REPO_+[107m [0m worktree_name = repo+[107m [0m commit = 05a4a45d0b981dad5c27db59dca482836d59f89e+[107m [0m short_commit = 05a4a45+[107m [0m upstream = origin/main+[107m [0m base = (unset)+[107m [0m base_worktree_path = (unset)+[107m [0m target = (unset)+[107m [0m target_worktree_path = (unset)+[107m [0m pr_number = (unset)+[107m [0m pr_url = (unset)+[107m [0m repo = repo+[107m [0m repo_path = _REPO_+[107m [0m owner = (unset)+[107m [0m primary_worktree_path = _REPO_+[107m [0m default_branch = main+[107m [0m remote = origin+[107m [0m remote_url = ../origin.git+[107m [0m cwd = _REPO_+[107m [0m hook_type = post-switch+[107m [0m hook_name = notify+[36m◎[39m [36mRunning post-remove: [1mcleanup[22m (user); post-switch: [1mnotify[22m (user) @ [1m_REPO_[22m[39m