Skip to content

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

feat: structure-driven hook execution ordering (#1713)

Maximilian Roos8ae8fbde1403
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 8d1d3979d..98c15f148 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -151,52 +151,30 @@ Manage approvals with `wt hook approvals add` and `wt hook approvals clear`.
# Configuration
-Hooks can be defined in two places: project config (`.config/wt.toml`) for repository-specific automation, or user config (`~/.config/worktrunk/config.toml`) for personal automation across all repositories.
-
-## Project hooks
-
-Project hooks are defined in `.config/wt.toml`. They can be a single command or multiple named commands:
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format — a single command or multiple named commands:
```toml
# Single command (string)
pre-start = "npm install"
-# Multiple commands (table) — run sequentially in declaration order
+# Multiple commands (table)
[pre-merge]
test = "cargo test"
build = "cargo build --release"
```
-## User hooks
-
-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](@/config.md#setting-overrides).
-
-```toml
-# ~/.config/worktrunk/config.toml
-[pre-start]
-setup = "echo 'Setting up worktree...'"
-
-[pre-merge]
-notify = "notify-send 'Merging {{ branch }}'"
-```
-
-User hooks support the same hook types and template variables as project hooks.
+For pre-* hooks, commands in a table run sequentially. For post-* hooks, they run concurrently in the background. Post-* hooks that need ordering guarantees can use [pipeline ordering](#pipeline-ordering).
-**Key differences from project hooks:**
+## Project vs user hooks
| Aspect | Project hooks | User hooks |
|--------|--------------|------------|
| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |
-| Scope | Single repository | All repositories (or per-project) |
+| Scope | Single repository | All repositories (or [per-project](@/config.md#setting-overrides)) |
| Approval | Required | Not required |
-| Execution order | After user hooks | Global first, then per-project |
+| Execution order | After user hooks | First |
-Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
-
-**Use cases:**
-- Personal notifications or logging
-- Editor/IDE integration
-- Repository-agnostic setup tasks
+Skip all hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
## Template variables
@@ -328,6 +306,54 @@ The `user:` and `project:` prefixes filter by source. Use `user:` or `project:`
The `--var KEY=VALUE` flag overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.
+# Pipeline Ordering <span class="badge-experimental"></span>
+
+By default, all commands in a `post-*` hook run concurrently in the background. When one command depends on another — `npm run build` needs `npm install` to finish first — use a list instead of a table:
+
+```toml
+[hooks]
+post-start = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" }
+]
+```
+
+The list runs steps in order. Each step is either a string (single command) or a map (named commands). Single-entry maps run one command; multi-entry maps run their commands concurrently. The TOML data structure encodes the execution model directly:
+
+- **String** — single command
+- **Map** (table) — concurrent commands
+- **List** (array) — serial pipeline
+
+The entire pipeline runs in the background as one process. Anonymous steps work too:
+
+```toml
+post-start = ["npm install", "npm run build"]
+```
+
+## How it works
+
+Steps are chained with `&&` in a compound shell command, so a failing step skips all later steps. A multi-entry map spawns its commands as background processes and waits for all to complete before the next step.
+
+For the example above, the generated command is:
+
+```
+{ npm install; } && { { npm run build; } & { npm run lint; } & wait; }
+```
+
+Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.
+
+## When to use pipelines
+
+Most hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:
+
+```toml
+[post-start]
+server = "npm run dev -- --port {{ branch | hash_port }}"
+copy = "wt step copy-ignored"
+```
+
+Pipelines matter when there's a dependency chain — typically setup steps that must complete before other tasks can start. Common pattern: install dependencies, then run build + dev server concurrently.
+
# Designing Effective Hooks
## post-start vs pre-start
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 4c75d329f..c05951aed 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -142,52 +142,30 @@ Manage approvals with `wt hook approvals add` and `wt hook approvals clear`.
# Configuration
-Hooks can be defined in two places: project config (`.config/wt.toml`) for repository-specific automation, or user config (`~/.config/worktrunk/config.toml`) for personal automation across all repositories.
-
-## Project hooks
-
-Project hooks are defined in `.config/wt.toml`. They can be a single command or multiple named commands:
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format — a single command or multiple named commands:
```toml
# Single command (string)
pre-start = "npm install"
-# Multiple commands (table) — run sequentially in declaration order
+# Multiple commands (table)
[pre-merge]
test = "cargo test"
build = "cargo build --release"
```
-## User hooks
-
-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](https://worktrunk.dev/config/#setting-overrides).
-
-```toml
-# ~/.config/worktrunk/config.toml
-[pre-start]
-setup = "echo 'Setting up worktree...'"
-
-[pre-merge]
-notify = "notify-send 'Merging {{ branch }}'"
-```
-
-User hooks support the same hook types and template variables as project hooks.
+For pre-* hooks, commands in a table run sequentially. For post-* hooks, they run concurrently in the background. Post-* hooks that need ordering guarantees can use [pipeline ordering](#pipeline-ordering).
-**Key differences from project hooks:**
+## Project vs user hooks
| Aspect | Project hooks | User hooks |
|--------|--------------|------------|
| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |
-| Scope | Single repository | All repositories (or per-project) |
+| Scope | Single repository | All repositories (or [per-project](https://worktrunk.dev/config/#setting-overrides)) |
| Approval | Required | Not required |
-| Execution order | After user hooks | Global first, then per-project |
+| Execution order | After user hooks | First |
-Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
-
-**Use cases:**
-- Personal notifications or logging
-- Editor/IDE integration
-- Repository-agnostic setup tasks
+Skip all hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
## Template variables
@@ -319,6 +297,54 @@ The `user:` and `project:` prefixes filter by source. Use `user:` or `project:`
The `--var KEY=VALUE` flag overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.
+# Pipeline Ordering [experimental]
+
+By default, all commands in a `post-*` hook run concurrently in the background. When one command depends on another — `npm run build` needs `npm install` to finish first — use a list instead of a table:
+
+```toml
+[hooks]
+post-start = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" }
+]
+```
+
+The list runs steps in order. Each step is either a string (single command) or a map (named commands). Single-entry maps run one command; multi-entry maps run their commands concurrently. The TOML data structure encodes the execution model directly:
+
+- **String** — single command
+- **Map** (table) — concurrent commands
+- **List** (array) — serial pipeline
+
+The entire pipeline runs in the background as one process. Anonymous steps work too:
+
+```toml
+post-start = ["npm install", "npm run build"]
+```
+
+## How it works
+
+Steps are chained with `&&` in a compound shell command, so a failing step skips all later steps. A multi-entry map spawns its commands as background processes and waits for all to complete before the next step.
+
+For the example above, the generated command is:
+
+```
+{ npm install; } && { { npm run build; } & { npm run lint; } & wait; }
+```
+
+Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.
+
+## When to use pipelines
+
+Most hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:
+
+```toml
+[post-start]
+server = "npm run dev -- --port {{ branch | hash_port }}"
+copy = "wt step copy-ignored"
+```
+
+Pipelines matter when there's a dependency chain — typically setup steps that must complete before other tasks can start. Common pattern: install dependencies, then run build + dev server concurrently.
+
# Designing Effective Hooks
## post-start vs pre-start
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 5ea307912..3d91dcb75 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1242,52 +1242,30 @@ Manage approvals with `wt hook approvals add` and `wt hook approvals clear`.
# Configuration
-Hooks can be defined in two places: project config (`.config/wt.toml`) for repository-specific automation, or user config (`~/.config/worktrunk/config.toml`) for personal automation across all repositories.
-
-## Project hooks
-
-Project hooks are defined in `.config/wt.toml`. They can be a single command or multiple named commands:
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format — a single command or multiple named commands:
```toml
# Single command (string)
pre-start = "npm install"
-# Multiple commands (table) — run sequentially in declaration order
+# Multiple commands (table)
[pre-merge]
test = "cargo test"
build = "cargo build --release"
```
-## User hooks
-
-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](@/config.md#setting-overrides).
-
-```toml
-# ~/.config/worktrunk/config.toml
-[pre-start]
-setup = "echo 'Setting up worktree...'"
-
-[pre-merge]
-notify = "notify-send 'Merging {{ branch }}'"
-```
-
-User hooks support the same hook types and template variables as project hooks.
+For pre-* hooks, commands in a table run sequentially. For post-* hooks, they run concurrently in the background. Post-* hooks that need ordering guarantees can use [pipeline ordering](#pipeline-ordering).
-**Key differences from project hooks:**
+## Project vs user hooks
| Aspect | Project hooks | User hooks |
|--------|--------------|------------|
| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |
-| Scope | Single repository | All repositories (or per-project) |
+| Scope | Single repository | All repositories (or [per-project](@/config.md#setting-overrides)) |
| Approval | Required | Not required |
-| Execution order | After user hooks | Global first, then per-project |
-
-Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
+| Execution order | After user hooks | First |
-**Use cases:**
-- Personal notifications or logging
-- Editor/IDE integration
-- Repository-agnostic setup tasks
+Skip all hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.
## Template variables
@@ -1419,6 +1397,54 @@ The `user:` and `project:` prefixes filter by source. Use `user:` or `project:`
The `--var KEY=VALUE` flag overrides built-in template variables — useful for testing hooks with different contexts without switching to that context.
+# Pipeline Ordering [experimental]
+
+By default, all commands in a `post-*` hook run concurrently in the background. When one command depends on another — `npm run build` needs `npm install` to finish first — use a list instead of a table:
+
+```toml
+[hooks]
+post-start = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" }
+]
+```
+
+The list runs steps in order. Each step is either a string (single command) or a map (named commands). Single-entry maps run one command; multi-entry maps run their commands concurrently. The TOML data structure encodes the execution model directly:
+
+- **String** — single command
+- **Map** (table) — concurrent commands
+- **List** (array) — serial pipeline
+
+The entire pipeline runs in the background as one process. Anonymous steps work too:
+
+```toml
+post-start = ["npm install", "npm run build"]
+```
+
+## How it works
+
+Steps are chained with `&&` in a compound shell command, so a failing step skips all later steps. A multi-entry map spawns its commands as background processes and waits for all to complete before the next step.
+
+For the example above, the generated command is:
+
+```
+{ npm install; } && { { npm run build; } & { npm run lint; } & wait; }
+```
+
+Pre-* hooks ignore pipeline structure — all commands run serially regardless, since pre-* hooks are blocking by nature.
+
+## When to use pipelines
+
+Most hooks don't need pipelines. A table of concurrent post-start commands is fine when they're independent:
+
+```toml
+[post-start]
+server = "npm run dev -- --port {{ branch | hash_port }}"
+copy = "wt step copy-ignored"
+```
+
+Pipelines matter when there's a dependency chain — typically setup steps that must complete before other tasks can start. Common pattern: install dependencies, then run build + dev server concurrently.
+
# Designing Effective Hooks
## post-start vs pre-start
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 7c2f28f21..c7d486663 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -252,7 +252,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
let context_json = serde_json::to_string(&context_map)
.expect("HashMap<String, String> serialization should never fail");
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
if opts.dry_run {
let expanded: Vec<_> = commands
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 8022f2a27..1404737fb 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -159,7 +159,6 @@ pub fn approve_alias_commands(
let cmds: Vec<_> = commands
.commands()
- .iter()
.map(|cmd| ApprovableCommand {
phase: Phase::Alias,
command: worktrunk::config::Command::new(
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 6412c5c6d..ccb76b319 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use std::collections::HashMap;
use std::path::Path;
use worktrunk::HookType;
-use worktrunk::config::{Command, CommandConfig, UserConfig, expand_template};
+use worktrunk::config::{Command, CommandConfig, HookStep, UserConfig, expand_template};
use worktrunk::git::Repository;
use worktrunk::path::to_posix_path;
@@ -15,6 +15,13 @@ pub struct PreparedCommand {
pub context_json: String,
}
+/// A step in a prepared pipeline, mirroring `HookStep`.
+#[derive(Debug)]
+pub enum PreparedStep {
+ Single(PreparedCommand),
+ Concurrent(Vec<PreparedCommand>),
+}
+
#[derive(Clone, Copy, Debug)]
pub struct CommandContext<'a> {
pub repo: &'a Repository,
@@ -220,12 +227,12 @@ pub fn prepare_commands(
hook_type: HookType,
source: HookSource,
) -> anyhow::Result<Vec<PreparedCommand>> {
- let commands = command_config.commands();
+ let commands: Vec<Command> = command_config.commands().cloned().collect();
if commands.is_empty() {
return Ok(Vec::new());
}
- let expanded_with_json = expand_commands(commands, ctx, extra_vars, hook_type, source)?;
+ let expanded_with_json = expand_commands(&commands, ctx, extra_vars, hook_type, source)?;
Ok(expanded_with_json
.into_iter()
@@ -236,3 +243,63 @@ pub fn prepare_commands(
})
.collect())
}
+
+/// Prepare pipeline steps for execution, preserving serial/concurrent structure.
+///
+/// Like `prepare_commands`, but returns `Vec<PreparedStep>` that preserves
+/// the pipeline structure from the config. Used by post-* hooks that need
+/// to distinguish serial steps from concurrent groups.
+pub fn prepare_steps(
+ command_config: &CommandConfig,
+ ctx: &CommandContext<'_>,
+ extra_vars: &[(&str, &str)],
+ hook_type: HookType,
+ source: HookSource,
+) -> anyhow::Result<Vec<PreparedStep>> {
+ let steps = command_config.steps();
+ if steps.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // Collect step sizes so we can re-partition after a single expand_commands call.
+ // This avoids calling build_hook_context (which spawns git subprocesses) per step.
+ let step_sizes: Vec<usize> = steps
+ .iter()
+ .map(|s| match s {
+ HookStep::Single(_) => 1,
+ HookStep::Concurrent(cmds) => cmds.len(),
+ })
+ .collect();
+
+ let all_commands: Vec<Command> = command_config.commands().cloned().collect();
+ let all_expanded = expand_commands(&all_commands, ctx, extra_vars, hook_type, source)?;
+ let mut expanded_iter = all_expanded.into_iter();
+
+ 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) = chunk.into_iter().next().unwrap();
+ result.push(PreparedStep::Single(PreparedCommand {
+ name: cmd.name,
+ expanded: cmd.expanded,
+ context_json: json,
+ }));
+ }
+ HookStep::Concurrent(_) => {
+ let prepared = chunk
+ .into_iter()
+ .map(|(cmd, json)| PreparedCommand {
+ name: cmd.name,
+ expanded: cmd.expanded,
+ context_json: json,
+ })
+ .collect();
+ result.push(PreparedStep::Concurrent(prepared));
+ }
+ }
+ }
+
+ Ok(result)
+}
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 1d2044551..be8cf3b2e 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::hooks::{
- HookCommandSpec, HookFailureStrategy, prepare_background_hooks, spawn_background_hooks,
+ HookCommandSpec, HookFailureStrategy, prepare_background_hooks, spawn_prepared_hooks,
};
use super::repository_ext::RepositoryCliExt;
@@ -240,7 +240,7 @@ impl CommitOptions<'_> {
.collect();
let hooks =
prepare_background_hooks(self.ctx, HookType::PostCommit, &extra_vars, None)?;
- spawn_background_hooks(self.ctx, hooks)?;
+ spawn_prepared_hooks(self.ctx, hooks)?;
}
Ok(())
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 9ad124bef..4bccca2e3 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -183,21 +183,36 @@ pub(crate) fn spawn_switch_background_hooks(
) -> anyhow::Result<()> {
let ctx = CommandContext::new(repo, config, branch, result.path(), yes);
- let mut hooks = super::hooks::prepare_background_hooks(
+ let mut flat_hooks = Vec::new();
+ let mut pipeline_hooks = Vec::new();
+
+ match super::hooks::prepare_background_hooks(
&ctx,
HookType::PostSwitch,
extra_vars,
hooks_display_path,
- )?;
+ )? {
+ super::hooks::PreparedHooks::Flat(cmds) => flat_hooks.extend(cmds),
+ super::hooks::PreparedHooks::Pipeline(steps) => pipeline_hooks.extend(steps),
+ }
+
if matches!(result, SwitchResult::Created { .. }) {
- hooks.extend(super::hooks::prepare_background_hooks(
+ match super::hooks::prepare_background_hooks(
&ctx,
HookType::PostStart,
extra_vars,
hooks_display_path,
- )?);
+ )? {
+ super::hooks::PreparedHooks::Flat(cmds) => flat_hooks.extend(cmds),
+ super::hooks::PreparedHooks::Pipeline(steps) => pipeline_hooks.extend(steps),
+ }
+ }
+
+ // Spawn pipeline hooks as compound commands, flat hooks as independent processes
+ if !pipeline_hooks.is_empty() {
+ super::hooks::spawn_hook_pipeline(&ctx, pipeline_hooks)?;
}
- super::hooks::spawn_background_hooks(&ctx, hooks)
+ super::hooks::spawn_background_hooks(&ctx, flat_hooks)
}
/// Handle the switch command.
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index a844b9535..caebb66f2 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -28,7 +28,8 @@ use super::command_executor::CommandContext;
use super::context::CommandEnv;
use super::hooks::{
HookCommandSpec, HookFailureStrategy, check_name_filter_matched, prepare_hook_commands,
- run_hook_with_filter, spawn_background_hooks,
+ prepare_pipeline_hooks_with_configs, run_hook_with_filter, spawn_background_hooks,
+ spawn_hook_pipeline,
};
use super::project_config::collect_commands_for_hooks;
@@ -66,6 +67,24 @@ fn run_post_hook(
) -> anyhow::Result<()> {
// Default to background execution; --foreground is for debugging.
if !foreground.unwrap_or(false) {
+ // Pipeline configs (list form) use compound shell command path.
+ // Name filtering falls through to the flat path (individual command execution).
+ let has_pipeline = [user_config, project_config]
+ .iter()
+ .any(|c| c.is_some_and(CommandConfig::is_pipeline));
+
+ if has_pipeline && name_filter.is_none() {
+ let steps = prepare_pipeline_hooks_with_configs(
+ ctx,
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ None,
+ )?;
+ return spawn_hook_pipeline(ctx, steps);
+ }
+
let commands = prepare_hook_commands(
ctx,
HookCommandSpec {
@@ -583,7 +602,7 @@ fn render_hook_commands(
approval_context: Option<(&Approvals, Option<&str>)>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
- let commands = config.commands();
+ let commands: Vec<_> = config.commands().collect();
if commands.is_empty() {
return Ok(());
}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 301e54457..47eb21a95 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -9,7 +9,9 @@ use worktrunk::styling::{
eprintln, error_message, format_bash_with_gutter, progress_message, verbosity, warning_message,
};
-use super::command_executor::{CommandContext, PreparedCommand, prepare_commands};
+use super::command_executor::{
+ CommandContext, PreparedCommand, PreparedStep, prepare_commands, prepare_steps,
+};
use crate::commands::process::{HookLog, spawn_detached};
use crate::output::execute_command_in_worktree;
@@ -258,6 +260,180 @@ pub fn spawn_background_hooks(
Ok(())
}
+/// Prepared hooks ready for background spawning — either flat commands or a pipeline.
+pub(crate) enum PreparedHooks {
+ /// Traditional flat commands (string or map config) — spawned independently.
+ Flat(Vec<SourcedCommand>),
+ /// Pipeline steps (list config) — spawned as one compound shell command.
+ Pipeline(Vec<SourcedStep>),
+}
+
+/// A pipeline step with source information, for pipeline-aware execution.
+pub struct SourcedStep {
+ pub step: PreparedStep,
+ pub source: HookSource,
+ pub hook_type: HookType,
+ pub display_path: Option<PathBuf>,
+}
+
+/// Build a compound shell command from pipeline steps.
+///
+/// Serial steps are chained with `&&`. Concurrent groups use background
+/// processes with `wait`. The entire result is one shell command string
+/// suitable for `spawn_detached`.
+///
+/// Example output: `cmd1 && cmd2 && { cmd3 & cmd4 & wait; }`
+fn build_pipeline_command(steps: &[SourcedStep]) -> String {
+ let mut parts = Vec::new();
+ for step in steps {
+ match &step.step {
+ PreparedStep::Single(cmd) => {
+ // Wrap in braces to prevent operator interaction between steps.
+ // Without this, `false || echo fallback && echo next` would
+ // parse as `false || (echo fallback && echo next)`.
+ parts.push(format!("{{ {}; }}", cmd.expanded));
+ }
+ PreparedStep::Concurrent(cmds) => {
+ let bg: Vec<String> = cmds
+ .iter()
+ .map(|c| format!("{{ {}; }} &", c.expanded))
+ .collect();
+ parts.push(format!("{{ {} wait; }}", bg.join(" ")));
+ }
+ }
+ }
+ parts.join(" && ")
+}
+
+/// Format a summary description of a pipeline for display.
+///
+/// Shows step names/counts with `→` separating serial steps.
+/// Example: "install → build, lint"
+fn format_pipeline_summary(steps: &[SourcedStep]) -> String {
+ let mut unnamed_idx = 0usize;
+ let mut parts = Vec::new();
+ for step in steps {
+ match &step.step {
+ PreparedStep::Single(cmd) => {
+ let name = match &cmd.name {
+ Some(n) => cformat!("<bold>{}</>", n),
+ None => {
+ let label = format!("cmd-{unnamed_idx}");
+ unnamed_idx += 1;
+ cformat!("<bold>{}</>", label)
+ }
+ };
+ parts.push(name);
+ }
+ PreparedStep::Concurrent(cmds) => {
+ let names: Vec<String> = cmds
+ .iter()
+ .map(|c| match &c.name {
+ Some(n) => cformat!("<bold>{}</>", n),
+ None => {
+ let label = format!("cmd-{unnamed_idx}");
+ unnamed_idx += 1;
+ cformat!("<bold>{}</>", label)
+ }
+ })
+ .collect();
+ parts.push(names.join(", "));
+ }
+ }
+ }
+ parts.join(" → ")
+}
+
+/// Spawn a hook pipeline as one background process.
+///
+/// Builds a compound shell command where serial steps are chained with `&&`
+/// and concurrent groups use background processes. The entire pipeline runs
+/// as one detached process.
+///
+/// Used for post-* hooks when the config uses a pipeline (list form).
+pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {
+ if steps.is_empty() {
+ return Ok(());
+ }
+
+ let hook_type = steps[0].hook_type;
+ let source = steps[0].source;
+ let display_path = steps[0].display_path.as_ref();
+
+ // Show summary: "Running post-start: install → build, lint"
+ let summary = format_pipeline_summary(&steps);
+ let message = match display_path {
+ Some(path) => {
+ let path_display = format_path_for_display(path);
+ cformat!("Running {hook_type}: {summary} @ <bold>{path_display}</>")
+ }
+ None => format!("Running {hook_type}: {summary}"),
+ };
+ eprintln!("{}", progress_message(message));
+
+ let pipeline_cmd = build_pipeline_command(&steps);
+ let hook_log = HookLog::hook(source, hook_type, "pipeline");
+ let log_label = format!("{hook_type} {source} pipeline");
+
+ // Use the first command's context JSON for the whole pipeline.
+ // All steps share the same base context (branch, worktree_path, etc.).
+ let context_json = steps.iter().find_map(|s| match &s.step {
+ PreparedStep::Single(cmd) => Some(cmd.context_json.as_str()),
+ PreparedStep::Concurrent(cmds) => cmds.first().map(|c| c.context_json.as_str()),
+ });
+
+ if let Err(err) = spawn_detached(
+ ctx.repo,
+ ctx.worktree_path,
+ &pipeline_cmd,
+ ctx.branch_or_head(),
+ &hook_log,
+ context_json,
+ ) {
+ eprintln!(
+ "{}",
+ warning_message(format!("Failed to spawn pipeline: {err}"))
+ );
+ } else {
+ worktrunk::command_log::log_command(&log_label, &pipeline_cmd, None, None);
+ }
+
+ Ok(())
+}
+
+/// Prepare hook steps as a pipeline, preserving serial/concurrent structure.
+///
+/// Accepts pre-looked-up configs to avoid redundant loading.
+pub(crate) fn prepare_pipeline_hooks_with_configs(
+ ctx: &CommandContext,
+ user_config: Option<&CommandConfig>,
+ proj_config: Option<&CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ display_path: Option<&Path>,
+) -> anyhow::Result<Vec<SourcedStep>> {
+ let display_path = display_path.map(|p| p.to_path_buf());
+ let mut all_steps = Vec::new();
+
+ let sources = [
+ (HookSource::User, user_config),
+ (HookSource::Project, proj_config),
+ ];
+
+ for (source, config) in sources {
+ let Some(config) = config else { continue };
+ let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?;
+ all_steps.extend(steps.into_iter().map(|step| SourcedStep {
+ step,
+ source,
+ hook_type,
+ display_path: display_path.clone(),
+ }));
+ }
+
+ Ok(all_steps)
+}
+
/// Group commands by hook type, preserving insertion order.
///
/// Returns a vector of (HookType, Vec<&SourcedCommand>) tuples.
@@ -304,7 +480,6 @@ pub(crate) fn check_name_filter_matched(
available.extend(
config
.commands()
- .iter()
.filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),
);
}
@@ -444,35 +619,58 @@ pub fn execute_hook(
/// Prepare background hooks with automatic config lookup.
///
-/// This is a convenience wrapper that:
-/// 1. Loads project config from the repository
-/// 2. Looks up user hooks from the config
-/// 3. Prepares commands ready for spawning
-///
-/// Use this to collect hooks from multiple types, then call `spawn_background_hooks`
-/// once to spawn them all with a unified message.
+/// Returns `PreparedHooks::Pipeline` when any source uses a list config,
+/// or `PreparedHooks::Flat` for traditional string/map configs.
+/// Callers should use `spawn_prepared_hooks` to execute the result.
pub(crate) fn prepare_background_hooks(
ctx: &CommandContext,
hook_type: HookType,
extra_vars: &[(&str, &str)],
display_path: Option<&Path>,
-) -> anyhow::Result<Vec<SourcedCommand>> {
+) -> anyhow::Result<PreparedHooks> {
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);
- prepare_hook_commands(
+ if [user_config, proj_config]
+ .iter()
+ .any(|c| c.is_some_and(CommandConfig::is_pipeline))
+ {
+ let steps = prepare_pipeline_hooks_with_configs(
+ ctx,
+ user_config,
+ proj_config,
+ hook_type,
+ extra_vars,
+ display_path,
+ )?;
+ return Ok(PreparedHooks::Pipeline(steps));
+ }
+
+ let commands = prepare_hook_commands(
ctx,
HookCommandSpec {
user_config,
project_config: proj_config,
hook_type,
extra_vars,
- name_filter: None, // no filter for automatic background hooks
+ name_filter: None,
display_path,
},
- )
+ )?;
+ Ok(PreparedHooks::Flat(commands))
+}
+
+/// Spawn prepared hooks (either flat or pipeline).
+pub(crate) fn spawn_prepared_hooks(
+ ctx: &CommandContext,
+ hooks: PreparedHooks,
+) -> anyhow::Result<()> {
+ match hooks {
+ PreparedHooks::Flat(commands) => spawn_background_hooks(ctx, commands),
+ PreparedHooks::Pipeline(steps) => spawn_hook_pipeline(ctx, steps),
+ }
}
#[cfg(test)]
@@ -532,4 +730,99 @@ mod tests {
assert_eq!(f.source, Some(HookSource::Project));
assert_eq!(f.name, "");
}
+
+ fn make_sourced_step(step: PreparedStep) -> SourcedStep {
+ SourcedStep {
+ step,
+ source: HookSource::User,
+ hook_type: worktrunk::HookType::PostStart,
+ display_path: None,
+ }
+ }
+
+ fn make_cmd(name: Option<&str>, expanded: &str) -> PreparedCommand {
+ PreparedCommand {
+ name: name.map(String::from),
+ expanded: expanded.to_string(),
+ context_json: "{}".to_string(),
+ }
+ }
+
+ #[test]
+ fn test_build_pipeline_command_serial_only() {
+ let steps = vec![
+ make_sourced_step(PreparedStep::Single(make_cmd(None, "npm install"))),
+ make_sourced_step(PreparedStep::Single(make_cmd(
+ Some("build"),
+ "npm run build",
+ ))),
+ ];
+ let cmd = build_pipeline_command(&steps);
+ assert_eq!(cmd, "{ npm install; } && { npm run build; }");
+ }
+
+ #[test]
+ fn test_build_pipeline_command_serial_then_concurrent() {
+ let steps = vec![
+ make_sourced_step(PreparedStep::Single(make_cmd(None, "npm install"))),
+ make_sourced_step(PreparedStep::Concurrent(vec![
+ make_cmd(Some("build"), "npm run build"),
+ make_cmd(Some("lint"), "npm run lint"),
+ ])),
+ ];
+ let cmd = build_pipeline_command(&steps);
+ assert_eq!(
+ cmd,
+ "{ npm install; } && { { npm run build; } & { npm run lint; } & wait; }"
+ );
+ }
+
+ #[test]
+ fn test_build_pipeline_command_single_concurrent() {
+ let steps = vec![make_sourced_step(PreparedStep::Concurrent(vec![make_cmd(
+ Some("only"),
+ "echo hi",
+ )]))];
+ let cmd = build_pipeline_command(&steps);
+ assert_eq!(cmd, "{ { echo hi; } & wait; }");
+ }
+
+ #[test]
+ fn test_format_pipeline_summary_named() {
+ let steps = vec![
+ make_sourced_step(PreparedStep::Single(make_cmd(
+ Some("install"),
+ "npm install",
+ ))),
+ make_sourced_step(PreparedStep::Concurrent(vec![
+ make_cmd(Some("build"), "npm run build"),
+ make_cmd(Some("lint"), "npm run lint"),
+ ])),
+ ];
+ let summary = format_pipeline_summary(&steps);
+ // Contains arrow and names (stripped of ANSI for assertion)
+ assert!(summary.contains("→"));
+ assert!(summary.contains("install"));
+ assert!(summary.contains("build"));
+ assert!(summary.contains("lint"));
+ }
+
+ #[test]
+ fn test_format_pipeline_summary_unnamed() {
+ let steps = vec![
+ make_sourced_step(PreparedStep::Single(make_cmd(None, "npm install"))),
+ make_sourced_step(PreparedStep::Single(make_cmd(None, "npm run build"))),
+ ];
+ let summary = format_pipeline_summary(&steps);
+ assert!(summary.contains("cmd-0"));
+ assert!(summary.contains("cmd-1"));
+ }
+
+ #[test]
+ fn test_is_pipeline() {
+ use worktrunk::config::CommandConfig;
+
+ let single = CommandConfig::single("npm install");
+ assert!(!single.is_pipeline());
+ }
}
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 1c262d33a..0e6fd27c1 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -34,16 +34,10 @@ pub fn collect_commands_for_hooks(
let mut commands = Vec::new();
for hook in hooks {
if let Some(config) = project_config.hooks.get(*hook) {
- commands.extend(
- config
- .commands()
- .iter()
- .cloned()
- .map(|command| ApprovableCommand {
- phase: Phase::Hook(*hook),
- command,
- }),
- );
+ commands.extend(config.commands().cloned().map(|command| ApprovableCommand {
+ phase: Phase::Hook(*hook),
+ command,
+ }));
}
}
commands
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 355a1faa8..55eaaaf15 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -34,7 +34,7 @@ use super::commit::{CommitGenerator, CommitOptions, StageMode};
use super::context::CommandEnv;
use super::hooks::{
HookCommandSpec, HookFailureStrategy, prepare_background_hooks, run_hook_with_filter,
- spawn_background_hooks,
+ spawn_prepared_hooks,
};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::BranchDeletionMode;
@@ -359,7 +359,7 @@ pub fn handle_squash(
if verify {
let extra_vars: Vec<(&str, &str)> = vec![("target", integration_target.as_str())];
let hooks = prepare_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)?;
- spawn_background_hooks(&ctx, hooks)?;
+ spawn_prepared_hooks(&ctx, hooks)?;
}
Ok(SquashResult::Squashed)
diff --git a/src/completion.rs b/src/completion.rs
index e609393f4..f7642b24f 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -250,7 +250,6 @@ impl ValueCompleter for HookCommandCompleter {
candidates.extend(
config
.commands()
- .iter()
.filter_map(|cmd| cmd.name.as_ref())
.map(|name| CompletionCandidate::new(name.clone())),
);
@@ -400,7 +399,7 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
// Use the first command's template for the help text
let first_template = cmd_config
.commands()
- .first()
+ .next()
.map(|c| c.template.as_str())
.unwrap_or("");
let help = truncate_template(first_template);
diff --git a/src/config/commands.rs b/src/config/commands.rs
index ba82cd27c..ea23bf42a 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -1,7 +1,30 @@
-//! Command configuration types for project hooks
+//! Command configuration types for hook pipelines.
//!
-//! Handles parsing and representation of commands that run during various phases
-//! of worktree and merge operations.
+//! The data structure determines execution order:
+//! - **String** → single command
+//! - **Map** (TOML table) → concurrent commands
+//! - **List** (TOML array) → serial pipeline (steps execute in order)
+//!
+//! List elements can be strings (anonymous serial steps) or maps (named commands).
+//! A single-entry map is a named serial step; a multi-entry map is a concurrent group.
+//!
+//! Examples:
+//! ```toml
+//! # Single command
+//! post-start = "npm install"
+//!
+//! # Concurrent (map)
+//! [hooks.post-start]
+//! build = "npm run build"
+//! lint = "npm run lint"
+//!
+//! # Serial pipeline with concurrent stage
+//! [hooks]
+//! post-start = [
+//! { install = "npm install" },
+//! { build = "npm run build", lint = "npm run lint" }
+//! ]
+//! ```
use std::collections::BTreeMap;
@@ -10,10 +33,10 @@ use schemars::JsonSchema;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};
-/// Represents a command with its template and optionally expanded form
+/// Represents a command with its template and optionally expanded form.
#[derive(Debug, Clone, PartialEq)]
pub struct Command {
- /// Optional name for the command (e.g., "build", "test", or auto-numbered "1", "2")
+ /// Optional name for the command (e.g., "build", "test")
pub name: Option<String>,
/// Template string that may contain variables like {{ branch }}, {{ worktree }}
pub template: String,
@@ -41,43 +64,96 @@ impl Command {
}
}
-/// Configuration for commands - canonical representation
+/// A step in a hook pipeline.
///
-/// Internally stores commands as `Vec<Command>` for uniform processing.
-/// Deserializes from two TOML formats:
-/// - Single string: `post-create = "npm install"`
-/// - Named table: `[post-create]` followed by `install = "npm install"`
+/// The execution model depends on the hook type:
+/// - **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.
+#[derive(Debug, Clone, PartialEq)]
+pub enum HookStep {
+ /// A single command (from a string in a list, or a single-entry map).
+ Single(Command),
+ /// Multiple commands that run concurrently (from a multi-entry map).
+ Concurrent(Vec<Command>),
+}
+
+/// Configuration for commands — canonical representation.
///
-/// **Order preservation:** Named commands preserve TOML insertion order (requires
-/// `preserve_order` feature on toml crate and IndexMap for deserialization). This
-/// allows users to control execution order explicitly.
+/// Internally stores a pipeline of `HookStep`s. Deserializes from three TOML forms:
+/// - Single string: `post-start = "npm install"`
+/// - Named table: `[post-start]` with `name = "command"` entries → one Concurrent step
+/// - Pipeline: `post-start = ["cmd", { a = "cmd1", b = "cmd2" }]` → serial steps
///
-/// This canonical form eliminates branching at call sites - code just iterates over commands.
+/// **Order preservation:** Named commands preserve TOML insertion order (IndexMap).
#[derive(Debug, Clone, PartialEq)]
pub struct CommandConfig {
- commands: Vec<Command>,
+ steps: Vec<HookStep>,
}
impl CommandConfig {
/// Create a config with a single unnamed command.
pub fn single(template: impl Into<String>) -> Self {
Self {
- commands: vec![Command::new(None, template.into())],
+ steps: vec![HookStep::Single(Command::new(None, template.into()))],
}
}
- /// Returns the commands as a slice
- pub fn commands(&self) -> &[Command] {
- &self.commands
+ /// Returns a flat iterator over all commands (for approval, completion, display).
+ pub fn commands(&self) -> impl Iterator<Item = &Command> {
+ self.steps.iter().flat_map(|step| match step {
+ HookStep::Single(cmd) => std::slice::from_ref(cmd).iter(),
+ HookStep::Concurrent(cmds) => cmds.iter(),
+ })
}
- /// Merge two configs by appending commands (base commands first, then overlay).
+ /// Returns true if this config uses a pipeline (list form with multiple steps).
+ /// Single-step configs (string or map) return false.
+ pub fn is_pipeline(&self) -> bool {
+ self.steps.len() > 1
+ }
+
+ /// Returns the pipeline steps for execution.
+ pub fn steps(&self) -> &[HookStep] {
+ &self.steps
+ }
+
+ /// Merge two configs by appending steps (base steps first, then overlay).
///
/// Used for per-project hook overrides where both global and project hooks run.
pub fn merge_append(&self, other: &Self) -> Self {
- let mut commands = self.commands.clone();
- commands.extend(other.commands.iter().cloned());
- Self { commands }
+ let mut steps = self.steps.clone();
+ steps.extend(other.steps.iter().cloned());
+ Self { steps }
+ }
+}
+
+/// Validate that no command names contain colons (would break log spec parsing).
+fn validate_no_colons<E: serde::de::Error>(map: &IndexMap<String, String>) -> Result<(), E> {
+ for name in map.keys() {
+ if name.contains(':') {
+ return Err(serde::de::Error::custom(format!(
+ "hook name '{}' cannot contain colons",
+ name
+ )));
+ }
+ }
+ Ok(())
+}
+
+/// Convert an IndexMap of named commands to a HookStep.
+/// Single-entry maps become `Single` (named serial step),
+/// multi-entry maps become `Concurrent`.
+fn map_to_step(map: IndexMap<String, String>) -> HookStep {
+ if map.len() == 1 {
+ let (name, template) = map.into_iter().next().unwrap();
+ HookStep::Single(Command::new(Some(name), template))
+ } else {
+ HookStep::Concurrent(
+ map.into_iter()
+ .map(|(name, template)| Command::new(Some(name), template))
+ .collect(),
+ )
}
}
@@ -96,58 +172,93 @@ pub fn append_aliases(
}
}
-// Custom deserialization to handle 2 TOML formats
+// Custom deserialization to handle 3 TOML formats
impl<'de> Deserialize<'de> for CommandConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
+ /// An entry in a pipeline list: either a string or a map of named commands.
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum PipelineEntry {
+ Anonymous(String),
+ Named(IndexMap<String, String>),
+ }
+
#[derive(Deserialize)]
#[serde(untagged)]
enum CommandConfigToml {
+ // post-start = "npm install"
Single(String),
- Named(IndexMap<String, String>),
+ // post-start = ["cmd1", { a = "cmd2", b = "cmd3" }]
+ Pipeline(Vec<PipelineEntry>),
+ // [hooks.post-start] with name = "command" entries
+ Concurrent(IndexMap<String, String>),
}
let toml = CommandConfigToml::deserialize(deserializer)?;
- let commands = match toml {
+ let steps = match toml {
CommandConfigToml::Single(cmd) => {
- // Phase will be set later when commands are collected
- vec![Command::new(None, cmd)]
+ vec![HookStep::Single(Command::new(None, cmd))]
}
- CommandConfigToml::Named(map) => {
- // IndexMap preserves insertion order from TOML
- // Validate hook names don't contain colons (would break log spec parsing)
- for name in map.keys() {
- if name.contains(':') {
- return Err(serde::de::Error::custom(format!(
- "hook name '{}' cannot contain colons",
- name
- )));
+ CommandConfigToml::Pipeline(entries) => {
+ let mut steps = Vec::new();
+ for entry in entries {
+ match entry {
+ PipelineEntry::Anonymous(cmd) => {
+ steps.push(HookStep::Single(Command::new(None, cmd)));
+ }
+ PipelineEntry::Named(map) => {
+ if map.is_empty() {
+ continue;
+ }
+ validate_no_colons(&map)?;
+ steps.push(map_to_step(map));
+ }
}
}
- map.into_iter()
+ steps
+ }
+ CommandConfigToml::Concurrent(map) => {
+ validate_no_colons(&map)?;
+ let commands: Vec<Command> = map
+ .into_iter()
.map(|(name, template)| Command::new(Some(name), template))
- .collect()
+ .collect();
+ vec![HookStep::Concurrent(commands)]
}
};
- Ok(CommandConfig { commands })
+ Ok(CommandConfig { steps })
}
}
-// JsonSchema for CommandConfig - describes the two TOML formats
+// JsonSchema for CommandConfig
impl JsonSchema for CommandConfig {
fn schema_name() -> std::borrow::Cow<'static, str> {
"CommandConfig".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
- // CommandConfig accepts either a string or an object with string values
- // We just need this for schema generation, not validation
schemars::json_schema!({
"oneOf": [
{ "type": "string" },
- { "type": "object", "additionalProperties": { "type": "string" } }
+ {
+ "type": "object",
+ "additionalProperties": { "type": "string" }
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ { "type": "string" },
+ {
+ "type": "object",
+ "additionalProperties": { "type": "string" }
+ }
+ ]
+ }
+ }
]
})
}
@@ -159,30 +270,75 @@ impl Serialize for CommandConfig {
where
S: serde::Serializer,
{
- // If single unnamed command, serialize as string
- if self.commands.len() == 1 && self.commands[0].name.is_none() {
- return self.commands[0].template.serialize(serializer);
+ // Single unnamed command → string
+ if self.steps.len() == 1
+ && let HookStep::Single(cmd) = &self.steps[0]
+ && cmd.name.is_none()
+ {
+ return cmd.template.serialize(serializer);
+ }
+
+ // Single concurrent step (all named) → named table
+ if self.steps.len() == 1
+ && let HookStep::Concurrent(cmds) = &self.steps[0]
+ {
+ return serialize_commands_as_map(cmds, serializer);
}
- // Serialize as named map. Generate keys for unnamed commands (can happen
- // when merging unnamed global hooks with named project hooks, though
- // merged configs are only used for execution, never serialized in production).
- let mut map = serializer.serialize_map(Some(self.commands.len()))?;
- let mut unnamed_counter = 0u32;
- for cmd in &self.commands {
- let key = match &cmd.name {
- Some(name) => name.clone(),
- None => {
- unnamed_counter += 1;
- format!("_{unnamed_counter}")
+ // Pipeline → array of mixed strings and tables
+ use serde::ser::SerializeSeq;
+ let mut seq = serializer.serialize_seq(Some(self.steps.len()))?;
+ for step in &self.steps {
+ match step {
+ HookStep::Single(cmd) => {
+ if let Some(name) = &cmd.name {
+ let mut map = IndexMap::new();
+ map.insert(name.as_str(), cmd.template.as_str());
+ seq.serialize_element(&map)?;
+ } else {
+ seq.serialize_element(&cmd.template)?;
+ }
+ }
+ HookStep::Concurrent(cmds) => {
+ let mut map = IndexMap::new();
+ let mut unnamed_counter = 0u32;
+ for c in cmds {
+ let key = match &c.name {
+ Some(name) => name.as_str().to_string(),
+ None => {
+ unnamed_counter += 1;
+ format!("_{unnamed_counter}")
+ }
+ };
+ map.insert(key, c.template.as_str());
+ }
+ seq.serialize_element(&map)?;
}
- };
- map.serialize_entry(&key, &cmd.template)?;
+ }
}
- map.end()
+ seq.end()
}
}
+fn serialize_commands_as_map<S>(cmds: &[Command], serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: serde::Serializer,
+{
+ let mut map = serializer.serialize_map(Some(cmds.len()))?;
+ let mut unnamed_counter = 0u32;
+ for cmd in cmds {
+ let key = match &cmd.name {
+ Some(name) => name.clone(),
+ None => {
+ unnamed_counter += 1;
+ format!("_{unnamed_counter}")
+ }
+ };
+ map.serialize_entry(&key, &cmd.template)?;
+ }
+ map.end()
+}
+
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
@@ -190,7 +346,7 @@ mod tests {
use super::*;
// ============================================================================
- // Command Tests
+ // Deserialization Tests
// ============================================================================
#[test]
@@ -203,10 +359,14 @@ mod tests {
}
let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
- let commands = wrapper.command.commands();
+ let commands: Vec<_> = wrapper.command.commands().collect();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].name, None);
assert_eq!(commands[0].template, "npm install");
+
+ // Single string → one Single step
+ assert_eq!(wrapper.command.steps().len(), 1);
+ assert!(matches!(&wrapper.command.steps()[0], HookStep::Single(_)));
}
#[test]
@@ -223,15 +383,21 @@ test = "cargo test"
}
let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
- let commands = wrapper.command.commands();
+ let commands: Vec<_> = wrapper.command.commands().collect();
assert_eq!(commands.len(), 2);
assert!(commands.iter().any(|c| c.name == Some("build".to_string())));
assert!(commands.iter().any(|c| c.name == Some("test".to_string())));
+
+ // Named table → one Concurrent step
+ assert_eq!(wrapper.command.steps().len(), 1);
+ assert!(matches!(
+ &wrapper.command.steps()[0],
+ HookStep::Concurrent(cmds) if cmds.len() == 2
+ ));
}
#[test]
fn test_deserialize_preserves_order() {
- // Order should match TOML insertion order
let toml_str = r#"
[command]
first = "echo 1"
@@ -245,9 +411,8 @@ third = "echo 3"
}
let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
- let commands = wrapper.command.commands();
+ let commands: Vec<_> = wrapper.command.commands().collect();
assert_eq!(commands.len(), 3);
- // IndexMap preserves insertion order
assert_eq!(commands[0].name, Some("first".to_string()));
assert_eq!(commands[1].name, Some("second".to_string()));
assert_eq!(commands[2].name, Some("third".to_string()));
@@ -255,7 +420,6 @@ third = "echo 3"
#[test]
fn test_deserialize_rejects_colons_in_name() {
- // Hook names cannot contain colons (would break log spec parsing)
let toml_str = r#"
[command]
"my:server" = "npm start"
@@ -278,12 +442,103 @@ third = "echo 3"
}
// ============================================================================
- // CommandConfig Serialization Tests
+ // Pipeline Deserialization Tests
+ // ============================================================================
+
+ #[test]
+ fn test_deserialize_pipeline_strings() {
+ let toml_str = r#"command = ["npm install", "npm run build"]"#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ assert_eq!(wrapper.command.steps().len(), 2);
+ assert!(
+ matches!(&wrapper.command.steps()[0], HookStep::Single(c) if c.template == "npm install")
+ );
+ assert!(
+ matches!(&wrapper.command.steps()[1], HookStep::Single(c) if c.template == "npm run build")
+ );
+ }
+
+ #[test]
+ fn test_deserialize_pipeline_mixed() {
+ let toml_str = r#"command = [
+ "npm install",
+ { build = "npm run build", lint = "npm run lint" }
+]"#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ assert_eq!(wrapper.command.steps().len(), 2);
+ assert!(matches!(&wrapper.command.steps()[0], HookStep::Single(c) if c.name.is_none()));
+ assert!(matches!(
+ &wrapper.command.steps()[1],
+ HookStep::Concurrent(cmds) if cmds.len() == 2
+ ));
+
+ let commands: Vec<_> = wrapper.command.commands().collect();
+ assert_eq!(commands.len(), 3);
+ }
+
+ #[test]
+ fn test_deserialize_pipeline_named_single() {
+ // Single-entry map in list → named serial step
+ let toml_str = r#"command = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" }
+]"#;
+
+ #[derive(Deserialize)]
+ struct Wrapper {
+ command: CommandConfig,
+ }
+
+ let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
+ assert_eq!(wrapper.command.steps().len(), 2);
+
+ // First step: named single
+ if let HookStep::Single(cmd) = &wrapper.command.steps()[0] {
+ assert_eq!(cmd.name.as_deref(), Some("install"));
+ assert_eq!(cmd.template, "npm install");
+ } else {
+ panic!("Expected Single step");
+ }
+
+ // Second step: concurrent group
+ assert!(matches!(
+ &wrapper.command.steps()[1],
+ HookStep::Concurrent(cmds) if cmds.len() == 2
+ ));
+ }
+
+ #[test]
+ fn test_deserialize_pipeline_rejects_colons() {
+ let toml_str = r#"command = [{ "my:hook" = "npm start" }]"#;
+
+ #[derive(Debug, Deserialize)]
+ struct Wrapper {
+ #[serde(rename = "command")]
+ _command: CommandConfig,
+ }
+
+ let result: Result<Wrapper, _> = toml::from_str(toml_str);
+ assert!(result.is_err());
+ }
+
+ // ============================================================================
+ // Serialization Tests
// ============================================================================
#[test]
fn test_serialize_single_unnamed() {
- // A single unnamed command should serialize as a string (when wrapped in a struct)
#[derive(Serialize)]
struct Wrapper {
cmd: CommandConfig,
@@ -291,7 +546,10 @@ third = "echo 3"
let wrapper = Wrapper {
cmd: CommandConfig {
- commands: vec![Command::new(None, "npm install".to_string())],
+ steps: vec![HookStep::Single(Command::new(
+ None,
+ "npm install".to_string(),
+ ))],
},
};
@@ -299,8 +557,7 @@ third = "echo 3"
}
#[test]
- fn test_serialize_named_commands() {
- // Multiple named commands should serialize as a table
+ fn test_serialize_concurrent() {
#[derive(Serialize)]
struct Wrapper {
cmd: CommandConfig,
@@ -308,10 +565,10 @@ third = "echo 3"
let wrapper = Wrapper {
cmd: CommandConfig {
- commands: vec![
+ steps: vec![HookStep::Concurrent(vec![
Command::new(Some("build".to_string()), "cargo build".to_string()),
Command::new(Some("test".to_string()), "cargo test".to_string()),
- ],
+ ])],
},
};
@@ -322,10 +579,35 @@ third = "echo 3"
"#);
}
+ #[test]
+ fn test_serialize_pipeline() {
+ #[derive(Serialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ let wrapper = Wrapper {
+ cmd: CommandConfig {
+ steps: vec![
+ HookStep::Single(Command::new(None, "npm install".to_string())),
+ HookStep::Concurrent(vec![
+ Command::new(Some("build".to_string()), "npm run build".to_string()),
+ Command::new(Some("lint".to_string()), "npm run lint".to_string()),
+ ]),
+ ],
+ },
+ };
+
+ assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"cmd = ["npm install", { build = "npm run build", lint = "npm run lint" }]"#);
+ }
+
#[test]
fn test_serialize_deserialize_roundtrip_single() {
let config = CommandConfig {
- commands: vec![Command::new(None, "echo hello".to_string())],
+ steps: vec![HookStep::Single(Command::new(
+ None,
+ "echo hello".to_string(),
+ ))],
};
#[derive(Serialize, Deserialize)]
@@ -337,17 +619,20 @@ third = "echo 3"
let serialized = toml::to_string(&wrapper).unwrap();
let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
- assert_eq!(deserialized.cmd.commands().len(), 1);
- assert_eq!(deserialized.cmd.commands()[0].template, "echo hello");
+ assert_eq!(deserialized.cmd.commands().count(), 1);
+ assert_eq!(
+ deserialized.cmd.commands().next().unwrap().template,
+ "echo hello"
+ );
}
#[test]
fn test_serialize_deserialize_roundtrip_named() {
let config = CommandConfig {
- commands: vec![
+ steps: vec![HookStep::Concurrent(vec![
Command::new(Some("a".to_string()), "echo a".to_string()),
Command::new(Some("b".to_string()), "echo b".to_string()),
- ],
+ ])],
};
#[derive(Serialize, Deserialize)]
@@ -359,91 +644,60 @@ third = "echo 3"
let serialized = toml::to_string(&wrapper).unwrap();
let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
- assert_eq!(deserialized.cmd.commands().len(), 2);
+ assert_eq!(deserialized.cmd.commands().count(), 2);
}
// ============================================================================
- // CommandConfig Methods Tests
+ // Commands() Flattening Tests
// ============================================================================
#[test]
- fn test_commands_returns_slice() {
+ fn test_commands_flattens_pipeline() {
let config = CommandConfig {
- commands: vec![
- Command::new(None, "cmd1".to_string()),
- Command::new(None, "cmd2".to_string()),
+ steps: vec![
+ HookStep::Single(Command::new(None, "cmd1".to_string())),
+ HookStep::Concurrent(vec![
+ Command::new(Some("a".to_string()), "cmd2".to_string()),
+ Command::new(Some("b".to_string()), "cmd3".to_string()),
+ ]),
+ HookStep::Single(Command::new(None, "cmd4".to_string())),
],
};
- let cmds = config.commands();
- assert_eq!(cmds.len(), 2);
+ let cmds: Vec<_> = config.commands().collect();
+ assert_eq!(cmds.len(), 4);
assert_eq!(cmds[0].template, "cmd1");
assert_eq!(cmds[1].template, "cmd2");
+ assert_eq!(cmds[2].template, "cmd3");
+ assert_eq!(cmds[3].template, "cmd4");
}
- #[test]
- fn test_command_config_equality() {
- let config1 = CommandConfig {
- commands: vec![Command::new(None, "test".to_string())],
- };
- let config2 = CommandConfig {
- commands: vec![Command::new(None, "test".to_string())],
- };
- assert_eq!(config1, config2);
- }
+ // ============================================================================
+ // Merge Tests
+ // ============================================================================
#[test]
- fn test_command_config_merge_append() {
+ fn test_merge_append_steps() {
let base = CommandConfig {
- commands: vec![
- Command::new(None, "echo base1".to_string()),
- Command::new(Some("named".to_string()), "echo base2".to_string()),
- ],
+ steps: vec![HookStep::Single(Command::new(None, "step1".to_string()))],
};
let overlay = CommandConfig {
- commands: vec![Command::new(None, "echo overlay".to_string())],
+ steps: vec![HookStep::Concurrent(vec![
+ Command::new(Some("a".to_string()), "step2a".to_string()),
+ Command::new(Some("b".to_string()), "step2b".to_string()),
+ ])],
};
let merged = base.merge_append(&overlay);
- assert_eq!(merged.commands.len(), 3);
- assert_eq!(merged.commands[0].template, "echo base1");
- assert_eq!(merged.commands[1].template, "echo base2");
- assert_eq!(merged.commands[2].template, "echo overlay");
- }
-
- #[test]
- fn test_command_config_merge_append_empty_base() {
- let base = CommandConfig { commands: vec![] };
- let overlay = CommandConfig {
- commands: vec![Command::new(None, "echo overlay".to_string())],
- };
-
- let merged = base.merge_append(&overlay);
- assert_eq!(merged.commands.len(), 1);
- assert_eq!(merged.commands[0].template, "echo overlay");
- }
-
- #[test]
- fn test_command_config_merge_append_empty_overlay() {
- let base = CommandConfig {
- commands: vec![Command::new(None, "echo base".to_string())],
- };
- let overlay = CommandConfig { commands: vec![] };
-
- let merged = base.merge_append(&overlay);
- assert_eq!(merged.commands.len(), 1);
- assert_eq!(merged.commands[0].template, "echo base");
+ assert_eq!(merged.steps.len(), 2);
+ assert!(matches!(&merged.steps[0], HookStep::Single(_)));
+ assert!(matches!(&merged.steps[1], HookStep::Concurrent(_)));
}
// ============================================================================
- // Serialization Edge Cases (merged configs)
+ // Backward Compatibility
// ============================================================================
- //
- // Note: Merged configs (from merge_append) are only used for execution,
- // never serialized in production. These tests verify serialization doesn't
- // panic, but round-trip fidelity isn't required.
- /// Serializing a merged config with mixed named/unnamed commands doesn't panic.
#[test]
fn test_serialize_mixed_named_unnamed_succeeds() {
#[derive(Serialize)]
@@ -453,24 +707,23 @@ third = "echo 3"
// Simulate merge of unnamed global + named project hooks
let global = CommandConfig {
- commands: vec![Command::new(None, "npm install".to_string())],
+ steps: vec![HookStep::Single(Command::new(
+ None,
+ "npm install".to_string(),
+ ))],
};
let per_project = CommandConfig {
- commands: vec![Command::new(
+ steps: vec![HookStep::Concurrent(vec![Command::new(
Some("setup".to_string()),
"echo setup".to_string(),
- )],
+ )])],
};
let merged = global.merge_append(&per_project);
- assert_eq!(merged.commands.len(), 2);
+ assert_eq!(merged.steps.len(), 2);
- // Should not panic - generates "_1" for unnamed command
+ // Pipeline serialization
let wrapper = Wrapper { cmd: merged };
- assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"
- [cmd]
- _1 = "npm install"
- setup = "echo setup"
- "#);
+ assert_snapshot!(toml::to_string(&wrapper).unwrap(), @r#"cmd = ["npm install", { setup = "echo setup" }]"#);
}
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 87b1571c3..050888dc0 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -72,7 +72,7 @@ impl WorktrunkConfig for ProjectConfig {
// Re-export public types
pub use approvals::{Approvals, approvals_path};
-pub use commands::{Command, CommandConfig, append_aliases};
+pub use commands::{Command, CommandConfig, HookStep, append_aliases};
pub use deprecation::DeprecationInfo;
pub use deprecation::Deprecations;
pub use deprecation::check_and_migrate;
@@ -303,9 +303,9 @@ mod tests {
let toml = r#"post-create = "npm install""#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.post_create.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
assert_eq!(commands.len(), 1);
- assert_eq!(commands[0], Command::new(None, "npm install".to_string()));
+ assert_eq!(*commands[0], Command::new(None, "npm install".to_string()));
}
#[test]
@@ -317,15 +317,15 @@ mod tests {
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.post_start.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
assert_eq!(commands.len(), 2);
// Preserves TOML insertion order
assert_eq!(
- commands[0],
+ *commands[0],
Command::new(Some("server".to_string()), "npm run dev".to_string())
);
assert_eq!(
- commands[1],
+ *commands[1],
Command::new(Some("watch".to_string()), "npm run watch".to_string())
);
}
@@ -341,7 +341,7 @@ mod tests {
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.pre_merge.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
// Extract just the names for easier verification
let names: Vec<_> = commands
@@ -371,7 +371,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.post_start.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
assert_eq!(commands.len(), 2);
// Should be in TOML order: task1, task2
@@ -405,9 +405,9 @@ task2 = "echo 'Task 2 running' > task2.txt"
let toml = r#"pre-merge = "cargo test""#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.pre_merge.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
assert_eq!(commands.len(), 1);
- assert_eq!(commands[0], Command::new(None, "cargo test".to_string()));
+ assert_eq!(*commands[0], Command::new(None, "cargo test".to_string()));
}
#[test]
@@ -420,22 +420,22 @@ task2 = "echo 'Task 2 running' > task2.txt"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
let cmd_config = config.hooks.pre_merge.unwrap();
- let commands = cmd_config.commands();
+ let commands: Vec<_> = cmd_config.commands().collect();
assert_eq!(commands.len(), 3);
// Preserves TOML insertion order
assert_eq!(
- commands[0],
+ *commands[0],
Command::new(
Some("format".to_string()),
"cargo fmt -- --check".to_string()
)
);
assert_eq!(
- commands[1],
+ *commands[1],
Command::new(Some("lint".to_string()), "cargo clippy".to_string())
);
assert_eq!(
- commands[2],
+ *commands[2],
Command::new(Some("test".to_string()), "cargo test".to_string())
);
}
@@ -694,7 +694,7 @@ lint = "cargo clippy"
.hooks
.post_create
.expect("post-create should be present");
- let commands = post_create.commands();
+ let commands: Vec<_> = post_create.commands().collect();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].name.as_deref(), Some("log"));
@@ -704,7 +704,7 @@ lint = "cargo clippy"
.hooks
.pre_merge
.expect("pre-merge should be present");
- let commands = pre_merge.commands();
+ let commands: Vec<_> = pre_merge.commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].name.as_deref(), Some("test"));
assert_eq!(commands[1].name.as_deref(), Some("lint"));
@@ -723,7 +723,7 @@ post-create = "npm install"
.hooks
.post_create
.expect("post-create should be present");
- let commands = post_create.commands();
+ let commands: Vec<_> = post_create.commands().collect();
assert_eq!(commands.len(), 1);
assert!(commands[0].name.is_none()); // single command has no name
assert_eq!(commands[0].template, "npm install");
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 90b90d41f..ce74bd4a1 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -635,12 +635,12 @@ mod tests {
("shared".into(), CommandConfig::single("other-cmd")),
]);
let result = merge_alias_maps(&Some(base), &Some(other)).unwrap();
- assert_eq!(result["a"].commands().len(), 1);
- assert_eq!(result["b"].commands().len(), 1);
+ assert_eq!(result["a"].commands().count(), 1);
+ assert_eq!(result["b"].commands().count(), 1);
// Collision: both commands are preserved (base first, then other)
- let shared = &result["shared"];
- assert_eq!(shared.commands().len(), 2);
- assert_eq!(shared.commands()[0].template, "base-cmd");
- assert_eq!(shared.commands()[1].template, "other-cmd");
+ let shared: Vec<_> = result["shared"].commands().collect();
+ assert_eq!(shared.len(), 2);
+ assert_eq!(shared[0].template, "base-cmd");
+ assert_eq!(shared[1].template, "other-cmd");
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 92cf8e955..9a80dca8e 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -1906,7 +1906,7 @@ fn test_hooks_merge_append_semantics() {
let effective = config.hooks(Some("github.com/user/repo"));
let post_start = effective.post_start.unwrap();
- let commands = post_start.commands();
+ let commands: Vec<_> = post_start.commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "echo global");
assert_eq!(commands[1].template, "echo project");
@@ -1925,7 +1925,7 @@ fn test_hooks_no_project_override_uses_global() {
let effective = config.hooks(Some("github.com/other/repo"));
let post_start = effective.post_start.unwrap();
- let commands = post_start.commands();
+ let commands: Vec<_> = post_start.commands().collect();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].template, "echo global");
}
@@ -1948,7 +1948,7 @@ fn test_hooks_project_only_no_global() {
let effective = config.hooks(Some("github.com/user/repo"));
let post_start = effective.post_start.unwrap();
- let commands = post_start.commands();
+ let commands: Vec<_> = post_start.commands().collect();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].template, "echo project");
}
@@ -1980,13 +1980,13 @@ fn test_hooks_different_hook_types_not_merged() {
// post-start: only global
let post_start = effective.post_start.unwrap();
- let start_commands = post_start.commands();
+ let start_commands: Vec<_> = post_start.commands().collect();
assert_eq!(start_commands.len(), 1);
assert_eq!(start_commands[0].template, "echo global-start");
// pre-commit: only project
let pre_commit = effective.pre_commit.unwrap();
- let commit_commands = pre_commit.commands();
+ let commit_commands: Vec<_> = pre_commit.commands().collect();
assert_eq!(commit_commands.len(), 1);
assert_eq!(commit_commands[0].template, "echo project-commit");
}
@@ -2004,7 +2004,7 @@ fn test_hooks_none_project_uses_global() {
let effective = config.hooks(None);
let post_start = effective.post_start.unwrap();
- let commands = post_start.commands();
+ let commands: Vec<_> = post_start.commands().collect();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].template, "echo global");
}
@@ -2132,7 +2132,7 @@ setup = "echo setup"
// Verify merge preserves order: global first, then project
let effective = config.hooks(Some("github.com/user/repo"));
- let commands = effective.post_start.as_ref().unwrap().commands();
+ let commands: Vec<_> = effective.post_start.as_ref().unwrap().commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "npm install"); // Global first
assert_eq!(commands[1].template, "echo setup"); // Project second
@@ -2177,7 +2177,7 @@ test = "npm test"
// Both commands present, global first
let effective = config.hooks(Some("github.com/user/repo"));
- let commands = effective.post_start.as_ref().unwrap().commands();
+ let commands: Vec<_> = effective.post_start.as_ref().unwrap().commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "cargo test");
assert_eq!(commands[1].template, "npm test");
@@ -2332,7 +2332,7 @@ fn test_hooks_merge_trait_appends_for_global_project_merge() {
let merged = global_hooks.merge_with(&project_hooks);
let pre_merge = merged.pre_merge.unwrap();
- let commands = pre_merge.commands();
+ let commands: Vec<_> = pre_merge.commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "global-lint"); // Global first
assert_eq!(commands[1].template, "project-lint"); // Project second
@@ -2349,7 +2349,7 @@ fn test_hooks_merge_folds_post_create_into_pre_start() {
let pre_start = merged
.get(HookType::PreStart)
.expect("should have pre-start");
- let commands = pre_start.commands();
+ let commands: Vec<_> = pre_start.commands().collect();
assert_eq!(commands.len(), 2, "Both hooks should be present");
assert_eq!(commands[0].template, "npm install"); // User's post-create first
assert_eq!(commands[1].template, "cargo test"); // Project's pre-start second
@@ -2367,7 +2367,7 @@ fn test_hooks_merge_same_source_both_pre_start_and_post_create() {
let pre_start = merged
.get(HookType::PreStart)
.expect("should have pre-start");
- let commands = pre_start.commands();
+ let commands: Vec<_> = pre_start.commands().collect();
assert_eq!(
commands.len(),
2,
@@ -2387,7 +2387,7 @@ fn test_hooks_merge_post_create_both_sides() {
let pre_start = merged
.get(HookType::PreStart)
.expect("should have pre-start");
- let commands = pre_start.commands();
+ let commands: Vec<_> = pre_start.commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "npm install");
assert_eq!(commands[1].template, "cargo build");
@@ -2409,24 +2409,30 @@ project-only = "only-project"
let aliases = config.aliases(Some("test-project"));
// Non-colliding aliases are present
- assert_eq!(aliases["global-only"].commands().len(), 1);
- assert_eq!(aliases["global-only"].commands()[0].template, "only-global");
- assert_eq!(aliases["project-only"].commands().len(), 1);
+ assert_eq!(aliases["global-only"].commands().count(), 1);
assert_eq!(
- aliases["project-only"].commands()[0].template,
+ aliases["global-only"].commands().next().unwrap().template,
+ "only-global"
+ );
+ assert_eq!(aliases["project-only"].commands().count(), 1);
+ assert_eq!(
+ aliases["project-only"].commands().next().unwrap().template,
"only-project"
);
// Colliding alias: both commands run (global first, then per-project)
- let shared = &aliases["shared"];
- assert_eq!(shared.commands().len(), 2);
- assert_eq!(shared.commands()[0].template, "global-cmd");
- assert_eq!(shared.commands()[1].template, "project-cmd");
+ let shared: Vec<_> = aliases["shared"].commands().collect();
+ assert_eq!(shared.len(), 2);
+ assert_eq!(shared[0].template, "global-cmd");
+ assert_eq!(shared[1].template, "project-cmd");
// Without project: only global aliases
let global_only = config.aliases(None);
- assert_eq!(global_only["shared"].commands().len(), 1);
- assert_eq!(global_only["shared"].commands()[0].template, "global-cmd");
+ assert_eq!(global_only["shared"].commands().count(), 1);
+ assert_eq!(
+ global_only["shared"].commands().next().unwrap().template,
+ "global-cmd"
+ );
}
/// Test that reload_projects_from handles permission errors
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 9c644a160..660de8bcd 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -14,6 +14,7 @@ use crate::commands::branch_deletion::{
use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_background_hooks,
+ spawn_hook_pipeline,
};
use crate::commands::process::{
HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,
@@ -851,12 +852,19 @@ fn spawn_hooks_after_remove(
let dest_branch = repo.worktree_at(main_path).branch()?;
let switch_ctx =
CommandContext::new(repo, &config, dest_branch.as_deref(), main_path, false);
- hooks.extend(prepare_background_hooks(
+ match prepare_background_hooks(
&switch_ctx,
worktrunk::HookType::PostSwitch,
&[],
display_path,
- )?);
+ )? {
+ crate::commands::hooks::PreparedHooks::Flat(cmds) => hooks.extend(cmds),
+ crate::commands::hooks::PreparedHooks::Pipeline(steps) => {
+ if !steps.is_empty() {
+ spawn_hook_pipeline(&switch_ctx, steps)?;
+ }
+ }
+ }
}
spawn_background_hooks(&remove_ctx, hooks)
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 6fba22d1c..3836f9c30 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1245,3 +1245,129 @@ approved-commands = ["echo 'POST-START-RAN' > post_start_marker.txt"]
"Post-start should NOT run when switching to existing worktree"
);
}
+
+// ============================================================================
+// Pipeline Tests (project config, list form)
+// ============================================================================
+
+#[rstest]
+fn test_post_start_project_pipeline(repo: TestRepo) {
+ // Project config with pipeline: serial setup, then concurrent tasks
+ repo.write_project_config(
+ r#"post-start = [
+ "echo SETUP > setup_marker.txt",
+ { task1 = "cat setup_marker.txt > task1_saw_setup.txt", task2 = "echo TASK2 > task2.txt" }
+]
+"#,
+ );
+ repo.commit("Add pipeline config");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = [
+ "echo SETUP > setup_marker.txt",
+ "cat setup_marker.txt > task1_saw_setup.txt",
+ "echo TASK2 > task2.txt",
+]
+"#,
+ );
+
+ snapshot_switch(
+ "post_start_project_pipeline",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ // task1 reads the setup marker — verifies serial-before-concurrent ordering
+ let task1_file = worktree_path.join("task1_saw_setup.txt");
+ wait_for_file_content(&task1_file);
+
+ let content = fs::read_to_string(&task1_file).unwrap();
+ assert!(
+ content.contains("SETUP"),
+ "Concurrent task should see serial step's output, got: {content}"
+ );
+}
+
+#[rstest]
+fn test_post_start_pipeline_with_template_vars(repo: TestRepo) {
+ // Pipeline with template variable expansion
+ repo.write_project_config(
+ r#"post-start = [
+ "echo {{ branch }} > branch_marker.txt",
+ { check = "cat branch_marker.txt > branch_check.txt" }
+]
+"#,
+ );
+ repo.commit("Add pipeline with templates");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = [
+ "echo {{ branch }} > branch_marker.txt",
+ "cat branch_marker.txt > branch_check.txt",
+]
+"#,
+ );
+
+ snapshot_switch(
+ "post_start_pipeline_template_vars",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let check_file = worktree_path.join("branch_check.txt");
+ wait_for_file_content(&check_file);
+
+ let content = fs::read_to_string(&check_file).unwrap();
+ assert!(
+ content.contains("feature"),
+ "Template variable should be expanded in pipeline, got: {content}"
+ );
+}
+
+#[rstest]
+fn test_post_start_mixed_user_pipeline_project_flat(repo: TestRepo) {
+ // User has a pipeline, project has flat concurrent commands.
+ // Both should execute.
+ repo.write_test_config(
+ r#"post-start = [
+ "echo USER_SETUP > user_pipeline_marker.txt",
+ { user_bg = "echo USER_BG > user_bg.txt" }
+]
+"#,
+ );
+
+ repo.write_project_config(
+ r#"[post-start]
+proj = "echo PROJECT > project_marker.txt"
+"#,
+ );
+ repo.commit("Add project config");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = ["echo PROJECT > project_marker.txt"]
+"#,
+ );
+
+ snapshot_switch(
+ "post_start_mixed_user_pipeline_project_flat",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+
+ // User pipeline should run
+ wait_for_file_content(&worktree_path.join("user_bg.txt"));
+ let user_bg = fs::read_to_string(worktree_path.join("user_bg.txt")).unwrap();
+ assert!(user_bg.contains("USER_BG"));
+
+ // Project flat hook should also run
+ wait_for_file_content(&worktree_path.join("project_marker.txt"));
+ let project = fs::read_to_string(worktree_path.join("project_marker.txt")).unwrap();
+ assert!(project.contains("PROJECT"));
+}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 263098a77..b84259d9d 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -2302,3 +2302,65 @@ check = "test -d {{ cwd }} && echo 'cwd_exists=true' > ../cwd_check.txt || echo
"cwd should point to an existing directory, got: {content}"
);
}
+
+// ============================================================================
+// Pipeline Tests (list form)
+// ============================================================================
+
+#[rstest]
+fn test_user_post_start_pipeline_serial_ordering(repo: TestRepo) {
+ // Pipeline: serial step creates a marker, concurrent step reads it.
+ // The compound shell command chains them with &&, so the marker
+ // exists when the concurrent step runs.
+ repo.write_test_config(
+ r#"post-start = [
+ "echo SETUP_DONE > pipeline_marker.txt",
+ { bg = "cat pipeline_marker.txt > bg_saw_marker.txt" }
+]
+"#,
+ );
+
+ snapshot_switch(
+ "user_post_start_pipeline_ordering",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let bg_file = worktree_path.join("bg_saw_marker.txt");
+ wait_for_file_content(&bg_file);
+
+ let content = fs::read_to_string(&bg_file).unwrap();
+ assert!(
+ content.contains("SETUP_DONE"),
+ "Concurrent step should see serial step's output, got: {content}"
+ );
+}
+
+#[rstest]
+fn test_user_post_start_pipeline_failure_skips_later_steps(repo: TestRepo) {
+ // First step fails → second step should not run (chained with &&).
+ repo.write_test_config(
+ r#"post-start = [
+ "exit 1",
+ { bg = "echo SHOULD_NOT_RUN > should_not_exist.txt" }
+]
+"#,
+ );
+
+ snapshot_switch(
+ "user_post_start_pipeline_failure",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ // Give background commands time to run (if they were going to)
+ thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let marker_file = worktree_path.join("should_not_exist.txt");
+ assert!(
+ !marker_file.exists(),
+ "Later pipeline steps should NOT run after serial step failure"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_mixed_user_pipeline_project_flat.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_mixed_user_pipeline_project_flat.snap
new file mode 100644
index 000000000..5bce534bc
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_mixed_user_pipeline_project_flat.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: cmd-0 → user_bg → proj @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_pipeline_template_vars.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_pipeline_template_vars.snap
new file mode 100644
index 000000000..81ab49267
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_pipeline_template_vars.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: cmd-0 → check @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_project_pipeline.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_project_pipeline.snap
new file mode 100644
index 000000000..4194897b4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_project_pipeline.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: cmd-0 → task1, task2 @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_failure.snap
new file mode 100644
index 000000000..8421a5d74
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_failure.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: cmd-0 → bg @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_ordering.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_ordering.snap
new file mode 100644
index 000000000..8421a5d74
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_ordering.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/user_hooks.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: cmd-0 → bg @ _REPO_.feature