Skip to content

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

Fix hook filtering, source isolation and template failure handling (#4429)

Maximilian Roose14c30e2376d
diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.md
index f7fba6a97..f5f566d3e 100644
--- a/docs/src/content/docs/hook.md
+++ b/docs/src/content/docs/hook.md
@@ -356,9 +356,9 @@ $ wt hook post-start
## Passing values
-`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
+`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any selected hook command — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
-Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
+Any `--KEY=VALUE` whose key isn't referenced by a selected hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
# Recipes
diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.md
index ce360f86f..a88ad9cf7 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/hook.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md
@@ -350,9 +350,9 @@ $ wt hook post-start
## Passing values
-`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
+`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any selected hook command — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
-Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
+Any `--KEY=VALUE` whose key isn't referenced by a selected hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
# Recipes
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index ce360f86f..a88ad9cf7 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -350,9 +350,9 @@ $ wt hook post-start
## Passing values
-`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
+`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any selected hook command — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
-Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
+Any `--KEY=VALUE` whose key isn't referenced by a selected hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
# Recipes
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 1b7867933..3bea63816 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1988,9 +1988,9 @@ $ wt hook post-start
## Passing values
-`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
+`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any selected hook command — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.
-Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
+Any `--KEY=VALUE` whose key isn't referenced by a selected hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.
# Recipes
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 62911cf40..2712fca02 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -446,7 +446,7 @@ pub(crate) fn load_aliases(
fn referenced_vars_for_entry(name: &str, entry: &AliasEntry) -> anyhow::Result<BTreeSet<String>> {
let mut out = BTreeSet::new();
for (_, cfg) in entry.iter() {
- out.extend(referenced_vars_for_config(cfg, name)?);
+ out.extend(referenced_vars_for_config(cfg, |_| name.to_owned())?);
}
Ok(out)
}
@@ -1599,7 +1599,8 @@ cmd = [
]
"#,
);
- let refs = worktrunk::config::referenced_vars_for_config(&cfg, "deploy").unwrap();
+ let refs =
+ worktrunk::config::referenced_vars_for_config(&cfg, |_| "deploy".to_owned()).unwrap();
let names: Vec<&str> = refs.iter().map(String::as_str).collect();
assert_eq!(names, vec!["args", "env", "target"]);
}
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 1b5fd350c..aa292f4b2 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -13,8 +13,8 @@ use color_print::cformat;
use serde::{Deserialize, Serialize};
use worktrunk::HookType;
use worktrunk::config::{
- Command, CommandConfig, HookStep, TemplateContext, UserConfig, VarScope, VarsMode,
- format_hook_variables, validate_template_syntax,
+ Command, CommandConfig, HookStep, TemplateContext, TemplateExpandError, UserConfig, VarScope,
+ VarsMode, format_hook_variables, validate_template_syntax,
};
use worktrunk::git::{ErrorExt, Repository, WorktrunkError};
use worktrunk::path::{format_path_for_display, to_posix_path};
@@ -41,9 +41,7 @@ pub struct PreparedCommand {
/// Template variables, frozen at preparation. Serialized to JSON only at
/// the process boundary (the background pipeline spec).
pub context: TemplateContext,
- /// Name used in template expansion errors: `"user:foo"` for named hook
- /// commands, `"user pre-merge hook"` for unnamed ones, the alias name for
- /// aliases.
+ /// Hook identity from [`HookSource::hook_label`], or the alias name.
pub template_name: String,
/// Label for the per-command announcement summary and render span.
/// For hooks: `"user:foo"` for named, `"user"` for unnamed. For aliases: alias name.
@@ -522,9 +520,10 @@ pub fn execute_pipeline_foreground(
/// expansion reads git config; racing on reads would produce inconsistent
/// state), announces each command (per the step's `PipelineKind` — hooks
/// render per-command announcements, aliases only announce the outer group),
-/// then dispatches to `run_concurrent_commands` which streams each child's
-/// output prefixed by its label and waits for all to complete before folding
-/// outcomes.
+/// skips failed expansions under `Warn` (or aborts before spawning under
+/// `FailFast`), then dispatches to `run_concurrent_commands` which streams each
+/// child's output prefixed by its label and waits for all to complete before
+/// folding outcomes.
fn run_concurrent_group(
cmds: &[PreparedCommand],
fg_step: &ForegroundStep,
@@ -534,39 +533,45 @@ fn run_concurrent_group(
) -> anyhow::Result<()> {
let directives = &fg_step.directives;
- let expanded: Vec<String> = cmds
- .iter()
- .map(|cmd| {
+ let mut admitted = Vec::new();
+ for cmd in cmds {
+ let expanded = {
let _span = Span::new(format!("template_render:{}", cmd.label));
resolve_command_str(cmd, repo)
- })
- .collect::<Result<_>>()?;
+ };
+ match expanded {
+ Ok(command_str) => admitted.push((cmd, command_str)),
+ Err(err) => {
+ handle_command_error(err, cmd, &fg_step.error_wrapper, failure_strategy)?;
+ }
+ }
+ }
- for (cmd, command_str) in cmds.iter().zip(&expanded) {
+ for (cmd, command_str) in &admitted {
announce_command(cmd, &fg_step.announce, fg_step.source, command_str);
}
// Both alias tables and hook tables produce named commands (TOML keys
// become `name`), so `cmd.name` is always `Some` here.
- let labels: Vec<&str> = cmds
+ let labels: Vec<&str> = admitted
.iter()
- .map(|cmd| {
+ .map(|(cmd, _)| {
cmd.name
.as_deref()
.expect("concurrent group commands are always named")
})
.collect();
- let log_labels: Vec<Option<String>> = cmds
+ let log_labels: Vec<Option<String>> = admitted
.iter()
- .map(|cmd| fg_step.announce.log_label(cmd))
+ .map(|(cmd, _)| fg_step.announce.log_label(cmd))
.collect();
let scrub_git_discovery = fg_step.announce.is_hook();
- let specs: Vec<ConcurrentCommand<'_>> = (0..cmds.len())
+ let specs: Vec<ConcurrentCommand<'_>> = (0..admitted.len())
.map(|i| ConcurrentCommand {
label: labels[i],
- expanded: &expanded[i],
+ expanded: &admitted[i].1,
working_dir: wt_path,
log_label: log_labels[i].as_deref(),
directives,
@@ -577,7 +582,7 @@ fn run_concurrent_group(
let outcomes = run_concurrent_commands(&specs)?;
let mut first_failure: Option<anyhow::Error> = None;
- for (outcome, cmd) in outcomes.into_iter().zip(cmds) {
+ for (outcome, (cmd, _)) in outcomes.into_iter().zip(&admitted) {
let Err(err) = outcome else { continue };
match handle_command_error(err, cmd, &fg_step.error_wrapper, failure_strategy) {
Ok(()) => {}
@@ -607,7 +612,13 @@ fn run_one_command(
let command_str = {
let _span = Span::new(format!("template_render:{}", cmd.label));
- resolve_command_str(cmd, repo)?
+ resolve_command_str(cmd, repo)
+ };
+ let command_str = match command_str {
+ Ok(command_str) => command_str,
+ Err(err) => {
+ return handle_command_error(err, cmd, &fg_step.error_wrapper, failure_strategy);
+ }
};
announce_command(cmd, &fg_step.announce, fg_step.source, &command_str);
@@ -673,14 +684,19 @@ fn announce_command(
/// Build the standard `ErrorWrapper` for hook steps.
///
-/// Wraps non-signal failures in `WorktrunkError::HookCommandFailed`. Signal
-/// errors short-circuit upstream (see [`handle_command_error`]).
+/// Retains expansion diagnostics; wraps execution failures in
+/// `WorktrunkError::HookCommandFailed`. Signal errors short-circuit upstream
+/// (see [`handle_command_error`]).
pub fn hook_error_wrapper(
hook_type: HookType,
source: HookSource,
show_template: bool,
) -> ErrorWrapper {
Box::new(move |cmd, error| {
+ // Expansion diagnostics already carry the full hook identity and template.
+ if error.downcast_ref::<TemplateExpandError>().is_some() {
+ return error;
+ }
WorktrunkError::HookCommandFailed {
hook_type,
source,
@@ -852,10 +868,7 @@ pub fn prepare_steps(
cmd_context.insert("hook_name", name.clone());
}
- let template_name = match &cmd.name {
- Some(_) => source.command_label(cmd.name.as_deref()),
- None => source.hook_label(hook_type, None),
- };
+ let template_name = source.hook_label(hook_type, cmd.name.as_deref());
Ok(PreparedCommand {
name: cmd.name.clone(),
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rs
index def888112..acde519e7 100644
--- a/src/commands/config/alias.rs
+++ b/src/commands/config/alias.rs
@@ -163,7 +163,7 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(
// so a flag binds if any entry's template references it.
let mut referenced: BTreeSet<String> = BTreeSet::new();
for (cfg, _) in &entries {
- referenced.extend(referenced_vars_for_config(cfg, &name)?);
+ referenced.extend(referenced_vars_for_config(cfg, |_| name.clone())?);
}
let mut parse_args = Vec::with_capacity(1 + args.len());
parse_args.push(name.clone());
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 9c4167d68..05515ba82 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -28,6 +28,7 @@ use super::command_executor::{
CommandContext, FailureStrategy, PreparedStep, prepare_steps, render_template_preview,
};
use super::context::CommandEnv;
+use super::hook_filter::selected_hook_configs;
use super::hooks::{HookAnnouncer, prepare_and_check, run_hooks_foreground};
use super::project_config::command_label;
use super::template_vars::TemplateVars;
@@ -56,24 +57,17 @@ fn run_post_hook(
.map(drop);
}
- // Filter path merges user + project matches into one pipeline (the user
- // cherry-picked specific names across sources). The default path keeps
- // sources independent so a user hook failure doesn't abort project hooks.
+ // Each source runs independently, including when names are filtered.
let mut announcer = HookAnnouncer::new(ctx.repo, false);
- if name_filters.is_empty() {
- announcer.register(ctx, hook_type, extra_vars, None)?;
- } else {
- let flat = prepare_and_check(
- ctx,
- user_config,
- project_config,
- hook_type,
- extra_vars,
- name_filters,
- )?;
- // `flat` is non-empty: a filter that matches nothing errors above.
- announcer.add_groups(ctx, hook_type, None, vec![flat]);
- }
+ let steps = prepare_and_check(
+ ctx,
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filters,
+ )?;
+ announcer.add_steps(ctx, hook_type, None, steps);
announcer.flush()
}
@@ -146,26 +140,17 @@ fn parse_shorthand_token(raw: &str) -> anyhow::Result<(String, String, String)>
Ok((key.replace('-', "_"), key.to_string(), value.to_string()))
}
-/// Union of top-level template variable names referenced across every command
-/// in both configs for this hook type. Matches alias pipeline semantics:
-/// referenced in any step is a binding candidate for the whole invocation.
+/// Union of top-level variables referenced by selected commands.
+/// A reference in any selected step makes the variable a binding candidate.
fn referenced_vars_union(
- user_config: Option<&CommandConfig>,
- project_config: Option<&CommandConfig>,
+ selected: &[(HookSource, CommandConfig)],
hook_type: HookType,
) -> anyhow::Result<std::collections::BTreeSet<String>> {
let mut out = std::collections::BTreeSet::new();
- if let Some(cfg) = user_config {
- out.extend(referenced_vars_for_config(
- cfg,
- &format!("user {hook_type} hook"),
- )?);
- }
- if let Some(cfg) = project_config {
- out.extend(referenced_vars_for_config(
- cfg,
- &format!("project {hook_type} hook"),
- )?);
+ for (source, config) in selected {
+ out.extend(referenced_vars_for_config(config, |name| {
+ source.hook_label(hook_type, name)
+ })?);
}
Ok(out)
}
@@ -179,7 +164,7 @@ pub struct HookCliArgs<'a> {
/// Explicit `--var KEY=VALUE` bindings (deprecated force-bind).
pub explicit_vars: &'a [(String, String)],
/// Raw `KEY=VALUE` tokens from the `--KEY=VALUE` shorthand. Smart-routed:
- /// bind if any hook template references KEY, else forward to `{{ args }}`.
+ /// bind if a selected template references KEY, else forward to `{{ args }}`.
pub shorthand_vars: &'a [String],
/// Tokens after `--` that forward to `{{ args }}` verbatim.
pub forwarded_args: &'a [String],
@@ -187,15 +172,14 @@ pub struct HookCliArgs<'a> {
/// Handle `wt hook` command
///
-/// When explicitly invoking hooks, ALL hooks run (both user and project).
-/// There's no skip flag - if you explicitly run hooks, all configured hooks run.
+/// Runs configured user and project hooks selected by optional source/name filters.
///
/// Works in detached HEAD state - the `{{ branch }}` template variable (and the
/// `{{ base }}` / `{{ target }}` names derived from it) is simply unset there.
///
/// Template variables come from three sources in [`HookCliArgs`], routed per
/// alias semantics:
-/// - `shorthand_vars` (`--KEY=VALUE`): binds `{{ KEY }}` if any hook template
+/// - `shorthand_vars` (`--KEY=VALUE`): binds `{{ KEY }}` if a selected hook template
/// references it; otherwise forwards `--KEY=VALUE` into `{{ args }}`.
/// - `forwarded_args` (tokens after `--`): forwards into `{{ args }}` verbatim.
/// - `explicit_vars` (`--var KEY=VALUE`): deprecated force-bind. Always binds,
@@ -256,7 +240,8 @@ pub fn run_hook(
// Smart-route shorthand: bind when the template references the key,
// forward otherwise. Mirrors `AliasOptions::parse` for the alias path.
- let referenced = referenced_vars_union(user_config, proj_config, hook_type)?;
+ let selected = selected_hook_configs(user_config, proj_config, name_filters);
+ let referenced = referenced_vars_union(&selected, hook_type)?;
let mut bindings: Vec<(String, String)> = Vec::new();
let mut args: Vec<String> = Vec::new();
for raw in shorthand_vars {
@@ -276,7 +261,7 @@ pub fn run_hook(
eprintln!(
"{}",
warning_message(
- "--var is deprecated; use --KEY=VALUE shorthand (binds automatically when any hook template references KEY)",
+ "--var is deprecated; use --KEY=VALUE shorthand (binds automatically when a selected hook template references KEY)",
)
);
bindings.extend(explicit_vars.iter().cloned());
diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rs
index 70e482aed..93c43d79b 100644
--- a/src/commands/hook_filter.rs
+++ b/src/commands/hook_filter.rs
@@ -1,6 +1,6 @@
//! Hook filter types for command filtering by source and name.
-use worktrunk::config::HookSource;
+use worktrunk::config::{CommandConfig, HookSource};
/// A parsed name filter, optionally scoped to a specific source.
///
@@ -45,3 +45,32 @@ impl<'a> ParsedFilter<'a> {
&& (self.name.is_empty() || name.is_some_and(|n| n == self.name))
}
}
+
+/// Select commands before template parsing, preparation, or execution.
+/// Shared by manual-hook argument routing and pipeline preparation.
+pub(crate) fn selected_hook_configs(
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+ name_filters: &[String],
+) -> Vec<(HookSource, CommandConfig)> {
+ let filters: Vec<_> = name_filters
+ .iter()
+ .map(|name| ParsedFilter::parse(name))
+ .collect();
+ [
+ (HookSource::User, user_config),
+ (HookSource::Project, project_config),
+ ]
+ .into_iter()
+ .filter_map(|(source, config)| {
+ let config = config?.filtered(|command| {
+ filters.is_empty()
+ || filters
+ .iter()
+ .any(|filter| filter.matches_command(source, command.name.as_deref()))
+ });
+ let has_commands = config.commands().next().is_some();
+ has_commands.then_some((source, config))
+ })
+ .collect()
+}
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rs
index 7a10b322d..01722c15c 100644
--- a/src/commands/hook_plan.rs
+++ b/src/commands/hook_plan.rs
@@ -25,7 +25,7 @@
//! hold no [`ProjectConfig`] and call no `load_project_config()` for the
//! covered hook types — re-derivation is a compile error, not a review check.
//! The `Repository` an executor still holds is used only for *rendering*
-//! ([`render_planned`] takes the frozen [`CommandConfig`] list, never config),
+//! ([`prepare_selected`] takes the frozen [`CommandConfig`] list, never config),
//! so it cannot re-select.
//!
//! The frozen unit is the *selected, source-tagged [`CommandConfig`] list* per
@@ -51,10 +51,9 @@ use worktrunk::git::add_hook_skip_hint;
use super::command_approval::approve_command_batch;
use super::command_executor::{
- CommandContext, FailureStrategy, PipelineKind, execute_pipeline_foreground, prepare_steps,
+ CommandContext, FailureStrategy, PipelineKind, execute_pipeline_foreground,
};
-use super::hook_announcement::SourcedStep;
-use super::hooks::{HookAnnouncer, into_source_groups, sourced_steps_to_foreground};
+use super::hooks::{HookAnnouncer, prepare_selected, sourced_steps_to_foreground};
use super::project_config::{ApprovableCommand, Phase};
use worktrunk::config::HookSource;
@@ -340,28 +339,6 @@ impl ApprovedHookPlan {
}
}
-/// Render the frozen selection into source-tagged steps. Takes the frozen
-/// `CommandConfig` list, never config — re-selection is impossible. `ctx`'s
-/// `Repository` is used only for template expansion.
-fn render_planned(
- entries: &[(HookSource, CommandConfig)],
- ctx: &CommandContext<'_>,
- extra_vars: &[(&str, &str)],
- hook_type: HookType,
-) -> anyhow::Result<Vec<SourcedStep>> {
- let mut out = Vec::new();
- for (source, cfg) in entries {
- let steps = prepare_steps(cfg, ctx, extra_vars, hook_type, *source)?.validated()?;
- for step in steps {
- out.push(SourcedStep {
- step,
- source: *source,
- });
- }
- }
- Ok(out)
-}
-
/// Foreground execution of a covered hook from the approved plan.
///
/// Replaces `execute_hook` for `pre-merge` / `pre-remove` / `pre-start`. The
@@ -382,7 +359,7 @@ pub fn execute_planned_hook(
failure_strategy: FailureStrategy,
display_path: Option<&Path>,
) -> anyhow::Result<()> {
- let sourced = render_planned(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)?;
+ let sourced = prepare_selected(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)?;
if sourced.is_empty() {
return Ok(());
}
@@ -400,7 +377,7 @@ pub fn execute_planned_hook(
///
/// The plan-backed counterpart of `HookAnnouncer::register`: steps are
/// rendered from the frozen selection and added via the announcer's existing
-/// config-free `add_groups`, with no `load_project_config()` at execution.
+/// config-free `add_steps`, with no `load_project_config()` at execution.
///
/// `anchor` is the worktree the hook runs in — the lookup key into the frozen
/// plan (see [`execute_planned_hook`]).
@@ -413,9 +390,9 @@ pub fn register_planned(
extra_vars: &[(&str, &str)],
display_path: Option<&Path>,
) -> anyhow::Result<()> {
- let sourced = render_planned(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)
+ let sourced = prepare_selected(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)
.context("failed to render planned hooks")?;
- announcer.add_groups(ctx, hook_type, display_path, into_source_groups(sourced));
+ announcer.add_steps(ctx, hook_type, display_path, sourced);
Ok(())
}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 5b11b760f..29ccb0eff 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -43,8 +43,8 @@
//!
//! **Invocation-resolved (no gate→exec mutation):** `pre-commit`,
//! `post-commit`, `pre-switch`, `wt hook <type>`, aliases. They resolve config
-//! from `ctx.repo.load_project_config()` at invocation via [`execute_hook`] /
-//! [`HookAnnouncer::register`]. Two facts make that re-read safe, and a new
+//! from `ctx.repo.load_project_config()` at invocation; manual hooks pass the
+//! loaded configs directly to preparation. Two facts make a re-read safe, and a new
//! call site must preserve **both**: (1) nothing between the gate and the
//! executor mutates the worktree `.config/wt.toml`; (2) the executor reads
//! through the **same `Repository` instance** the gate used —
@@ -82,14 +82,14 @@ use worktrunk::styling::{
};
use super::command_executor::{
- CommandContext, FailureStrategy, ForegroundStep, PipelineKind, PreparedCommand, PreparedStep,
- alias_error_wrapper, execute_pipeline_foreground, hook_error_wrapper, prepare_steps,
+ CommandContext, FailureStrategy, ForegroundStep, PipelineKind, alias_error_wrapper,
+ execute_pipeline_foreground, hook_error_wrapper, prepare_steps,
};
use super::hook_announcement::{SourcedStep, format_pipeline_summary};
use crate::commands::process::{HookLog, spawn_detached_exec};
use crate::output::DirectivePassthrough;
-use super::hook_filter::ParsedFilter;
+use super::hook_filter::{ParsedFilter, selected_hook_configs};
use worktrunk::config::HookSource;
/// Prepare hook steps from both user and project configs, preserving pipeline
@@ -100,12 +100,8 @@ use worktrunk::config::HookSource;
/// name filter to individual commands within each step. The filter supports
/// source prefixes: `user:foo` or `project:foo` to run only from one source.
///
-/// Shared by [`run_hooks_foreground`] and the dry-run branch of `run_hook`
-/// (in `hook_commands.rs`) so both paths produce the same "no commands
-/// matched" error when a filter mismatches. `run_post_hook`'s filter path
-/// additionally relies on the error as a guarantee: `Ok` under a non-empty
-/// filter implies non-empty steps, which [`HookAnnouncer::add_groups`]
-/// requires.
+/// Shared by foreground, background registration, and dry-run so each path
+/// produces the same "no commands matched" error when a filter mismatches.
pub(crate) fn prepare_and_check(
ctx: &CommandContext,
user_config: Option<&CommandConfig>,
@@ -114,35 +110,8 @@ pub(crate) fn prepare_and_check(
extra_vars: &[(&str, &str)],
name_filters: &[String],
) -> anyhow::Result<Vec<SourcedStep>> {
- let parsed_filters: Vec<ParsedFilter<'_>> = name_filters
- .iter()
- .map(|f| ParsedFilter::parse(f))
- .collect();
-
- let mut result = Vec::new();
-
- let sources = [
- (HookSource::User, user_config),
- (HookSource::Project, project_config),
- ];
-
- for (source, config) in sources {
- let Some(config) = config else { continue };
-
- if !parsed_filters.is_empty() && !parsed_filters.iter().any(|f| f.matches_source(source)) {
- continue;
- }
-
- let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?.validated()?;
- for step in steps {
- if let Some(filtered) = filter_step_by_name(step, source, &parsed_filters) {
- result.push(SourcedStep {
- step: filtered,
- source,
- });
- }
- }
- }
+ let selected = selected_hook_configs(user_config, project_config, name_filters);
+ let result = prepare_selected(&selected, ctx, extra_vars, hook_type)?;
// Every surviving step keeps at least one command, so an empty result
// under a non-empty filter means nothing matched.
@@ -158,34 +127,22 @@ pub(crate) fn prepare_and_check(
Ok(result)
}
-/// Filter commands within a step by name. Returns `None` if all commands were
-/// filtered out. A `Concurrent` group reduced to one command collapses to `Single`.
-fn filter_step_by_name(
- step: PreparedStep,
- source: HookSource,
- parsed_filters: &[ParsedFilter<'_>],
-) -> Option<PreparedStep> {
- if parsed_filters.is_empty() {
- return Some(step);
- }
-
- let matches = |cmd: &PreparedCommand| {
- parsed_filters
- .iter()
- .any(|f| f.matches_command(source, cmd.name.as_deref()))
- };
-
- match step {
- PreparedStep::Single(cmd) => matches(&cmd).then_some(PreparedStep::Single(cmd)),
- PreparedStep::Concurrent(cmds) => {
- let mut kept: Vec<_> = cmds.into_iter().filter(matches).collect();
- match kept.len() {
- 0 => None,
- 1 => Some(PreparedStep::Single(kept.pop().unwrap())),
- _ => Some(PreparedStep::Concurrent(kept)),
- }
- }
+/// Prepare frozen source/config selections without reading configuration.
+pub(crate) fn prepare_selected(
+ entries: &[(HookSource, CommandConfig)],
+ ctx: &CommandContext<'_>,
+ extra_vars: &[(&str, &str)],
+ hook_type: HookType,
+) -> anyhow::Result<Vec<SourcedStep>> {
+ let mut out = Vec::new();
+ for (source, config) in entries {
+ let steps = prepare_steps(config, ctx, extra_vars, hook_type, *source)?.validated()?;
+ out.extend(steps.into_iter().map(|step| SourcedStep {
+ step,
+ source: *source,
+ }));
}
+ Ok(out)
}
/// Build the error for a filter that matched no commands.
@@ -294,7 +251,7 @@ pub struct HookAnnouncer<'a> {
/// any short-lived `CommandContext`s 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.
-/// `steps` is non-empty by construction (see [`HookAnnouncer::add_groups`]).
+/// `steps` is non-empty by construction (see [`HookAnnouncer::add_steps`]).
struct PendingPipeline {
worktree_path: PathBuf,
branch: Option<String>,
@@ -316,22 +273,16 @@ impl<'a> HookAnnouncer<'a> {
}
}
- /// Add one pipeline per step group, all sharing `hook_type` and
- /// `display_path` and running in `ctx`'s worktree.
- ///
- /// Groups come from [`into_source_groups`] (one pipeline per source — the
- /// canonical shape) or as a single merged group (`wt hook`'s filter path,
- /// where the user cherry-picked names across sources). Callers never pass
- /// empty groups.
- pub fn add_groups(
+ /// Register one independent background pipeline per source.
+ /// Grouping here keeps user and project failures and logs separate.
+ pub fn add_steps(
&mut self,
ctx: &CommandContext<'_>,
hook_type: HookType,
display_path: Option<&Path>,
- groups: Vec<Vec<SourcedStep>>,
+ steps: Vec<SourcedStep>,
) {
- for steps in groups {
- debug_assert!(!steps.is_empty(), "add_groups: empty step group");
+ for steps in into_source_groups(steps) {
self.pending.push(PendingPipeline {
worktree_path: ctx.worktree_path.to_path_buf(),
branch: ctx.branch.map(String::from),
@@ -344,8 +295,7 @@ impl<'a> HookAnnouncer<'a> {
/// Prepare and add user+project pipelines for a single hook type, reading
/// the project config from `ctx.repo.load_project_config()` — the worktree
- /// this hook acts on. Used by the invocation-resolved hooks
- /// (`pre-commit` / `post-commit` and `wt hook <type>`'s no-filter path),
+ /// this hook acts on. Used by invocation-resolved `post-commit` hooks,
/// where nothing mutates config between approval and execution. The
/// plan-backed hooks use [`super::hook_plan::register_planned`] instead.
///
@@ -368,7 +318,7 @@ impl<'a> HookAnnouncer<'a> {
extra_vars,
&[],
)?;
- self.add_groups(ctx, hook_type, display_path, into_source_groups(flat));
+ self.add_steps(ctx, hook_type, display_path, flat);
Ok(())
}
@@ -427,7 +377,7 @@ impl Drop for HookAnnouncer<'_> {
/// Announce and spawn background hook pipelines.
///
/// Module-private implementation of [`HookAnnouncer::flush`] — sites construct
-/// a [`HookAnnouncer`] (one per command) and `register`/`add_groups` into it;
+/// a [`HookAnnouncer`] (one per command) and `register`/`add_steps` into it;
/// `flush` lands here. The function stays separate to keep the announce/spawn
/// formatting isolated from the announcer's pending-list bookkeeping.
///
@@ -556,10 +506,10 @@ fn report_dropped_pipelines(dropped: &[PendingPipeline]) {
/// Group sourced steps into one Vec per source, preserving insertion order.
///
-/// Used by background callers that want one pipeline per source (the canonical
-/// shape — a user hook failure shouldn't abort project hooks). The flat input
-/// already lists user steps before project steps, so contiguous chunks suffice.
-pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>> {
+/// Background sources execute independently: a user hook failure must not abort
+/// project hooks. The flat input already lists user steps before project steps,
+/// so contiguous chunks suffice.
+fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>> {
let mut groups: Vec<Vec<SourcedStep>> = Vec::new();
for step in flat {
match groups.last_mut() {
@@ -602,8 +552,7 @@ fn print_background_variable_table(pipelines: &[PendingPipeline], hook_type: Hoo
fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: PendingPipeline) -> anyhow::Result<()> {
use super::run_pipeline::PipelineSpec;
- // Registration never adds an empty step group (asserted in `add_groups`),
- // so `steps[0]` is safe.
+ // `add_steps` constructs non-empty groups with one source each.
let source = pipeline.steps[0].source;
// Only names the pipeline's log file, so a detached worktree needs some
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 883fa404a..783b56044 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -15,8 +15,8 @@ use normalize_path::NormalizePath;
use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{
- UserConfig, ValidationScope, VarScope, referenced_vars_for_templates, template_references_var,
- validate_template,
+ HookSource, UserConfig, ValidationScope, VarScope, referenced_vars_for_templates,
+ template_references_var, validate_template,
};
use worktrunk::git::remote_ref::{self, RemoteRefInfo, parse_ref_url};
use worktrunk::git::{
@@ -2323,7 +2323,10 @@ fn validate_switch_templates(
for &hook_type in switch_post_hook_types(plan.is_create()) {
let user_cfg = user_hooks.get(hook_type);
let proj_cfg = project_config.as_ref().and_then(|c| c.hooks.get(hook_type));
- for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {
+ for (source, cfg) in [
+ (HookSource::User, user_cfg),
+ (HookSource::Project, proj_cfg),
+ ] {
if let Some(cfg) = cfg {
for cmd in cfg.commands() {
// Skip full validation for templates referencing {{ vars.X }} —
@@ -2333,10 +2336,7 @@ fn validate_switch_templates(
if template_references_var(&cmd.template, "vars") {
continue;
}
- let name = match &cmd.name {
- Some(n) => format!("{source} {hook_type}:{n}"),
- None => format!("{source} {hook_type} hook"),
- };
+ let name = source.hook_label(hook_type, cmd.name.as_deref());
validate_template(
&cmd.template,
ValidationScope::Hook(hook_type),
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 3e7bfdf5a..0c2bd4732 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -98,6 +98,28 @@ impl CommandConfig {
&self.steps
}
+ /// Keep matching commands, preserving serial order and concurrent groups.
+ /// A concurrent group with one retained command becomes a single step.
+ pub fn filtered(&self, mut retain: impl FnMut(&Command) -> bool) -> Self {
+ let steps = self
+ .steps
+ .iter()
+ .filter_map(|step| match step {
+ HookStep::Single(cmd) => retain(cmd).then(|| HookStep::Single(cmd.clone())),
+ HookStep::Concurrent(commands) => {
+ let mut kept: Vec<_> =
+ commands.iter().filter(|cmd| retain(cmd)).cloned().collect();
+ match kept.len() {
+ 0 => None,
+ 1 => kept.pop().map(HookStep::Single),
+ _ => Some(HookStep::Concurrent(kept)),
+ }
+ }
+ })
+ .collect();
+ Self { steps }
+ }
+
/// Merge two configs by appending steps (base steps first, then overlay).
///
/// Used for per-project hook overrides where both global and project hooks run.
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 9589544ec..ac270eeb3 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -1047,19 +1047,19 @@ pub fn referenced_vars_for_templates<'a>(
/// a binding candidate for the whole invocation. A syntax error in any
/// template fails here so the user sees it before flags are routed — a
/// silent skip could mask a typo and change how subsequent CLI args bind.
-/// `name` labels the failing alias or hook in the error, which matches
-/// [`expand_template`]'s parse-failure shape so syntax errors render
-/// identically wherever they surface.
+/// `label` identifies the failing command in the error, so hooks can retain
+/// their source, type and optional command name while aliases keep their alias
+/// name. The error matches [`expand_template`]'s parse-failure shape.
pub fn referenced_vars_for_config(
cfg: &super::CommandConfig,
- name: &str,
+ label: impl Fn(Option<&str>) -> String,
) -> anyhow::Result<BTreeSet<String>> {
let env = minijinja::Environment::new();
let mut out = BTreeSet::new();
for cmd in cfg.commands() {
- let tmpl = env
- .template_from_str(&cmd.template)
- .map_err(|e| build_template_error(&e, &cmd.template, name, Vec::new()))?;
+ let tmpl = env.template_from_str(&cmd.template).map_err(|e| {
+ build_template_error(&e, &cmd.template, &label(cmd.name.as_deref()), Vec::new())
+ })?;
out.extend(tmpl.undeclared_variables(false));
}
Ok(out)
@@ -3413,7 +3413,7 @@ mod tests {
#[test]
fn test_referenced_vars_for_config_syntax_error_propagates() {
let cfg = super::super::CommandConfig::single("echo {{ unclosed");
- let err = referenced_vars_for_config(&cfg, "deploy").unwrap_err();
+ let err = referenced_vars_for_config(&cfg, |_| "deploy".to_owned()).unwrap_err();
let msg = format!("{err:#}");
assert!(msg.contains("Failed to expand deploy"), "got: {msg}");
assert!(msg.contains("syntax error"), "got: {msg}");
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 661ac72b7..8c2df97d1 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -38,6 +38,21 @@ hello = "echo Hello from {{ branch }}"
));
}
+/// Alias expansion errors retain the alias identity and underlying diagnostic.
+#[rstest]
+fn test_step_alias_runtime_undefined_variable(repo: TestRepo) {
+ repo.write_test_config(
+ r#"
+[aliases]
+deploy = "echo {{ nope }}"
+"#,
+ );
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["deploy"], None));
+ });
+}
+
/// `wt config alias dry-run <name>` shows the expanded command without running it
/// (no approval needed — preview never executes project commands).
#[rstest]
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 57a27ee67..3f12dafbd 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1763,7 +1763,18 @@ fn test_switch_picker_preview_auto_refreshes_when_compute_lands(repo: TestRepo)
/// succeeds — proving the pre-flight aborts cleanly rather than leaving a
/// half-created worktree behind.
#[rstest]
-fn test_switch_picker_create_validates_templates_before_worktree(repo: TestRepo) {
+#[case::unnamed(r#"pre-start = "echo {{ unclosed""#, "pre-start user hook")]
+#[case::named(
+ r#"[pre-start]
+broken = "echo {{ unclosed"
+"#,
+ "pre-start user:broken"
+)]
+fn test_switch_picker_create_validates_templates_before_worktree(
+ repo: TestRepo,
+ #[case] config: &str,
+ #[case] label: &str,
+) {
repo.run_git(&["remote", "remove", "origin"]);
// Broken `pre-start` in user config: unbalanced `{{` is a minijinja parse
@@ -1771,7 +1782,7 @@ fn test_switch_picker_create_validates_templates_before_worktree(repo: TestRepo)
// Project config would also trigger the validation path, but it routes
// through the approval gate first and would prompt for a TTY response —
// user-config hooks are trusted and exercise validation directly.
- repo.write_test_config(r#"pre-start = "echo {{ unclosed""#);
+ repo.write_test_config(config);
let env_vars = repo.test_env_vars();
@@ -1792,6 +1803,13 @@ fn test_switch_picker_create_validates_templates_before_worktree(repo: TestRepo)
"Expected non-zero exit when pre-start template is broken.\nScreen:\n{}",
result.screen()
);
+ assert!(
+ result
+ .screen()
+ .contains(&format!("Failed to expand {label}: syntax error")),
+ "The pre-flight error must identify the hook source and command.\nScreen:\n{}",
+ result.screen()
+ );
// Branch must not have been created — pre-flight runs before any
// `git worktree add` / `git branch`.
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index b27ff2ea6..b688afbd6 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -18,6 +18,7 @@ use rstest::rstest;
use std::fs;
use std::thread;
use std::time::Duration;
+use worktrunk::config::HookSource;
#[rstest]
#[cfg(unix)]
@@ -1380,10 +1381,9 @@ broken = "echo {{ does_not_exist }} > should_not_exist.txt"
.join("runner.log");
wait_for_file_content(&runner_log);
let log_content = fs::read_to_string(&runner_log).unwrap();
- // Same label the foreground path renders for this command (see the
- // foreground_pipeline_undefined_var_runs_earlier_steps snapshot).
+ // Template errors identify the hook type, source, and command.
assert_snapshot!(log_content, @"
- ✗ Failed to expand user:broken: undefined variable does_not_exist @ line 1
+ ✗ Failed to expand post-start user:broken: undefined variable does_not_exist @ line 1
  echo {{ does_not_exist }} > should_not_exist.txt
↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
");
@@ -1426,8 +1426,8 @@ fn test_background_concurrent_template_failure_reaps_admitted_child(repo: TestRe
"name": name,
"template": template,
"context": {},
- "template_name": format!("user:{name}"),
- "label": format!("user:{name}"),
+ "template_name": HookSource::User.hook_label(worktrunk::HookType::PostCreate, Some(name)),
+ "label": HookSource::User.command_label(Some(name)),
})
};
let spec = serde_json::json!({
@@ -1483,7 +1483,7 @@ fn test_background_concurrent_template_failure_reaps_admitted_child(repo: TestRe
crate::common::wait_for("concurrent preparation failure", || {
fs::read_to_string(&runner_log)
.unwrap()
- .contains("Failed to expand user:broken:")
+ .contains("Failed to expand post-start user:broken:")
});
assert_eq!(kill(pid, None), Err(nix::errno::Errno::ESRCH));
@@ -1502,6 +1502,68 @@ fn test_background_concurrent_template_failure_reaps_admitted_child(repo: TestRe
assert_eq!(status.code(), Some(1));
}
+/// Filtered background hooks keep each source's execution and logs independent.
+#[rstest]
+#[case::user(HookSource::User)]
+#[case::project(HookSource::Project)]
+fn test_filtered_background_hooks_preserve_sources(
+ repo: TestRepo,
+ #[case] failing_source: HookSource,
+) {
+ let user_exit = if failing_source == HookSource::User {
+ "exit 7"
+ } else {
+ "true"
+ };
+ let project_exit = if failing_source == HookSource::Project {
+ "exit 7"
+ } else {
+ "true"
+ };
+ repo.write_test_config(&format!(
+ r#"[post-start]
+fmt = "echo USER_LOG; echo ran > user.txt; {user_exit}"
+"#
+ ));
+ repo.write_project_config(&format!(
+ r#"[post-start]
+fmt = "echo PROJECT_LOG; echo ran > project.txt; {project_exit}"
+"#
+ ));
+
+ let output = repo
+ .wt_command()
+ .args(["hook", "post-start", "fmt", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ wait_for_file_content(&repo.root_path().join("user.txt"));
+ wait_for_file_content(&repo.root_path().join("project.txt"));
+
+ let logs = resolve_git_common_dir(repo.root_path()).join("wt/logs/main");
+ let runner = logs
+ .join(failing_source.to_string())
+ .join("post-start/runner.log");
+ crate::common::wait_for("source-qualified background failure", || {
+ fs::read_to_string(&runner)
+ .is_ok_and(|text| text.contains("failed (exit code 7)") && text.ends_with('\n'))
+ });
+ let user_log = fs::read_to_string(logs.join("user/post-start/fmt.log")).unwrap();
+ let project_log = fs::read_to_string(logs.join("project/post-start/fmt.log")).unwrap();
+ let failure = fs::read_to_string(runner).unwrap();
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_snapshot!(format!("filtered_background_sources_{failing_source}"), format!(
+ "announcement:\n{}\nuser/fmt.log:\n{user_log}\nproject/fmt.log:\n{project_log}\n{failing_source}/runner.log:\n{failure}",
+ String::from_utf8_lossy(&output.stderr),
+ ));
+ });
+}
+
/// Runner-log failures use the same hook/status grammar as foreground failures.
#[rstest]
fn test_background_hook_failure_labels_in_runner_log(repo: TestRepo) {
@@ -1551,8 +1613,7 @@ exit 9
/// A semantic template error in a foreground pipeline step surfaces when that
/// step runs: earlier steps execute first, then the broken step's render
-/// aborts the pipeline. (Pre-change, prep expanded every template upfront and
-/// nothing ran.) Syntax errors still abort before step 1.
+/// aborts the pipeline. Syntax errors still abort before step 1.
#[rstest]
fn test_foreground_pipeline_undefined_var_runs_earlier_steps(repo: TestRepo) {
repo.write_test_config(
@@ -1580,6 +1641,108 @@ fn test_foreground_pipeline_undefined_var_runs_earlier_steps(repo: TestRepo) {
);
}
+/// Runtime expansion obeys the same foreground policy as child failures:
+/// Warn admits healthy concurrent siblings and later commands from either
+/// source; FailFast rejects the group before spawning any command in it.
+#[rstest]
+#[case::warn_serial(true, false, true)]
+#[case::warn_concurrent(true, true, true)]
+#[case::warn_all_broken(true, true, false)]
+#[case::failfast_serial(false, false, true)]
+#[case::failfast_concurrent(false, true, true)]
+fn test_foreground_template_failure_policy(
+ repo: TestRepo,
+ #[case] warn: bool,
+ #[case] concurrent: bool,
+ #[case] healthy_sibling: bool,
+) {
+ let hook_type = if warn { "post-start" } else { "pre-merge" };
+ let broken = r#"broken = "echo {{ does_not_exist }}""#;
+ let sibling = if healthy_sibling {
+ r#"sibling = "echo ran > sibling.txt", "#
+ } else {
+ r#"also_broken = "echo {{ missing_too }}", "#
+ };
+ let failing_step = if concurrent {
+ format!("{{ {sibling}{broken} }}")
+ } else {
+ format!("{{ {broken} }}")
+ };
+ repo.write_test_config(&format!(
+ r#"{hook_type} = [
+ {{ first = "echo ran > first.txt" }},
+ {failing_step},
+ {{ later = "echo ran > later.txt" }},
+]
+"#,
+ ));
+ repo.write_project_config(&format!(
+ r#"[{hook_type}]
+project = "echo ran > project.txt"
+"#,
+ ));
+ let output = repo
+ .wt_command()
+ .args(["hook", hook_type, "--foreground", "--yes"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(output.status.success(), warn, "{stderr}");
+ assert!(repo.root_path().join("first.txt").exists(), "{stderr}");
+ for name in ["later.txt", "project.txt"] {
+ assert_eq!(
+ repo.root_path().join(name).exists(),
+ warn,
+ "{name}: {stderr}"
+ );
+ }
+ assert_eq!(
+ repo.root_path().join("sibling.txt").exists(),
+ warn && concurrent && healthy_sibling,
+ "{stderr}",
+ );
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_snapshot!(
+ format!("foreground_template_policy_{warn}_{concurrent}_{healthy_sibling}"),
+ stderr,
+ );
+ });
+}
+
+/// An ordinary shell status 130 remains a failure under Warn, so healthy
+/// concurrent siblings and subsequent source/serial commands still run.
+#[rstest]
+#[case::serial(false)]
+#[case::concurrent(true)]
+fn test_foreground_warn_status_130_continues(repo: TestRepo, #[case] concurrent: bool) {
+ let first = if concurrent {
+ r#"{ fail = "exit 130", sibling = "echo ran > sibling.txt" }"#
+ } else {
+ r#"{ fail = "exit 130" }"#
+ };
+ repo.write_test_config(&format!(
+ r#"post-start = [{first}, {{ later = "echo ran > later.txt" }}]
+"#,
+ ));
+ repo.write_project_config(
+ r#"[post-start]
+project = "echo ran > project.txt"
+"#,
+ );
+ let output = repo
+ .wt_command()
+ .args(["hook", "post-start", "--foreground", "--yes"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(output.status.success(), "{stderr}");
+ assert!(stderr.contains("failed (exit code 130)"), "{stderr}");
+ assert!(repo.root_path().join("later.txt").exists(), "{stderr}");
+ assert!(repo.root_path().join("project.txt").exists(), "{stderr}");
+ assert_eq!(repo.root_path().join("sibling.txt").exists(), concurrent);
+}
+
#[rstest]
fn test_hook_template_typo_names_variable(repo: TestRepo) {
repo.write_test_config("pre-merge = \"echo {{ brnch }}\"\n");
@@ -1739,27 +1902,45 @@ marker = "printf POST_REMOVE_RAN > '{marker_path}'"
assert_eq!(fs::read_to_string(marker).unwrap(), "POST_REMOVE_RAN");
}
+/// Manual hook argument routing parses templates before pipeline preparation.
+/// Its syntax errors must identify the same source and command as execution
+/// errors, including which named command failed.
#[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""#);
+#[case::user_unnamed(HookSource::User, None)]
+#[case::user_named(HookSource::User, Some("broken"))]
+#[case::project_unnamed(HookSource::Project, None)]
+#[case::project_named(HookSource::Project, Some("broken"))]
+fn test_standalone_hook_post_remove_invalid_template(
+ repo: TestRepo,
+ #[case] source: HookSource,
+ #[case] name: Option<&str>,
+) {
+ let config = match name {
+ Some(name) => format!(
+ r#"[post-remove]
+{name} = "echo {{{{ invalid"
+"#
+ ),
+ None => r#"post-remove = "echo {{ invalid""#.to_owned(),
+ };
+ match source {
+ HookSource::User => repo.write_test_config(&config),
+ HookSource::Project => repo.write_project_config(&config),
+ }
- let mut cmd = crate::common::wt_command();
- cmd.current_dir(repo.root_path());
- cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ let mut cmd = repo.wt_command();
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("syntax error"),
- "Error should mention template expansion failure, got: {stderr}"
- );
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_cmd_snapshot!(
+ format!(
+ "standalone_hook_post_remove_invalid_template_{source}_{}",
+ name.unwrap_or("unnamed")
+ ),
+ cmd
+ );
+ });
}
#[rstest]
@@ -2976,38 +3157,77 @@ bar = "echo ran > project_bar.txt"
);
}
-/// A bare source filter (`user:` / `project:`) asks for every hook from one
-/// source, so it runs them all without naming any.
+/// Source selection excludes malformed templates in the other configuration.
#[rstest]
-fn test_hook_bare_source_filter_runs_that_source(repo: TestRepo) {
- repo.write_test_config(
- r#"[pre-merge]
-fmt = "echo ran > user_fmt.txt"
-lint = "echo ran > user_lint.txt"
-"#,
- );
- repo.write_project_config(r#"pre-merge = "echo ran > project.txt""#);
+#[case::user(HookSource::User)]
+#[case::project(HookSource::Project)]
+fn test_hook_bare_source_filter_runs_that_source(repo: TestRepo, #[case] source: HookSource) {
+ let selected = r#"[pre-merge]
+fmt = "echo ran > selected_fmt.txt"
+lint = "echo ran > selected_lint.txt"
+"#;
+ let excluded = r#"pre-merge = "echo {{ unclosed""#;
+ match source {
+ HookSource::User => {
+ repo.write_test_config(selected);
+ repo.write_project_config(excluded);
+ }
+ HookSource::Project => {
+ repo.write_test_config(excluded);
+ repo.write_project_config(selected);
+ }
+ }
repo.commit("Add pre-merge hooks");
-
+ let filter = format!("{source}:");
let output = repo
.wt_command()
- .args(["hook", "pre-merge", "user:", "--yes"])
+ .args(["hook", "pre-merge", &filter, "--yes"])
.output()
- .expect("Failed to run wt hook pre-merge");
-
+ .unwrap();
assert!(
output.status.success(),
- "wt hook pre-merge user: failed: {}",
+ "{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
- repo.root_path().join("user_fmt.txt").exists()
- && repo.root_path().join("user_lint.txt").exists(),
- "user: should run every user hook"
+ repo.root_path().join("selected_fmt.txt").exists()
+ && repo.root_path().join("selected_lint.txt").exists()
+ );
+}
+
+/// Only selected commands participate in syntax validation and shorthand binding.
+#[rstest]
+#[case::syntax("echo {{ unclosed")]
+#[case::routing("echo {{ key }}")]
+fn test_hook_named_filter_selects_before_template_parsing(
+ repo: TestRepo,
+ #[case] excluded_template: &str,
+ #[values(HookSource::User, HookSource::Project)] source: HookSource,
+) {
+ let config = format!(
+ r#"[pre-merge]
+valid = "printf '%s' {{{{ args }}}} > selected.txt"
+broken = "{excluded_template}"
+"#
);
+ match source {
+ HookSource::User => repo.write_test_config(&config),
+ HookSource::Project => repo.write_project_config(&config),
+ }
+ let filter = format!("{source}:valid");
+ let output = repo
+ .wt_command()
+ .args(["hook", "pre-merge", &filter, "--yes", "--key=value"])
+ .output()
+ .unwrap();
assert!(
- !repo.root_path().join("project.txt").exists(),
- "user: must not reach the project hook"
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(
+ fs::read_to_string(repo.root_path().join("selected.txt")).unwrap(),
+ "--key=value"
);
}
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
index cfc5ccd36..0c9a9c460 100644
--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_syntax_error.snap
@@ -64,7 +64,7 @@ exit_code: 0
PROJECT HOOKS @ _REPO_/.config/wt.toml
❯ pre-commit broken: (requires approval)
-  # Failed to expand project:broken: syntax error: unexpected end of input, expected end of variable block @ line 1
+  # Failed to expand pre-commit project:broken: syntax error: unexpected end of input, expected end of variable block @ line 1
  echo {{ branch
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
index b4d89fc1f..f1a6ad243 100644
--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap
@@ -64,7 +64,7 @@ exit_code: 0
PROJECT HOOKS @ _REPO_/.config/wt.toml
❯ pre-commit optional-var: (requires approval)
-  # Failed to expand project:optional-var: undefined variable base @ line 1
+  # Failed to expand pre-commit project:optional-var: undefined variable base @ line 1
  echo {{ base }}
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_template_expansion.snap
index 6dca7004e..472a3628d 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_template_expansion.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_verbose_template_expansion.snap
@@ -65,9 +65,9 @@ exit_code: 0
  ../{{ repo }}.{{ branch | sanitize }}
○ worktree-path result
  ../repo.verbose-hooks
-○ project:setup source
+○ pre-start project:setup source
  echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'
-○ project:setup result
+○ pre-start project:setup result
  echo 'Setting up verbose-hooks in _REPO_.verbose-hooks'
○ pre-start template variables:
  branch = verbose-hooks
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_runtime_undefined_variable.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_runtime_undefined_variable.snap
new file mode 100644
index 000000000..dc7d85650
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_runtime_undefined_variable.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - deploy
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to expand deploy: undefined variable nope @ line 1
+  echo {{ nope }}
+↳ Available variables: args, branch, cwd, repo, repo_path, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_project.snap b/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_project.snap
new file mode 100644
index 000000000..93179334a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_project.snap
@@ -0,0 +1,15 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: "format!(\"announcement:\\n{}\\nuser/fmt.log:\\n{user_log}\\nproject/fmt.log:\\n{project_log}\\n{failing_source}/runner.log:\\n{failure}\",\nString::from_utf8_lossy(&output.stderr),)"
+---
+announcement:
+◎ Running post-start: fmt (user); fmt (project)
+
+user/fmt.log:
+USER_LOG
+
+project/fmt.log:
+PROJECT_LOG
+
+project/runner.log:
+✗ post-start project:fmt failed (exit code 7)
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_user.snap b/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_user.snap
new file mode 100644
index 000000000..47ca4f391
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__filtered_background_sources_user.snap
@@ -0,0 +1,15 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: "format!(\"announcement:\\n{}\\nuser/fmt.log:\\n{user_log}\\nproject/fmt.log:\\n{project_log}\\n{failing_source}/runner.log:\\n{failure}\",\nString::from_utf8_lossy(&output.stderr),)"
+---
+announcement:
+◎ Running post-start: fmt (user); fmt (project)
+
+user/fmt.log:
+USER_LOG
+
+project/fmt.log:
+PROJECT_LOG
+
+user/runner.log:
+✗ post-start user:fmt failed (exit code 7)
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
index d84b1c024..e879053ee 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
@@ -47,6 +47,6 @@ exit_code: 1
----- stderr -----
◎ Running pre-merge user:first
  echo FIRST_RAN > first_marker.txt
-✗ Failed to expand user:broken: undefined variable does_not_exist @ line 1
+✗ Failed to expand pre-merge user:broken: undefined variable does_not_exist @ line 1
  echo {{ does_not_exist }}
↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_false_true.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_false_true.snap
new file mode 100644
index 000000000..8354c0174
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_false_true.snap
@@ -0,0 +1,9 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: stderr
+---
+◎ Running pre-merge user:first
+  echo ran > first.txt
+✗ Failed to expand pre-merge user:broken: undefined variable does_not_exist @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_true_true.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_true_true.snap
new file mode 100644
index 000000000..8354c0174
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_false_true_true.snap
@@ -0,0 +1,9 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: stderr
+---
+◎ Running pre-merge user:first
+  echo ran > first.txt
+✗ Failed to expand pre-merge user:broken: undefined variable does_not_exist @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_false_true.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_false_true.snap
new file mode 100644
index 000000000..2f8c6410a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_false_true.snap
@@ -0,0 +1,14 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: stderr
+---
+◎ Running post-start user:first
+  echo ran > first.txt
+✗ Failed to expand post-start user:broken: undefined variable does_not_exist @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
+◎ Running post-start user:later
+  echo ran > later.txt
+◎ Running post-start project:project
+  echo ran > project.txt
+
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_false.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_false.snap
new file mode 100644
index 000000000..c38e1b4fe
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_false.snap
@@ -0,0 +1,17 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: stderr
+---
+◎ Running post-start user:first
+  echo ran > first.txt
+✗ Failed to expand post-start user:also_broken: undefined variable missing_too @ line 1
+  echo {{ missing_too }}
+↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
+✗ Failed to expand post-start user:broken: undefined variable does_not_exist @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
+◎ Running post-start user:later
+  echo ran > later.txt
+◎ Running post-start project:project
+  echo ran > project.txt
+
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_true.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_true.snap
new file mode 100644
index 000000000..3eaa43979
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_template_policy_true_true_true.snap
@@ -0,0 +1,16 @@
+---
+source: tests/integration_tests/user_hooks.rs
+expression: stderr
+---
+◎ Running post-start user:first
+  echo ran > first.txt
+✗ Failed to expand post-start user:broken: undefined variable does_not_exist @ line 1
+  echo {{ does_not_exist }}
+↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
+◎ Running post-start user:sibling
+  echo ran > sibling.txt
+◎ Running post-start user:later
+  echo ran > later.txt
+◎ Running post-start project:project
+  echo ran > project.txt
+
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_variable_table.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_variable_table.snap
index e880ee69b..86e9480a7 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_variable_table.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_verbose_variable_table.snap
@@ -60,9 +60,9 @@ exit_code: 0
----- stdout -----
----- stderr -----
-○ user:noop source
+○ pre-switch user:noop source
  true
-○ user:noop result
+○ pre-switch user:noop result
  true
○ pre-switch template variables:
  branch = feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_broken.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_broken.snap
new file mode 100644
index 000000000..7858d4fa7
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_broken.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - post-remove
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to expand post-remove project:broken: syntax error: unexpected end of input, expected end of variable block @ line 1
+  echo {{ invalid
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_unnamed.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_unnamed.snap
new file mode 100644
index 000000000..e3b559558
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_project_unnamed.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - post-remove
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to expand post-remove project hook: syntax error: unexpected end of input, expected end of variable block @ line 1
+  echo {{ invalid
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_broken.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_broken.snap
new file mode 100644
index 000000000..2ad5b0dad
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_broken.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - post-remove
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to expand post-remove user:broken: syntax error: unexpected end of input, expected end of variable block @ line 1
+  echo {{ invalid
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_unnamed.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_unnamed.snap
new file mode 100644
index 000000000..c492d9028
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_remove_invalid_template_user_unnamed.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - hook
+ - post-remove
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to expand post-remove user hook: syntax error: unexpected end of input, expected end of variable block @ line 1
+  echo {{ invalid