Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: route all background hooks through pipeline-aware API (#1910)
Maximilian Roos5cd7da344eac
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 89b30a451..0c872de45 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -27,9 +27,8 @@ use super::command_executor::build_hook_context;use super::command_executor::CommandContext;use super::context::CommandEnv;use super::hooks::{- HookCommandSpec, HookFailureStrategy, check_name_filter_matched, prepare_hook_commands,- prepare_pipeline_hooks_with_configs, run_hook_with_filter, spawn_background_hooks,- spawn_hook_pipeline,+ HookCommandSpec, HookFailureStrategy, check_name_filter_matched, prepare_background_hooks,+ prepare_hook_commands, run_hook_with_filter, spawn_background_hooks, spawn_prepared_hooks,};use super::project_config::collect_commands_for_hooks;@@ -67,37 +66,27 @@ fn run_post_hook() -> anyhow::Result<()> {// Default to background execution; --foreground is for debugging.if !foreground.unwrap_or(false) {- // Pipeline configs (list form) use the background pipeline runner.- // 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(+ if name_filter.is_some() {+ // Name filtering operates on individual commands — use the flat path+ // which extracts matching commands regardless of pipeline structure.+ let commands = prepare_hook_commands(ctx,- user_config,- project_config,- hook_type,- extra_vars,- None,+ HookCommandSpec {+ user_config,+ project_config,+ hook_type,+ extra_vars,+ name_filter,+ display_path: None,+ },)?;- return spawn_hook_pipeline(ctx, steps);+ check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;+ return spawn_background_hooks(ctx, commands);}- let commands = prepare_hook_commands(- ctx,- HookCommandSpec {- user_config,- project_config,- hook_type,- extra_vars,- name_filter,- display_path: None,- },- )?;- check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;- return spawn_background_hooks(ctx, commands);+ // No name filter: use the unified path that auto-detects pipeline vs flat.+ let hooks = prepare_background_hooks(ctx, hook_type, extra_vars, None)?;+ return spawn_prepared_hooks(ctx, hooks);}run_filtered_hook(diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 9133abdc1..f22368a22 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -237,11 +237,32 @@ pub fn spawn_background_hooks(// Use HookLog with the command's own hook_type for consistent log file naminglet hook_log = HookLog::hook(cmd.source, cmd.hook_type, &name);+ // Lazy commands (referencing vars.) carry the raw template in lazy_template.+ // Expand them before spawning, same as run_hook_with_filter does for foreground.+ let expanded = if let Some(ref template) = cmd.prepared.lazy_template {+ let name_label = cmd.summary_name();+ match expand_lazy_template(template, &cmd.prepared.context_json, ctx.repo, &name_label)+ {+ Ok(s) => s,+ Err(err) => {+ eprintln!(+ "{}",+ warning_message(format!(+ "Failed to expand template for \"{name_label}\": {err}"+ ))+ );+ continue;+ }+ }+ } else {+ cmd.prepared.expanded.clone()+ };+let log_label = format!("{} {}", cmd.hook_type, cmd.summary_name());if let Err(err) = spawn_detached(ctx.repo,ctx.worktree_path,- &cmd.prepared.expanded,+ &expanded,ctx.branch_or_head(),&hook_log,Some(&cmd.prepared.context_json),@@ -254,7 +275,7 @@ pub fn spawn_background_hooks(eprintln!("{}", warning_message(message));} else {// Background: outcome unknown, log with null exit/duration- worktrunk::command_log::log_command(&log_label, &cmd.prepared.expanded, None, None);+ worktrunk::command_log::log_command(&log_label, &expanded, None, None);}}@@ -346,8 +367,10 @@ pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> any};eprintln!("{}", progress_message(message));- // Extract context from the first command. All steps share the same base context.- let context: std::collections::HashMap<String, String> = steps+ // Extract base context from the first command. All steps share the same base context,+ // but per-step metadata (hook_name) is stripped — it gets injected per-step by the+ // background runner.+ let mut context: std::collections::HashMap<String, String> = steps.iter().find_map(|s| match &s.step {PreparedStep::Single(cmd) => Some(&cmd.context_json),@@ -356,6 +379,7 @@ pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> any.map(|json| serde_json::from_str(json).context("failed to deserialize context_json")).transpose()?.unwrap_or_default();+ context.remove("hook_name");// Build pipeline spec from prepared steps. Use the raw template for lazy// steps (vars-referencing) and the expanded command for eager steps.@@ -418,7 +442,7 @@ pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> any/// 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(+fn prepare_pipeline_hooks_with_configs(ctx: &CommandContext,user_config: Option<&CommandConfig>,proj_config: Option<&CommandConfig>,@@ -542,15 +566,8 @@ pub fn run_hook_with_filter(// Lazy commands (referencing vars.) are expanded just before execution// so that vars set by earlier commands in the pipeline are available.let expanded = if let Some(ref template) = cmd.prepared.lazy_template {- let context_map: std::collections::HashMap<String, String> =- serde_json::from_str(&cmd.prepared.context_json)- .expect("context_json round-trip should never fail");- let vars: std::collections::HashMap<&str, &str> = context_map- .iter()- .map(|(k, v)| (k.as_str(), v.as_str()))- .collect();let name = cmd.summary_name();- worktrunk::config::expand_template(template, &vars, true, ctx.repo, &name)?+ expand_lazy_template(template, &cmd.prepared.context_json, ctx.repo, &name)?} else {cmd.prepared.expanded.clone()};@@ -703,6 +720,27 @@ pub(crate) fn spawn_prepared_hooks(}}+/// Expand a lazy template using its command's context JSON.+///+/// Used by both `spawn_background_hooks` (background) and `run_hook_with_filter`+/// (foreground) to expand templates that reference `vars.*` at execution time.+fn expand_lazy_template(+ template: &str,+ context_json: &str,+ repo: &worktrunk::git::Repository,+ label: &str,+) -> anyhow::Result<String> {+ let context_map: std::collections::HashMap<String, String> =+ serde_json::from_str(context_json).context("failed to deserialize context_json")?;+ let vars: std::collections::HashMap<&str, &str> = context_map+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();+ Ok(worktrunk::config::expand_template(+ template, &vars, true, repo, label,+ )?)+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 20375fda9..4bd38d66b 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -9,8 +9,7 @@ use super::command_executor::CommandContext;use super::commit::CommitOptions;use super::context::CommandEnv;use super::hooks::{- HookCommandSpec, HookFailureStrategy, execute_hook, prepare_hook_commands,- spawn_background_hooks,+ HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_prepared_hooks,};use super::project_config::{ApprovableCommand, collect_commands_for_hooks};use super::repository_ext::{@@ -356,25 +355,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {extra.push(("short_commit", sc));}- let project_config = ctx.repo.load_project_config()?;- let user_hooks_cfg = ctx.config.hooks(ctx.project_id().as_deref());- let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(- &user_hooks_cfg,- project_config.as_ref(),- HookType::PostMerge,- );- let commands = prepare_hook_commands(- &ctx,- HookCommandSpec {- user_config: user_cfg,- project_config: proj_cfg,- hook_type: HookType::PostMerge,- extra_vars: &extra,- name_filter: None,- display_path,- },- )?;- spawn_background_hooks(&ctx, commands)?;+ let hooks = prepare_background_hooks(&ctx, HookType::PostMerge, &extra, display_path)?;+ spawn_prepared_hooks(&ctx, hooks)?;}Ok(())diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex c4d168a47..7660c0f51 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -27,9 +27,12 @@ use super::branch_deletion::delete_branch_if_safe;use super::handle_switch::{approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,};-use super::hooks::{HookFailureStrategy, execute_hook, spawn_background_hooks};+use super::hooks::{+ HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_prepared_hooks,+};use super::list::collect;use super::repository_ext::{RemoveTarget, RepositoryCliExt};+use super::worktree::hooks::PostRemoveContext;use super::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,execute_switch, offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,@@ -133,15 +136,20 @@ impl PickerCollector {// Spawn post-remove hooks in background (log to files, no terminal output).let post_ctx =CommandContext::new(&repo, config, Some(hook_branch), main_path, false);- let post_hooks = post_ctx.prepare_post_remove_commands(- hook_branch,+ let remove_vars = PostRemoveContext::new(worktree_path,removed_commit.as_deref(),+ main_path,+ &repo,+ );+ let extra_vars = remove_vars.extra_vars(hook_branch);+ let hooks = prepare_background_hooks(+ &post_ctx,+ worktrunk::HookType::PostRemove,+ &extra_vars,None, // no display path in TUI context)?;- if !post_hooks.is_empty() {- spawn_background_hooks(&post_ctx, post_hooks)?;- }+ spawn_prepared_hooks(&post_ctx, hooks)?;}RemoveResult::BranchOnly {branch_name,diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex 0c5a52f12..97cfb8c16 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -82,14 +82,12 @@ pub fn run_pipeline() -> anyhow::Result<()> {let repo =Repository::at(&spec.worktree_path).context("failed to open repository for pipeline")?;- let context_json =- serde_json::to_string(&spec.context).context("failed to serialize pipeline context")?;-for step in &spec.steps {match step {PipelineStepSpec::Single { template, name } => {let expanded = expand_now(template, &spec, &repo, name.as_deref())?;- let mut child = spawn_shell_command(&expanded, &spec.worktree_path, &context_json)?;+ let step_json = build_step_context_json(&spec.context, name.as_deref())?;+ let mut child = spawn_shell_command(&expanded, &spec.worktree_path, &step_json)?;let status = child.wait().context("failed to wait for child process")?;if !status.success() {bail!(@@ -100,7 +98,7 @@ pub fn run_pipeline() -> anyhow::Result<()> {}}PipelineStepSpec::Concurrent { commands } => {- run_concurrent_group(commands, &spec, &repo, &context_json)?;+ run_concurrent_group(commands, &spec, &repo)?;}}}@@ -109,17 +107,23 @@ pub fn run_pipeline() -> anyhow::Result<()> {}/// Expand a template using the spec's context and fresh vars from git config.+///+/// Injects per-step `hook_name` into the vars so each step sees its own name,+/// not the first step's name (the shared context has `hook_name` stripped).fn expand_now(template: &str,spec: &PipelineSpec,repo: &Repository,name: Option<&str>,) -> anyhow::Result<String> {- let vars: HashMap<&str, &str> = spec+ let mut vars: HashMap<&str, &str> = spec.context.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();+ if let Some(n) = name {+ vars.insert("hook_name", n);+ }let label = name.unwrap_or("pipeline step");// shell_escape=true — values are interpolated into a string passed to a shell,// so they must be escaped to prevent word splitting and metachar injection.@@ -158,13 +162,13 @@ fn run_concurrent_group(commands: &[super::pipeline_spec::PipelineCommandSpec],spec: &PipelineSpec,repo: &Repository,- context_json: &str,) -> anyhow::Result<()> {let mut children = Vec::with_capacity(commands.len());for cmd in commands {let expanded = expand_now(&cmd.template, spec, repo, cmd.name.as_deref())?;- let child = spawn_shell_command(&expanded, &spec.worktree_path, context_json)?;+ let cmd_json = build_step_context_json(&spec.context, cmd.name.as_deref())?;+ let child = spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json)?;children.push((cmd.name.clone(), expanded, child));}@@ -185,6 +189,24 @@ fn run_concurrent_group(Ok(())}+/// Build per-step context JSON, injecting `hook_name` when the step has a name.+///+/// The shared pipeline context has `hook_name` stripped (it varies per step).+/// This function adds it back for the specific step so commands receive the+/// correct `hook_name` on stdin.+fn build_step_context_json(+ base_context: &HashMap<String, String>,+ name: Option<&str>,+) -> anyhow::Result<String> {+ if let Some(n) = name {+ let mut ctx = base_context.clone();+ ctx.insert("hook_name".into(), n.into());+ serde_json::to_string(&ctx).context("failed to serialize step context")+ } else {+ serde_json::to_string(base_context).context("failed to serialize step context")+ }+}+fn format_exit(code: Option<i32>) -> String {code.map_or("signal".to_string(), |c| format!("exit code {c}"))}diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex 298d89404..bc501d526 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -1,16 +1,16 @@//! Hook execution for worktree operations.//!-//! CommandContext implementations for pre-start and post-remove hooks.+//! CommandContext implementations for pre-start hooks, and PostRemoveContext+//! for building template variables for post-remove hooks.use std::path::Path;use worktrunk::HookType;+use worktrunk::git::Repository;use worktrunk::path::to_posix_path;use crate::commands::command_executor::CommandContext;-use crate::commands::hooks::{- HookCommandSpec, HookFailureStrategy, SourcedCommand, execute_hook, prepare_hook_commands,-};+use crate::commands::hooks::{HookFailureStrategy, execute_hook};impl<'a> CommandContext<'a> {/// Execute pre-start commands sequentially (blocking)@@ -30,82 +30,76 @@ impl<'a> CommandContext<'a> {crate::output::post_hook_display_path(self.worktree_path),)}+}- /// Prepare post-remove commands for background spawning.- ///- /// Returns prepared commands without spawning them, so the caller can batch- /// them with other hook types (e.g., post-switch) into a single output line.- ///- /// Template variables reflect the removed worktree (not where commands run from),- /// so hooks can reference the removed path and branch correctly.- ///- /// `removed_branch`: The branch that was removed (for `{{ branch }}`).- /// `removed_worktree_path`: The removed worktree's path (for `{{ worktree_path }}`, etc.).- /// `removed_commit`: The commit SHA of the removed worktree's HEAD (for `{{ commit }}`).- /// `display_path`: When `Some`, shows the path in hook announcements.- pub fn prepare_post_remove_commands(- &self,- removed_branch: &str,+/// Context for post-remove hooks, holding owned strings for template variables.+///+/// Post-remove hooks need template variables that reflect the *removed* worktree+/// (not the destination), since hooks may reference the removed path and branch+/// (e.g., for cleanup scripts that use the path in container names). This struct+/// owns the computed strings so callers can borrow them as extra_vars.+pub(crate) struct PostRemoveContext {+ worktree_path_str: String,+ worktree_name: String,+ commit: String,+ short_commit: String,+ target_path_str: String,+ target_branch: String,+}++impl PostRemoveContext {+ pub fn new(removed_worktree_path: &Path,removed_commit: Option<&str>,- display_path: Option<&Path>,- ) -> anyhow::Result<Vec<SourcedCommand>> {- let project_config = self.repo.load_project_config()?;-- // Template variables should reflect the removed worktree, not where we run from.- // The removed worktree path no longer exists, but hooks may need to reference it- // (e.g., for cleanup scripts that use the path in container names).+ main_path: &Path,+ repo: &Repository,+ ) -> Self {let worktree_path_str = to_posix_path(&removed_worktree_path.to_string_lossy());let worktree_name = removed_worktree_path.file_name().and_then(|n| n.to_str())- .unwrap_or("unknown");+ .unwrap_or("unknown")+ .to_string();- // Build extra_vars with all removed worktree context.- // Commit is captured before removal to ensure it reflects the removed worktree's state.- let commit = removed_commit.unwrap_or("");+ let commit = removed_commit.unwrap_or("").to_string();let short_commit = if commit.len() >= 7 {- &commit[..7]+ commit[..7].to_string()} else {- commit+ commit.clone()};+// Target vars: where the user ends up after removal (primary worktree).- // self.worktree_path is main_path (set by caller). Look up its branch- // rather than using self.branch (which is the removed branch).- let target_path_str = to_posix_path(&self.worktree_path.to_string_lossy());- let target_branch_owned = self- .repo- .worktree_at(self.worktree_path)+ let target_path_str = to_posix_path(&main_path.to_string_lossy());+ let target_branch = repo+ .worktree_at(main_path).branch().ok().flatten().unwrap_or_default();- let target_branch = target_branch_owned.as_str();- let extra_vars: Vec<(&str, &str)> = vec![- ("branch", removed_branch),- ("worktree_path", &worktree_path_str),- ("worktree", &worktree_path_str), // deprecated alias- ("worktree_name", worktree_name),- ("commit", commit),- ("short_commit", short_commit),- ("target", target_branch),- ("target_worktree_path", &target_path_str),- ];+ Self {+ worktree_path_str,+ worktree_name,+ commit,+ short_commit,+ target_path_str,+ target_branch,+ }+ }- let user_hooks = self.config.hooks(self.project_id().as_deref());- prepare_hook_commands(- self,- HookCommandSpec {- user_config: user_hooks.post_remove.as_ref(),- project_config: project_config- .as_ref()- .and_then(|c| c.hooks.post_remove.as_ref()),- hook_type: HookType::PostRemove,- extra_vars: &extra_vars,- name_filter: None,- display_path,- },- )+ /// Build extra_vars that override the base context with removed-worktree identity.+ ///+ /// `removed_branch` is borrowed from the caller (it outlives the returned Vec).+ pub fn extra_vars<'a>(&'a self, removed_branch: &'a str) -> Vec<(&'a str, &'a str)> {+ vec![+ ("branch", removed_branch),+ ("worktree_path", &self.worktree_path_str),+ ("worktree", &self.worktree_path_str), // deprecated alias+ ("worktree_name", &self.worktree_name),+ ("commit", &self.commit),+ ("short_commit", &self.short_commit),+ ("target", &self.target_branch),+ ("target_worktree_path", &self.target_path_str),+ ]}}diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 755da5754..338957337 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -78,7 +78,7 @@//!//! The shell wrapper is generated by `wt config shell init <shell>` from templates in `templates/`.-mod hooks;+pub(crate) mod hooks;mod push;mod resolve;mod switch;diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex bb1bfce4b..aa651bc97 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -20,6 +20,7 @@ use crate::commands::hooks::{use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};+use crate::commands::worktree::hooks::PostRemoveContext;use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,stage_worktree_removal,@@ -833,16 +834,29 @@ fn spawn_hooks_after_remove(super::pre_hook_display_path(main_path)};+ // Build post-remove template variables from the removed worktree identity.+ let remove_vars =+ PostRemoveContext::new(removed_worktree_path, removed_commit, main_path, repo);+ let extra_vars = remove_vars.extra_vars(removed_branch);+// All hooks use remove_ctx for spawning: log files are named after the removed// branch since both post-remove and post-switch are consequences of that removal.- // Template variables differ per hook type (prepared separately below).let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), main_path, false);- let mut hooks = remove_ctx.prepare_post_remove_commands(- removed_branch,- removed_worktree_path,- removed_commit,++ let mut flat_hooks = Vec::new();++ // Post-remove hooks (pipeline-aware via prepare_background_hooks).+ match prepare_background_hooks(+ &remove_ctx,+ worktrunk::HookType::PostRemove,+ &extra_vars,display_path,- )?;+ )? {+ crate::commands::hooks::PreparedHooks::Flat(cmds) => flat_hooks.extend(cmds),+ crate::commands::hooks::PreparedHooks::Pipeline(steps) => {+ spawn_hook_pipeline(&remove_ctx, steps)?;+ }+ }// Post-switch: only when the user actually changed directory.// Uses its own context for template variable preparation (dest branch),@@ -857,16 +871,14 @@ fn spawn_hooks_after_remove(&[],display_path,)? {- crate::commands::hooks::PreparedHooks::Flat(cmds) => hooks.extend(cmds),+ crate::commands::hooks::PreparedHooks::Flat(cmds) => flat_hooks.extend(cmds),crate::commands::hooks::PreparedHooks::Pipeline(steps) => {- if !steps.is_empty() {- spawn_hook_pipeline(&switch_ctx, steps)?;- }+ spawn_hook_pipeline(&switch_ctx, steps)?;}}}- spawn_background_hooks(&remove_ctx, hooks)+ spawn_background_hooks(&remove_ctx, flat_hooks)}// ============================================================================diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 1665f7049..d6e79bfcd 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -2,7 +2,7 @@ use crate::common::{TestRepo, make_snapshot_cmd, merge_scenario,mock_commands::{create_mock_cargo, create_mock_llm_auth},repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,- repo_with_multi_commit_feature, setup_snapshot_settings, wait_for_file,+ repo_with_multi_commit_feature, setup_snapshot_settings, wait_for_file, wait_for_file_content,};use insta_cmd::assert_cmd_snapshot;use path_slash::PathExt as _;@@ -2643,3 +2643,47 @@ fn test_merge_no_ff_target_without_worktree(repo: TestRepo) {"Should create merge commit even without target worktree");}++// ============================================================================+// Post-merge pipeline test (Bug 1 regression test)+// ============================================================================++#[rstest]+fn test_merge_post_merge_pipeline_serial_ordering(mut repo: TestRepo) {+ // Post-merge with a pipeline config (list form) should preserve serial ordering.+ // Before the fix, pipelines were flattened into independent background commands,+ // losing serial/concurrent semantics.+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).unwrap();+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-merge = [+ "echo STEP_ONE_DONE > step_one_marker.txt",+ "cat step_one_marker.txt > step_two_saw_one.txt"+]+"#,+ )+ .unwrap();++ repo.commit("Add pipeline config");++ let feature_wt = repo.add_feature();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "merge",+ &["main", "--yes"],+ Some(&feature_wt)+ ));++ // Step 2 reads step 1's output. With pipeline semantics, step 2 runs after step 1.+ // Without pipeline semantics (flat), they'd race and step 2 would likely fail.+ let marker_file = repo.root_path().join("step_two_saw_one.txt");+ wait_for_file_content(&marker_file);++ let content = fs::read_to_string(&marker_file).unwrap();+ assert!(+ content.contains("STEP_ONE_DONE"),+ "Step 2 should see step 1's output (serial pipeline), got: {content}"+ );+}diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex bd802b5f5..64dfe7cce 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -2558,6 +2558,54 @@ fn test_user_post_start_pipeline_shell_escaping(repo: TestRepo) {);}+// ============================================================================+// Pipeline hook_name isolation (Bug 2 regression test)+// ============================================================================++#[rstest]+fn test_user_post_start_pipeline_hook_name_per_step(repo: TestRepo) {+ // Each step in a pipeline should see its own hook_name, not the first step's name.+ // Before the fix, step 2 would see step 1's hook_name because the shared pipeline+ // context included hook_name from the first command's context_json.+ repo.write_test_config(+ r#"post-start = [+ { step_one = "echo {{ hook_name }} > step_one_name.txt" },+ { step_two = "echo {{ hook_name }} > step_two_name.txt" }+]+"#,+ );++ snapshot_switch(+ "user_post_start_pipeline_hook_name_per_step",+ &repo,+ &["--create", "feature"],+ );++ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");++ let step_one_file = worktree_path.join("step_one_name.txt");+ let step_two_file = worktree_path.join("step_two_name.txt");+ wait_for_file_content(&step_one_file);+ wait_for_file_content(&step_two_file);++ let step_one_name = fs::read_to_string(&step_one_file)+ .unwrap()+ .trim()+ .to_string();+ let step_two_name = fs::read_to_string(&step_two_file)+ .unwrap()+ .trim()+ .to_string();+ assert_eq!(+ step_one_name, "step_one",+ "Step 1 should see its own hook_name"+ );+ assert_eq!(+ step_two_name, "step_two",+ "Step 2 should see its own hook_name, not step 1's"+ );+}+#[rstest]fn test_user_post_switch_pipeline_via_switch_create(repo: TestRepo) {// Post-switch with pipeline config, triggered by `wt switch --create`.@@ -2587,3 +2635,82 @@ fn test_user_post_switch_pipeline_via_switch_create(repo: TestRepo) {"Pipeline serial ordering should be preserved for post-switch, got: {content}");}++// ============================================================================+// Post-remove pipeline (Bug 1 regression test)+// ============================================================================++#[rstest]+fn test_user_post_remove_pipeline_serial_ordering(mut repo: TestRepo) {+ // Post-remove with a pipeline config should preserve serial ordering.+ // Before the fix, prepare_post_remove_commands returned flat commands,+ // so pipeline configs lost serial/concurrent semantics.+ let _feature_wt = repo.add_worktree("feature");++ repo.write_test_config(+ r#"post-remove = [+ "echo REMOVE_STEP_1 > ../remove_step1.txt",+ "cat ../remove_step1.txt > ../remove_step2.txt"+]+"#,+ );++ snapshot_remove(+ "user_post_remove_pipeline_ordering",+ &repo,+ &["feature", "--force-delete"],+ Some(repo.root_path()),+ );++ // Step 2 reads step 1's output. With pipeline semantics, step 2 runs after step 1.+ let parent = repo.root_path().parent().unwrap();+ let step2_file = parent.join("remove_step2.txt");+ wait_for_file_content(&step2_file);++ let content = fs::read_to_string(&step2_file).unwrap();+ assert!(+ content.contains("REMOVE_STEP_1"),+ "Step 2 should see step 1's output (serial pipeline), got: {content}"+ );+}++// ============================================================================+// Name-filtered lazy template (Bug 3 regression test)+// ============================================================================++#[rstest]+fn test_standalone_hook_name_filtered_lazy_template(repo: TestRepo) {+ // A pipeline step that uses {{ vars.X }} should expand correctly when+ // name-filtered via `wt hook post-start db`. Before the fix, the flat+ // spawn path passed the raw unexpanded template to the shell.+ //+ // vars.* are read from git config, so we pre-set the value.+ repo.write_test_config(+ r#"post-start = [+ { setup = "echo setup" },+ { db = "echo {{ vars.name }} > lazy_filtered.txt" }+]+"#,+ );++ // Pre-set vars.name via git config (same mechanism as pipeline step 1 would use).+ // Test repo starts on main branch.+ repo.run_git(&["config", "worktrunk.state.main.vars.name", "test-db"]);++ // Run just the 'db' step by name. This goes through the flat background path+ // since name filtering bypasses the pipeline runner.+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "hook", &["post-start", "db"], None);+ assert_cmd_snapshot!("standalone_hook_name_filtered_lazy_template", cmd);+ });++ let marker_file = repo.root_path().join("lazy_filtered.txt");+ wait_for_file_content(&marker_file);++ let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();+ assert_eq!(+ content, "test-db",+ "Lazy template should expand {{ vars.name }} from git config"+ );+}diff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_pipeline_serial_ordering.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_pipeline_serial_ordering.snapnew file mode 100644index 000000000..97fb4f73a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_pipeline_serial_ordering.snap@@ -0,0 +1,54 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--yes"+ 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 -----+[36m◎[39m [36mMerging 1 commit to [1mmain[22m @ [2m[HASH][22m (no commit/squash/rebase needed)[39m+[107m [0m * [33m[HASH][m Add feature file+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 1 file changed, 1 insertion(+)+[32m✓[39m [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m+[36m◎[39m [36mRemoving [1mfeature[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-merge: [1mcmd-0[22m → [1mcmd-1[22m @ [1m_REPO_[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_lazy_template.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_lazy_template.snapnew file mode 100644index 000000000..b403b3cef--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_name_filtered_lazy_template.snap@@ -0,0 +1,46 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - hook+ - post-start+ - db+ 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 -----+[36m◎[39m [36mRunning post-start: [1muser:db[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_pipeline_ordering.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_pipeline_ordering.snapnew file mode 100644index 000000000..4973de02a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_remove_pipeline_ordering.snap@@ -0,0 +1,47 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - remove+ - feature+ - "--force-delete"+ 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 -----+[36m◎[39m [36mRemoving [1mfeature[22m worktree & branch in background (--force-delete)[39m+[36m◎[39m [36mRunning post-remove: [1mcmd-0[22m → [1mcmd-1[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_hook_name_per_step.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_hook_name_per_step.snapnew file mode 100644index 000000000..c86b350e1--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_post_start_pipeline_hook_name_per_step.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 -----+[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-start: [1mstep_one[22m → [1mstep_two[22m @ [1m_REPO_.feature[22m[39m