Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(hooks): unify dispatch and replace CommandOrigin with closures (#2472)
Maximilian Roosd2ef2ee90ccc
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 5d798ce04..05f9e338a 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -46,8 +46,8 @@ use worktrunk::styling::{use crate::commands::command_approval::approve_alias_commands;use crate::commands::command_executor::{- CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,- build_hook_context, execute_pipeline_foreground,+ AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,+ alias_error_wrapper, build_hook_context, execute_pipeline_foreground,};use crate::commands::hooks::{format_pipeline_summary_from_names, step_names_from_config};use crate::commands::{build_invalid_subcommand_error, similar_subcommands};@@ -542,27 +542,27 @@ fn run_alias(// Build ForegroundSteps: all alias commands use lazy expansion so vars.*// references resolved from git config at execution time are visible to// later steps that set vars via `wt config state vars set`.- let origin = CommandOrigin::Alias {- name: opts.name.clone(),- };+ let alias_name = opts.name.clone();let foreground_steps: Vec<ForegroundStep> = cmd_config.steps().iter().map(|step| {let prepared = match step {HookStep::Single(cmd) => {- PreparedStep::Single(alias_prepared_command(cmd, &context_json))+ PreparedStep::Single(alias_prepared_command(cmd, &context_json, &alias_name))}HookStep::Concurrent(cmds) => PreparedStep::Concurrent(cmds.iter()- .map(|cmd| alias_prepared_command(cmd, &context_json))+ .map(|cmd| alias_prepared_command(cmd, &context_json, &alias_name)).collect(),),};ForegroundStep {step: prepared,- origin: origin.clone(),concurrent: true,+ announce: AnnouncePolicy::None,+ pipe_stdin: false,+ error_wrapper: alias_error_wrapper(alias_name.clone()),}}).collect();@@ -577,12 +577,18 @@ fn run_alias(}/// Build a PreparedCommand for an alias, deferring template expansion to execution time.-fn alias_prepared_command(cmd: &worktrunk::config::Command, context_json: &str) -> PreparedCommand {+fn alias_prepared_command(+ cmd: &worktrunk::config::Command,+ context_json: &str,+ alias_name: &str,+) -> PreparedCommand {PreparedCommand {name: cmd.name.clone(),expanded: cmd.template.clone(),context_json: context_json.to_string(),lazy_template: Some(cmd.template.clone()),+ label: alias_name.to_string(),+ log_label: None,}}diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex a36f3399b..5629947f7 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -259,3 +259,20 @@ pub fn approve_hooks_filtered(let approvals = Approvals::load().context("Failed to load approvals")?;approve_command_batch(&commands, &project_id, &approvals, ctx.yes, false)}++/// Approve `hook_types` and centralize the "decline → continue without hooks" message.+///+/// Returns `true` when approval succeeded (hooks should run) and `false` when the+/// user declined (caller should fall through without hook execution). Emits+/// `on_decline` as an info message on the decline path.+pub fn approve_or_skip(+ ctx: &super::command_executor::CommandContext<'_>,+ hook_types: &[HookType],+ on_decline: &str,+) -> anyhow::Result<bool> {+ let approved = approve_hooks(ctx, hook_types)?;+ if !approved {+ worktrunk::styling::eprintln!("{}", worktrunk::styling::info_message(on_decline));+ }+ Ok(approved)+}diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 43c0570f0..97f53fc6f 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,7 +1,7 @@use std::collections::HashMap;use std::path::{Path, PathBuf};-use anyhow::{Context, Result, bail};+use anyhow::{Context, Result};use color_print::cformat;use worktrunk::HookType;use worktrunk::config::{@@ -28,6 +28,11 @@ pub struct PreparedCommand {/// Raw template for lazy expansion at execution time (when template references `vars.`)./// When `Some`, the `expanded` field is a placeholder — use `lazy_template` instead.pub lazy_template: Option<String>,+ /// Label for template expansion errors and per-command announcement summary.+ /// For hooks: `"user:foo"` for named, `"user"` for unnamed. For aliases: alias name.+ pub label: String,+ /// Log label for command tracing (e.g. `"pre-merge user:foo"`). `None` skips logging.+ pub log_label: Option<String>,}/// A step in a prepared pipeline, mirroring `HookStep`.@@ -47,29 +52,46 @@ impl PreparedStep {}}-/// Where a foreground command originated — determines announcement format,-/// error wrapping, and log label.-#[derive(Clone, Debug)]-pub enum CommandOrigin {- /// Hook command with source attribution.+/// Per-step announcement policy — replaces the per-command match on origin.+///+/// Hook steps render a per-command `Running {type} {label} @ {path}` line plus+/// the bash gutter. Alias steps suppress per-command rendering because the+/// caller emits a single summary line for the whole pipeline.+pub enum AnnouncePolicy {Hook {- source: HookSource,hook_type: HookType,- /// Path shown in announcement when commands run in a different directory- /// than where the user invoked the command.display_path: Option<PathBuf>,},- /// Alias command.- Alias { name: String },+ None,}-/// A pipeline step ready for foreground execution, with origin metadata.+/// Wraps a command failure (FailFast path) into the final error.+///+/// Receives the failing command, the message extracted from the inner error,+/// and the optional exit code (set when the inner error is+/// `WorktrunkError::ChildProcessExited`). Signal-derived errors bypass this+/// wrapper and short-circuit to `AlreadyDisplayed` — see+/// [`handle_command_error`] for the rationale.+///+/// The wrapper is invoked on the calling thread after concurrent children+/// have joined (`run_concurrent_group` folds outcomes serially), so no+/// `Send + Sync` bounds are required.+pub type ErrorWrapper = Box<dyn Fn(&PreparedCommand, String, Option<i32>) -> anyhow::Error>;++/// A pipeline step ready for foreground execution, with rendering / error policy.pub struct ForegroundStep {pub step: PreparedStep,- pub origin: CommandOrigin,/// Whether `Concurrent` steps actually run concurrently. When `false`,/// concurrent commands execute serially (deprecated pre-* table form).pub concurrent: bool,+ /// How to announce each command before execution.+ pub announce: AnnouncePolicy,+ /// Pipe `context_json` to the child's stdin (hooks); when `false`, inherit+ /// the parent's stdin so interactive children keep the controlling tty+ /// (aliases).+ pub pipe_stdin: bool,+ /// Wraps a per-command failure into the final error returned to the caller.+ pub error_wrapper: ErrorWrapper,}/// Controls how foreground execution responds to command failures.@@ -81,6 +103,18 @@ pub enum FailureStrategy {Warn,}+impl FailureStrategy {+ /// Default strategy for a hook type: `pre-*` block (fail-fast),+ /// `post-*` warn-and-continue.+ pub fn default_for(hook_type: HookType) -> Self {+ if hook_type.is_pre() {+ Self::FailFast+ } else {+ Self::Warn+ }+ }+}+#[derive(Clone, Copy, Debug)]pub struct CommandContext<'a> {pub repo: &'a Repository,@@ -297,23 +331,12 @@ pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> St////// This is the canonical foreground execution path for both hooks and aliases./// Handles serial/concurrent step execution, per-command announcement, lazy-/// template resolution, and origin-aware error handling.+/// template resolution, and policy-driven error handling.////// Each `ForegroundStep` carries a `concurrent` flag. When true, `Concurrent`/// steps spawn threads via `thread::scope`. When false (deprecated pre-*/// single-table form), `Concurrent` steps execute serially. Pipeline configs/// (`[[hook]]` blocks), aliases, and post-* hooks set `concurrent: true`.-///-/// TODO(unify-hook-alias): this function centralized dispatch but left four-/// per-origin branch points. Follow-ups to collapse them:-/// 1. Unify the error type: one `CommandFailed { origin_label, exit_code,-/// message }` lets `handle_command_error` drop its origin match.-/// 2. Unify announcement policy (decide per-command vs single-summary for-/// both); `announce_command`'s dispatch disappears.-/// 3. Push log/expansion labels onto `PreparedCommand` at prep time so-/// `command_log_label` / `expansion_label` go away.-/// 4. Longer term: treat hooks as aliases bound to triggers so `hooks.rs`-/// becomes a trigger-dispatcher + config loader over the alias machinery.pub fn execute_pipeline_foreground(steps: &[ForegroundStep],repo: &Repository,@@ -324,31 +347,17 @@ pub fn execute_pipeline_foreground(for fg_step in steps {match &fg_step.step {PreparedStep::Single(cmd) => {- run_one_command(- cmd,- &fg_step.origin,- repo,- wt_path,- directives,- failure_strategy,- )?;+ run_one_command(cmd, fg_step, repo, wt_path, directives, failure_strategy)?;}PreparedStep::Concurrent(cmds) => {if !fg_step.concurrent {for cmd in cmds {- run_one_command(- cmd,- &fg_step.origin,- repo,- wt_path,- directives,- failure_strategy,- )?;+ run_one_command(cmd, fg_step, repo, wt_path, directives, failure_strategy)?;}} else {run_concurrent_group(cmds,- &fg_step.origin,+ fg_step,repo,wt_path,directives,@@ -363,22 +372,22 @@ pub fn execute_pipeline_foreground(/// Run every command in a concurrent group via the prefixed-line executor.///-/// Announces each command up front (origin-aware — hooks render per-command-/// announcements, aliases only announce the outer group), expands all-/// templates sequentially (template expansion reads git config; racing on-/// reads would produce inconsistent state), then dispatches to+/// Announces each command up front (per the step's `AnnouncePolicy` — hooks+/// render per-command announcements, aliases only announce the outer group),+/// expands all templates sequentially (template expansion reads git config;+/// racing on reads would produce inconsistent state), 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],- origin: &CommandOrigin,+ fg_step: &ForegroundStep,repo: &Repository,wt_path: &Path,directives: &DirectivePassthrough,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {for cmd in cmds {- announce_command(cmd, origin);+ announce_command(cmd, &fg_step.announce);}// Commands with `lazy_template` are re-expanded at execution time so@@ -387,20 +396,14 @@ fn run_concurrent_group(let mut expanded: Vec<String> = Vec::with_capacity(cmds.len());for cmd in cmds {if let Some(template) = &cmd.lazy_template {- let label = expansion_label(cmd, origin);let context: HashMap<String, String> = serde_json::from_str(&cmd.context_json).context("failed to deserialize context_json")?;- expanded.push(expand_shell_template(template, &context, repo, &label)?);+ expanded.push(expand_shell_template(template, &context, repo, &cmd.label)?);} else {expanded.push(cmd.expanded.clone());}}- let log_labels: Vec<Option<String>> = cmds- .iter()- .map(|cmd| command_log_label(cmd, origin))- .collect();-// 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@@ -420,7 +423,7 @@ fn run_concurrent_group(expanded: &expanded[i],working_dir: wt_path,context_json: &cmd.context_json,- log_label: log_labels[i].as_deref(),+ log_label: cmd.log_label.as_deref(),directives,}).collect();@@ -430,7 +433,7 @@ fn run_concurrent_group(let mut first_failure: Option<anyhow::Error> = None;for (outcome, cmd) in outcomes.into_iter().zip(cmds) {let Err(err) = outcome else { continue };- match handle_command_error(err, cmd, origin, failure_strategy) {+ match handle_command_error(err, cmd, &fg_step.error_wrapper, failure_strategy) {Ok(()) => {}Err(e) => {if first_failure.is_none() {@@ -448,117 +451,121 @@ fn run_concurrent_group(/// Execute a single prepared command: announce, expand, run, handle errors.fn run_one_command(cmd: &PreparedCommand,- origin: &CommandOrigin,+ fg_step: &ForegroundStep,repo: &Repository,wt_path: &Path,directives: &DirectivePassthrough,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {- announce_command(cmd, origin);+ announce_command(cmd, &fg_step.announce);let lazy_expanded;let command_str = if let Some(template) = &cmd.lazy_template {- let label = expansion_label(cmd, origin);let context: HashMap<String, String> = serde_json::from_str(&cmd.context_json).context("failed to deserialize context_json")?;- lazy_expanded = expand_shell_template(template, &context, repo, &label)?;+ lazy_expanded = expand_shell_template(template, &context, repo, &cmd.label)?;&lazy_expanded} else {&cmd.expanded};- let log_label = command_log_label(cmd, origin);// Hooks get a documented JSON context on stdin; aliases inherit stdin so// interactive children (e.g. `wt switch`'s picker) keep their controlling// terminal. Piping JSON into an interactive alias body steals the tty.- let stdin_json = match origin {- CommandOrigin::Hook { .. } => Some(cmd.context_json.as_str()),- CommandOrigin::Alias { .. } => None,+ let stdin_json = if fg_step.pipe_stdin {+ Some(cmd.context_json.as_str())+ } else {+ None};let result = execute_shell_command(wt_path,command_str,stdin_json,- log_label.as_deref(),+ cmd.log_label.as_deref(),directives.clone(),);match result {Ok(()) => Ok(()),- Err(err) => handle_command_error(err, cmd, origin, failure_strategy),+ Err(err) => handle_command_error(err, cmd, &fg_step.error_wrapper, failure_strategy),}}-/// Announce a command before execution, formatted per origin.+/// Announce a command before execution, formatted per the step's policy.///-/// Hooks get per-command announcements with the expanded command in a gutter.-/// Aliases show a single summary line before the pipeline (in the caller),-/// so no per-command announcement here.-fn announce_command(cmd: &PreparedCommand, origin: &CommandOrigin) {- match origin {- CommandOrigin::Hook {- source,- hook_type,- display_path,- } => {- let summary = command_summary_name(cmd.name.as_deref(), *source);- let full_label = match &cmd.name {- Some(_) => format_command_label(&hook_type.to_string(), Some(&summary)),- None => format!("Running {hook_type} {summary} hook"),- };- let message = match display_path.as_deref() {- Some(path) => {- let path_display = format_path_for_display(path);- cformat!("{full_label} @ <bold>{path_display}</>")- }- None => full_label,- };- if verbosity() >= 1 {- let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)- .expect("context_json is always serialized from a HashMap<String, String>");- let vars = format_hook_variables(*hook_type, &ctx);- eprintln!("{}", info_message("template variables:"));- eprintln!("{}", format_with_gutter(&vars, None));- }- eprintln!("{}", progress_message(message));- eprintln!("{}", format_bash_with_gutter(&cmd.expanded));+/// Hook policies emit a per-command "Running …" line plus the bash gutter.+/// Alias policies (`AnnouncePolicy::None`) emit nothing — the alias caller+/// renders a single pipeline summary externally.+fn announce_command(cmd: &PreparedCommand, policy: &AnnouncePolicy) {+ let AnnouncePolicy::Hook {+ hook_type,+ display_path,+ } = policy+ else {+ return;+ };++ let full_label = match &cmd.name {+ Some(_) => format_command_label(&hook_type.to_string(), Some(&cmd.label)),+ None => format!("Running {hook_type} {} hook", cmd.label),+ };+ let message = match display_path.as_deref() {+ Some(path) => {+ let path_display = format_path_for_display(path);+ cformat!("{full_label} @ <bold>{path_display}</>")}- CommandOrigin::Alias { .. } => {}- }+ None => full_label,+ };+ if verbosity() >= 1 {+ let ctx: HashMap<String, String> = serde_json::from_str(&cmd.context_json)+ .expect("context_json is always serialized from a HashMap<String, String>");+ let vars = format_hook_variables(*hook_type, &ctx);+ eprintln!("{}", info_message("template variables:"));+ eprintln!("{}", format_with_gutter(&vars, None));+ }+ eprintln!("{}", progress_message(message));+ eprintln!("{}", format_bash_with_gutter(&cmd.expanded));}-/// Log label for command tracing: "pre-merge user:foo" for hooks, None for aliases.-fn command_log_label(cmd: &PreparedCommand, origin: &CommandOrigin) -> Option<String> {- match origin {- CommandOrigin::Hook {- source, hook_type, ..- } => {- let summary = command_summary_name(cmd.name.as_deref(), *source);- Some(format!("{hook_type} {summary}"))+/// Build the standard `ErrorWrapper` for hook steps.+///+/// Wraps non-signal failures in `WorktrunkError::HookCommandFailed`. Signal+/// errors short-circuit upstream (see [`handle_command_error`]).+pub fn hook_error_wrapper(hook_type: HookType) -> ErrorWrapper {+ Box::new(move |cmd, err_msg, exit_code| {+ WorktrunkError::HookCommandFailed {+ hook_type,+ command_name: cmd.name.clone(),+ error: err_msg,+ exit_code,}- CommandOrigin::Alias { .. } => None,- }+ .into()+ })}-/// Label used for template expansion error messages.-fn expansion_label(cmd: &PreparedCommand, origin: &CommandOrigin) -> String {- match origin {- CommandOrigin::Hook { source, .. } => command_summary_name(cmd.name.as_deref(), *source),- CommandOrigin::Alias { name } => name.clone(),- }+/// Build the standard `ErrorWrapper` for alias steps.+///+/// Children that report a child exit code surface as `AlreadyDisplayed` so+/// `wt` propagates the alias's exit status. Anything else (template errors,+/// spawn failures) is wrapped with the alias name.+pub fn alias_error_wrapper(alias_name: String) -> ErrorWrapper {+ Box::new(move |_cmd, err_msg, exit_code| match exit_code {+ Some(code) => WorktrunkError::AlreadyDisplayed { exit_code: code }.into(),+ None => anyhow::anyhow!("Failed to run alias '{}': {}", alias_name, err_msg),+ })}-/// Handle a command execution error per origin and failure strategy.+/// Handle a command execution error via the step's `ErrorWrapper`.///-/// Signal-derived child exits (SIGINT/SIGTERM) bypass both `origin` wrapping-/// and `failure_strategy`: the error is returned as `AlreadyDisplayed` with-/// the `128 + signal` exit code so the enclosing loop aborts. This enforces-/// the project-wide Ctrl-C cancellation policy — see the "Signal Handling"+/// Signal-derived child exits (SIGINT/SIGTERM) bypass the wrapper and+/// `failure_strategy`: the error is returned as `AlreadyDisplayed` with the+/// `128 + signal` exit code so the enclosing loop aborts. This enforces the+/// project-wide Ctrl-C cancellation policy — see the "Signal Handling"/// section of the root `CLAUDE.md` for the rationale.fn handle_command_error(err: anyhow::Error,cmd: &PreparedCommand,- origin: &CommandOrigin,+ error_wrapper: &ErrorWrapper,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {if let Some(exit_code) = interrupt_exit_code(&err) {@@ -577,22 +584,7 @@ fn handle_command_error(};match failure_strategy {- FailureStrategy::FailFast => match origin {- CommandOrigin::Hook { hook_type, .. } => Err(WorktrunkError::HookCommandFailed {- hook_type: *hook_type,- command_name: cmd.name.clone(),- error: err_msg,- exit_code,- }- .into()),- CommandOrigin::Alias { name } => {- if let Some(code) = exit_code {- Err(WorktrunkError::AlreadyDisplayed { exit_code: code }.into())- } else {- bail!("Failed to run alias '{}': {}", name, err_msg)- }- }- },+ FailureStrategy::FailFast => Err(error_wrapper(cmd, err_msg, exit_code)),FailureStrategy::Warn => {let message = match &cmd.name {Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),@@ -702,28 +694,31 @@ pub fn prepare_steps(let all_expanded = expand_commands(&all_commands, ctx, extra_vars, hook_type, source, true)?;let mut expanded_iter = all_expanded.into_iter();+ let make_prepared = |cmd: Command, json: String, lazy: Option<String>| -> PreparedCommand {+ let label = command_summary_name(cmd.name.as_deref(), source);+ let log_label = format!("{hook_type} {label}");+ PreparedCommand {+ name: cmd.name,+ expanded: cmd.expanded,+ context_json: json,+ lazy_template: lazy,+ label,+ log_label: Some(log_label),+ }+ };+let mut result = Vec::new();for (step, &size) in steps.iter().zip(&step_sizes) {let chunk: Vec<_> = expanded_iter.by_ref().take(size).collect();match step {HookStep::Single(_) => {let (cmd, json, lazy) = chunk.into_iter().next().unwrap();- result.push(PreparedStep::Single(PreparedCommand {- name: cmd.name,- expanded: cmd.expanded,- context_json: json,- lazy_template: lazy,- }));+ result.push(PreparedStep::Single(make_prepared(cmd, json, lazy)));}HookStep::Concurrent(_) => {let prepared = chunk.into_iter()- .map(|(cmd, json, lazy)| PreparedCommand {- name: cmd.name,- expanded: cmd.expanded,- context_json: json,- lazy_template: lazy,- })+ .map(|(cmd, json, lazy)| make_prepared(cmd, json, lazy)).collect();result.push(PreparedStep::Concurrent(prepared));}@@ -738,11 +733,15 @@ mod tests {use super::*;fn make_cmd(name: Option<&str>) -> PreparedCommand {+ let label = command_summary_name(name, HookSource::User);+ let log_label = format!("pre-merge {label}");PreparedCommand {name: name.map(String::from),expanded: "echo test".to_string(),context_json: "{}".to_string(),lazy_template: None,+ label,+ log_label: Some(log_label),}}@@ -755,12 +754,8 @@ mod tests {}.into();let cmd = make_cmd(Some("lint"));- let origin = CommandOrigin::Hook {- source: HookSource::User,- hook_type: HookType::PreMerge,- display_path: None,- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);+ let wrapper = hook_error_wrapper(HookType::PreMerge);+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();assert!(matches!(@@ -774,36 +769,11 @@ mod tests {#[test]fn test_handle_command_error_hook_failfast_non_child_worktrunk_error() {- // WorktrunkError that isn't ChildProcessExited (line 439 coverage)+ // WorktrunkError that isn't ChildProcessExitedlet err: anyhow::Error = WorktrunkError::CommandNotApproved.into();let cmd = make_cmd(Some("build"));- let origin = CommandOrigin::Hook {- source: HookSource::User,- hook_type: HookType::PreMerge,- display_path: None,- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);- let err = result.unwrap_err();- let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();- assert!(matches!(- wt_err,- WorktrunkError::HookCommandFailed {- exit_code: None,- ..- }- ));- }-- #[test]- fn test_handle_command_error_hook_failfast_other_error() {- let err = anyhow::anyhow!("something else");- let cmd = make_cmd(None);- let origin = CommandOrigin::Hook {- source: HookSource::Project,- hook_type: HookType::PreCommit,- display_path: None,- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);+ let wrapper = hook_error_wrapper(HookType::PreMerge);+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();assert!(matches!(@@ -824,10 +794,8 @@ mod tests {}.into();let cmd = make_cmd(None);- let origin = CommandOrigin::Alias {- name: "deploy".into(),- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);+ let wrapper = alias_error_wrapper("deploy".into());+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();assert!(matches!(@@ -840,10 +808,8 @@ mod tests {fn test_handle_command_error_alias_failfast_other_error() {let err = anyhow::anyhow!("template error");let cmd = make_cmd(None);- let origin = CommandOrigin::Alias {- name: "deploy".into(),- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);+ let wrapper = alias_error_wrapper("deploy".into());+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err_msg = result.unwrap_err().to_string();assert!(err_msg.contains("Failed to run alias 'deploy'"));assert!(err_msg.contains("template error"));@@ -858,61 +824,21 @@ mod tests {}.into();let cmd = make_cmd(Some("lint"));- let origin = CommandOrigin::Hook {- source: HookSource::User,- hook_type: HookType::PostStart,- display_path: None,- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::Warn);+ let wrapper = hook_error_wrapper(HookType::PostStart);+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);assert!(result.is_ok());}#[test]fn test_handle_command_error_warn_unnamed() {+ // Covers the `cmd.name = None` branch of the Warn arm.let err = anyhow::anyhow!("unexpected failure");let cmd = make_cmd(None);- let origin = CommandOrigin::Hook {- source: HookSource::User,- hook_type: HookType::PostStart,- display_path: None,- };- let result = handle_command_error(err, &cmd, &origin, FailureStrategy::Warn);+ let wrapper = hook_error_wrapper(HookType::PostStart);+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);assert!(result.is_ok());}- #[test]- fn test_command_log_label() {- let cmd = make_cmd(Some("lint"));- let hook_origin = CommandOrigin::Hook {- source: HookSource::User,- hook_type: HookType::PreMerge,- display_path: None,- };- assert_eq!(- command_log_label(&cmd, &hook_origin),- Some("pre-merge user:lint".to_string())- );-- let alias_origin = CommandOrigin::Alias {- name: "deploy".into(),- };- assert_eq!(command_log_label(&cmd, &alias_origin), None);- }-- #[test]- fn test_expansion_label() {- let cmd = make_cmd(Some("build"));- let hook_origin = CommandOrigin::Hook {- source: HookSource::Project,- hook_type: HookType::PreStart,- display_path: None,- };- assert_eq!(expansion_label(&cmd, &hook_origin), "project:build");-- let alias_origin = CommandOrigin::Alias { name: "ci".into() };- assert_eq!(expansion_label(&cmd, &alias_origin), "ci");- }-#[test]fn test_template_references_var_for_vars() {// Real vars referencesdiff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 2edb12218..36bebed90 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -8,7 +8,7 @@ use worktrunk::styling::{use super::command_executor::CommandContext;use super::command_executor::FailureStrategy;-use super::hooks::{HookCommandSpec, spawn_background_hooks};+use super::hooks::{execute_hook, spawn_background_hooks};use super::repository_ext::warn_about_untracked_files;// Re-export StageMode from config for use by CLI@@ -177,20 +177,14 @@ impl CommitOptions<'_> {.map(|target| ("target", target)).collect();- // Run pre-commit hooks (user first, then project)- super::hooks::run_hook_with_filter(+ // Run pre-commit hooks (user first, then project).+ execute_hook(self.ctx,- HookCommandSpec {- user_config: user_cfg,- project_config: proj_cfg,- hook_type: HookType::PreCommit,- extra_vars: &extra_vars,- name_filters: &[],- display_path: crate::output::pre_hook_display_path(self.ctx.worktree_path),- },+ HookType::PreCommit,+ &extra_vars,FailureStrategy::FailFast,- )- .map_err(worktrunk::git::add_hook_skip_hint)?;+ crate::output::pre_hook_display_path(self.ctx.worktree_path),+ )?;}// Use the worktree path from context — this is the target worktree whendiff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 45d15234d..722dab5fc 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -10,14 +10,13 @@ use worktrunk::config::{UserConfig, ValidationScope, expand_template, template_references_var, validate_template,};use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};-use worktrunk::styling::{eprintln, info_message};use crate::cli::SwitchFormat;-use super::command_approval::approve_hooks;+use super::command_approval::{approve_hooks, approve_or_skip};use super::command_executor::FailureStrategy;use super::command_executor::{CommandContext, build_hook_context};-use super::hooks::execute_hook;+use super::hooks::{execute_hook, prepare_background_pipelines, run_hooks_background};use super::template_vars::TemplateVars;use super::worktree::{SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, offer_bare_repo_worktree_path_fix,@@ -139,7 +138,6 @@ pub(crate) fn run_pre_switch_hooks(HookType::PreSwitch,&extra_vars,FailureStrategy::FailFast,- &[],crate::output::pre_hook_display_path(pre_ctx.worktree_path),)?;}@@ -178,20 +176,12 @@ pub(crate) fn approve_switch_hooks(}let ctx = CommandContext::new(repo, config, plan.branch(), plan.worktree_path(), yes);- let approved = approve_hooks(&ctx, switch_post_hook_types(plan.is_create()))?;-- if !approved {- eprintln!(- "{}",- info_message(if plan.is_create() {- "Commands declined, continuing worktree creation"- } else {- "Commands declined"- })- );- }-- Ok(approved)+ let on_decline = if plan.is_create() {+ "Commands declined, continuing worktree creation"+ } else {+ "Commands declined"+ };+ approve_or_skip(&ctx, switch_post_hook_types(plan.is_create()), on_decline)}/// Spawn post-switch (and post-start for creates) background hooks.@@ -206,32 +196,19 @@ pub(crate) fn spawn_switch_background_hooks() -> anyhow::Result<()> {let ctx = CommandContext::new(repo, config, branch, result.path(), yes);- let mut pipelines = Vec::new();- pipelines.extend(- super::hooks::prepare_background_hooks(+ let mut pipelines =+ prepare_background_pipelines(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;++ if matches!(result, SwitchResult::Created { .. }) {+ pipelines.extend(prepare_background_pipelines(&ctx,- HookType::PostSwitch,+ HookType::PostStart,extra_vars,hooks_display_path,- )?- .into_iter()- .map(|g| (ctx, g)),- );-- if matches!(result, SwitchResult::Created { .. }) {- pipelines.extend(- super::hooks::prepare_background_hooks(- &ctx,- HookType::PostStart,- extra_vars,- hooks_display_path,- )?- .into_iter()- .map(|g| (ctx, g)),- );+ )?);}- super::hooks::announce_and_spawn_background_hooks(pipelines, false)+ run_hooks_background(pipelines, false)}/// Handle the switch command.diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 3aff91af9..f17107ba4 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -25,11 +25,11 @@ use super::command_approval::approve_hooks_filtered;use super::command_executor::build_hook_context;use super::command_executor::CommandContext;-use super::command_executor::{FailureStrategy, command_summary_name};+use super::command_executor::FailureStrategy;use super::context::CommandEnv;use super::hooks::{- HookCommandSpec, check_name_filter_matched, count_sourced_commands, prepare_sourced_steps,- run_hook_with_filter, spawn_background_hooks, spawn_hook_pipeline,+ HookCommandSpec, lookup_hook_configs, prepare_and_check, prepare_background_pipelines,+ run_hooks_background, run_hooks_foreground,};fn run_filtered_hook(@@ -41,7 +41,7 @@ fn run_filtered_hook(name_filters: &[String],failure_strategy: FailureStrategy,) -> anyhow::Result<()> {- run_hook_with_filter(+ run_hooks_foreground(ctx,HookCommandSpec {user_config,@@ -64,42 +64,42 @@ fn run_post_hook(extra_vars: &[(&str, &str)],name_filters: &[String],) -> anyhow::Result<()> {- // Default to background execution; --foreground is for debugging.- if !foreground.unwrap_or(false) {- if !name_filters.is_empty() {- let steps = prepare_sourced_steps(- ctx,- HookCommandSpec {- user_config,- project_config,- hook_type,- extra_vars,- name_filters,- display_path: None,- },- )?;- check_name_filter_matched(- name_filters,- count_sourced_commands(&steps),+ // --foreground is for debugging; default is background.+ if foreground.unwrap_or(false) {+ return run_filtered_hook(+ ctx,+ user_config,+ project_config,+ hook_type,+ extra_vars,+ name_filters,+ FailureStrategy::Warn,+ );+ }++ // 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.+ let pipelines = if name_filters.is_empty() {+ prepare_background_pipelines(ctx, hook_type, extra_vars, None)?+ } else {+ let flat = prepare_and_check(+ ctx,+ HookCommandSpec {user_config,project_config,- )?;- return spawn_hook_pipeline(ctx, steps);+ hook_type,+ extra_vars,+ name_filters,+ display_path: None,+ },+ )?;+ if flat.is_empty() {+ return Ok(());}-- // No name filter: prepare and spawn source-grouped pipelines.- return spawn_background_hooks(ctx, hook_type, extra_vars, None);- }-- run_filtered_hook(- ctx,- user_config,- project_config,- hook_type,- extra_vars,- name_filters,- FailureStrategy::Warn,- )+ vec![(*ctx, flat)]+ };+ run_hooks_background(pipelines, false)}/// Build best-effort directional vars for manual `wt hook` invocation.@@ -256,10 +256,8 @@ pub fn run_hook(// Get effective user hooks (global + per-project merged)let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let (user_config, proj_config) = (- user_hooks.get(hook_type),- project_config.as_ref().and_then(|c| c.hooks.get(hook_type)),- );+ let (user_config, proj_config) =+ lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);// No hooks configured: warn and exit successfully. Running hooks that// don't exist is a no-op, so scripts can invoke `wt hook <type>`// unconditionally without special-casing empty configuration.@@ -326,7 +324,7 @@ pub fn run_hook(extra_vars.push((ALIAS_ARGS_KEY, &args_json));if dry_run {- let steps = prepare_sourced_steps(+ let steps = prepare_and_check(&ctx,HookCommandSpec {user_config,@@ -337,20 +335,13 @@ pub fn run_hook(display_path: None,},)?;- check_name_filter_matched(- name_filters,- count_sourced_commands(&steps),- user_config,- proj_config,- )?;for sourced in steps {for cmd in sourced.step.into_commands() {- let summary = command_summary_name(cmd.name.as_deref(), sourced.source);let label = if cmd.name.is_some() {- cformat!("{hook_type} <bold>{summary}</> would run:")+ cformat!("{hook_type} <bold>{}</> would run:", cmd.label)} else {- cformat!("{hook_type} <bold>{summary}</> hook would run:")+ cformat!("{hook_type} <bold>{}</> hook would run:", cmd.label)};eprintln!("{}",@@ -364,27 +355,19 @@ pub fn run_hook(return Ok(());}- // Execute the hook based on type- // pre-* hooks are blocking (fail-fast), post-* hooks run in background- match hook_type {- HookType::PreSwitch- | HookType::PreStart- | HookType::PreRemove- | HookType::PreCommit- | HookType::PreMerge => run_filtered_hook(+ // pre-* hooks block (fail-fast); post-* hooks default to background.+ if hook_type.is_pre() {+ run_filtered_hook(&ctx,user_config,proj_config,hook_type,&extra_vars,name_filters,- FailureStrategy::FailFast,- ),- HookType::PostStart- | HookType::PostSwitch- | HookType::PostCommit- | HookType::PostMerge- | HookType::PostRemove => run_post_hook(+ FailureStrategy::default_for(hook_type),+ )+ } else {+ run_post_hook(&ctx,foreground,user_config,@@ -392,7 +375,7 @@ pub fn run_hook(hook_type,&extra_vars,name_filters,- ),+ )}}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 657a4e8ab..513243152 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -12,8 +12,8 @@ use worktrunk::styling::{};use super::command_executor::{- CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,- execute_pipeline_foreground, prepare_steps,+ AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,+ execute_pipeline_foreground, hook_error_wrapper, prepare_steps,};use crate::commands::process::{HookLog, spawn_detached_exec};use crate::output::DirectivePassthrough;@@ -40,7 +40,7 @@ pub struct HookCommandSpec<'cfg, 'vars, 'name, 'path> {////// `display_path`: When `Some`, the path is shown in hook announcements (e.g., "@ ~/repo")./// Use this when commands run in a different directory than where the user invoked the command.-pub fn prepare_sourced_steps(+fn prepare_sourced_steps(ctx: &CommandContext,spec: HookCommandSpec<'_, '_, '_, '_>,) -> anyhow::Result<Vec<SourcedStep>> {@@ -129,7 +129,7 @@ fn filter_step_by_name(}/// Count total commands across all sourced steps (for `check_name_filter_matched`).-pub(crate) fn count_sourced_commands(steps: &[SourcedStep]) -> usize {+fn count_sourced_commands(steps: &[SourcedStep]) -> usize {steps.iter().map(|s| match &s.step {@@ -304,7 +304,7 @@ impl<'a> HookAnnouncer<'a> {/// Add prepared pipelines to the announcer.///- /// Pipelines come from `prepare_background_hooks` / its callers, which+ /// Pipelines come from `prepare_background_pipelines` / its callers, which/// already filter out empty source groups — empty `steps` is unreachable.pub fn extend<'b, I>(&mut self, pipelines: I)where@@ -327,8 +327,8 @@ impl<'a> HookAnnouncer<'a> {extra_vars: &[(&str, &str)],display_path: Option<&Path>,) -> anyhow::Result<()> {- let groups = prepare_background_hooks(ctx, hook_type, extra_vars, display_path)?;- self.extend(groups.into_iter().map(|g| (*ctx, g)));+ let pipelines = prepare_background_pipelines(ctx, hook_type, extra_vars, display_path)?;+ self.extend(pipelines);Ok(())}@@ -361,11 +361,11 @@ impl<'a> HookAnnouncer<'a> {}).collect();- announce_and_spawn_pipelines(pipelines, self.show_branch)+ run_hooks_background(pipelines, self.show_branch)}}-impl<'a> Drop for HookAnnouncer<'a> {+impl Drop for HookAnnouncer<'_> {/// Best-effort flush on drop so hooks registered before an early-return/// error still spawn. Without this, a `register` error in a later phase/// would silently swallow earlier-registered pipelines — a regression@@ -384,37 +384,34 @@ impl<'a> Drop for HookAnnouncer<'a> {}}-/// Announce and spawn background hooks for one or more hook types.+/// Announce and spawn background hook pipelines.///-/// Convenience wrapper around `HookAnnouncer` for sites that produce all-/// pipelines in one place (e.g., post-switch + post-start on create). For-/// commands that fire hooks at multiple moments, use `HookAnnouncer` directly-/// so the whole command shares one announce line.-///-/// Each pipeline carries its own `CommandContext` so that different hook types-/// can use different contexts (e.g., post-remove uses the removed branch while+/// Displays a single combined summary line covering all hook types, then+/// spawns each pipeline independently. Pipelines may carry different+/// `CommandContext`s (e.g., post-remove uses the removed branch while/// post-switch uses the destination branch).-pub fn announce_and_spawn_background_hooks(+///+/// When `show_branch` is true, includes the branch name for disambiguation in batch+/// contexts (e.g., prune removing multiple worktrees):+/// `Running post-remove for feature: docs; post-switch for feature: zellij-tab`+///+/// Without `show_branch`: `Running post-switch: zellij-tab; post-start: deps, assets, docs`+///+/// Sites that fire hooks at multiple moments within the same `wt` command+/// should batch through [`HookAnnouncer`] so all phases share one announce+/// line; this entry is the convenience for callers that produce all pipelines+/// in one place.+pub fn run_hooks_background(pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,show_branch: bool,) -> anyhow::Result<()> {- let non_empty: Vec<_> = pipelines+ let pipelines: Vec<_> = pipelines.into_iter().filter(|(_, steps)| !steps.is_empty()).collect();- if non_empty.is_empty() {+ if pipelines.is_empty() {return Ok(());}- announce_and_spawn_pipelines(non_empty, show_branch)-}--/// Format the combined `Running …` line for `pipelines`, print it, and spawn-/// each source group as an independent pipeline. Caller is responsible for-/// filtering out empty groups before calling.-fn announce_and_spawn_pipelines(- pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,- show_branch: bool,-) -> anyhow::Result<()> {// Build combined summary, merging groups with the same hook type:// "post-switch: zellij-tab; post-start: deps, assets, docs"let display_path = pipelines@@ -474,6 +471,54 @@ fn announce_and_spawn_pipelines(Ok(())}+/// 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>> {+ let mut groups: Vec<Vec<SourcedStep>> = Vec::new();+ for step in flat {+ match groups.last_mut() {+ Some(g) if g.last().is_some_and(|s| s.source == step.source) => g.push(step),+ _ => groups.push(vec![step]),+ }+ }+ groups+}++/// 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`].+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>)>> {+ let project_config = ctx.repo.load_project_config()?;+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+ let (user_config, proj_config) =+ lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);+ let flat = prepare_and_check(+ ctx,+ HookCommandSpec {+ user_config,+ project_config: proj_config,+ hook_type,+ extra_vars,+ name_filters: &[],+ display_path,+ },+ )?;+ Ok(into_source_groups(flat)+ .into_iter()+ .map(|g| (*ctx, g))+ .collect())+}+/// Emit a `template variables:` block per distinct hook type in `pipelines`.////// Background hooks don't flow through `announce_command` (which prints the@@ -504,66 +549,28 @@ fn print_background_variable_tables(pipelines: &[(CommandContext<'_>, Vec<Source}}-/// Prepare and spawn all source-group pipelines for a single hook type.-///-/// Wraps `prepare_background_hooks` + `announce_and_spawn_background_hooks` so-/// callers produce exactly one `Running {hook}: …` announce line even when-/// both user and project configs contribute pipelines. Iterating the prepared-/// groups and calling `spawn_hook_pipeline` per group is a footgun — it prints-/// one announce line per source.-pub fn spawn_background_hooks(- ctx: &CommandContext,- hook_type: HookType,- extra_vars: &[(&str, &str)],- display_path: Option<&Path>,-) -> anyhow::Result<()> {- let pipelines: Vec<_> = prepare_background_hooks(ctx, hook_type, extra_vars, display_path)?- .into_iter()- .map(|g| (*ctx, g))- .collect();- announce_and_spawn_background_hooks(pipelines, false)-}--/// Spawn a filter-matched hook pipeline as a background `wt hook run-pipeline`.-///-/// The name-filter path merges user + project matches into one pipeline (vs.-/// the source-grouped path that produces one pipeline per source). For the-/// source-grouped path, use `spawn_background_hooks` instead.-///-/// `check_name_filter_matched` must have run first — it guarantees `steps` is-/// non-empty. The filter path always calls with `display_path: None`, so no-/// path annotation is rendered.-pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {- let hook_type = steps[0].hook_type;- let summary = format_pipeline_summary(&steps);- eprintln!(- "{}",- progress_message(format!("Running {hook_type}: {summary}"))- );- spawn_hook_pipeline_quiet(ctx, steps)-}-/// Spawn a hook pipeline without displaying a summary line.///-/// Used by `announce_and_spawn_background_hooks` which handles display separately.+/// Used by `run_hooks_background` after the combined announcement is printed.fn spawn_hook_pipeline_quiet(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};let hook_type = steps[0].hook_type;let source = steps[0].source;- // Extract base context from the first command. All steps share the same base context,- // but per-step metadata (hook_name) is stripped — it gets injected per-step by the- // background runner.- let mut context: std::collections::HashMap<String, String> = steps- .iter()- .find_map(|s| match &s.step {- PreparedStep::Single(cmd) => Some(&cmd.context_json),- PreparedStep::Concurrent(cmds) => cmds.first().map(|c| &c.context_json),- })- .map(|json| serde_json::from_str(json).context("failed to deserialize context_json"))- .transpose()?- .unwrap_or_default();+ // Extract base context from the first command. Both call sites+ // (`run_hooks_background` and `run_post_hook`'s filter path) skip empty+ // step lists before reaching here, so `steps[0]` is safe; every step's+ // first command carries the same base context (only `hook_name` differs+ // per step — strip it so the runner re-injects per step).+ debug_assert!(!steps.is_empty(), "spawn_hook_pipeline_quiet: empty steps");+ let first_cmd = match &steps[0].step {+ PreparedStep::Single(cmd) => cmd,+ PreparedStep::Concurrent(cmds) => &cmds[0],+ };+ let mut context: std::collections::HashMap<String, String> =+ serde_json::from_str(&first_cmd.context_json)+ .context("failed to deserialize context_json")?;context.remove("hook_name");// Build pipeline spec from prepared steps. Use the raw template for lazy@@ -627,7 +634,7 @@ fn spawn_hook_pipeline_quiet(ctx: &CommandContext, steps: Vec<SourcedStep>) -> a/// Check if name filters were provided but no commands matched./// Returns an error listing available command names if so.-pub(crate) fn check_name_filter_matched(+fn check_name_filter_matched(name_filters: &[String],total_commands_run: usize,user_config: Option<&CommandConfig>,@@ -671,33 +678,49 @@ pub(crate) fn check_name_filter_matched(Ok(())}-/// Run user and project hooks for a given hook type.-///-/// This is the canonical implementation for running hooks from both sources.-/// Runs user hooks first, then project hooks sequentially. Handles name filtering-/// and returns an error if a name filter was provided but no matching command found.+/// Prepare sourced steps and verify any name filter matched at least one+/// command. Returns the steps (possibly empty if no hooks are configured).///-/// `display_path`: Pass `ctx.hooks_display_path()` for automatic detection, or-/// explicit `Some(path)` when hooks run somewhere the user won't be cd'd to.-pub fn run_hook_with_filter(+/// 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.+pub(crate) fn prepare_and_check(ctx: &CommandContext,spec: HookCommandSpec<'_, '_, '_, '_>,- failure_strategy: FailureStrategy,-) -> anyhow::Result<()> {- let sourced_steps = prepare_sourced_steps(ctx, spec)?;+) -> anyhow::Result<Vec<SourcedStep>> {let HookCommandSpec {user_config,project_config,name_filters,..} = spec;-+ let sourced_steps = prepare_sourced_steps(ctx, spec)?;check_name_filter_matched(name_filters,count_sourced_commands(&sourced_steps),user_config,project_config,)?;+ Ok(sourced_steps)+}++/// Run user and project hooks for a given hook type in the foreground.+///+/// Used directly only by the `wt hook <type>` path, which intentionally+/// leaves errors unwrapped (the user explicitly asked for the hooks; the+/// `--no-hooks` hint would be misleading). Operation-driven callers should go+/// through [`execute_hook`] which auto-looks-up configs and adds the skip+/// hint.+///+/// `display_path` (in the spec): pass `pre_hook_display_path(ctx.worktree_path)`+/// for automatic detection, or `Some(path)` when hooks run somewhere the user+/// won't be cd'd to.+pub(crate) fn run_hooks_foreground(+ ctx: &CommandContext,+ spec: HookCommandSpec<'_, '_, '_, '_>,+ failure_strategy: FailureStrategy,+) -> anyhow::Result<()> {+ let sourced_steps = prepare_and_check(ctx, spec)?;if sourced_steps.is_empty() {return Ok(());@@ -714,11 +737,12 @@ pub fn run_hook_with_filter(.map(|sourced| ForegroundStep {concurrent: sourced.is_pipeline,step: sourced.step,- origin: CommandOrigin::Hook {- source: sourced.source,+ announce: AnnouncePolicy::Hook {hook_type: sourced.hook_type,display_path: sourced.display_path,},+ pipe_stdin: true,+ error_wrapper: hook_error_wrapper(sourced.hook_type),}).collect();@@ -743,36 +767,51 @@ pub(crate) fn lookup_hook_configs<'a>()}-/// Run a hook type with automatic config lookup.+/// Spawn background hooks for a single hook type (post-commit, post-merge, …).///-/// This is a convenience wrapper that:-/// 1. Loads project config from the repository-/// 2. Looks up user hooks from the config-/// 3. Calls `run_hook_with_filter` with the appropriate hook configs-/// 4. Adds the hook skip hint to errors+/// Symmetric to [`execute_hook`] for the background path: auto-loads project+/// config, prepares source-grouped pipelines, and spawns. Single-type callers+/// (commit, step_commands::handle_squash, picker post-remove) prefer this;+/// multi-type batches (handle_switch's PostSwitch + PostStart) build pipelines+/// via [`prepare_background_pipelines`] and call [`run_hooks_background`]+/// directly so all types share one announce line.+pub(crate) fn spawn_background_hooks(+ ctx: &CommandContext,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ display_path: Option<&Path>,+) -> anyhow::Result<()> {+ let pipelines = prepare_background_pipelines(ctx, hook_type, extra_vars, display_path)?;+ run_hooks_background(pipelines, false)+}++/// Run a single hook type in the foreground for an operation (merge, switch,+/// commit, remove, …).///-/// Use this instead of manually looking up configs and calling `run_hook_with_filter`.-pub fn execute_hook(+/// Auto-loads project config, looks up the per-type configs, runs the hooks,+/// and tags failures with `add_hook_skip_hint` so the user sees the+/// `--no-hooks` reminder. This is the canonical operation-driven entry point;+/// the only path that should bypass it is `wt hook <type>` (which calls+/// [`run_hooks_foreground`] directly so failures don't carry the hint).+pub(crate) fn execute_hook(ctx: &CommandContext,hook_type: HookType,extra_vars: &[(&str, &str)],failure_strategy: FailureStrategy,- name_filters: &[String],display_path: Option<&Path>,) -> anyhow::Result<()> {let project_config = ctx.repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());let (user_config, proj_config) =lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);-- run_hook_with_filter(+ run_hooks_foreground(ctx,HookCommandSpec {user_config,project_config: proj_config,hook_type,extra_vars,- name_filters,+ name_filters: &[],display_path,},failure_strategy,@@ -780,55 +819,6 @@ pub fn execute_hook(.map_err(worktrunk::git::add_hook_skip_hint)}-/// Prepare background hooks with automatic config lookup.-///-/// Returns pipeline steps grouped by source — one group per source that has-/// hooks configured. Each group should be spawned as an independent pipeline-/// so that user and project hooks remain independent (a user hook failure-/// doesn't abort project hooks).-pub(crate) fn prepare_background_hooks(- ctx: &CommandContext,- hook_type: HookType,- extra_vars: &[(&str, &str)],- display_path: Option<&Path>,-) -> anyhow::Result<Vec<Vec<SourcedStep>>> {- let project_config = ctx.repo.load_project_config()?;- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let (user_config, proj_config) =- lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);-- let display_path = display_path.map(|p| p.to_path_buf());- let mut groups = Vec::new();-- let sources = [- (HookSource::User, user_config),- (HookSource::Project, proj_config),- ];-- for (source, config) in sources {- let Some(config) = config else { continue };- let is_pipeline = config.is_pipeline();- let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?;- if steps.is_empty() {- continue;- }- groups.push(- steps- .into_iter()- .map(|step| SourcedStep {- step,- source,- hook_type,- display_path: display_path.clone(),- is_pipeline,- })- .collect(),- );- }-- Ok(groups)-}-#[cfg(test)]mod tests {use super::*;@@ -900,11 +890,17 @@ mod tests {}fn make_cmd(name: Option<&str>, expanded: &str) -> PreparedCommand {+ let label = match name {+ Some(n) => format!("user:{n}"),+ None => "user".to_string(),+ };PreparedCommand {name: name.map(String::from),expanded: expanded.to_string(),context_json: "{}".to_string(),lazy_template: None,+ label,+ log_label: None,}}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 72753d2ca..06fe2d017 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -164,11 +164,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// If commands were declined, skip hooks but continue with merge// Shadow verify to gate all subsequent hook execution on approval- let verify = if !approved {+ let verify = if approved {+ verify+ } else {eprintln!("{}", info_message("Commands declined, continuing merge"));false- } else {- verify};// Handle uncommitted changes (skip if --no-commit) - track whether commit occurred@@ -234,7 +234,6 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {HookType::PreMerge,&vars.as_extra_vars(),FailureStrategy::FailFast,- &[],crate::output::pre_hook_display_path(ctx.worktree_path),)?;}diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 8bbc1f6c0..5583f709b 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -206,7 +206,6 @@ impl PickerCollector {worktrunk::HookType::PreRemove,&extra_vars,FailureStrategy::FailFast,- &[],None, // no display path in TUI context)?;diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 2805d2ae6..55673dd94 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -35,11 +35,11 @@ use worktrunk::styling::{verbosity, warning_message,};-use super::command_approval::approve_hooks;+use super::command_approval::approve_or_skip;use super::command_executor::FailureStrategy;use super::commit::{CommitGenerator, CommitOptions, StageMode};use super::context::CommandEnv;-use super::hooks::{HookCommandSpec, run_hook_with_filter, spawn_background_hooks};+use super::hooks::{execute_hook, spawn_background_hooks};use super::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;use worktrunk::git::BranchDeletionMode;@@ -81,20 +81,12 @@ pub fn step_commit(// "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)// Shadow verify: if user declines approval, skip hooks but continue commit- let verify = if verify {- let approved = approve_hooks(&ctx, &[HookType::PreCommit, HookType::PostCommit])?;- if !approved {- eprintln!(- "{}",- info_message("Commands declined, committing without hooks",)- );- false- } else {- true- }- } else {- false // --no-hooks was passed- };+ let verify = verify+ && approve_or_skip(+ &ctx,+ &[HookType::PreCommit, HookType::PostCommit],+ "Commands declined, committing without hooks",+ )?;let mut options = CommitOptions::new(&ctx);options.verify = verify;@@ -159,16 +151,11 @@ pub fn handle_squash(// "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)// Shadow verify: if user declines approval, skip hooks but continue squashlet verify = if verify {- let approved = approve_hooks(&ctx, &[HookType::PreCommit, HookType::PostCommit])?;- if !approved {- eprintln!(- "{}",- info_message("Commands declined, squashing without hooks")- );- false- } else {- true- }+ approve_or_skip(+ &ctx,+ &[HookType::PreCommit, HookType::PostCommit],+ "Commands declined, squashing without hooks",+ )?} else {// Show skip message when --no-hooks was passed and hooks existif any_hooks_exist {@@ -196,22 +183,16 @@ pub fn handle_squash(}}- // Run pre-commit hooks (user first, then project)+ // Run pre-commit hooks (user first, then project).if verify {let extra_vars = [("target", integration_target.as_str())];- run_hook_with_filter(+ execute_hook(&ctx,- HookCommandSpec {- user_config: user_cfg,- project_config: proj_cfg,- hook_type: HookType::PreCommit,- extra_vars: &extra_vars,- name_filters: &[],- display_path: crate::output::pre_hook_display_path(ctx.worktree_path),- },+ HookType::PreCommit,+ &extra_vars,FailureStrategy::FailFast,- )- .map_err(worktrunk::git::add_hook_skip_hint)?;+ crate::output::pre_hook_display_path(ctx.worktree_path),+ )?;}// Get merge base with target branch (required for squash)@@ -1383,18 +1364,15 @@ pub fn step_prune(} else {let env = CommandEnv::for_action_branchless()?;let ctx = env.context(yes);- let approved = approve_hooks(+ approve_or_skip(&ctx,&[HookType::PreRemove,HookType::PostRemove,HookType::PostSwitch,],- )?;- if !approved {- eprintln!("{}", info_message("Commands declined, continuing removal"));- }- approved+ "Commands declined, continuing removal",+ )?};let mut removed: Vec<Candidate> = Vec::new();diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex f803ac86e..c0ffef6f0 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -27,7 +27,6 @@ impl<'a> CommandContext<'a> {HookType::PreStart,extra_vars,FailureStrategy::FailFast,- &[],crate::output::post_hook_display_path(self.worktree_path),)}diff --git a/src/git/mod.rs b/src/git/mod.rsindex a5514474e..36e9bf510 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -434,6 +434,29 @@ pub enum HookType {PostRemove,}+impl HookType {+ /// True for `pre-*` hooks. `pre-*` hooks block the operation and propagate+ /// failures fail-fast; `post-*` hooks run after success and default to+ /// background-with-warn.+ ///+ /// Uses an exhaustive match (not `matches!`) so a new variant trips a+ /// compile-time nudge instead of silently classifying as post-*.+ pub fn is_pre(self) -> bool {+ match self {+ HookType::PreSwitch+ | HookType::PreStart+ | HookType::PreCommit+ | HookType::PreMerge+ | HookType::PreRemove => true,+ HookType::PostSwitch+ | HookType::PostStart+ | HookType::PostCommit+ | HookType::PostMerge+ | HookType::PostRemove => false,+ }+ }+}+/// Reference to a branch for parallel task execution.////// Works for both worktree items (has path) and branch-only items (no worktree).diff --git a/src/main.rs b/src/main.rsindex e98ce3477..606cdf3ca 100644--- a/src/main.rs+++ b/src/main.rs@@ -15,7 +15,7 @@ use worktrunk::styling::{eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,};-use commands::command_approval::approve_hooks;+use commands::command_approval::approve_or_skip;use commands::command_executor::CommandContext;use commands::worktree::RemoveResult;@@ -768,18 +768,15 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {&approve_worktree_path,yes,);- let approved = approve_hooks(+ approve_or_skip(&ctx,&[HookType::PreRemove,HookType::PostRemove,HookType::PostSwitch,],- )?;- if !approved {- eprintln!("{}", info_message("Commands declined, continuing removal"));- }- Ok(approved)+ "Commands declined, continuing removal",+ )};let branches = args.branches;diff --git a/src/output/global.rs b/src/output/global.rsindex b013d71b5..f3e397b89 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -575,10 +575,10 @@ pub fn compute_hooks_display_path<'a>(////// ```ignore/// // In pre-commit, pre-merge, pre-remove hooks:-/// run_hook_with_filter(..., pre_hook_display_path(ctx.worktree_path))?;+/// run_hooks_foreground(..., pre_hook_display_path(ctx.worktree_path))?;////// // In manual wt hook commands (even for post-* hook types):-/// run_hook_with_filter(..., pre_hook_display_path(ctx.worktree_path))?;+/// run_hooks_foreground(..., pre_hook_display_path(ctx.worktree_path))?;/// ```pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::path::Path> {let cwd = match std::env::current_dir() {@@ -601,7 +601,7 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat/// # Examples////// ```ignore-/// // Prepare and spawn hooks with display path:+/// // Spawn hooks with display path:/// spawn_background_hooks(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;/// ```pub fn post_hook_display_path(destination: &std::path::Path) -> Option<&std::path::Path> {diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 2cdc91c1b..99d98fb92 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -12,7 +12,7 @@ use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};use crate::commands::command_executor::CommandContext;use crate::commands::command_executor::FailureStrategy;use crate::commands::hooks::{- HookAnnouncer, announce_and_spawn_background_hooks, execute_hook, prepare_background_hooks,+ HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,};use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,@@ -922,17 +922,12 @@ fn spawn_hooks_after_remove(let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);// Collect post-remove and post-switch hooks for a single combined announcement.- let mut pipelines = Vec::new();- pipelines.extend(- prepare_background_hooks(- &remove_ctx,- worktrunk::HookType::PostRemove,- &extra_vars,- display_path,- )?- .into_iter()- .map(|g| (remove_ctx, g)),- );+ let mut pipelines = prepare_background_pipelines(+ &remove_ctx,+ worktrunk::HookType::PostRemove,+ &extra_vars,+ display_path,+ )?;// Post-switch: only when the user actually changed directory.// Uses its own context with the destination branch for template variables.@@ -945,22 +940,18 @@ fn spawn_hooks_after_remove(if let Some(ref dest_branch) = dest_branch {let switch_ctx =CommandContext::new(repo, &config, dest_branch.as_deref(), ctx.main_path, false);- pipelines.extend(- prepare_background_hooks(- &switch_ctx,- worktrunk::HookType::PostSwitch,- &[],- display_path,- )?- .into_iter()- .map(|g| (switch_ctx, g)),- );+ pipelines.extend(prepare_background_pipelines(+ &switch_ctx,+ worktrunk::HookType::PostSwitch,+ &[],+ display_path,+ )?);}if let Some(announcer) = announcer {announcer.extend(pipelines);} else {- announce_and_spawn_background_hooks(pipelines, ctx.show_branch_in_hooks)?;+ run_hooks_background(pipelines, ctx.show_branch_in_hooks)?;}Ok(())@@ -1235,7 +1226,6 @@ fn execute_pre_remove_hooks_if_needed(worktrunk::HookType::PreRemove,&extra_vars,FailureStrategy::FailFast,- &[],display_path,)}diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 83a524ed4..21d355dd3 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1446,6 +1446,29 @@ approved-commands = ["echo 'PROJECT_POST_START' > project_bg.txt"]// Standalone Hook Execution Tests (wt hook <type>)// ============================================================================+#[rstest]+fn test_standalone_hook_failure_omits_skip_hint(repo: TestRepo) {+ // `wt hook <type>` is the user explicitly requesting hooks. When a hook+ // fails, suggesting `--no-hooks` makes no sense (they didn't ask for the+ // operation that runs hooks; they asked for the hooks themselves). The+ // hint must be reserved for operation-driven hooks (merge, commit, ...).+ repo.write_project_config(r#"pre-merge = "exit 1""#);++ let mut cmd = repo.wt_command();+ cmd.args(["hook", "pre-merge", "--yes"]);++ let output = cmd.output().unwrap();+ assert!(+ !output.status.success(),+ "wt hook pre-merge should fail when hook exits non-zero"+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !stderr.contains("--no-hooks"),+ "wt hook <type> failure must not suggest --no-hooks; got: {stderr}"+ );+}+#[rstest]fn test_standalone_hook_post_create(repo: TestRepo) {// Write project config with pre-start hook