Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(hooks): flatten the hook execution call chain (#3036)
Maximilian Roosa95d1705165b
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex aafe720e4..66b57067c 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -224,12 +224,10 @@ impl CommitOptions<'_> {pub fn commit(self, announcer: &mut HookAnnouncer<'_>) -> anyhow::Result<CommitOutcome> {let project_config = self.ctx.repo.load_project_config()?;let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());- let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(- &user_hooks,- project_config.as_ref(),- HookType::PreCommit,- );- let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();+ let any_hooks_exist = user_hooks.get(HookType::PreCommit).is_some()+ || project_config+ .as_ref()+ .is_some_and(|c| c.hooks.get(HookType::PreCommit).is_some());// Only print "Skipping pre-commit hooks (--no-hooks)" when --no-hooks was actually// passed. If hooks are disabled because the caller declined an approval prompt@@ -249,7 +247,6 @@ impl CommitOptions<'_> {HookType::PreCommit,&template_vars.as_extra_vars(),FailureStrategy::FailFast,- crate::output::pre_hook_display_path(self.ctx.worktree_path),)?;}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 453e32baa..47b5076ae 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -22,39 +22,11 @@ use worktrunk::styling::{};use super::command_approval::approve_hooks_filtered;-use super::command_executor::build_hook_context;--use super::command_executor::CommandContext;-use super::command_executor::FailureStrategy;+use super::command_executor::{CommandContext, FailureStrategy, build_hook_context};use super::context::CommandEnv;-use super::hooks::{- HookAnnouncer, HookCommandSpec, lookup_hook_configs, prepare_and_check, run_hooks_foreground,-};+use super::hooks::{HookAnnouncer, prepare_and_check, run_hooks_foreground};use super::template_vars::TemplateVars;-fn run_filtered_hook(- ctx: &CommandContext,- user_config: Option<&CommandConfig>,- project_config: Option<&CommandConfig>,- hook_type: HookType,- extra_vars: &[(&str, &str)],- name_filters: &[String],- failure_strategy: FailureStrategy,-) -> anyhow::Result<()> {- run_hooks_foreground(- ctx,- HookCommandSpec {- user_config,- project_config,- hook_type,- extra_vars,- name_filters,- display_path: crate::output::pre_hook_display_path(ctx.worktree_path),- },- failure_strategy,- )-}-fn run_post_hook(ctx: &CommandContext,foreground: Option<bool>,@@ -66,7 +38,7 @@ fn run_post_hook() -> anyhow::Result<()> {// --foreground is for debugging; default is background.if foreground.unwrap_or(false) {- return run_filtered_hook(+ return run_hooks_foreground(ctx,user_config,project_config,@@ -80,25 +52,20 @@ fn run_post_hook(// 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 mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);+ 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,- HookCommandSpec {- user_config,- project_config,- hook_type,- extra_vars,- name_filters,- display_path: None,- },+ user_config,+ project_config,+ hook_type,+ extra_vars,+ name_filters,)?;- if flat.is_empty() {- return Ok(());- }- announcer.extend(std::iter::once((*ctx, hook_type, None, flat)));+ // `flat` is non-empty: a filter that matches nothing errors above.+ announcer.add_groups(ctx, hook_type, None, vec![flat]);}announcer.flush()}@@ -247,8 +214,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) =- lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);+ let user_config = user_hooks.get(hook_type);+ let proj_config = project_config.as_ref().and_then(|c| c.hooks.get(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.@@ -312,14 +279,11 @@ pub fn run_hook(if dry_run {let steps = prepare_and_check(&ctx,- HookCommandSpec {- user_config,- project_config: proj_config,- hook_type,- extra_vars: &extra_vars,- name_filters,- display_path: None,- },+ user_config,+ proj_config,+ hook_type,+ &extra_vars,+ name_filters,)?;for sourced in steps {@@ -343,7 +307,7 @@ pub fn run_hook(// pre-* hooks block (fail-fast); post-* hooks default to background.if hook_type.is_pre() {- run_filtered_hook(+ run_hooks_foreground(&ctx,user_config,proj_config,diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsindex 1d5df3b69..e50435bd3 100644--- a/src/commands/hook_plan.rs+++ b/src/commands/hook_plan.rs@@ -55,9 +55,7 @@ use super::command_executor::{};use super::hook_announcement::SourcedStep;use super::hook_filter::HookSource;-use super::hooks::{- HookAnnouncer, into_source_groups, lookup_hook_configs, sourced_steps_to_foreground,-};+use super::hooks::{HookAnnouncer, into_source_groups, sourced_steps_to_foreground};use super::project_config::{ApprovableCommand, Phase};/// One `(hook_type, anchor)`'s frozen, source-tagged selection.@@ -121,8 +119,8 @@ impl<'a> HookPlanBuilder<'a> {pub fn add(&mut self, anchor: &Path, hook_types: &[HookType]) -> &mut Self {let user_hooks = self.user.hooks(self.project_id);for &hook_type in hook_types {- let (user_cfg, proj_cfg) =- lookup_hook_configs(&user_hooks, self.project_config, hook_type);+ let user_cfg = user_hooks.get(hook_type);+ let proj_cfg = self.project_config.and_then(|c| c.hooks.get(hook_type));let mut selection: Selection = Vec::new();if let Some(cfg) = user_cfg {selection.push((HookSource::User, cfg.clone()));@@ -391,7 +389,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 `extend`, with no `load_project_config()` at execution.+/// config-free `add_groups`, 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`]).@@ -406,12 +404,7 @@ pub fn register_planned() -> anyhow::Result<()> {let sourced = render_planned(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type).context("failed to render planned hooks")?;- let dp = display_path.map(Path::to_path_buf);- announcer.extend(- into_source_groups(sourced)- .into_iter()- .map(|g| (*ctx, hook_type, dp.clone(), g)),- );+ announcer.add_groups(ctx, hook_type, display_path, into_source_groups(sourced));Ok(())}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 2bedf0e62..0e67a6e18 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -68,7 +68,7 @@ use std::path::{Path, PathBuf};use anyhow::Context;use color_print::cformat;use worktrunk::HookType;-use worktrunk::config::{CommandConfig, UserConfig, format_hook_variables};+use worktrunk::config::{CommandConfig, format_hook_variables};use worktrunk::git::{Repository, add_hook_skip_hint};use worktrunk::path::format_path_for_display;use worktrunk::styling::{@@ -86,38 +86,28 @@ use crate::output::DirectivePassthrough;// Re-export for backward compatibility with existing importspub use super::hook_filter::{HookSource, ParsedFilter};-/// Shared hook selection and rendering inputs for preparation/execution.-#[derive(Clone, Copy)]-pub struct HookCommandSpec<'cfg, 'vars, 'name, 'path> {- pub user_config: Option<&'cfg CommandConfig>,- pub project_config: Option<&'cfg CommandConfig>,- pub hook_type: HookType,- pub extra_vars: &'vars [(&'vars str, &'vars str)],- pub name_filters: &'name [String],- pub display_path: Option<&'path Path>,-}--/// Prepare hook steps from both user and project configs, preserving pipeline structure.+/// Prepare hook steps from both user and project configs, preserving pipeline+/// structure, and verify any name filter matched at least one command.+/// Returns the steps (possibly empty if no hooks are configured).///-/// Collects steps from user config first, then project config, applying the name filter-/// to individual commands within each step. The filter supports source prefixes:-/// `user:foo` or `project:foo` to run only from one source.+/// Collects steps from user config first, then project config, applying the+/// name filter to individual commands within each step. The filter supports+/// source prefixes: `user:foo` or `project:foo` to run only from one source.///-/// `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.-fn prepare_sourced_steps(+/// 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.+pub(crate) fn prepare_and_check(ctx: &CommandContext,- spec: HookCommandSpec<'_, '_, '_, '_>,+ user_config: Option<&CommandConfig>,+ project_config: Option<&CommandConfig>,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ name_filters: &[String],) -> anyhow::Result<Vec<SourcedStep>> {- let HookCommandSpec {- user_config,- project_config,- hook_type,- extra_vars,- name_filters,- display_path: _,- } = spec;-let parsed_filters: Vec<ParsedFilter<'_>> = name_filters.iter().map(|f| ParsedFilter::parse(f))@@ -150,6 +140,16 @@ fn prepare_sourced_steps(}}+ // Every surviving step keeps at least one command, so an empty result+ // under a non-empty filter means nothing matched.+ if !name_filters.is_empty() && result.is_empty() {+ return Err(no_matching_commands_error(+ name_filters,+ user_config,+ project_config,+ ));+ }+Ok(result)}@@ -183,27 +183,45 @@ fn filter_step_by_name(}}-/// Count total commands across all sourced steps (for `check_name_filter_matched`).-fn count_sourced_commands(steps: &[SourcedStep]) -> usize {- steps+/// Build the error for a name filter that matched no commands, listing the+/// available command names across the filters' source scopes.+fn no_matching_commands_error(+ name_filters: &[String],+ user_config: Option<&CommandConfig>,+ project_config: Option<&CommandConfig>,+) -> anyhow::Error {+ // Show the combined filter string in the error+ let filter_display = name_filters.join(", ");++ let parsed_filters: Vec<ParsedFilter<'_>> = name_filters.iter()- .map(|s| match &s.step {- PreparedStep::Single(_) => 1,- PreparedStep::Concurrent(cmds) => cmds.len(),- })- .sum()-}+ .map(|f| ParsedFilter::parse(f))+ .collect();+ let mut available = Vec::new();-/// One background hook pipeline, carrying its source group of steps with the-/// announce-time metadata (`hook_type`, `display_path`) already resolved.-/// Background flow only ever sees hooks, so the metadata is unwrapped here-/// rather than threaded through `PipelineKind`.-pub(crate) type BackgroundPipeline<'c> = (- CommandContext<'c>,- HookType,- Option<PathBuf>,- Vec<SourcedStep>,-);+ let sources = [+ (HookSource::User, user_config),+ (HookSource::Project, project_config),+ ];+ for (source, config) in sources {+ let Some(config) = config else { continue };+ // Include this source if any filter matches it+ if !parsed_filters.iter().any(|f| f.matches_source(source)) {+ continue;+ }+ available.extend(+ config+ .commands()+ .filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),+ );+ }++ worktrunk::git::GitError::HookCommandNotFound {+ name: filter_display,+ available,+ }+ .into()+}/// Coordinates background hook announcements within a single `wt` command.///@@ -220,16 +238,14 @@ pub(crate) type BackgroundPipeline<'c> = (pub struct HookAnnouncer<'a> {pending: Vec<PendingPipeline>,repo: &'a Repository,- /// Shared config used to rebuild `CommandContext`s at flush time.- config: &'a UserConfig,show_branch: bool,}-/// Owned spawn data for a registered pipeline. Stores enough to rebuild a-/// `CommandContext` at flush time so the announcer can outlive any short-lived-/// contexts at the registration site. 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.+/// One registered background hook pipeline, owned so the announcer can outlive+/// 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`]).struct PendingPipeline {worktree_path: PathBuf,branch: Option<String>,@@ -242,32 +258,35 @@ impl<'a> HookAnnouncer<'a> {/// `show_branch=true` includes the branch name for disambiguation in batch/// contexts (e.g., prune removing multiple worktrees):/// `Running post-remove for feature: docs (user); post-switch for feature: zellij-tab (user)`- pub fn new(repo: &'a Repository, config: &'a UserConfig, show_branch: bool) -> Self {+ pub fn new(repo: &'a Repository, show_branch: bool) -> Self {Self {pending: Vec::new(),repo,- config,show_branch,}}- /// Add prepared pipelines to the announcer.+ /// Add one pipeline per step group, all sharing `hook_type` and+ /// `display_path` and running in `ctx`'s worktree.///- /// Pipelines come from `prepare_background_pipelines` / its callers, which- /// already filter out empty source groups — empty `steps` is unreachable.- /// Each pipeline's hook type and display path are passed alongside the- /// steps; background flow doesn't need `PipelineKind` since it only ever- /// handles hooks (aliases run in the foreground).- pub fn extend<'b, I>(&mut self, pipelines: I)- where- I: IntoIterator<Item = BackgroundPipeline<'b>>,- {- for (ctx, hook_type, display_path, steps) in pipelines {+ /// 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(+ &mut self,+ ctx: &CommandContext<'_>,+ hook_type: HookType,+ display_path: Option<&Path>,+ groups: Vec<Vec<SourcedStep>>,+ ) {+ for steps in groups {+ debug_assert!(!steps.is_empty(), "add_groups: empty step group");self.pending.push(PendingPipeline {worktree_path: ctx.worktree_path.to_path_buf(),branch: ctx.branch.map(String::from),hook_type,- display_path,+ display_path: display_path.map(Path::to_path_buf),steps,});}@@ -276,9 +295,12 @@ 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 filter path), where- /// nothing mutates config between approval and execution. The plan-backed- /// hooks use [`super::hook_plan::register_planned`] instead.+ /// (`pre-commit` / `post-commit` and `wt hook <type>`'s no-filter path),+ /// where nothing mutates config between approval and execution. The+ /// plan-backed hooks use [`super::hook_plan::register_planned`] instead.+ ///+ /// Each source's steps become an independent pipeline so a user hook+ /// failure doesn't abort project hooks.pub fn register(&mut self,ctx: &CommandContext<'_>,@@ -287,14 +309,16 @@ impl<'a> HookAnnouncer<'a> {display_path: Option<&Path>,) -> anyhow::Result<()> {let project_config = ctx.repo.load_project_config()?;- let pipelines = prepare_background_pipelines(+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+ let flat = prepare_and_check(ctx,- project_config.as_ref(),+ user_hooks.get(hook_type),+ project_config.as_ref().and_then(|c| c.hooks.get(hook_type)),hook_type,extra_vars,- display_path,+ &[],)?;- self.extend(pipelines);+ self.add_groups(ctx, hook_type, display_path, into_source_groups(flat));Ok(())}@@ -303,33 +327,11 @@ impl<'a> HookAnnouncer<'a> {/// No-op when nothing was registered. Drains `pending` so the announcer/// can be reused (though one-per-command is the intended pattern).pub fn flush(&mut self) -> anyhow::Result<()> {- let mut pending = std::mem::take(&mut self.pending);+ let pending = std::mem::take(&mut self.pending);if pending.is_empty() {return Ok(());}-- // Borrow `worktree_path` / `branch` from each `pending` slot for- // CommandContext while moving `steps` out via `mem::take`. `pending`- // outlives `pipelines`, so the borrow checker is satisfied.- let pipelines: Vec<_> = pending- .iter_mut()- .map(|p| {- (- CommandContext::new(- self.repo,- self.config,- p.branch.as_deref(),- &p.worktree_path,- false,- ),- p.hook_type,- p.display_path.clone(),- std::mem::take(&mut p.steps),- )- })- .collect();-- run_hooks_background(pipelines, self.show_branch)+ run_hooks_background(self.repo, pending, self.show_branch)}}@@ -355,46 +357,42 @@ 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`/`extend` into it;+/// a [`HookAnnouncer`] (one per command) and `register`/`add_groups` into it;/// `flush` lands here. The function stays separate to keep the announce/spawn/// formatting isolated from the announcer's pending-list bookkeeping.////// Emits a single combined `Running ...` line covering every registered hook/// type (see module-level grammar), with the path suffix at the end. Pipelines-/// may carry different `CommandContext`s (e.g., post-remove uses the removed-/// branch while post-switch uses the destination branch); the announce shares-/// one line because every bundled clause shares the same path.+/// may carry different worktrees (e.g., post-remove uses the removed branch+/// while post-switch uses the destination branch); the announce shares one+/// line because every bundled clause shares the same path.////// When `show_branch` is true, the announce includes the branch name for/// disambiguation in batch contexts (e.g., prune removing multiple worktrees):/// `Running post-remove for feature: user: docs`.fn run_hooks_background(- pipelines: Vec<BackgroundPipeline<'_>>,+ repo: &Repository,+ pipelines: Vec<PendingPipeline>,show_branch: bool,) -> anyhow::Result<()> {- let pipelines: Vec<_> = pipelines- .into_iter()- .filter(|(_, _, _, steps)| !steps.is_empty())- .collect();- if pipelines.is_empty() {- return Ok(());- }-// Merge per-source summaries by hook type so user+project for the same// type render as one clause: `post-merge: sync, push (user); build (project)`.// Pull `display_path` off the first pipeline that has one — every hook// pipeline in this batch shares a path; the path slot is bundle-wide.let mut display_path: Option<&Path> = None;let mut type_summaries: Vec<(HookType, Vec<String>)> = Vec::new();- for (_, hook_type, dp, group) in &pipelines {+ for pipeline in &pipelines {if display_path.is_none() {- display_path = dp.as_deref();+ display_path = pipeline.display_path.as_deref();}- let summary = format_pipeline_summary(group);- if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| ht == hook_type) {+ let summary = format_pipeline_summary(&pipeline.steps);+ if let Some(entry) = type_summaries+ .iter_mut()+ .find(|(ht, _)| *ht == pipeline.hook_type)+ {entry.1.push(summary);} else {- type_summaries.push((*hook_type, vec![summary]));+ type_summaries.push((pipeline.hook_type, vec![summary]));}}@@ -404,7 +402,7 @@ fn run_hooks_background(let branch_suffix = if show_branch {pipelines.first()- .and_then(|(ctx, _, _, _)| ctx.branch)+ .and_then(|p| p.branch.as_deref()).map(|b| cformat!(" for <bold>{b}</>"))} else {None@@ -430,8 +428,8 @@ fn run_hooks_background(};eprintln!("{}", progress_message(message));- for (ctx, hook_type, _, group) in pipelines {- spawn_hook_pipeline_quiet(&ctx, hook_type, group)?;+ for pipeline in &pipelines {+ spawn_hook_pipeline_quiet(repo, pipeline)?;}Ok(())@@ -453,44 +451,6 @@ pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>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. Each-/// group is returned with its `(hook_type, display_path)` metadata.-///-/// `project_config` is the resolved `.config/wt.toml` for this hook's anchor-/// worktree, passed by [`HookAnnouncer::register`] from-/// `ctx.repo.load_project_config()`. Only the invocation-resolved hooks reach-/// here; plan-backed hooks render from the frozen plan instead (see the-/// module-level "Which `.config/wt.toml` a hook reads" docs).-pub(crate) fn prepare_background_pipelines<'c>(- ctx: &CommandContext<'c>,- project_config: Option<&worktrunk::config::ProjectConfig>,- hook_type: HookType,- extra_vars: &[(&str, &str)],- display_path: Option<&Path>,-) -> anyhow::Result<Vec<BackgroundPipeline<'c>>> {- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let (user_config, proj_config) = lookup_hook_configs(&user_hooks, project_config, hook_type);- let flat = prepare_and_check(- ctx,- HookCommandSpec {- user_config,- project_config: proj_config,- hook_type,- extra_vars,- name_filters: &[],- display_path,- },- )?;- let display_path_owned = display_path.map(|p| p.to_path_buf());- Ok(into_source_groups(flat)- .into_iter()- .map(|g| (*ctx, hook_type, display_path_owned.clone(), g))- .collect())-}-/// Emit a `template variables:` block for one hook type, using the first/// matching pipeline's first step context.///@@ -498,14 +458,13 @@ pub(crate) fn prepare_background_pipelines<'c>(/// table in the foreground path), so this is the symmetric entry point./// Called once per hook type from `run_hooks_background`, immediately before/// that hook type's `Running ...` line, so each hook type reads as one block.-fn print_background_variable_table(pipelines: &[BackgroundPipeline<'_>], hook_type: HookType) {- for (_, ht, _, group) in pipelines {- if *ht != hook_type {+fn print_background_variable_table(pipelines: &[PendingPipeline], hook_type: HookType) {+ for pipeline in pipelines {+ if pipeline.hook_type != hook_type {continue;}- // `into_source_groups` produces non-empty groups, and- // `run_hooks_background` filters empties — `group[0]` is safe.- let cmd = match &group[0].step {+ // Pipelines carry non-empty steps by construction — `steps[0]` is safe.+ let cmd = match &pipeline.steps[0].step {PreparedStep::Single(cmd) => cmd,PreparedStep::Concurrent(cmds) => &cmds[0],};@@ -523,21 +482,16 @@ fn print_background_variable_table(pipelines: &[BackgroundPipeline<'_>], hook_ty/// Spawn a hook pipeline without displaying a summary line.////// Used by `run_hooks_background` after the combined announcement is printed.-fn spawn_hook_pipeline_quiet(- ctx: &CommandContext,- hook_type: HookType,- steps: Vec<SourcedStep>,-) -> anyhow::Result<()> {+fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> anyhow::Result<()> {use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};+ // Extract base context from the first command. Registration never adds an+ // empty step group (asserted in `add_groups`), 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).+ let steps = &pipeline.steps;let source = steps[0].source;-- // 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],@@ -568,14 +522,17 @@ fn spawn_hook_pipeline_quiet(}).collect();+ // "HEAD" fallback matches `CommandContext::branch_or_head` for detached HEAD.+ let branch = pipeline.branch.as_deref().unwrap_or("HEAD");+ let hook_type = pipeline.hook_type;let spec = PipelineSpec {- worktree_path: ctx.worktree_path.to_path_buf(),- branch: ctx.branch_or_head().to_string(),+ worktree_path: pipeline.worktree_path.clone(),+ branch: branch.to_string(),hook_type,source,context,steps: spec_steps,- log_dir: ctx.repo.wt_logs_dir(),+ log_dir: repo.wt_logs_dir(),};let spec_json = serde_json::to_vec(&spec).context("failed to serialize pipeline spec")?;@@ -586,11 +543,11 @@ fn spawn_hook_pipeline_quiet(let log_label = format!("{hook_type} {source} runner");if let Err(err) = spawn_detached_exec(- ctx.repo,- ctx.worktree_path,+ repo,+ &pipeline.worktree_path,&wt_bin,&["hook", "run-pipeline"],- ctx.branch_or_head(),+ branch,&hook_log,&spec_json,) {@@ -606,78 +563,6 @@ fn spawn_hook_pipeline_quiet(Ok(())}-/// Check if name filters were provided but no commands matched.-/// Returns an error listing available command names if so.-fn check_name_filter_matched(- name_filters: &[String],- total_commands_run: usize,- user_config: Option<&CommandConfig>,- project_config: Option<&CommandConfig>,-) -> anyhow::Result<()> {- if !name_filters.is_empty() && total_commands_run == 0 {- // Show the combined filter string in the error- let filter_display = name_filters.join(", ");-- // Use the first filter to determine source scope for available commands,- // but collect across all filters' source scopes- let parsed_filters: Vec<ParsedFilter<'_>> = name_filters- .iter()- .map(|f| ParsedFilter::parse(f))- .collect();- let mut available = Vec::new();-- let sources = [- (HookSource::User, user_config),- (HookSource::Project, project_config),- ];- for (source, config) in sources {- let Some(config) = config else { continue };- // Include this source if any filter matches it- if !parsed_filters.iter().any(|f| f.matches_source(source)) {- continue;- }- available.extend(- config- .commands()- .filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),- );- }-- return Err(worktrunk::git::GitError::HookCommandNotFound {- name: filter_display,- available,- }- .into());- }- Ok(())-}--/// Prepare sourced steps and verify any name filter matched at least one-/// command. Returns the steps (possibly empty if no hooks are configured).-///-/// 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<'_, '_, '_, '_>,-) -> 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)-}-/// Convert source-tagged steps into foreground steps with pipeline-kind policy.////// Shared between hook and alias dispatch. The `kind` argument supplies the@@ -735,24 +620,36 @@ pub(crate) fn sourced_steps_to_foreground(/// 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.+/// The announcement shows the worktree path when commands run somewhere other+/// than the user's cwd ([`crate::output::pre_hook_display_path`] — pre-hooks+/// and manual `wt hook` invocations both run with the user still at cwd).pub(crate) fn run_hooks_foreground(ctx: &CommandContext,- spec: HookCommandSpec<'_, '_, '_, '_>,+ user_config: Option<&CommandConfig>,+ project_config: Option<&CommandConfig>,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ name_filters: &[String],failure_strategy: FailureStrategy,) -> anyhow::Result<()> {- let kind = PipelineKind::Hook {- hook_type: spec.hook_type,- display_path: spec.display_path.map(|p| p.to_path_buf()),- };- let sourced_steps = prepare_and_check(ctx, spec)?;+ let sourced_steps = prepare_and_check(+ ctx,+ user_config,+ project_config,+ hook_type,+ extra_vars,+ name_filters,+ )?;if sourced_steps.is_empty() {return Ok(());}+ let kind = PipelineKind::Hook {+ hook_type,+ display_path: crate::output::pre_hook_display_path(ctx.worktree_path)+ .map(Path::to_path_buf),+ };let foreground_steps = sourced_steps_to_foreground(sourced_steps, &kind);execute_pipeline_foreground(@@ -763,18 +660,6 @@ pub(crate) fn run_hooks_foreground()}-/// Look up user and project configs for a given hook type.-pub(crate) fn lookup_hook_configs<'a>(- user_hooks: &'a worktrunk::config::HooksConfig,- project_config: Option<&'a worktrunk::config::ProjectConfig>,- hook_type: HookType,-) -> (Option<&'a CommandConfig>, Option<&'a CommandConfig>) {- (- user_hooks.get(hook_type),- project_config.and_then(|c| c.hooks.get(hook_type)),- )-}-/// Run a single hook type in the foreground for an operation (merge, switch,/// commit, remove, …).///@@ -792,22 +677,16 @@ pub(crate) fn execute_hook(hook_type: HookType,extra_vars: &[(&str, &str)],failure_strategy: FailureStrategy,- 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_hooks_foreground(ctx,- HookCommandSpec {- user_config,- project_config: proj_config,- hook_type,- extra_vars,- name_filters: &[],- display_path,- },+ user_hooks.get(hook_type),+ project_config.as_ref().and_then(|c| c.hooks.get(hook_type)),+ hook_type,+ extra_vars,+ &[],failure_strategy,).map_err(add_hook_skip_hint)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 700e43560..518019c01 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -267,7 +267,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// (from auto-commit or squash), post-remove + post-switch (from worktree// removal), and post-merge share a single `◎ Running …` line flushed at// the end.- let mut announcer = HookAnnouncer::new(repo, config, false);+ let mut announcer = HookAnnouncer::new(repo, false);// The project commit-append is gated independently of hook approval:// declining it drops only the append, never the (possibly already-approved)diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 8449ebeea..31908b0c7 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -290,7 +290,7 @@ impl PickerCollector {} => {let main_repo = Repository::at(main_path)?;let plan = approved_removal_plan(repo, main_path, worktree_path, approvals)?;- let mut announcer = HookAnnouncer::new(&main_repo, main_repo.user_config(), false);+ let mut announcer = HookAnnouncer::new(&main_repo, false);handle_remove_output(result,/* foreground */ true,diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex 2fd85a120..04438191e 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -65,7 +65,7 @@ pub fn step_commit(// Only warn about untracked if we're staging alloptions.warn_about_untracked = stage_mode == StageMode::All;- let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);+ let mut announcer = HookAnnouncer::new(ctx.repo, false);let outcome = options.commit(&mut announcer)?;announcer.flush()?;Ok(Some(outcome))diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 03c7904be..baaa1de60 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -217,7 +217,7 @@ fn try_remove(candidate: &Candidate, ctx: &RemovalContext<'_>) -> anyhow::Resultreturn Ok(false);}};- let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, true);+ let mut announcer = HookAnnouncer::new(ctx.repo, true);// `SynchronousForNonCurrent`: prune keeps the rename-failure fallback's// `.git/config` rewrite serialized with its integration-check readers.handle_remove_output(diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex c03ebb197..acaf8549d 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -16,7 +16,7 @@ use super::super::command_approval::{use super::super::command_executor::FailureStrategy;use super::super::commit::{CommitGenerator, CommitOutcome, HookGate, StageMode};use super::super::context::CommandEnv;-use super::super::hooks::{self, HookAnnouncer, execute_hook};+use super::super::hooks::{HookAnnouncer, execute_hook};use super::super::repository_ext::RepositoryCliExt;use super::super::template_vars::TemplateVars;use super::shared::print_dry_run;@@ -107,9 +107,10 @@ pub fn handle_squash(// Check if any pre-commit hooks exist (needed for skip message and approval)let project_config = repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let (user_cfg, proj_cfg) =- hooks::lookup_hook_configs(&user_hooks, project_config.as_ref(), HookType::PreCommit);- let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();+ let any_hooks_exist = user_hooks.get(HookType::PreCommit).is_some()+ || project_config+ .as_ref()+ .is_some_and(|c| c.hooks.get(HookType::PreCommit).is_some());// Resolve the hook gate: Run triggers an approval prompt and downgrades to Silent// on decline (approve_or_skip prints its own message). NoHooksFlag prints the skip@@ -163,7 +164,6 @@ pub fn handle_squash(HookType::PreCommit,&template_vars.as_extra_vars(),FailureStrategy::FailFast,- crate::output::pre_hook_display_path(ctx.worktree_path),)?;}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex afc7f9a0c..65fb65dd8 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1358,7 +1358,6 @@ fn run_pre_switch_hooks(HookType::PreSwitch,&extra_vars,FailureStrategy::FailFast,- crate::output::pre_hook_display_path(pre_ctx.worktree_path),)?;}Ok(())@@ -1443,7 +1442,7 @@ fn spawn_switch_background_hooks(let hook_repo = Repository::at(result.path())?;let ctx = CommandContext::new(&hook_repo, config, branch, result.path(), yes);- let mut announcer = HookAnnouncer::new(&hook_repo, config, false);+ let mut announcer = HookAnnouncer::new(&hook_repo, false);register_planned(&mut announcer,hook_plan,@@ -1977,11 +1976,8 @@ fn validate_switch_templates(let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());for &hook_type in switch_post_hook_types(plan.is_create()) {- let (user_cfg, proj_cfg) = crate::commands::hooks::lookup_hook_configs(- &user_hooks,- project_config.as_ref(),- hook_type,- );+ 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)] {if let Some(cfg) = cfg {for cmd in cfg.commands() {diff --git a/src/main.rs b/src/main.rsindex ac7bed18f..7c1c642ec 100644--- a/src/main.rs+++ b/src/main.rs@@ -260,13 +260,12 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {} else {// Approval is handled inside handle_squash (like step_commit).let repo = Repository::current()?;- let config = UserConfig::load().context("Failed to load config")?;let hooks = if verify {HookGate::Run} else {HookGate::NoHooksFlag};- let mut announcer = HookAnnouncer::new(&repo, &config, false);+ let mut announcer = HookAnnouncer::new(&repo, false);let format = args.format;let result = handle_squash(args.target.as_deref(),@@ -1019,7 +1018,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {yes,)?;- let mut announcer = HookAnnouncer::new(&repo, &config, false);+ let mut announcer = HookAnnouncer::new(&repo, false);handle_remove_output(&result,args.foreground,@@ -1082,7 +1081,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {let show_branch =plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;let run = |result: &RemoveResult| -> anyhow::Result<()> {- let mut announcer = HookAnnouncer::new(&repo, &config, show_branch);+ let mut announcer = HookAnnouncer::new(&repo, show_branch);handle_remove_output(result,args.foreground,diff --git a/src/output/global.rs b/src/output/global.rsindex 31eab7b01..052d9e6c8 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -603,11 +603,10 @@ pub fn compute_hooks_display_path<'a>(/// # Examples////// ```ignore-/// // In pre-commit, pre-merge, pre-remove hooks:-/// run_hooks_foreground(..., pre_hook_display_path(ctx.worktree_path))?;-///-/// // In manual wt hook commands (even for post-* hook types):-/// run_hooks_foreground(..., pre_hook_display_path(ctx.worktree_path))?;+/// // `run_hooks_foreground` computes this internally for all foreground+/// // hooks (including manual `wt hook` runs of post-* hook types);+/// // plan-backed pre-hooks pass it explicitly:+/// execute_planned_hook(..., 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() {