Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(hooks): background runner labels template errors like the foreground (#3047)
Maximilian Roos96c3af485351
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 2940fb04d..04ef73b78 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -503,6 +503,7 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> a.map(|s| match &s.step {PreparedStep::Single(cmd) => PipelineStepSpec::Single {name: cmd.name.clone(),+ template_name: cmd.template_name.clone(),template: cmd.template.clone(),},PreparedStep::Concurrent(cmds) => PipelineStepSpec::Concurrent {@@ -510,6 +511,7 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> a.iter().map(|c| PipelineCommandSpec {name: c.name.clone(),+ template_name: c.template_name.clone(),template: c.template.clone(),}).collect(),diff --git a/src/commands/pipeline_spec.rs b/src/commands/pipeline_spec.rsindex 63a914d98..48d9314b8 100644--- a/src/commands/pipeline_spec.rs+++ b/src/commands/pipeline_spec.rs@@ -31,6 +31,12 @@ pub struct PipelineSpec {pub enum PipelineStepSpec {Single {name: Option<String>,+ /// Label for template-expansion errors, copied from+ /// `PreparedCommand::template_name` so runner-log errors read the+ /// same as foreground ones (`"Failed to expand user:foo: …"`).+ /// Command-failure messages instead use `name`, mirroring the+ /// foreground's `HookCommandFailed { command_name }`.+ template_name: String,template: String,},Concurrent {@@ -41,6 +47,8 @@ pub enum PipelineStepSpec {#[derive(Serialize, Deserialize)]pub struct PipelineCommandSpec {pub name: Option<String>,+ /// See `PipelineStepSpec::Single::template_name`.+ pub template_name: String,pub template: String,}@@ -62,16 +70,19 @@ mod tests {steps: vec![PipelineStepSpec::Single {name: Some("install".into()),+ template_name: "user:install".into(),template: "npm install".into(),},PipelineStepSpec::Concurrent {commands: vec![PipelineCommandSpec {name: Some("build".into()),+ template_name: "user:build".into(),template: "npm run build".into(),},PipelineCommandSpec {name: None,+ template_name: "user post-create hook".into(),template: "echo {{ vars.tag }}".into(),},],@@ -91,8 +102,13 @@ mod tests {// Verify step structure survives roundtripmatch &roundtripped.steps[0] {- PipelineStepSpec::Single { name, template } => {+ PipelineStepSpec::Single {+ name,+ template_name,+ template,+ } => {assert_eq!(name.as_deref(), Some("install"));+ assert_eq!(template_name, "user:install");assert_eq!(template, "npm install");}_ => panic!("expected Single step"),diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex a6d9bce2b..614e34949 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -96,19 +96,22 @@ pub fn run_pipeline() -> anyhow::Result<()> {for step in &spec.steps {match step {- PipelineStepSpec::Single { template, name } => {+ PipelineStepSpec::Single {+ template,+ template_name,+ name,+ } => {let log_name = command_log_name(name.as_deref(), cmd_index);let log_file = create_command_log(&spec, &log_name)?;let step_ctx = step_context(&spec.context, name.as_deref());- let label = name.as_deref().unwrap_or("pipeline step");- let expanded = expand_shell_template(template, &step_ctx, &repo, label)?;+ let expanded = expand_shell_template(template, &step_ctx, &repo, template_name)?;let step_json = serde_json::to_string(&*step_ctx).context("failed to serialize step context")?;let mut child =spawn_shell_command(&expanded, &spec.worktree_path, &step_json, log_file)?;let status = child.wait().context("failed to wait for child process")?;if !status.success() {- return Err(failure_error(&status, &expanded));+ return Err(failure_error(&status, name.as_deref().unwrap_or(&expanded)));}cmd_index += 1;}@@ -198,8 +201,7 @@ fn run_concurrent_group(let log_name = command_log_name(cmd.name.as_deref(), *cmd_index);let log_file = create_command_log(spec, &log_name)?;let cmd_ctx = step_context(&spec.context, cmd.name.as_deref());- let label = cmd.name.as_deref().unwrap_or("pipeline step");- let expanded = expand_shell_template(&cmd.template, &cmd_ctx, repo, label)?;+ let expanded = expand_shell_template(&cmd.template, &cmd_ctx, repo, &cmd.template_name)?;let cmd_json =serde_json::to_string(&*cmd_ctx).context("failed to serialize step context")?;let mut child = spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json, log_file)?;diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 8da541878..f77f936e3 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -10,6 +10,7 @@ use crate::common::{TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, resolve_git_common_dir,setup_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_file_count,};+use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;use path_slash::PathExt as _;use rstest::rstest;@@ -1121,15 +1122,59 @@ broken = "echo {{ does_not_exist }} > should_not_exist.txt".join("runner.log");wait_for_file_content(&runner_log);let log_content = fs::read_to_string(&runner_log).unwrap();- assert!(- log_content.contains("Failed to expand"),- "runner log should contain the template error, got: {log_content}"- );+ // Same label the foreground path renders for this command (see the+ // foreground_pipeline_undefined_var_runs_earlier_steps snapshot).+ assert_snapshot!(log_content, @"+ [31m✗[39m [31mFailed to expand user:broken: undefined value @ line 1[39m+ [107m [0m echo {{ does_not_exist }} > should_not_exist.txt+ [2m↳[22m [2mAvailable variables: [4margs[24m, [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_name[24m, [4mhook_type[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mupstream[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m+ ");// The step never ran.assert!(!repo.root_path().join("should_not_exist.txt").exists());}+/// Runner-log failure messages label steps the way the foreground does:+/// named steps by command name, unnamed steps by the expanded command.+#[rstest]+fn test_background_hook_failure_labels_in_runner_log(repo: TestRepo) {+ repo.write_test_config(+ r#"post-start = [{ broken = "exit 7" }]+post-switch = "exit 9"+"#,+ );++ for hook_type in ["post-start", "post-switch"] {+ let mut cmd = crate::common::wt_command();+ cmd.current_dir(repo.root_path());+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());+ cmd.args(["hook", hook_type, "--yes"]);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "background spawn should succeed; the step fails later in the runner.\nstderr: {}",+ String::from_utf8_lossy(&output.stderr),+ );+ }++ let runner_log = |hook_type: &str| {+ resolve_git_common_dir(repo.root_path())+ .join("wt/logs")+ .join(worktrunk::path::sanitize_for_filename("main"))+ .join("user")+ .join(hook_type)+ .join("runner.log")+ };++ let named = runner_log("post-start");+ wait_for_file_content(&named);+ assert_snapshot!(fs::read_to_string(&named).unwrap(), @"[31m✗[39m [31mcommand failed with exit code 7: broken[39m");++ let unnamed = runner_log("post-switch");+ wait_for_file_content(&unnamed);+ assert_snapshot!(fs::read_to_string(&unnamed).unwrap(), @"[31m✗[39m [31mcommand failed with exit code 9: exit 9[39m");+}+/// A semantic template error in a foreground pipeline step surfaces when that/// step runs: earlier steps execute first, then the broken step's render/// aborts the pipeline. (Pre-change, prep expanded every template upfront and