Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(hooks): enable concurrent execution in pre-* pipeline blocks (#2249)
Maximilian Roosea9a52dfdcc3
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 8291290e1..716bec104 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -251,7 +251,7 @@ build = "npm run build"lint = "npm run lint"```-When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order:+When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order. A failing step aborts the rest of the pipeline:```toml# Two blocks, run in order.@@ -273,12 +273,6 @@ In summary, the bracket count tracks the shape:- `[post-start]` — one section of concurrent commands- `[[post-start]]` — one of multiple sections, run in order-## How it works--Steps run in order. A failing step aborts the pipeline — later steps don't run. A multi-entry map spawns its commands concurrently and waits for all to complete before the next step.--Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.-## When to use pipelinesMost hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex e58a4c2eb..e3791180b 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -249,7 +249,7 @@ build = "npm run build"lint = "npm run lint"```-When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order:+When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order. A failing step aborts the rest of the pipeline:```toml# Two blocks, run in order.@@ -271,12 +271,6 @@ In summary, the bracket count tracks the shape:- `[post-start]` — one section of concurrent commands- `[[post-start]]` — one of multiple sections, run in order-## How it works--Steps run in order. A failing step aborts the pipeline — later steps don't run. A multi-entry map spawns its commands concurrently and waits for all to complete before the next step.--Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.-## When to use pipelinesMost hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 81c5c7b28..f837adc2e 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1455,7 +1455,7 @@ build = "npm run build"lint = "npm run lint"```-When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order:+When one command depends on another — `npm run build` needs `npm install` to finish first — use `[[hook]]` blocks to run steps in order. A failing step aborts the rest of the pipeline:```toml# Two blocks, run in order.@@ -1477,12 +1477,6 @@ In summary, the bracket count tracks the shape:- `[post-start]` — one section of concurrent commands- `[[post-start]]` — one of multiple sections, run in order-## How it works--Steps run in order. A failing step aborts the pipeline — later steps don't run. A multi-entry map spawns its commands concurrently and waits for all to complete before the next step.--Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.-## When to use pipelinesMost hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex fd74f3461..8c0f0553a 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -386,6 +386,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {ForegroundStep {step: prepared,origin: origin.clone(),+ concurrent: true,}}).collect();@@ -396,7 +397,6 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {&wt_path,&directives,FailureStrategy::FailFast,- true, // aliases support concurrent execution)}diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 4bb061c44..77a67cbd0 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -64,6 +64,9 @@ pub enum CommandOrigin {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,}/// Controls how foreground execution responds to command failures.@@ -272,11 +275,10 @@ pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> St/// Handles serial/concurrent step execution, per-command announcement, lazy/// template resolution, and origin-aware error handling.///-/// When `concurrent` is true, `Concurrent` steps spawn threads via-/// `thread::scope`. When false (foreground hooks), `Concurrent` steps execute-/// serially — a compat fallback for the **deprecated** pre-hook table form.-/// The canonical pre-* hook shape is a list of `Single` steps; concurrent-/// execution is reserved for aliases and the background pipeline runner.+/// 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:@@ -294,7 +296,6 @@ pub fn execute_pipeline_foreground(wt_path: &Path,directives: &DirectivePassthrough,failure_strategy: FailureStrategy,- concurrent: bool,) -> anyhow::Result<()> {for fg_step in steps {match &fg_step.step {@@ -309,7 +310,7 @@ pub fn execute_pipeline_foreground()?;}PreparedStep::Concurrent(cmds) => {- if !concurrent {+ if !fg_step.concurrent {for cmd in cmds {run_one_command(cmd,@@ -356,20 +357,19 @@ fn run_concurrent_group(announce_command(cmd, origin);}- // The concurrent path requires `lazy_template` so expansion sees the- // fresh git-config state at execution time (prior pipeline steps may- // have set `vars.*`). Alias prep sets this unconditionally; hook prep- // will when concurrent hooks ship.+ // Commands with `lazy_template` are re-expanded at execution time so+ // they see fresh git-config state (e.g., `vars.*` set by earlier steps).+ // Commands without it were already expanded at prep time — use `expanded`.let mut expanded: Vec<String> = Vec::with_capacity(cmds.len());for cmd in cmds {- let template = cmd- .lazy_template- .as_ref()- .expect("concurrent group commands must carry a 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)?);+ 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)?);+ } else {+ expanded.push(cmd.expanded.clone());+ }}let log_labels: Vec<Option<String>> = cmds@@ -377,10 +377,8 @@ fn run_concurrent_group(.map(|cmd| command_log_label(cmd, origin)).collect();- // Alias tables always produce named commands (TOML keys become `name`),- // and the concurrent path is alias-only today — so `cmd.name` is always- // `Some` here. When foreground concurrent hooks eventually ship, this- // will need an origin-aware fallback; for now, require the name.+ // 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.iter().map(|cmd| {diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 91e568f92..ad4ae6161 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -69,6 +69,7 @@ pub fn prepare_sourced_steps(continue;}+ let is_pipeline = config.is_pipeline();let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?;for step in steps {if let Some(filtered) = filter_step_by_name(step, &parsed_filters) {@@ -77,6 +78,7 @@ pub fn prepare_sourced_steps(source,hook_type,display_path: display_path.clone(),+ is_pipeline,});}}@@ -139,6 +141,10 @@ pub struct SourcedStep {pub source: HookSource,pub hook_type: HookType,pub display_path: Option<PathBuf>,+ /// Whether this step came from a pipeline config (`[[hook]]` blocks).+ /// Pipeline `Concurrent` steps run concurrently; non-pipeline `Concurrent`+ /// steps (deprecated single-table form) run serially.+ pub is_pipeline: bool,}/// Format a pipeline summary from per-step command names.@@ -502,9 +508,13 @@ pub fn run_hook_with_filter(let directives = DirectivePassthrough::inherit_from_env();// Convert SourcedSteps → ForegroundSteps for the shared executor.+ // Pipeline configs (`[[hook]]` blocks) get concurrent execution within each+ // block. Non-pipeline configs (deprecated single-table `[hook]` form) run+ // their commands serially.let foreground_steps: Vec<ForegroundStep> = sourced_steps.into_iter().map(|sourced| ForegroundStep {+ concurrent: sourced.is_pipeline,step: sourced.step,origin: CommandOrigin::Hook {source: sourced.source,@@ -514,18 +524,12 @@ pub fn run_hook_with_filter(}).collect();- // Foreground hooks always execute serially, even when the prepared step is- // `Concurrent`. That input shape is the deprecated pre-hook table form — we- // still accept it but run it sequentially ("for pre-* hooks, commands in a- // table run sequentially", `src/cli/mod.rs`). Concurrent execution is- // reserved for aliases and the background pipeline runner (`run_pipeline.rs`).execute_pipeline_foreground(&foreground_steps,ctx.repo,ctx.worktree_path,&directives,failure_strategy,- false,)}@@ -605,6 +609,7 @@ pub(crate) fn prepare_background_hooks(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;@@ -617,6 +622,7 @@ pub(crate) fn prepare_background_hooks(source,hook_type,display_path: display_path.clone(),+ is_pipeline,}).collect(),);@@ -691,6 +697,7 @@ mod tests {source: HookSource::User,hook_type: worktrunk::HookType::PostStart,display_path: None,+ is_pipeline: false,}}diff --git a/src/config/commands.rs b/src/config/commands.rsindex bac58a910..6d318f14a 100644--- a/src/config/commands.rs+++ b/src/config/commands.rs@@ -77,10 +77,12 @@ impl Command {/// A step in a hook pipeline.///-/// The execution model depends on the hook type:+/// The execution model depends on the hook type and config form:/// - **Post-* hooks**: `Single` steps run serially, `Concurrent` steps spawn in parallel./// The entire pipeline runs in the background as one detached process.-/// - **Pre-* hooks**: All commands run serially regardless of step type.+/// - **Pre-* hooks (pipeline form)**: `Single` steps run serially, `Concurrent` steps+/// run in parallel. The pipeline blocks until complete.+/// - **Pre-* hooks (deprecated table form)**: All commands run serially.#[derive(Debug, Clone, PartialEq)]pub enum HookStep {/// A single command (from a string in a list, or a single-entry map).@@ -100,6 +102,10 @@ pub enum HookStep {#[derive(Debug, Clone, PartialEq)]pub struct CommandConfig {steps: Vec<HookStep>,+ /// Whether this config was deserialized from a pipeline form (TOML array:+ /// `[[hook]]` blocks or inline `hook = [...]`). Non-pipeline forms are a+ /// bare string (`hook = "cmd"`) or a single table (`[hook]`).+ pipeline: bool,}impl CommandConfig {@@ -107,6 +113,7 @@ impl CommandConfig {pub fn single(template: impl Into<String>) -> Self {Self {steps: vec![HookStep::Single(Command::new(None, template.into()))],+ pipeline: false,}}@@ -118,10 +125,10 @@ impl CommandConfig {})}- /// Returns true if this config uses a pipeline (list form with multiple steps).- /// Single-step configs (string or map) return false.+ /// Whether this config uses a pipeline form (`[[hook]]` blocks or inline array).+ /// A single `[[hook]]` block counts as a pipeline even though it has one step.pub fn is_pipeline(&self) -> bool {- self.steps.len() > 1+ self.pipeline}/// Returns the pipeline steps for execution.@@ -135,7 +142,10 @@ impl CommandConfig {pub fn merge_append(&self, other: &Self) -> Self {let mut steps = self.steps.clone();steps.extend(other.steps.iter().cloned());- Self { steps }+ Self {+ steps,+ pipeline: self.pipeline || other.pipeline,+ }}}@@ -262,6 +272,7 @@ impl<'de> Deserialize<'de> for CommandConfig {fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {Ok(CommandConfig {steps: vec![HookStep::Single(Command::new(None, v.to_string()))],+ pipeline: false,})}@@ -284,7 +295,10 @@ impl<'de> Deserialize<'de> for CommandConfig {}}}- Ok(CommandConfig { steps })+ Ok(CommandConfig {+ steps,+ pipeline: true,+ })}fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>@@ -303,6 +317,7 @@ impl<'de> Deserialize<'de> for CommandConfig {.collect();Ok(CommandConfig {steps: vec![HookStep::Concurrent(commands)],+ pipeline: false,})}}@@ -722,6 +737,7 @@ broken = 42None,"npm install".to_string(),))],+ pipeline: false,},};@@ -741,6 +757,7 @@ broken = 42Command::new(Some("build".to_string()), "cargo build".to_string()),Command::new(Some("test".to_string()), "cargo test".to_string()),])],+ pipeline: false,},};@@ -767,6 +784,7 @@ broken = 42Command::new(Some("lint".to_string()), "npm run lint".to_string()),]),],+ pipeline: true,},};@@ -780,6 +798,7 @@ broken = 42None,"echo hello".to_string(),))],+ pipeline: false,};#[derive(Serialize, Deserialize)]@@ -805,6 +824,7 @@ broken = 42Command::new(Some("a".to_string()), "echo a".to_string()),Command::new(Some("b".to_string()), "echo b".to_string()),])],+ pipeline: false,};#[derive(Serialize, Deserialize)]@@ -834,6 +854,7 @@ broken = 42]),HookStep::Single(Command::new(None, "cmd4".to_string())),],+ pipeline: true,};let cmds: Vec<_> = config.commands().collect();@@ -852,12 +873,14 @@ broken = 42fn test_merge_append_steps() {let base = CommandConfig {steps: vec![HookStep::Single(Command::new(None, "step1".to_string()))],+ pipeline: false,};let overlay = CommandConfig {steps: vec![HookStep::Concurrent(vec![Command::new(Some("a".to_string()), "step2a".to_string()),Command::new(Some("b".to_string()), "step2b".to_string()),])],+ pipeline: false,};let merged = base.merge_append(&overlay);@@ -883,12 +906,14 @@ broken = 42None,"npm install".to_string(),))],+ pipeline: false,};let per_project = CommandConfig {steps: vec![HookStep::Concurrent(vec![Command::new(Some("setup".to_string()),"echo setup".to_string(),)])],+ pipeline: false,};let merged = global.merge_append(&per_project);diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex f0e82b940..e253f08d1 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -3100,3 +3100,104 @@ setup = "'{wt_toml}' switch --create hook-created --no-hooks""inner wt should not warn about shell integration being uninstalled, got: {stderr}",);}++// ============================================================================+// Pre-* Pipeline Concurrent Execution Tests+// ============================================================================++/// Pipeline blocks in pre-* hooks run their concurrent commands concurrently.+/// The second block has two commands — both should produce output with prefixed+/// labels (the concurrent execution style).+#[rstest]+fn test_pre_merge_pipeline_concurrent_block(repo: TestRepo) {+ repo.write_project_config(+ r#"[[pre-merge]]+setup = "echo SETUP"++[[pre-merge]]+lint = "echo LINT"+test = "echo TEST"+"#,+ );+ repo.commit("Add pipeline pre-merge hooks");++ let mut cmd = repo.wt_command();+ cmd.args(["hook", "pre-merge", "--yes"]);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "pre-merge pipeline should succeed.\nstderr: {}",+ String::from_utf8_lossy(&output.stderr),+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ // All three commands should have run.+ assert!(stderr.contains("SETUP"), "setup step should run: {stderr}");+ assert!(stderr.contains("LINT"), "lint command should run: {stderr}");+ assert!(stderr.contains("TEST"), "test command should run: {stderr}");++ // Concurrent commands get prefixed labels (e.g., "lint │ LINT").+ // Serial commands do not. The "│" separator confirms the concurrent path.+ assert!(+ stderr.contains("│ LINT") && stderr.contains("│ TEST"),+ "concurrent block commands should have prefixed labels: {stderr}",+ );+}++/// Deprecated single-table form (`[pre-merge]`) still runs commands serially,+/// even though the commands are parsed as a `Concurrent` step.+#[rstest]+fn test_pre_merge_deprecated_table_runs_serially(repo: TestRepo) {+ repo.write_project_config(+ r#"[pre-merge]+lint = "echo LINT"+test = "echo TEST"+"#,+ );+ repo.commit("Add table-form pre-merge hooks");++ let mut cmd = repo.wt_command();+ cmd.args(["hook", "pre-merge", "--yes"]);+ let output = cmd.output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("LINT") && stderr.contains("TEST"),+ "both commands should run: {stderr}",+ );+ // Serial execution does not use the "│" prefix labels.+ assert!(+ !stderr.contains("│ LINT") && !stderr.contains("│ TEST"),+ "deprecated table form should run serially (no prefix labels): {stderr}",+ );+}++/// A single `[[pre-merge]]` block (one block, multiple entries) runs+/// concurrently — the `[[]]` syntax is the pipeline form even with one block.+#[rstest]+fn test_pre_merge_single_pipeline_block_runs_concurrently(repo: TestRepo) {+ repo.write_project_config(+ r#"[[pre-merge]]+lint = "echo LINT"+test = "echo TEST"+"#,+ );+ repo.commit("Add single-block pipeline pre-merge hooks");++ let mut cmd = repo.wt_command();+ cmd.args(["hook", "pre-merge", "--yes"]);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "single-block pipeline should succeed.\nstderr: {}",+ String::from_utf8_lossy(&output.stderr),+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("│ LINT") && stderr.contains("│ TEST"),+ "single [[pre-merge]] block should run concurrently: {stderr}",+ );+}