Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(process): retain command identity and native failure causes (#4352)
Maximilian Roos0874f5f603f1
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 0f6de2a39..752a9b9e9 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -61,8 +61,9 @@ use crate::commands::command_executor::{use crate::commands::hook_announcement::{SourcedStep, format_pipeline_summary_from_names, step_names_from_config,};-use crate::commands::hooks::{HookSource, sourced_steps_to_foreground};+use crate::commands::hooks::sourced_steps_to_foreground;use crate::commands::{build_invalid_subcommand_error, similar_subcommands};+use worktrunk::config::HookSource;/// Built-in `wt step` subcommand names. Aliases with these names are/// reachable via `wt <name>` (top-level) but shadowed via `wt step <name>`.diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex c481ae97f..c5fecf50a 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -29,8 +29,9 @@ use worktrunk::styling::{stderr, warning_message,};-use super::hook_filter::{HookSource, ParsedFilter};+use super::hook_filter::ParsedFilter;use super::project_config::{ApprovableCommand, Phase, collect_commands_for_hooks};+use worktrunk::config::HookSource;/// Batch approval helper used when multiple commands are queued for execution./// Returns `Ok(true)` when execution may continue, `Ok(false)` when the userdiff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 0a95c8d92..b6c83388a 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,3 +1,10 @@+//! Foreground execution for prepared hook and alias pipelines.+//!+//! Prepared commands retain their configured identity; templates render just+//! before execution so earlier steps can update variables. This layer owns+//! announcements and failure policy. The process runner owns child status and+//! cancellation, and error wrappers preserve that typed source chain.+use std::collections::HashMap;use std::path::{Path, PathBuf};@@ -19,9 +26,9 @@ use worktrunk::styling::{use worktrunk::trace::Span;use super::format_command_label;-use super::hook_filter::HookSource;use crate::output::concurrent::{ConcurrentCommand, run_concurrent_commands};use crate::output::{DirectivePassthrough, execute_shell_command};+use worktrunk::config::HookSource;#[derive(Debug, Serialize, Deserialize)]pub struct PreparedCommand {@@ -70,16 +77,15 @@ impl PreparedStep {/// Wraps a command failure (FailFast path) into the final error.///-/// Receives the failing command, the message extracted from the inner error,-/// and the optional exit code (set when the inner error is-/// `WorktrunkError::ChildProcessExited`). Signal-derived errors bypass this+/// Receives the failing command and its original error, retaining typed status+/// and the source of spawn failures. Signal-derived errors bypass this/// wrapper and short-circuit to `Interrupted` — see/// [`handle_command_error`] for the rationale.////// The wrapper is invoked on the calling thread after concurrent children/// have joined (`run_concurrent_group` folds outcomes serially), so no/// `Send + Sync` bounds are required.-pub type ErrorWrapper = Box<dyn Fn(&PreparedCommand, String, Option<i32>) -> anyhow::Error>;+pub type ErrorWrapper = Box<dyn Fn(&PreparedCommand, anyhow::Error) -> anyhow::Error>;/// What kind of pipeline a sourced step belongs to.///@@ -128,6 +134,7 @@ pub struct ForegroundStep {/// line plus the bash gutter; aliases stay silent (the caller emits one/// pipeline summary line).pub announce: PipelineKind,+ pub source: HookSource,/// Merge the child's stdout onto wt's stderr (`true`, hooks) or pass it/// through unchanged (`false`, aliases). Hooks merge so their output stays/// ordered with wt's own stderr "Running …" lines; aliases pass through so@@ -446,14 +453,6 @@ pub fn render_template_preview()?)}-/// Short summary name: "user:name" for named commands, "user" otherwise.-pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> String {- match name {- Some(n) => format!("{source}:{n}"),- None => source.to_string(),- }-}-/// Execute a pipeline of prepared steps in the foreground.////// This is the canonical foreground execution path for both hooks and aliases.@@ -508,7 +507,7 @@ fn run_concurrent_group(.collect::<Result<_>>()?;for (cmd, command_str) in cmds.iter().zip(&expanded) {- announce_command(cmd, &fg_step.announce, command_str);+ announce_command(cmd, &fg_step.announce, fg_step.source, command_str);}// Both alias tables and hook tables produce named commands (TOML keys@@ -573,7 +572,7 @@ fn run_one_command(let _span = Span::new(format!("template_render:{}", cmd.label));resolve_command_str(cmd, repo)?};- announce_command(cmd, &fg_step.announce, &command_str);+ announce_command(cmd, &fg_step.announce, fg_step.source, &command_str);// Foreground steps inherit the parent's stdin so an interactive child keeps// its controlling terminal — a `pre-*` hook can prompt (e.g. `gum confirm`@@ -602,7 +601,12 @@ fn run_one_command(/// showing `command_str` — the rendered command about to run. Alias pipelines/// emit nothing — the alias caller renders a single pipeline summary/// externally.-fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind, command_str: &str) {+fn announce_command(+ cmd: &PreparedCommand,+ kind: &PipelineKind,+ source: HookSource,+ command_str: &str,+) {let PipelineKind::Hook {hook_type,display_path,@@ -613,7 +617,7 @@ fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind, command_str: &stlet full_label = match &cmd.name {Some(_) => format_command_label(&hook_type.to_string(), Some(&cmd.label)),- None => format!("Running {hook_type} {} hook", cmd.label),+ None => format!("Running {}", source.hook_label(*hook_type, None)),};let message = match display_path.as_deref() {Some(path) => {@@ -638,13 +642,18 @@ fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind, command_str: &st////// Wraps non-signal failures in `WorktrunkError::HookCommandFailed`. Signal/// errors short-circuit upstream (see [`handle_command_error`]).-pub fn hook_error_wrapper(hook_type: HookType) -> ErrorWrapper {- Box::new(move |cmd, err_msg, exit_code| {+pub fn hook_error_wrapper(+ hook_type: HookType,+ source: HookSource,+ show_template: bool,+) -> ErrorWrapper {+ Box::new(move |cmd, error| {WorktrunkError::HookCommandFailed {hook_type,+ source,command_name: cmd.name.clone(),- error: err_msg,- exit_code,+ template: show_template.then(|| cmd.template.clone()),+ error,}.into()})@@ -654,11 +663,14 @@ pub fn hook_error_wrapper(hook_type: HookType) -> ErrorWrapper {////// Children that report a child exit code surface as `AlreadyDisplayed` so/// `wt` propagates the alias's exit status. Anything else (template errors,-/// spawn failures) is wrapped with the alias name.+/// spawn failures) is wrapped with the alias and configured member names.pub fn alias_error_wrapper(alias_name: String) -> ErrorWrapper {- Box::new(move |_cmd, err_msg, exit_code| match exit_code {+ Box::new(move |cmd, error| match error.exit_code() {Some(code) => WorktrunkError::AlreadyDisplayed { exit_code: code }.into(),- None => anyhow::anyhow!("Failed to run alias '{}': {}", alias_name, err_msg),+ None => error.context(match &cmd.name {+ Some(name) => format!("Failed to run alias '{alias_name}' command '{name}'"),+ None => format!("Failed to run alias '{alias_name}'"),+ }),})}@@ -679,25 +691,14 @@ fn handle_command_error(return Err(WorktrunkError::Interrupted { signal, hint: None }.into());}- let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {- match wt_err {- WorktrunkError::ChildProcessExited { message, code, .. } => {- (message.clone(), Some(*code))- }- _ => (err.to_string(), None),- }- } else {- (err.to_string(), None)- };-match failure_strategy {- FailureStrategy::FailFast => Err(error_wrapper(cmd, err_msg, exit_code)),+ FailureStrategy::FailFast => Err(error_wrapper(cmd, err)),FailureStrategy::Warn => {- let message = match &cmd.name {- Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),- None => format!("Command failed: {err_msg}"),- };- eprintln!("{}", error_message(message));+ let error = error_wrapper(cmd, err);+ let rendered = error+ .render_diagnostic()+ .unwrap_or_else(|| error_message(error.to_string()).to_string());+ eprintln!("{rendered}");Ok(())}}@@ -799,8 +800,8 @@ pub fn prepare_steps(}let template_name = match &cmd.name {- Some(name) => format!("{source}:{name}"),- None => format!("{source} {hook_type} hook"),+ Some(_) => source.command_label(cmd.name.as_deref()),+ None => source.hook_label(hook_type, None),};Ok(PreparedCommand {@@ -808,7 +809,7 @@ pub fn prepare_steps(template: cmd.template.clone(),context: cmd_context,template_name,- label: command_summary_name(cmd.name.as_deref(), source),+ label: source.command_label(cmd.name.as_deref()),})})?;Ok(PreparedPipeline(steps))@@ -819,7 +820,7 @@ mod tests {use super::*;fn make_cmd(name: Option<&str>) -> PreparedCommand {- let label = command_summary_name(name, HookSource::User);+ let label = HookSource::User.command_label(name);PreparedCommand {name: name.map(String::from),template: "echo test".to_string(),@@ -832,23 +833,18 @@ mod tests {#[test]fn test_handle_command_error_hook_failfast_child_process_exited() {let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 42,- message: "command failed".into(),- signal: None,+ physical_signal: None,}.into();let cmd = make_cmd(Some("lint"));- let wrapper = hook_error_wrapper(HookType::PreMerge);+ let wrapper = hook_error_wrapper(HookType::PreMerge, HookSource::User, false);let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();- assert!(matches!(- wt_err,- WorktrunkError::HookCommandFailed {- exit_code: Some(42),- ..- }- ));+ assert!(matches!(wt_err, WorktrunkError::HookCommandFailed { .. }));+ assert_eq!(err.exit_code(), Some(42));}#[test]@@ -856,25 +852,55 @@ mod tests {// WorktrunkError that isn't ChildProcessExitedlet err: anyhow::Error = WorktrunkError::CommandNotApproved.into();let cmd = make_cmd(Some("build"));- let wrapper = hook_error_wrapper(HookType::PreMerge);+ let wrapper = hook_error_wrapper(HookType::PreMerge, HookSource::User, false);let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();- assert!(matches!(- wt_err,- WorktrunkError::HookCommandFailed {- exit_code: None,- ..- }- ));+ assert!(matches!(wt_err, WorktrunkError::HookCommandFailed { .. }));+ assert_eq!(err.exit_code(), None);+ }++ #[test]+ fn test_hook_spawn_failure_retains_io_error_and_has_no_child_exit_code() {+ let missing = tempfile::tempdir().unwrap().path().join("missing-cwd");+ let shell = worktrunk::shell_exec::ShellConfig::get().unwrap();+ let error = worktrunk::shell_exec::Cmd::new(shell.executable.to_string_lossy())+ .current_dir(&missing)+ .run()+ .unwrap_err();+ let cmd = make_cmd(Some("check"));+ let error = handle_command_error(+ error.into(),+ &cmd,+ &hook_error_wrapper(HookType::PreMerge, HookSource::User, false),+ FailureStrategy::FailFast,+ )+ .unwrap_err();+ assert_eq!(error.exit_code(), None);+ assert_eq!(error.to_string(), "pre-merge user:check failed");+ let detail = format!("{error:#}");+ assert!(detail.contains("Failed to execute"));+ assert!(detail.contains(&worktrunk::path::format_path_for_display(&missing)));+ let io_error = error.root_cause().downcast_ref::<std::io::Error>().unwrap();+ assert_eq!(io_error.kind(), std::io::ErrorKind::NotFound);+ let io_detail = io_error.to_string();+ assert_eq!(detail.matches(&io_detail).count(), 1);+ assert_eq!(+ error+ .render_diagnostic()+ .unwrap()+ .matches(&io_detail)+ .count(),+ 1+ );}#[test]fn test_handle_command_error_alias_failfast_child_process_exited() {let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "exit 1".into(),- signal: None,+ physical_signal: None,}.into();let cmd = make_cmd(None);@@ -894,21 +920,21 @@ mod tests {let cmd = make_cmd(None);let wrapper = alias_error_wrapper("deploy".into());let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::FailFast);- let err_msg = result.unwrap_err().to_string();- assert!(err_msg.contains("Failed to run alias 'deploy'"));- assert!(err_msg.contains("template error"));+ let error = result.unwrap_err();+ assert_eq!(error.to_string(), "Failed to run alias 'deploy'");+ assert_eq!(error.root_cause().to_string(), "template error");}#[test]fn test_handle_command_error_warn_continues() {let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "lint failed".into(),- signal: None,+ physical_signal: None,}.into();let cmd = make_cmd(Some("lint"));- let wrapper = hook_error_wrapper(HookType::PostCreate);+ let wrapper = hook_error_wrapper(HookType::PostCreate, HookSource::User, false);let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);assert!(result.is_ok());}@@ -916,13 +942,13 @@ mod tests {#[test]fn test_handle_command_error_warn_signal_aborts() {let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 143,- message: "terminated".into(),- signal: Some(15),+ physical_signal: Some(15),}.into();let cmd = make_cmd(Some("cleanup"));- let wrapper = hook_error_wrapper(HookType::PostCreate);+ let wrapper = hook_error_wrapper(HookType::PostCreate, HookSource::User, false);let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);let err = result.unwrap_err();let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();@@ -940,7 +966,7 @@ mod tests {// Covers the `cmd.name = None` branch of the Warn arm.let err = anyhow::anyhow!("unexpected failure");let cmd = make_cmd(None);- let wrapper = hook_error_wrapper(HookType::PostCreate);+ let wrapper = hook_error_wrapper(HookType::PostCreate, HookSource::User, false);let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);assert!(result.is_ok());}diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 27f8afe59..e6ad7d72d 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -38,7 +38,7 @@ use crate::commands::command_executor::{CommandContext, build_hook_context, render_template_preview,};use crate::commands::did_you_mean;-use crate::commands::hooks::HookSource;+use worktrunk::config::HookSource;/// Show the configured template(s) for an alias — or, with no name, every/// configured alias's template(s).diff --git a/src/commands/custom.rs b/src/commands/custom.rsindex 1d7f30366..58012a1cd 100644--- a/src/commands/custom.rs+++ b/src/commands/custom.rs@@ -156,8 +156,8 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Reslet child = match spawned {Ok(child) => Arc::new(child),Err(error) => {- trace.fail(&error);- return Err(error).with_context(|| format!("failed to execute {}", path.display()));+ trace.fail(error.as_ref());+ return Err(error);}};#[cfg(unix)]@@ -324,9 +324,12 @@ mod tests {// (the success path is covered by the signal test above).let err = run_custom(Path::new("/no/such/wt-custom-7f3a9b2c"), &[], None).expect_err("spawning a missing binary should fail");- assert!(- err.to_string().contains("failed to execute"),- "expected spawn-failure context, got: {err}"+ assert_eq!(+ err.to_string(),+ "Failed to execute /no/such/wt-custom-7f3a9b2c");+ let cause = err.root_cause().downcast_ref::<std::io::Error>().unwrap();+ assert_eq!(cause.kind(), std::io::ErrorKind::NotFound);+ assert_eq!(format!("{err:#}").matches(&cause.to_string()).count(), 1);}}diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 1d7da24ff..09c980e4a 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -109,22 +109,23 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any// hints from typed diagnostics) and a plain string for// JSON (consumers shouldn't see ANSI codes or symbols).let (exit_info, exit_code, stderr_detail, json_detail) =- if let Some(WorktrunkError::ChildProcessExited { code, message, .. }) =+ if let Some(WorktrunkError::ChildProcessExited { code, .. }) =err.downcast_ref::<WorktrunkError>(){(- format!(" (exit code {code})"),+ format!(" ({err})"),serde_json::json!(code),None,- message.clone(),+ err.to_string(),)} else {- let styled = err.render_diagnostic().unwrap_or_else(|| err.to_string());+ let detail = err.display_message();+ let styled = err.render_diagnostic().unwrap_or_else(|| detail.clone());(" (spawn failed)".to_string(),serde_json::json!(null),Some(styled),- err.to_string(),+ detail,)};eprintln!(diff --git a/src/commands/hook_announcement.rs b/src/commands/hook_announcement.rsindex 065e2d84a..ec680dd2d 100644--- a/src/commands/hook_announcement.rs+++ b/src/commands/hook_announcement.rs@@ -68,7 +68,7 @@use color_print::cformat;use super::command_executor::PreparedStep;-use super::hook_filter::HookSource;+use worktrunk::config::HookSource;/// A pipeline step with source information, for pipeline-aware execution.///diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 2971d230b..2d91c67db 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -28,10 +28,10 @@ use super::command_executor::{CommandContext, FailureStrategy, PreparedStep, prepare_steps, render_template_preview,};use super::context::CommandEnv;-use super::hook_filter::HookSource;use super::hooks::{HookAnnouncer, prepare_and_check, run_hooks_foreground};use super::project_config::command_label;use super::template_vars::TemplateVars;+use worktrunk::config::HookSource;fn run_post_hook(ctx: &CommandContext,diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rsindex 4cab5b825..70e482aed 100644--- a/src/commands/hook_filter.rs+++ b/src/commands/hook_filter.rs@@ -1,33 +1,6 @@//! Hook filter types for command filtering by source and name.-//!-//! These types are shared between `hooks.rs` (command preparation/execution)-//! and `command_approval.rs` (approval flow). Re-exported from `hooks.rs`-//! for backward compatibility.-/// Whether a hook or alias body came from user config or project config.-///-/// Drives approval and source-qualified filtering.-#[derive(- Clone,- Copy,- Debug,- PartialEq,- Eq,- PartialOrd,- Ord,- serde::Serialize,- serde::Deserialize,- strum::Display,- strum::EnumString,-)]-#[serde(rename_all = "kebab-case")]-#[strum(serialize_all = "kebab-case")]-pub enum HookSource {- /// User config (~/.config/worktrunk/config.toml). No approval required.- User,- /// Project config (.config/wt.toml). Approval is handled at the gate.- Project,-}+use worktrunk::config::HookSource;/// A parsed name filter, optionally scoped to a specific source.///diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsindex 870f9af37..33f25a464 100644--- a/src/commands/hook_plan.rs+++ b/src/commands/hook_plan.rs@@ -54,9 +54,9 @@ use super::command_executor::{CommandContext, FailureStrategy, PipelineKind, execute_pipeline_foreground, prepare_steps,};use super::hook_announcement::SourcedStep;-use super::hook_filter::HookSource;use super::hooks::{HookAnnouncer, into_source_groups, sourced_steps_to_foreground};use super::project_config::{ApprovableCommand, Phase};+use worktrunk::config::HookSource;/// One `(hook_type, anchor)`'s frozen, source-tagged selection.///diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 3ff645744..1af3343d4 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -87,8 +87,8 @@ use super::hook_announcement::{SourcedStep, format_pipeline_summary};use crate::commands::process::{HookLog, spawn_detached_exec};use crate::output::DirectivePassthrough;-// Re-export for backward compatibility with existing imports-pub use super::hook_filter::{HookSource, ParsedFilter};+use super::hook_filter::ParsedFilter;+use worktrunk::config::HookSource;/// Prepare hook steps from both user and project configs, preserving pipeline/// structure, and verify any name filter matched at least one command.@@ -255,11 +255,11 @@ fn no_matching_commands_error(if !parsed_filters.iter().any(|f| f.matches_source(source)) {continue;}- available.extend(- config- .commands()- .filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),- );+ available.extend(config.commands().filter_map(|c| {+ c.name+ .as_deref()+ .map(|name| source.command_label(Some(name)))+ }));}worktrunk::git::GitError::HookCommandNotFound {@@ -667,12 +667,15 @@ pub(crate) fn sourced_steps_to_foreground(.map(|sourced| {let directives = DirectivePassthrough::inherit_from_env();let (redirect_stdout_to_stderr, error_wrapper) = match kind {- PipelineKind::Hook { hook_type, .. } => (true, hook_error_wrapper(*hook_type)),+ PipelineKind::Hook { hook_type, .. } => {+ (true, hook_error_wrapper(*hook_type, sourced.source, false))+ }PipelineKind::Alias { name } => (false, alias_error_wrapper(name.clone())),};ForegroundStep {step: sourced.step,announce: kind.clone(),+ source: sourced.source,redirect_stdout_to_stderr,error_wrapper,directives,diff --git a/src/commands/picker/pager.rs b/src/commands/picker/pager.rsindex 9f320e76b..bb17cd349 100644--- a/src/commands/picker/pager.rs+++ b/src/commands/picker/pager.rs@@ -103,7 +103,8 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> SOk(child) => child,Err(e) => {trace.fail(&e);- tracing::debug!(error = %e, "Failed to spawn pager: {}", e);+ let error = anyhow::Error::new(e);+ tracing::debug!(error = %format!("{error:#}"), "Failed to spawn pager");return text.to_string();}};diff --git a/src/commands/process.rs b/src/commands/process.rsindex f320a8e7b..9720d4c5c 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -8,7 +8,7 @@ use worktrunk::git::{HookType, Repository};use worktrunk::path::{format_path_for_display, sanitize_for_filename};use worktrunk::utils::epoch_now;-use crate::commands::hook_filter::HookSource;+use worktrunk::config::HookSource;// ==================== Hook Log Specification ====================@@ -493,7 +493,7 @@ pub fn sweep_stale_trash(repo: &Repository) {"",&HookLog::Shared(InternalOp::TrashSweep),) {- tracing::debug!(error = %e, "Failed to spawn stale trash sweep: {e}");+ tracing::debug!(error = %format!("{e:#}"), "Failed to spawn stale trash sweep");}}diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex 863b09751..37729f9fe 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -70,10 +70,10 @@ use worktrunk::shell_exec::{ShellConfig, scrub_git_discovery_env_vars};use worktrunk::trace::CommandTrace;use super::command_executor::{- PreparedCommand, PreparedStep, expand_shell_template, wait_first_error,+ PreparedCommand, PreparedStep, expand_shell_template, hook_error_wrapper, wait_first_error,};-use super::hook_filter::HookSource;use super::process::HookLog;+use worktrunk::config::HookSource;/// Serialized specification for a background hook pipeline.///@@ -115,6 +115,7 @@ pub fn run_pipeline() -> anyhow::Result<()> {fs::create_dir_all(&log_dir).with_context(|| format!("failed to create log directory: {}", log_dir.display()))?;+ let error_wrapper = hook_error_wrapper(spec.hook_type, spec.source, true);let mut cmd_index = 0usize;for step in &spec.steps {@@ -125,12 +126,13 @@ pub fn run_pipeline() -> anyhow::Result<()> {let expanded =expand_shell_template(&cmd.template, &cmd.context, &repo, &cmd.template_name)?;let (mut child, mut trace) =- spawn_shell_command(&expanded, &spec.worktree_path, log_file)?;+ spawn_shell_command(&expanded, &spec.worktree_path, log_file)+ .map_err(|error| error_wrapper(cmd, error))?;let status = wait_resolving(&mut child, &mut trace, &expanded)?;if !status.success() {- return Err(failure_error(- &status,- cmd.name.as_deref().unwrap_or(&expanded),+ return Err(error_wrapper(+ cmd,+ WorktrunkError::from_child_status(&status, None).into(),));}cmd_index += 1;@@ -179,7 +181,7 @@ fn spawn_shell_command(Ok(child) => child,Err(e) => {trace.fail(&e);- return Err(e).with_context(|| format!("failed to spawn: {expanded}"));+ return Err(e.into());}};@@ -224,12 +226,12 @@ fn run_concurrent_group(log_dir: &Path,cmd_index: &mut usize,) -> anyhow::Result<()> {+ let error_wrapper = hook_error_wrapper(spec.hook_type, spec.source, true);let serial = super::force_serial_concurrent();- let mut children: Vec<(Option<String>, String, Child, CommandTrace)> =- Vec::with_capacity(if serial { 0 } else { commands.len() });+ let mut children = Vec::with_capacity(if serial { 0 } else { commands.len() });// Spawn (and, in serial mode, run) each command. Wrapped so that a mid-loop- // error — a setup `?` or a spawn failure for a later command — tears down+ // setup or expansion error tears down// the children already spawned this group rather than dropping them with// unresolved trace guards (and as unreaped orphans).let spawn_result = (|| -> anyhow::Result<()> {@@ -238,43 +240,52 @@ fn run_concurrent_group(let log_file = create_command_log(spec, log_dir, &log_name)?;let expanded =expand_shell_template(&cmd.template, &cmd.context, repo, &cmd.template_name)?;- let (mut child, mut trace) =- spawn_shell_command(&expanded, &spec.worktree_path, log_file)?;+ let spawned = spawn_shell_command(&expanded, &spec.worktree_path, log_file)+ .map_err(|error| error_wrapper(cmd, error));*cmd_index += 1;if serial {+ let (mut child, mut trace) = spawned?;let status = wait_resolving(&mut child, &mut trace, &expanded)?;if !status.success() {- return Err(failure_error(- &status,- cmd.name.as_deref().unwrap_or(&expanded),+ return Err(error_wrapper(+ cmd,+ WorktrunkError::from_child_status(&status, None).into(),));}} else {- children.push((cmd.name.clone(), expanded, child, trace));+ children.push((cmd, expanded, spawned));}}Ok(())})();if let Err(e) = spawn_result {- for (_, _, mut child, mut trace) in children {- let _ = child.kill();- let _ = child.wait();- trace.complete(false);+ for (_, _, spawned) in children {+ if let Ok((mut child, mut trace)) = spawned {+ let _ = child.kill();+ let _ = child.wait();+ trace.complete(false);+ }}return Err(e);}- wait_first_error(children.into_iter().map(- |(name, expanded, mut child, mut trace)| -> anyhow::Result<()> {- let status = wait_resolving(&mut child, &mut trace, &expanded)?;- if !status.success() {- return Err(failure_error(&status, name.as_deref().unwrap_or(&expanded)));- }- Ok(())- },- ))+ wait_first_error(+ children+ .into_iter()+ .map(|(cmd, expanded, spawned)| -> anyhow::Result<()> {+ let (mut child, mut trace) = spawned?;+ let status = wait_resolving(&mut child, &mut trace, &expanded)?;+ if !status.success() {+ return Err(error_wrapper(+ cmd,+ WorktrunkError::from_child_status(&status, None).into(),+ ));+ }+ Ok(())+ }),+ )}/// Derive the log file name for a command.@@ -297,98 +308,74 @@ fn create_command_log(spec: &PipelineSpec, log_dir: &Path, name: &str) -> anyhow.with_context(|| format!("failed to create log file: {}", path.display()))}-/// Build the `anyhow::Error` for a failed pipeline step.-///-/// Signal-killed children surface as `WorktrunkError::ChildProcessExited`-/// with `signal: Some(sig)` and `code: 128 + sig`, matching the foreground-/// convention established by `shell_exec`. That lets `exit_code()` and-/// `interrupt_signal()` work consistently and the `wt hook run-pipeline`-/// process exits 130 on SIGINT and 143 on SIGTERM — the expectation the-/// "Signal Handling" section of the project `AGENTS.md` sets for every-/// command loop.-///-/// Non-signal failures carry the child's exit code verbatim so log readers-/// (and any future observer of the background process) see the real code-/// instead of a generic `1`.-///-/// On non-Unix (`status.signal()` unavailable), the function falls through-/// to the exit-code path; `status.code()` is always `Some` on Windows.-fn failure_error(status: &ExitStatus, label: &str) -> anyhow::Error {- #[cfg(unix)]- {- use std::os::unix::process::ExitStatusExt;- if let Some(sig) = status.signal() {- let message = format!(- "pipeline step terminated by {}: {label}",- format_signal(sig)- );- return WorktrunkError::ChildProcessExited {- code: 128 + sig,- message,- signal: Some(sig),- }- .into();- }- }- let code = status.code().unwrap_or(1);- let message = format!("command failed with exit code {code}: {label}");- WorktrunkError::ChildProcessExited {- code,- message,- signal: None,- }- .into()-}--/// Render a signal number as `signal N (SIGNAME)`, or `signal N` if nix-/// doesn't recognize it (platform-specific or real-time signals).-#[cfg(unix)]-fn format_signal(sig: i32) -> String {- match nix::sys::signal::Signal::try_from(sig) {- Ok(signal) => format!("signal {sig} ({signal})"),- Err(_) => format!("signal {sig}"),- }-}-#[cfg(all(test, unix))]mod tests {use super::*;use std::os::unix::process::ExitStatusExt;use worktrunk::git::ErrorExt;+ fn failure_error(+ status: &ExitStatus,+ hook_type: HookType,+ name: Option<&str>,+ ) -> anyhow::Error {+ let cmd = PreparedCommand {+ name: name.map(str::to_owned),+ template: "exit 7".into(),+ context: Default::default(),+ template_name: "user hook".into(),+ label: name.map_or_else(|| "user".into(), |name| format!("user:{name}")),+ };+ hook_error_wrapper(hook_type, HookSource::User, true)(+ &cmd,+ WorktrunkError::from_child_status(status, None).into(),+ )+ }+fn downcast_child_exit(err: &anyhow::Error) -> (i32, Option<i32>, String) {- match err.downcast_ref::<WorktrunkError>() {+ match err.chain().find_map(|error| {+ error+ .downcast_ref::<WorktrunkError>()+ .filter(|error| matches!(error, WorktrunkError::ChildProcessExited { .. }))+ }) {Some(WorktrunkError::ChildProcessExited {code,- message,- signal,- }) => (*code, *signal, message.clone()),+ physical_signal,+ ..+ }) => (*code, *physical_signal, format!("{err:#}")),_ => panic!("expected ChildProcessExited, got {err:?}"),}}+ #[test]+ fn pipeline_spawn_failure_retains_working_directory_and_io_cause() {+ let dir = tempfile::tempdir().unwrap();+ let missing = dir.path().join("missing-worktree");+ let log = fs::File::create(dir.path().join("command.log")).unwrap();+ let error = spawn_shell_command("true", &missing, log).err().unwrap();+ let cause = error.root_cause().downcast_ref::<std::io::Error>().unwrap();+ assert_eq!(cause.kind(), std::io::ErrorKind::NotFound);+ assert_eq!(cause.raw_os_error(), Some(2));+ assert_eq!(error.exit_code(), None);+ let detail = error.display_message();+ assert!(detail.contains(&worktrunk::path::format_path_for_display(&missing)));+ assert_eq!(detail.matches(&cause.to_string()).count(), 1, "{detail}");+ }+#[test]fn signal_exit_reports_named_signal_and_shell_exit_code() {let cases = [(15,143,- "pipeline step terminated by signal 15 (SIGTERM): my-step",- ),- (- 2,- 130,- "pipeline step terminated by signal 2 (SIGINT): my-step",- ),- (- 9,- 137,- "pipeline step terminated by signal 9 (SIGKILL): my-step",+ "pre-merge user:my-step failed: killed by signal 15",),+ (2, 130, "pre-merge user:my-step failed: killed by signal 2"),+ (9, 137, "pre-merge user:my-step failed: killed by signal 9"),];for (sig, expected_code, expected_msg) in cases {let status = ExitStatus::from_raw(sig);- let err = failure_error(&status, "my-step");+ let err = failure_error(&status, HookType::PreMerge, Some("my-step"));let (code, signal, message) = downcast_child_exit(&err);assert_eq!(signal, Some(sig), "signal field for {sig}");assert_eq!(code, expected_code, "exit code for {sig}");@@ -405,11 +392,11 @@ mod tests {fn non_signal_exit_preserves_child_code() {// Non-signal exit: raw value is (code << 8) on Unix.let status = ExitStatus::from_raw(2 << 8);- let err = failure_error(&status, "my-step");+ let err = failure_error(&status, HookType::PreMerge, Some("my-step"));let (code, signal, message) = downcast_child_exit(&err);assert_eq!(signal, None);assert_eq!(code, 2);- assert_eq!(message, "command failed with exit code 2: my-step");+ assert_eq!(message, "pre-merge user:my-step failed: exit code 2");// Non-signal errors must NOT trip the interrupt abort path.assert_eq!(err.interrupt_signal(), None);}diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rsindex 760fdc256..fc3cf663a 100644--- a/src/commands/step/rebase.rs+++ b/src/commands/step/rebase.rs@@ -140,9 +140,9 @@ mod tests {fn child_exit(code: i32, signal: Option<i32>) -> anyhow::Error {WorktrunkError::ChildProcessExited {+ cancellation: None,code,- message: "rebase failed".to_string(),- signal,+ physical_signal: signal,}.into()}diff --git a/src/config/hooks.rs b/src/config/hooks.rsindex dda57b078..caa033fd3 100644--- a/src/config/hooks.rs+++ b/src/config/hooks.rs@@ -5,6 +5,48 @@ use crate::git::HookType;use super::commands::CommandConfig;+/// Whether a hook or alias body came from user config or project config.+///+/// Drives approval and source-qualified filtering.+#[derive(+ Clone,+ Copy,+ Debug,+ PartialEq,+ Eq,+ PartialOrd,+ Ord,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+)]+#[serde(rename_all = "kebab-case")]+#[strum(serialize_all = "kebab-case")]+pub enum HookSource {+ /// User config (~/.config/worktrunk/config.toml). No approval required.+ User,+ /// Project config (.config/wt.toml). Approval is handled at the gate.+ Project,+}++impl HookSource {+ /// Source-qualified command identity, shared by announcements and failures.+ pub fn command_label(self, name: Option<&str>) -> String {+ match name {+ Some(name) => format!("{self}:{name}"),+ None => self.to_string(),+ }+ }+ /// Hook identity in announcements and failure summaries.+ pub fn hook_label(self, hook_type: HookType, name: Option<&str>) -> String {+ match name {+ Some(_) => format!("{hook_type} {}", self.command_label(name)),+ None => format!("{hook_type} {self} hook"),+ }+ }+}+/// Shared hook configuration for user and project configs.#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct HooksConfig {diff --git a/src/config/mod.rs b/src/config/mod.rsindex c810a0613..7cc119827 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -218,7 +218,7 @@ pub use expansion::{validate_list_column_template, validate_template, validate_template_syntax, vars_available_in,vars_map_to_value,};-pub use hooks::HooksConfig;+pub use hooks::{HookSource, HooksConfig};pub use project::{ProjectCiConfig, ProjectCommitConfig, ProjectCommitGenerationConfig, ProjectConfig,ProjectForgeConfig, ProjectListConfig, valid_project_config_keys,diff --git a/src/git/error.rs b/src/git/error.rsindex 3473bde8c..db063ffa0 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -21,6 +21,7 @@//! chain looking for the first type that implements `Diagnostic` and//! emits its rendered output.+use crate::config::HookSource;use std::borrow::Cow;use std::path::{Path, PathBuf};@@ -118,14 +119,13 @@ pub trait ErrorExt {////// When a [`CommandError`] is anywhere in the chain, returns its captured/// stderr/stdout via [`CommandError::combined_output`] — that's git's actual- /// error message, often multi-line. Otherwise falls back to the top-level- /// `Display`, which under the [`Diagnostic`] split is the typed error's- /// short single-line label.+ /// error message, often multi-line. Typed diagnostics keep their top-level+ /// `Display` label; ordinary errors include their source chain so an I/O+ /// failure's cause survives when embedded in another error.////// Use this when embedding a sub-error's text inside another typed error's/// message field (e.g., `GitError::PushFailed::error`) so the user sees git's- /// real reason- /// rather than just the [`CommandError`] single-line summary.+ /// real reason rather than the [`CommandError`] single-line summary.fn display_message(&self) -> String;/// Extract a propagatable exit code from the error.@@ -263,13 +263,35 @@ impl CommandError {}}+/// One description of a child status, shared by captured and streamed runners.+/// A signal is the cause; its shell-compatible exit code is only an exit policy.+pub fn process_exit_description(code: Option<i32>, signal: Option<i32>) -> String {+ match (code, signal) {+ (_, Some(signal)) => format!("killed by signal {signal}"),+ (Some(code), None) => format!("exit code {code}"),+ (None, None) => "unknown exit status".to_string(),+ }+}++/// Plain detail for errors whose Display describes only their own layer.+pub(crate) fn error_chain_message(error: &(dyn std::error::Error + 'static)) -> String {+ anyhow::Chain::new(error)+ .map(ToString::to_string)+ .collect::<Vec<_>>()+ .join(": ")+}+impl std::fmt::Display for CommandError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match (self.exit_code, self.signal) {- (Some(code), _) => write!(f, "{} failed (exit {})", self.command_string(), code),- (None, Some(sig)) => write!(f, "{} failed (signal {})", self.command_string(), sig),- (None, None) => write!(f, "{} failed", self.command_string()),+ if self.exit_code.is_none() && self.signal.is_none() {+ return write!(f, "{} failed", self.command_string());}+ write!(+ f,+ "{} failed ({})",+ self.command_string(),+ process_exit_description(self.exit_code, self.signal)+ )}}@@ -1790,23 +1812,20 @@ impl std::fmt::Display for GitError {/// for cases that need exit code extraction or special handling.#[derive(Debug)]pub enum WorktrunkError {- /// Child outcome, retaining its exit code independently of cancellation.- ///- /// `signal` records native signal termination or a cancellation observed by- /// wt. A child may catch that cancellation and exit normally, even with 0;- /// `code` still records its real outcome. Loops classify cancellation from- /// `signal`, never by inferring from `code`.+ /// Physical child outcome, independently of observed operation cancellation.+ /// A caught interrupt may leave a normal child exit, including zero.ChildProcessExited {code: i32,- message: String,- signal: Option<i32>,+ physical_signal: Option<i32>,+ cancellation: Option<i32>,},/// Hook command failedHookCommandFailed {hook_type: HookType,+ source: HookSource,command_name: Option<String>,- error: String,- exit_code: Option<i32>,+ template: Option<String>,+ error: anyhow::Error,},/// Command was not approved by user (silent error)CommandNotApproved,@@ -1823,16 +1842,23 @@ pub enum WorktrunkError {impl std::fmt::Display for WorktrunkError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {- WorktrunkError::ChildProcessExited { message, .. } => f.write_str(message),+ WorktrunkError::ChildProcessExited {+ code,+ physical_signal,+ ..+ } => f.write_str(&process_exit_description(Some(*code), *physical_signal)),WorktrunkError::HookCommandFailed {hook_type,+ source,command_name,- error,..- } => match command_name {- Some(name) => write!(f, "{hook_type} command failed: {name}: {error}"),- None => write!(f, "{hook_type} command failed: {error}"),- },+ } => {+ write!(+ f,+ "{} failed",+ source.hook_label(*hook_type, command_name.as_deref())+ )+ }// on_skip callback handles the printing for CommandNotApproved;// AlreadyDisplayed has already shown its error via output functions.WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => Ok(()),@@ -1856,14 +1882,10 @@ impl WorktrunkError {.code().or_else(|| signal.map(|signal| 128 + signal)).unwrap_or(1);- let message = match signal {- Some(signal) => format!("terminated by signal {signal}"),- None => format!("exit status: {code}"),- };Self::ChildProcessExited {code,- message,- signal: cancellation.or(signal),+ physical_signal: signal,+ cancellation,}}@@ -1871,7 +1893,7 @@ impl WorktrunkError {pub fn exit_code(&self) -> Option<i32> {match self {WorktrunkError::ChildProcessExited { code, .. } => Some(*code),- WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,+ WorktrunkError::HookCommandFailed { error, .. } => error.exit_code(),WorktrunkError::AlreadyDisplayed { exit_code } => Some(*exit_code),WorktrunkError::Interrupted { signal, .. } => Some(128 + signal),WorktrunkError::CommandNotApproved => None,@@ -1882,23 +1904,49 @@ impl WorktrunkError {impl Diagnostic for WorktrunkError {fn render(&self) -> String {match self {- WorktrunkError::ChildProcessExited { message, .. } => {- error_message(message).to_string()+ WorktrunkError::ChildProcessExited { .. } => {+ error_message(self.to_string()).to_string()}WorktrunkError::HookCommandFailed {hook_type,+ source,command_name,+ template,error,- ..} => {- if let Some(name) = command_name {- error_message(cformat!(- "{hook_type} command failed: <bold>{name}</>: {error}"- ))- .to_string()- } else {- error_message(format!("{hook_type} command failed: {error}")).to_string()+ let label = source.hook_label(*hook_type, command_name.as_deref());+ let summary = cformat!("<bold>{label}</> failed");+ let child_status =+ error+ .chain()+ .find_map(|cause| match cause.downcast_ref::<WorktrunkError>() {+ Some(error @ WorktrunkError::ChildProcessExited { .. }) => {+ Some(error.to_string())+ }+ _ => None,+ });+ let mut rendered = match &child_status {+ Some(status) => error_message(format!("{summary} ({status})")).to_string(),+ None => error_message(summary).to_string(),+ };+ if command_name.is_none()+ && let Some(template) = template+ {+ rendered.push('\n');+ rendered.push_str(&format_bash_with_gutter(template));+ }+ if child_status.is_none() {+ rendered.push('\n');+ rendered.push_str(&format_with_gutter(+ &error+ .chain()+ .map(ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n"),+ None,+ ));}+ rendered}// Silent — caller already handled display; render is empty.WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => {@@ -1926,7 +1974,14 @@ impl Diagnostic for WorktrunkError {}}-impl std::error::Error for WorktrunkError {}+impl std::error::Error for WorktrunkError {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ match self {+ Self::HookCommandFailed { error, .. } => Some(error.as_ref()),+ _ => None,+ }+ }+}impl ErrorExt for anyhow::Error {fn render_diagnostic(&self) -> Option<String> {@@ -1947,7 +2002,11 @@ impl ErrorExt for anyhow::Error {body};}- self.to_string()+ if self.render_diagnostic().is_some() {+ self.to_string()+ } else {+ error_chain_message(self.as_ref())+ }}fn exit_code(&self) -> Option<i32> {@@ -1960,22 +2019,27 @@ impl ErrorExt for anyhow::Error {fn interrupt_signal(&self) -> Option<i32> {// Stream mode (`Cmd::stream`) reports a signal kill as a typed- // `ChildProcessExited { signal }`. An error that already classified- // as `Interrupted` stays one, so loops that re-check errors bubbling- // through them can't demote it.- match self.downcast_ref::<WorktrunkError>() {- Some(WorktrunkError::ChildProcessExited {- signal: Some(sig @ (SIGINT | SIGTERM)),- ..- }) => return Some(*sig),- Some(WorktrunkError::Interrupted {- signal: sig @ (SIGINT | SIGTERM),- ..- }) => return Some(*sig),- _ => {}+ // `ChildProcessExited` with a physical signal or observed cancellation.+ // An error already classified as `Interrupted` stays one, so loops+ // re-checking errors bubbling through them cannot demote it.+ if let Some(signal) = self.chain().find_map(|cause| {+ match cause.downcast_ref::<WorktrunkError>() {+ Some(WorktrunkError::ChildProcessExited {+ physical_signal,+ cancellation,+ ..+ }) => cancellation.or(*physical_signal),+ Some(WorktrunkError::Interrupted { signal, .. }) => Some(*signal),+ _ => None,+ }+ .filter(|signal| matches!(*signal, SIGINT | SIGTERM))+ }) {+ return Some(signal);}#[cfg(unix)]- if let Some(error) = self.downcast_ref::<crate::shell_exec::StreamCommandError>()+ if let Some(error) = self+ .chain()+ .find_map(|cause| cause.downcast_ref::<crate::shell_exec::StreamCommandError>())&& let Some(signal @ (SIGINT | SIGTERM)) =std::os::unix::process::ExitStatusExt::signal(&error.status){@@ -2194,13 +2258,32 @@ mod tests {");}+ #[test]+ #[cfg(unix)]+ fn child_status_description_preserves_physical_outcome_during_cancellation() {+ for (script, code, description) in [+ ("exit 0", 0, "exit code 0"),+ ("kill -9 $$", 137, "killed by signal 9"),+ ] {+ let output = crate::shell_exec::Cmd::new("sh")+ .args(["-c", script])+ .run()+ .unwrap();+ let error: anyhow::Error =+ WorktrunkError::from_child_status(&output.status, Some(2)).into();+ assert_eq!(error.to_string(), description);+ assert_eq!(error.exit_code(), Some(code));+ assert_eq!(error.interrupt_signal(), Some(2));+ }+ }+#[test]fn test_exit_code() {// ChildProcessExitedlet err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 42,- message: "test".into(),- signal: None,+ physical_signal: None,}.into();assert_eq!(err.exit_code(), Some(42));@@ -2208,9 +2291,15 @@ mod tests {// HookCommandFailed with codelet err: anyhow::Error = WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("test".into()),- error: "failed".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),}.into();assert_eq!(err.exit_code(), Some(1));@@ -2218,9 +2307,10 @@ mod tests {// HookCommandFailed without codelet err: anyhow::Error = WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: None,- error: "failed".into(),- exit_code: None,+ error: anyhow::anyhow!("failed"),}.into();assert_eq!(err.exit_code(), None);@@ -2246,9 +2336,15 @@ mod tests {// Wrapped hook errorlet inner: anyhow::Error = WorktrunkError::HookCommandFailed {hook_type: HookType::PreCommit,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("lint".into()),- error: "failed".into(),- exit_code: Some(7),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 7,+ physical_signal: None,+ }+ .into(),}.into();assert_eq!(add_hook_skip_hint(inner).exit_code(), Some(7));@@ -2258,17 +2354,17 @@ mod tests {fn test_interrupt_signal() {// Signal-derived child exit → the signallet err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 130,- message: "terminated by signal 2".into(),- signal: Some(2),+ physical_signal: Some(2),}.into();assert_eq!(err.interrupt_signal(), Some(2));let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 143,- message: "terminated by signal 15".into(),- signal: Some(15),+ physical_signal: Some(15),}.into();assert_eq!(err.interrupt_signal(), Some(15));@@ -2284,9 +2380,9 @@ mod tests {// Ordinary non-zero exit → not an interruptlet err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "exit status: 1".into(),- signal: None,+ physical_signal: None,}.into();assert_eq!(err.interrupt_signal(), None);@@ -2328,12 +2424,27 @@ mod tests {.into();assert_eq!(err.interrupt_signal(), expected, "capture signal {sig}");let streamed: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 128 + sig,- message: format!("terminated by signal {sig}"),- signal: Some(sig),+ physical_signal: Some(sig),}.into();assert_eq!(streamed.interrupt_signal(), expected, "stream signal {sig}");+ #[cfg(unix)]+ {+ use std::os::unix::process::ExitStatusExt;+ let error: anyhow::Error = crate::shell_exec::StreamCommandError {+ command: "git rebase".into(),+ status: std::process::ExitStatus::from_raw(sig),+ output: String::new(),+ }+ .into();+ assert_eq!(+ error.context("rebasing worktree").interrupt_signal(),+ expected,+ "contextual stream signal {sig}"+ );+ }}}@@ -2342,34 +2453,46 @@ mod tests {// Wraps HookCommandFailed with --no-hooks hintlet inner: anyhow::Error = WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("test".into()),- error: "failed".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),}.into();assert_snapshot!(render_anyhow(&add_hook_skip_hint(inner)), @"- [31m✗[39m [31mpre-merge command failed: [1mtest[22m: failed[39m+ [31m✗[39m [31m[1mpre-merge user:test[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22m");// pre-commit hook typelet inner: anyhow::Error = WorktrunkError::HookCommandFailed {hook_type: HookType::PreCommit,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("build".into()),- error: "Build failed".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),}.into();assert_snapshot!(render_anyhow(&add_hook_skip_hint(inner)), @"- [31m✗[39m [31mpre-commit command failed: [1mbuild[22m: Build failed[39m+ [31m✗[39m [31m[1mpre-commit user:build[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-commit hooks, re-run with [4m--no-hooks[24m[22m");// Passes through non-hook errors unchanged (no --no-hooks hint)let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "test".into(),- signal: None,+ physical_signal: None,}.into();assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));@@ -2441,19 +2564,24 @@ mod tests {assert_snapshot!(WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("lint".into()),- error: "lint failed".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }.into(),}.to_string(),- @"pre-merge command failed: lint: lint failed"+ @"pre-merge user:lint failed");assert_snapshot!(WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "exit status: 1".into(),- signal: None,+ physical_signal: None,}.to_string(),- @"exit status: 1"+ @"exit code 1");// Silent variantsassert_eq!(WorktrunkError::CommandNotApproved.to_string(), "");@@ -2479,27 +2607,38 @@ mod tests {#[test]fn snapshot_worktrunk_error_display() {let err = WorktrunkError::ChildProcessExited {+ cancellation: None,code: 1,- message: "Command failed".into(),- signal: None,+ physical_signal: None,};- assert_snapshot!(err.render(), @"[31m✗[39m [31mCommand failed[39m");+ assert_snapshot!(err.render(), @"[31m✗[39m [31mexit code 1[39m");let err = WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: Some("lint".into()),- error: "lint failed".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),};- assert_snapshot!(err.render(), @"[31m✗[39m [31mpre-merge command failed: [1mlint[22m: lint failed[39m");+ assert_snapshot!(err.render(), @"[31m✗[39m [31m[1mpre-merge user:lint[22m failed (exit code 1)[39m");let err = WorktrunkError::HookCommandFailed {hook_type: HookType::PreCreate,+ source: HookSource::User,+ template: Some("echo test".into()),command_name: None,- error: "setup failed".into(),- exit_code: None,+ error: anyhow::anyhow!("setup failed"),};- assert_snapshot!(err.render(), @"[31m✗[39m [31mpre-start command failed: setup failed[39m");+ assert_snapshot!(err.render(), @"+ [31m✗[39m [31m[1mpre-start user hook[22m failed[39m+ [107m [0m [2m[0m[2m[34mecho[0m[2m test[0m+ [107m [0m setup failed+ ");// Silent errors produce empty outputassert_eq!(format!("{}", WorktrunkError::CommandNotApproved), "");@@ -2976,7 +3115,7 @@ mod tests {fn command_error_display_is_single_line() {let err = sample_command_error();let s = err.to_string();- assert_eq!(s, "git worktree list failed (exit 128)");+ assert_eq!(s, "git worktree list failed (exit code 128)");assert!(!s.contains('\n'));}@@ -2994,7 +3133,7 @@ mod tests {signal: None,};assert_eq!(err.command_string(), "git");- assert_eq!(err.to_string(), "git failed (exit 1)");+ assert_eq!(err.to_string(), "git failed (exit code 1)");}#[test]@@ -3070,9 +3209,9 @@ mod tests {exit_code: None,signal: Some(11),};- assert_eq!(err.to_string(), "git fetch failed (signal 11)");+ assert_eq!(err.to_string(), "git fetch failed (killed by signal 11)");- // No exit code and no signal (e.g. hand-built in tests): bare summary.+ // No exit code and no signal (e.g. hand-built in tests): no guessed status.let err = CommandError {signal: None,..errdiff --git a/src/git/mod.rs b/src/git/mod.rsindex 249df5e31..765642c1b 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};mod ci_platform;mod diff;mod error;+pub(crate) use error::error_chain_message;pub mod fsmonitor;mod parse;#[cfg(unix)]@@ -88,6 +89,7 @@ pub use error::{add_hook_skip_hint,// Shared phrasing for an unmerged index ("1 path with unresolved conflicts")format_unresolved_conflicts,+ process_exit_description,// Render a single error via Diagnostic if it implements onetry_render_diagnostic,};diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex bf7537c5c..306775116 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -147,7 +147,8 @@ use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};// Import types from parent moduleuse super::{- CommandError, DefaultBranchName, ForgeKind, GitError, GitItemId, LineDiff, WorktreeInfo,+ CommandError, DefaultBranchName, ErrorExt, ForgeKind, GitError, GitItemId, LineDiff,+ WorktreeInfo,};// Re-export types needed by submodules@@ -1901,7 +1902,7 @@ impl Repository {}Err(e) => {trace.fail(&e);- tracing::debug!(error = %e, "fsmonitor daemon start failed (usually fine): {e}");+ tracing::debug!(error = %crate::git::error_chain_message(&e), "fsmonitor daemon start failed (usually fine)");}}}@@ -2167,10 +2168,8 @@ impl Repository {);}if let Some(cmd_err) = CommandError::find_in(err) {- let exit_info = match cmd_err.exit_code {- Some(code) => format!("exit code {code}"),- None => "killed by signal".to_string(),- };+ let exit_info =+ super::error::process_exit_description(cmd_err.exit_code, cmd_err.signal);return (cmd_err.combined_output(),Some(super::error::FailedCommand {@@ -2179,7 +2178,7 @@ impl Repository {}),);}- (err.to_string(), None)+ (err.display_message(), None)}}diff --git a/src/help_pager.rs b/src/help_pager.rsindex 04a250c6d..36ddd683b 100644--- a/src/help_pager.rs+++ b/src/help_pager.rs@@ -102,7 +102,8 @@ fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> Result<bool> {}match error.downcast_ref::<WorktrunkError>() {Some(WorktrunkError::ChildProcessExited {- signal: Some(_), ..+ physical_signal: Some(_),+ ..}) => Err(error).with_context(|| format!("Help pager `{pager_cmd}` failed")),Some(WorktrunkError::ChildProcessExited { code, .. })if !matches!(*code, 126 | 127) =>@@ -185,7 +186,7 @@ mod tests {assert!(matches!(error.downcast_ref::<worktrunk::git::WorktrunkError>(),Some(worktrunk::git::WorktrunkError::ChildProcessExited {- signal: Some(9),+ physical_signal: Some(9),..})));diff --git a/src/main.rs b/src/main.rsindex ba68d8492..4cde50da9 100644--- a/src/main.rs+++ b/src/main.rs@@ -1311,7 +1311,7 @@ mod tests {fn renders_command_error_without_context() {let err: anyhow::Error = permission_denied_command_error().into();let out = format_command_error(&err);- assert!(out.contains("git worktree list failed (exit 128)"));+ assert!(out.contains("git worktree list failed (exit code 128)"));assert!(out.contains("Permission denied"));assert!(out.contains("unknown error occurred while reading"));}diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 6892c5a39..68a263b8e 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -20,7 +20,9 @@//! Ctrl-C reaches the native job through the kernel; a caught key preserves//! each child's normal status. PID-targeted SIGTERM reaches owned direct children.//!-//! All direct children complete before the caller receives results in input order.+//! Every admitted child runs to completion. Spawn failures occupy the same+//! per-command outcome slots as child exits; the pipeline owns identity and+//! failure policy. Cancellation alone stops admission and drains owned children.use shared_child::SharedChild;#[cfg(not(unix))]@@ -74,7 +76,8 @@ pub struct ConcurrentCommand<'a> {/// Run every command concurrently and return each per-child result in input/// order. `Err(WorktrunkError::ChildProcessExited { .. })` signals a non-zero-/// exit; other errors come from spawn/IO failures.+/// exit; a spawn failure occupies that command's result slot. Outer errors+/// come from executor setup, output collection, or cancellation.////// When the `WORKTRUNK_TEST_SERIAL_CONCURRENT` env var is set, commands run/// sequentially in input order — same prefix-line output path, just one child@@ -96,63 +99,50 @@ pub fn run_concurrent_commands(#[cfg(unix)]let signals = ForegroundSignals::install()?;- // Spawn each child and record its start time for commands.jsonl. If any- // spawn fails partway, kill and reap every child we already spawned —- // otherwise they'd outlive wt as unreaped orphans with nobody draining- // their pipes (and `Child::drop` does not kill the process on Unix).- let mut children: Vec<SpawnedChild> = Vec::with_capacity(cmds.len());- for (i, cmd) in cmds.iter().enumerate() {+ let mut children = Vec::with_capacity(cmds.len());+ let mut outcomes = (0..cmds.len()).map(|_| Ok(())).collect::<Vec<_>>();+ for (index, cmd) in cmds.iter().enumerate() {match spawn_child(shell,- i,+ index,cmd,#[cfg(unix)]&signals,) {- Ok(spawned) => children.push(spawned),- Err(e) => {+ Ok(spawned) => children.push((index, spawned)),+ Err(error) => {#[cfg(unix)]- if e.interrupt_signal().is_some() {- // Keep admitted children's cleanup and the original- // startup cancellation through the normal drain path.- return drain_children(children, cmds, 0, prefix_width, signals);+ if error.interrupt_signal().is_some() {+ // Drain admitted children through the normal cancellation owner.+ drain_children(children, cmds, prefix_width, signals)?;+ return Err(error);}- abort_spawned_children(children);- return Err(e);+ outcomes[index] = Err(error);}}}- drain_children(+ for (index, outcome) in drain_children(children,cmds,- 0,prefix_width,#[cfg(unix)]signals,- )-}--/// Reap owned children when the group cannot finish spawning. Resolve their-/// traces even though their normal outcome collectors will never run.-fn abort_spawned_children(children: Vec<SpawnedChild>) {- for mut spawned in children {- let _ = spawned.child.kill();- let _ = spawned.child.wait();- spawned.trace.complete(false);+ )? {+ outcomes[index] = outcome;}+ Ok(outcomes)}/// Wait independently of output EOF. Cancellation releases remaining pipes/// after all direct waits; ordinary exits preserve descendant output to EOF.#[cfg(unix)]fn drain_children(- mut children: Vec<SpawnedChild>,+ mut children: Vec<(usize, SpawnedChild)>,cmds: &[ConcurrentCommand<'_>],- offset: usize,prefix_width: usize,signals: ForegroundSignals,-) -> anyhow::Result<Vec<anyhow::Result<()>>> {+) -> anyhow::Result<Vec<(usize, anyhow::Result<()>)>> {use nix::poll::{PollFd, PollFlags, PollTimeout, poll};use std::io::ErrorKind;use std::os::fd::AsFd;@@ -164,8 +154,8 @@ fn drain_children(control.set_nonblocking(true)?;wake.set_nonblocking(true)?;let mut pipes = Vec::with_capacity(children.len() * 2);- for (index, child) in children.iter().enumerate() {- let prefix = render_prefix(index + offset, cmds[index].label, prefix_width);+ for (index, child) in &children {+ let prefix = render_prefix(*index, cmds[*index].label, prefix_width);if let Some(stdout) = child.child.take_stdout() {pipes.push(OutputPipe::new(prefix.clone(), stdout)?);}@@ -178,7 +168,7 @@ fn drain_children(let (control, wake, mut pipes) = match setup {Ok(prepared) => prepared,Err(error) => {- for child in &mut children {+ for (_, child) in &mut children {let _ = child.child.kill();let _ = child.child.wait();child.trace.fail(&error);@@ -186,7 +176,10 @@ fn drain_children(return Err(error).context("Failed to prepare concurrent command output");}};- let processes: Vec<_> = children.iter().map(|child| child.child.clone()).collect();+ let processes: Vec<_> = children+ .iter()+ .map(|(_, child)| child.child.clone())+ .collect();let (tx, rx) = mpsc::channel();let notify = WakeSender {tx,@@ -202,8 +195,9 @@ fn drain_children(thread::scope(|scope| {// Observe every exit independently: a later child's interruption must// cancel the operation while an earlier child is still cleaning up.- for (index, (child, cmd)) in children.into_iter().zip(cmds).enumerate() {+ for (index, child) in children {let notify = notify.clone();+ let cmd = &cmds[index];scope.spawn(move || notify.send(index, collect_outcome(child, cmd)));}loop {@@ -289,7 +283,7 @@ fn drain_children(return Err(WorktrunkError::Interrupted { signal, hint: None }.into());}outcomes.sort_unstable_by_key(|(index, _)| *index);- Ok(outcomes.into_iter().map(|(_, outcome)| outcome).collect())+ Ok(outcomes)}#[cfg(unix)]@@ -394,25 +388,19 @@ impl OutputPipe {/// Platforms without Unix poll retain blocking readers and direct-child waits.#[cfg(not(unix))]fn drain_children(- children: Vec<SpawnedChild>,+ children: Vec<(usize, SpawnedChild)>,cmds: &[ConcurrentCommand<'_>],- offset: usize,prefix_width: usize,-) -> anyhow::Result<Vec<anyhow::Result<()>>> {+) -> anyhow::Result<Vec<(usize, anyhow::Result<()>)>> {let (tx, rx) = mpsc::channel::<Event>();let mut readers = Vec::new();- for (index, child) in children.iter().enumerate() {- let label = cmds[index].label.to_string();+ for (index, child) in &children {+ let label = cmds[*index].label.to_string();if let Some(stdout) = child.child.take_stdout() {- readers.push(spawn_reader(- index + offset,- label.clone(),- stdout,- tx.clone(),- ));+ readers.push(spawn_reader(*index, label.clone(), stdout, tx.clone()));}if let Some(stderr) = child.child.take_stderr() {- readers.push(spawn_reader(index + offset, label, stderr, tx.clone()));+ readers.push(spawn_reader(*index, label, stderr, tx.clone()));}}drop(tx);@@ -421,8 +409,7 @@ fn drain_children(let waiter = scope.spawn(move || {children.into_iter()- .zip(cmds)- .map(|(child, cmd)| collect_outcome(child, cmd))+ .map(|(index, child)| (index, collect_outcome(child, &cmds[index]))).collect()});for event in rx {@@ -461,21 +448,32 @@ fn run_serial_with_prefix(for (index, cmd) in cmds.iter().enumerate() {#[cfg(unix)]let signals = ForegroundSignals::install()?;- let spawned = spawn_child(+ match spawn_child(shell,index,cmd,#[cfg(unix)]&signals,- )?;- outcomes.extend(drain_children(- vec![spawned],- std::slice::from_ref(cmd),- index,- prefix_width,- #[cfg(unix)]- signals,- )?);+ ) {+ Ok(spawned) => {+ for (_, outcome) in drain_children(+ vec![(index, spawned)],+ cmds,+ prefix_width,+ #[cfg(unix)]+ signals,+ )? {+ outcomes.push(outcome);+ }+ }+ Err(error) => {+ #[cfg(unix)]+ if error.interrupt_signal().is_some() {+ return Err(error);+ }+ outcomes.push(Err(error));+ }+ }}Ok(outcomes)}@@ -537,9 +535,8 @@ fn spawn_child(let child = match spawned {Ok(child) => Arc::new(child),Err(e) => {- trace.fail(&e);- return Err(e)- .with_context(|| format!("failed to spawn concurrent command '{}'", cmd.label));+ trace.fail(e.as_ref());+ return Err(e);}};@@ -653,6 +650,77 @@ fn render_prefix(index: usize, label: &str, width: usize) -> String {mod tests {use super::*;+ #[test]+ #[cfg(unix)]+ fn test_real_concurrent_process_failure_descriptions() {+ use worktrunk::git::ErrorExt;+ for (script, description, code) in [+ ("exit 7", "exit code 7", 7),+ ("kill -9 $$", "killed by signal 9", 137),+ ] {+ let cwd = tempfile::tempdir().unwrap();+ let directives = DirectivePassthrough::default();+ let mut outcomes = run_concurrent_commands(&[ConcurrentCommand {+ label: "check",+ expanded: script,+ working_dir: cwd.path(),+ log_label: None,+ directives: &directives,+ scrub_git_discovery: false,+ }])+ .unwrap();+ let error = outcomes.pop().unwrap().unwrap_err();+ assert_eq!(error.to_string(), description);+ assert_eq!(error.exit_code(), Some(code));+ }+ }++ #[test]+ fn test_concurrent_spawn_failure_retains_member_outcomes_and_io_source() {+ let cwd = tempfile::tempdir().unwrap();+ let missing = cwd.path().join("missing");+ let directives = DirectivePassthrough::default();+ let specs =+ [cwd.path(), missing.as_path(), cwd.path()].map(|working_dir| ConcurrentCommand {+ label: "check",+ expanded: "printf completed > completed",+ working_dir,+ log_label: None,+ directives: &directives,+ scrub_git_discovery: false,+ });+ insta::allow_duplicates! {+ for serial in [false, true] {+ let outcomes = if serial {+ run_serial_with_prefix(ShellConfig::get().unwrap(), &specs, "check".len())+ } else {+ run_concurrent_commands(&specs)+ }+ .unwrap();+ assert_eq!(outcomes.len(), 3);+ let mut outcomes = outcomes.into_iter();+ outcomes.next().unwrap().unwrap();+ let error = outcomes.next().unwrap().unwrap_err();+ outcomes.next().unwrap().unwrap();+ assert_eq!(+ std::fs::read_to_string(cwd.path().join("completed")).unwrap(),+ "completed"+ );+ #[cfg(unix)]+ {+ use worktrunk::git::ErrorExt;+ let path = worktrunk::path::format_path_for_display(&missing);+ let detail = error.display_message().replace(&path, "_MISSING_");+ insta::assert_snapshot!(detail, @"Failed to execute sh @ _MISSING_: No such file or directory (os error 2)");+ }+ let preserved = error.downcast_ref::<std::io::Error>().unwrap();+ let native = error.root_cause().downcast_ref::<std::io::Error>().unwrap();+ assert!(native.raw_os_error().is_some());+ assert_eq!(preserved.kind(), native.kind());+ }+ }+ }+#[test]fn test_empty_cmds_returns_empty() {let outcomes = run_concurrent_commands(&[]).expect("no spawn should happen");diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex c2c72f211..f42b55128 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -79,7 +79,8 @@ use std::time::{Duration, Instant};use anyhow::Context;use shared_child::SharedChild;-use crate::git::{ErrorExt, GitError, WorktrunkError};+use crate::git::WorktrunkError;+use crate::path::format_path_for_display;use crate::styling::eprintln;use crate::sync::Semaphore;use crate::trace::CommandTrace;@@ -116,7 +117,7 @@ pub(crate) fn with_process_creation_guard<T>(/// Spawn a child under the shared process-creation guard.pub fn spawn(command: &mut Command) -> std::io::Result<std::process::Child> {- with_process_creation_guard(|| command.spawn())+ with_process_creation_guard(|| command.spawn()).map_err(|error| spawn_error(command, error))}/// Spawn a shared child under the same process-creation lock as [`spawn`].@@ -124,6 +125,7 @@ pub fn spawn_shared_child(command: &mut Command) -> std::io::Result<SharedChild>// SharedChild::new calls try_wait and can reap a short-lived child here.// Keep SharedChild::spawn's unreaped ownership for process-tree cleanup.with_process_creation_guard(|| SharedChild::spawn(command))+ .map_err(|error| spawn_error(command, error))}/// Create wakeup endpoints under the same guard as process creation.@@ -1266,6 +1268,45 @@ impl CapturedChild {}}+/// A spawn failure identifies the program and cwd actually supplied to the OS.+/// `NotFound` can mean a missing program, cwd, or interpreter, so it does not+/// establish which is absent. Keep the original I/O error as the source.+#[derive(Debug)]+struct SpawnError {+ program: std::ffi::OsString,+ cwd: Option<std::path::PathBuf>,+ source: std::io::Error,+}++impl std::fmt::Display for SpawnError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Failed to execute {}", self.program.to_string_lossy())?;+ if let Some(cwd) = &self.cwd {+ write!(f, " @ {}", format_path_for_display(cwd))?;+ }+ Ok(())+ }+}++impl std::error::Error for SpawnError {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ Some(&self.source)+ }+}++/// Enrich an OS spawn failure without changing its kind or guessing its cause.+fn spawn_error(command: &std::process::Command, source: std::io::Error) -> std::io::Error {+ let cwd = command.get_current_dir().map(std::path::Path::to_path_buf);+ std::io::Error::new(+ source.kind(),+ SpawnError {+ program: command.get_program().to_os_string(),+ cwd,+ source,+ },+ )+}+/// Structured error from [`Cmd::delayed_stream`].////// Separates command output from command identity so callers can format each@@ -1295,10 +1336,11 @@ impl std::fmt::Display for StreamCommandError {impl StreamCommandError {pub fn exit_info(&self) -> String {- self.status- .code()- .map(|code| format!("exit code {code}"))- .unwrap_or_else(|| "killed by signal".to_string())+ #[cfg(unix)]+ let signal = std::os::unix::process::ExitStatusExt::signal(&self.status);+ #[cfg(not(unix))]+ let signal = None;+ crate::git::process_exit_description(self.status.code(), signal)}}@@ -1505,30 +1547,33 @@ impl Cmd {/// commands haven't been cancelled. Background callers check after taking/// their semaphore permit: a command can be cancelled while parked on the/// semaphore, and that is the common case in a large fan-out.- fn check_before_spawn(&self) -> std::io::Result<()> {+ fn check_before_spawn(&self, command: &Command) -> std::io::Result<()> {if background_cancelled() {return Err(cancelled_error());}- self.check_spawn_preconditions()- }-- fn check_spawn_preconditions(&self) -> std::io::Result<()> {- if let Some(dir) = &self.current_dir {- let metadata = std::fs::metadata(dir)?;- if !metadata.is_dir() {- return Err(std::io::Error::new(- ErrorKind::NotADirectory,- format!("{} is not a directory", dir.display()),- ));+ self.check_spawn_preconditions(command)+ }++ fn check_spawn_preconditions(&self, command: &Command) -> std::io::Result<()> {+ (|| {+ if let Some(dir) = &self.current_dir {+ let metadata = std::fs::metadata(dir)?;+ if !metadata.is_dir() {+ return Err(std::io::Error::new(+ ErrorKind::NotADirectory,+ format!("{} is not a directory", dir.display()),+ ));+ }}- }- let program = Path::new(&self.program);- if !self.shell_wrap && program.is_absolute() {- ensure_executable_path(program)?;- }+ let program = Path::new(&self.program);+ if !self.shell_wrap && program.is_absolute() {+ ensure_executable_path(program)?;+ }- Ok(())+ Ok(())+ })()+ .map_err(|error| spawn_error(command, error))}fn apply_common_settings(&self, cmd: &mut Command) {@@ -1800,15 +1845,15 @@ impl Cmd {let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str).reads_stdin(self.stdin_data.is_some());- if let Err(e) = self.check_before_spawn() {+ let mut cmd = self.direct_command();+ self.apply_common_settings(&mut cmd);++ if let Err(e) = self.check_before_spawn(&cmd) {trace.fail(&e);external_log.record(None);return Err(e);}- let mut cmd = self.direct_command();- self.apply_common_settings(&mut cmd);-// Preparation failures and child outcomes resolve the same trace.let result = (|| {let stdin = self@@ -1887,13 +1932,14 @@ impl Cmd {self.log_run_start(&cmd_str);let mut trace = CommandTrace::new(self.context.as_deref(), &cmd_str);- if let Err(e) = self.check_before_spawn() {+ let mut cmd = self.direct_command();+ self.apply_common_settings(&mut cmd);++ if let Err(e) = self.check_before_spawn(&cmd) {trace.fail(&e);return Err(e);}- let mut cmd = self.direct_command();- self.apply_common_settings(&mut cmd);cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -1970,11 +2016,16 @@ impl Cmd {let _guard = (!is_foreground_thread()).then(|| semaphore().acquire());+ let mut first = self.direct_command();+ self.apply_common_settings(&mut first);+ let mut second = next.direct_command();+ next.apply_common_settings(&mut second);+// Validate both commands before spawning either. Nothing has spawned// yet, so a cancellation or precondition failure emits a one-shot// failed record rather than holding a guard across an execution that// never happens.- if let Err(e) = self.check_before_spawn() {+ if let Err(e) = self.check_before_spawn(&first) {// stdin_data is still owned here (taken below), so it reflects// whether the source would have read a buffer; the sink always reads// the upstream pipe.@@ -1986,7 +2037,7 @@ impl Cmd {);return Err(e);}- if let Err(e) = next.check_spawn_preconditions() {+ if let Err(e) = next.check_spawn_preconditions(&second) {CommandTrace::record_failed(next.context.as_deref(), &second_cmd_str, true, &e);return Err(e);}@@ -2003,8 +2054,6 @@ impl Cmd {first_trace.fail(error);})?.unwrap_or_else(Stdio::null);- let mut first = self.direct_command();- self.apply_common_settings(&mut first);first.stdin(input).stdout(Stdio::piped())@@ -2021,8 +2070,6 @@ impl Cmd {.stdout.take().expect("stdout was configured as piped");- let mut second = next.direct_command();- next.apply_common_settings(&mut second);second.stdin(Stdio::from(first_stdout)).stdout(Stdio::piped())@@ -2137,7 +2184,7 @@ impl Cmd {apply_cd_directive_env(&mut cmd, path);}- if let Err(e) = self.check_spawn_preconditions() {+ if let Err(e) = self.check_spawn_preconditions(&cmd) {// Nothing spawned yet — emit a one-shot failed record (the trace// guard is constructed just before spawn, below).CommandTrace::record_failed(@@ -2146,9 +2193,7 @@ impl Cmd {self.stdin_data.is_some(),&e,);- return Err(anyhow::Error::from(GitError::Other {- message: format!("Failed to execute command ({}): {}", exec_mode, e),- }));+ return Err(e.into());}#[cfg(not(unix))]@@ -2196,16 +2241,10 @@ impl Cmd {let spawned = spawn_shared_child(&mut cmd).map_err(anyhow::Error::from);let child = match spawned {Ok(child) => Arc::new(child),- Err(error) if error.interrupt_signal().is_some() => {- trace.fail(&error);+ Err(error) => {+ trace.fail(error.as_ref());return Err(error);}- Err(e) => {- trace.fail(&e);- return Err(anyhow::Error::from(GitError::Other {- message: format!("Failed to execute command ({}): {}", exec_mode, e),- }));- }};#[cfg(unix)]@@ -2317,7 +2356,7 @@ impl Cmd {Ok(child) => child,Err(e) => {trace.fail(&e);- return Err(e).with_context(|| format!("Failed to spawn: {}", cmd_str));+ return Err(e.into());}};@@ -3205,7 +3244,7 @@ print(*counts)wt_err,WorktrunkError::ChildProcessExited {code: 141,- signal: Some(13),+ physical_signal: Some(13),..}));@@ -3230,12 +3269,159 @@ print(*counts)}}+ #[test]+ #[cfg(unix)]+ fn test_real_process_failure_descriptions() {+ for (script, description) in [+ ("exit 7", "exit code 7"),+ ("kill -9 $$", "killed by signal 9"),+ ] {+ let output = Cmd::new("sh").args(["-c", script]).run().unwrap();+ let error =+ crate::git::CommandError::from_failed_output("sh", &["-c", script], &output);+ assert!(+ error+ .to_string()+ .ends_with(&format!("failed ({description})"))+ );+ let error = Cmd::new("sh").args(["-c", script]).stream().unwrap_err();+ assert_eq!(error.to_string(), description);+ let error = Cmd::new("sh")+ .args(["-c", script])+ .delayed_stream(1000, None)+ .unwrap_err();+ let (_, command) = crate::git::Repository::extract_failed_command(&error);+ assert_eq!(command.unwrap().exit_info, description);+ }+ }++ #[test]+ #[cfg(unix)]+ fn test_spawn_errors_identify_program_and_cwd_without_guessing_cause() {+ use crate::git::ErrorExt;+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let script = dir.path().join("broken-interpreter");+ std::fs::write(&script, "#!/no/such/interpreter-7f3a9b2c\n").unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ let missing_cwd = dir.path().join("missing");+ for (program, cwd) in [+ ("missing-program-7f3a9b2c".to_string(), dir.path()),+ ("/bin/sh".to_string(), missing_cwd.as_path()),+ (script.to_string_lossy().into_owned(), dir.path()),+ ] {+ for command in [+ Cmd::new(&program).current_dir(cwd),+ Cmd::new(&program).current_dir(cwd).stdin_bytes("{}"),+ Cmd::new(&program)+ .current_dir(cwd)+ .timeout(Duration::from_secs(1)),+ ] {+ let error = command.run().unwrap_err();+ assert_eq!(error.kind(), ErrorKind::NotFound);+ assert!(error.to_string().contains(&program), "{error}");+ assert!(+ error+ .to_string()+ .contains(&cwd.to_string_lossy().to_string()),+ "{error}"+ );+ let source = std::error::Error::source(error.get_ref().unwrap()).unwrap();+ assert_eq!(+ source+ .downcast_ref::<std::io::Error>()+ .unwrap()+ .raw_os_error(),+ Some(2)+ );+ let cause = source.to_string();+ // The borrowed detail used by captured-command traces and the+ // embedded Git-failure detail both retain the OS cause once.+ let trace_detail = crate::git::error_chain_message(&error);+ let error: anyhow::Error = error.into();+ let detail = error.display_message();+ assert_eq!(detail, trace_detail);+ assert_eq!(detail.matches(&cause).count(), 1, "{detail}");+ let (extracted, command) = crate::git::Repository::extract_failed_command(&error);+ assert_eq!(extracted, detail);+ assert!(command.is_none());+ }+ let error = Cmd::new(&program).current_dir(cwd).stream().unwrap_err();+ assert!(error.to_string().contains(&program), "{error}");+ assert!(+ error+ .to_string()+ .contains(&cwd.to_string_lossy().to_string()),+ "{error}"+ );+ assert_eq!(error.exit_code(), None);+ assert!(+ error+ .chain()+ .any(|source| source.downcast_ref::<std::io::Error>().is_some())+ );+ }+ }+#[test]fn test_cmd_run_spawn_failure_is_errored() {let err = Cmd::new("/no/such/binary-7f3a9b2c").run().unwrap_err();assert_eq!(err.kind(), ErrorKind::NotFound);}+ /// Every runner reports the native OS cause once through the same trace owner.+ /// A scoped subscriber records real failures without changing the process logger.+ #[test]+ #[cfg(all(feature = "cli", unix))]+ fn test_spawn_trace_retains_io_cause_once_in_every_execution_mode() {+ let log = tempfile::NamedTempFile::new().unwrap();+ let subscriber = tracing_subscriber::fmt()+ .without_time()+ .with_ansi(false)+ .with_max_level(tracing::Level::DEBUG)+ .with_writer(std::sync::Arc::new(log.reopen().unwrap()))+ .finish();+ let causes = tracing::subscriber::with_default(subscriber, || {+ let missing = "worktrunk-no-such-program-trace";+ [+ Cmd::new(missing).run().unwrap_err().into(),+ Cmd::new(missing)+ .stdin_bytes("{}")+ .run()+ .unwrap_err()+ .into(),+ Cmd::new(missing)+ .timeout(Duration::from_secs(1))+ .run()+ .unwrap_err()+ .into(),+ Cmd::new(missing).stream().unwrap_err(),+ Cmd::new(missing).delayed_stream(-1, None).unwrap_err(),+ Cmd::new(missing)+ .pipe_into(Cmd::new("cat"))+ .unwrap_err()+ .into(),+ Cmd::new("true")+ .pipe_into(Cmd::new(missing))+ .unwrap_err()+ .into(),+ ]+ .into_iter()+ .map(|error: anyhow::Error| error.root_cause().to_string())+ .collect::<Vec<_>>()+ });+ let output = std::fs::read_to_string(log.path()).unwrap();+ let events: Vec<_> = output+ .lines()+ .filter(|line| line.contains("cmd_errored"))+ .collect();+ assert_eq!(events.len(), causes.len(), "{output}");+ for (event, cause) in events.into_iter().zip(causes) {+ assert!(event.contains("Failed to execute worktrunk-no-such-program-trace"));+ assert_eq!(event.matches(&cause).count(), 1, "{event}");+ }+ }+#[test]fn test_cmd_run_missing_current_dir_is_errored() {let err = Cmd::new("sh")@@ -3287,7 +3473,7 @@ print(*counts)assert!(result.is_err());let msg = result.unwrap_err().to_string();assert!(- msg.contains("Failed to execute command"),+ msg.contains("Failed to execute /no/such/binary"),"expected spawn-failure message, got: {msg}");}@@ -3425,7 +3611,7 @@ print(*counts)// delay_ms=-1 disables phase 1; the spawn failure resolves the trace// via `fail` rather than dropping it unresolved.let err = Cmd::new(MISSING_CMD).delayed_stream(-1, None).unwrap_err();- assert!(err.to_string().contains("Failed to spawn"), "{err}");+ assert!(err.to_string().contains("Failed to execute"), "{err}");}#[test]diff --git a/src/trace/emit.rs b/src/trace/emit.rsindex 0f7f2901a..4b23868d2 100644--- a/src/trace/emit.rs+++ b/src/trace/emit.rs@@ -344,16 +344,21 @@ impl CommandTrace {/// nothing to time. Equivalent to `new` immediately followed by `fail`./// `reads_stdin` records the same stdin shape a successful run would have, so/// a precondition-failed stdin command is excluded from dedup like any other.- pub fn record_failed(context: Option<&str>, cmd: &str, reads_stdin: bool, err: impl Display) {+ pub fn record_failed(+ context: Option<&str>,+ cmd: &str,+ reads_stdin: bool,+ err: &(dyn std::error::Error + 'static),+ ) {let mut trace = Self::new(context, cmd).reads_stdin(reads_stdin);trace.fail(err);}/// The command never ran to completion (spawn failure, wait failure)./// Emits an `err=…` record with the elapsed duration.- pub fn fail(&mut self, err: impl Display) {+ pub fn fail(&mut self, err: &(dyn std::error::Error + 'static)) {let dur_us = self.start.elapsed().as_micros() as u64;- command_errored(self, dur_us, err);+ command_errored(self, dur_us, crate::git::error_chain_message(err));self.resolved = true;}}@@ -474,10 +479,15 @@ mod tests {drop(completed);let mut failed = CommandTrace::new(None, "git nope");- failed.fail(std::io::Error::other("boom"));+ failed.fail(&std::io::Error::other("boom"));drop(failed);- CommandTrace::record_failed(None, "git nope", false, "precondition");+ CommandTrace::record_failed(+ None,+ "git nope",+ false,+ &std::io::Error::other("precondition"),+ );}#[test]diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rsindex eac2e1493..d4f84f2ed 100644--- a/tests/integration_tests/custom.rs+++ b/tests/integration_tests/custom.rs@@ -297,7 +297,7 @@ fn custom_subcommand_alias_propagates_non_fatal_git_failure() {.ansi_strip().into_owned();assert!(- stderr.contains("git rev-parse --git-common-dir failed (exit 1)"),+ stderr.contains("git rev-parse --git-common-dir failed (exit code 1)"),"git's own failure should surface: {stderr}");assert!(diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex 246ded9a6..f6cc8fcc7 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -682,6 +682,6 @@ fn test_for_each_json_with_failure(repo: TestRepo) {assert_eq!(item["success"], false);assert_eq!(item["exit_code"], 1);// error field contains the raw message from the child process- assert_eq!(item["error"], "exit status: 1");+ assert_eq!(item["error"], "exit code 1");}}diff --git a/tests/integration_tests/foreground_jobs.rs b/tests/integration_tests/foreground_jobs.rsindex 66bb2f1f9..068722472 100644--- a/tests/integration_tests/foreground_jobs.rs+++ b/tests/integration_tests/foreground_jobs.rs@@ -485,8 +485,7 @@ sys.exit(code)// Verbose trace records retain the physical child status. A separate// user-facing failure for cancellation would be misleading.assert!(- !shell.output.contains("✗ terminated by signal")- && !shell.output.contains("✗ exit status:"),+ !shell.output.contains("✗ killed by signal") && !shell.output.contains("✗ exit code"),"{}",shell.output);diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex b7692aea8..4b5729c60 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -416,22 +416,40 @@ fn integration_errors_render() {fn command_errors_render() {let hook_with_name = WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: worktrunk::config::HookSource::User,+ template: Some("echo test".into()),command_name: Some("test".into()),- error: "exit code 1".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),};let hook_without_name = WorktrunkError::HookCommandFailed {hook_type: HookType::PreCreate,+ source: worktrunk::config::HookSource::User,+ template: Some("echo test".into()),command_name: None,- error: "command not found".into(),- exit_code: Some(127),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 127,+ physical_signal: None,+ }+ .into(),};let hook_with_hint = add_hook_skip_hint(WorktrunkError::HookCommandFailed {hook_type: HookType::PreMerge,+ source: worktrunk::config::HookSource::User,+ template: Some("echo test".into()),command_name: Some("test".into()),- error: "exit code 1".into(),- exit_code: Some(1),+ error: WorktrunkError::ChildProcessExited {+ cancellation: None,+ code: 1,+ physical_signal: None,+ }+ .into(),}.into(),);diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__command_errors.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__command_errors.snapindex 094d598f7..e0992cf07 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__command_errors.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__command_errors.snap@@ -41,13 +41,14 @@ expression: render_cases(cases)## named hook failed-[31m✗[39m [31mpre-merge command failed: [1mtest[22m: exit code 1[39m+[31m✗[39m [31m[1mpre-merge user:test[22m failed (exit code 1)[39m## unnamed hook failed-[31m✗[39m [31mpre-start command failed: command not found[39m+[31m✗[39m [31m[1mpre-start user hook[22m failed (exit code 127)[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m test[0m## hook failed with skip hint-[31m✗[39m [31mpre-merge command failed: [1mtest[22m: exit code 1[39m+[31m✗[39m [31m[1mpre-merge user:test[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 3e7ea577e..9e35ded2d 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -2660,3 +2660,42 @@ probe = "echo hello""detached `branch` should read `(unset)`, not `(unused)`, got: {branch_row}");}++/// The first alias step moves its worktree, so the next child's cwd is absent.+#[rstest]+#[cfg(unix)]+#[case::serial(false)]+#[case::concurrent(true)]+fn test_alias_spawn_failure_has_one_source_detail(repo: TestRepo, #[case] concurrent: bool) {+ repo.write_test_config(+ if concurrent {+ r#"[aliases]+move-away = ["mv {{ worktree_path }} {{ worktree_path }}.moved", { check = "true", sibling = "true" }]+"#+ } else {+ r#"[aliases]+move-away = ["mv {{ worktree_path }} {{ worktree_path }}.moved", "true"]+"#+ }+ );+ let output = repo.wt_command().arg("move-away").output().unwrap();+ assert_eq!(output.status.code(), Some(1));+ assert!(!repo.root_path().exists());+ assert!(repo.root_path().with_file_name("repo.moved").exists());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert_eq!(stderr.matches("Failed to execute").count(), 1, "{stderr}");+ assert_eq!(stderr.matches("os error 2").count(), 1, "{stderr}");+ if concurrent {+ assert!(stderr.contains("command 'check'"), "{stderr}");+ }+ setup_snapshot_settings(&repo).bind(|| {+ insta::assert_snapshot!(+ if concurrent {+ "alias_concurrent_spawn_failure_has_one_source_detail"+ } else {+ "alias_spawn_failure_has_one_source_detail"+ },+ stderr+ );+ });+}diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex e3f62fb4f..e580c27ba 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -2655,7 +2655,7 @@ elif branch == 'b':.into_owned();assert!(stderr.contains("a: important refusal"), "{stderr}");assert!(- stderr.contains("pre-remove command failed: one: exit status: 3"),+ stderr.contains("pre-remove user:one failed (exit code 3)"),"{stderr}");assert!(@@ -2755,10 +2755,7 @@ elif branch == 'a':.ansi_strip().into_owned();assert!(stderr.contains("a: important refusal"), "{stderr}");- assert!(- stderr.contains("pre-remove command failed: exit status: 3"),- "{stderr}"- );+ assert!(stderr.contains("failed (exit code 3)"), "{stderr}");assert!(stderr.contains("To skip pre-remove hooks, re-run with --no-hooks"),"{stderr}"diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 8f69ca71e..fdec15ad9 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -565,7 +565,7 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"/// Implementation mirrors `test_for_each_aborts_on_signal_exit`: the first/// hook step self-signals via SIGTERM after touching a marker. SIGINT against/// the parent wt would kill the test harness, so we drive the same-/// `ChildProcessExited { signal: Some(_), .. }` path with an in-child signal.+/// `ChildProcessExited { physical_signal: Some(_), .. }` path with an in-child signal.#[rstest]#[cfg(unix)]fn test_pre_merge_pipeline_aborts_on_signal_exit(repo: TestRepo) {@@ -1366,13 +1366,125 @@ broken = "echo {{ does_not_exist }} > should_not_exist.txt"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.+/// A later preparation error must reap already admitted concurrent children and+/// resolve their traces before the background runner reports its failure.+#[rstest]+#[cfg(unix)]+fn test_background_concurrent_template_failure_reaps_admitted_child(repo: TestRepo) {+ use nix::fcntl::OFlag;+ use nix::sys::signal::{Signal, kill, killpg};+ use nix::sys::stat::Mode;+ use nix::unistd::{Pid, mkfifo};+ use std::io::Write;+ use std::os::unix::{fs::OpenOptionsExt, process::CommandExt};+ use std::process::{Child, Stdio};++ struct Runner {+ child: Child,+ waited: bool,+ }+ impl Drop for Runner {+ fn drop(&mut self) {+ if !self.waited {+ // The unreaped leader reserves this group ID, including when+ // an assertion fails while the runner is blocked on the FIFO.+ let _ = killpg(Pid::from_raw(self.child.id() as i32), Signal::SIGKILL);+ let _ = self.child.wait();+ }+ }+ }++ let admitted = "printf '%s' $$ > admitted.pid; exec sleep 60";+ let command = |name: &str, template: &str| {+ serde_json::json!({+ "name": name,+ "template": template,+ "context": {},+ "template_name": format!("user:{name}"),+ "label": format!("user:{name}"),+ })+ };+ let spec = serde_json::json!({+ "worktree_path": repo.root_path(),+ "branch": "main",+ "hook_type": worktrunk::HookType::PostCreate,+ "source": worktrunk::config::HookSource::User,+ "steps": [{"Concurrent": [+ command("admitted", admitted),+ command("broken", "echo {{ does_not_exist }}"),+ ]}],+ });+ let logs = resolve_git_common_dir(repo.root_path()).join("wt/logs");+ let hook_logs = logs.join("main/user/post-start");+ fs::create_dir_all(&hook_logs).unwrap();+ let blocked_log = hook_logs.join("broken.log");+ mkfifo(&blocked_log, Mode::S_IRUSR | Mode::S_IWUSR).unwrap();++ let runner_log = repo.root_path().join("runner-error.log");+ let child = repo+ .wt_command()+ .args(["-vv", "hook", "run-pipeline"])+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(fs::File::create(&runner_log).unwrap())+ .process_group(0)+ .spawn()+ .unwrap();+ let mut runner = Runner {+ child,+ waited: false,+ };+ runner+ .child+ .stdin+ .take()+ .unwrap()+ .write_all(&serde_json::to_vec(&spec).unwrap())+ .unwrap();++ // Opening the second command's log blocks preparation until we have+ // observed the first child's PID. The FIFO supplies ordering, not a delay.+ let pid_path = repo.root_path().join("admitted.pid");+ wait_for_file_content(&pid_path);+ let pid = Pid::from_raw(fs::read_to_string(pid_path).unwrap().parse().unwrap());+ kill(pid, None).expect("admitted child must still be running");+ let _reader = fs::OpenOptions::new()+ .read(true)+ .custom_flags(OFlag::O_NONBLOCK.bits())+ .open(blocked_log)+ .unwrap();++ crate::common::wait_for("concurrent preparation failure", || {+ fs::read_to_string(&runner_log)+ .unwrap()+ .contains("Failed to expand user:broken:")+ });+ assert_eq!(kill(pid, None), Err(nix::errno::Errno::ESRCH));++ let trace = fs::read_to_string(logs.join("trace.jsonl")).unwrap();+ let outcomes: Vec<_> = worktrunk::trace::parse_lines(&trace)+ .into_iter()+ .filter(|entry| {+ matches!(&entry.kind,+ worktrunk::trace::TraceEntryKind::Command { command, .. } if command == admitted)+ })+ .map(|entry| entry.is_success())+ .collect();+ assert_eq!(outcomes, [false], "{trace}");+ let status = runner.child.wait().unwrap();+ runner.waited = true;+ assert_eq!(status.code(), Some(1));+}++/// Runner-log failures use the same hook/status grammar as foreground failures.#[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"+post-switch = """+true+exit 9+""""#,);@@ -1400,11 +1512,15 @@ post-switch = "exit 9"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");+ assert_snapshot!(fs::read_to_string(&named).unwrap(), @"[31m✗[39m [31m[1mpost-start user:broken[22m failed (exit code 7)[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");+ assert_snapshot!(fs::read_to_string(&unnamed).unwrap(), @"+ [31m✗[39m [31m[1mpost-switch user hook[22m failed (exit code 9)[39m+ [107m [0m [2m[0m[2m[34mtrue[0m+ [107m [0m [2m[0m[2m[34mexit[0m[2m 9[0m+ ");}/// A semantic template error in a foreground pipeline step surfaces when that@@ -4768,6 +4884,110 @@ fn test_concurrent_hook_does_not_inherit_git_discovery_vars(repo: TestRepo) {assert_git_env_scrubbed(&marker);}+/// A serial project hook and a concurrent user hook share status and source grammar.+#[rstest]+#[case(false, "project")]+#[case(true, "user")]+fn test_hook_failure_status_and_source(+ repo: TestRepo,+ #[case] concurrent: bool,+ #[case] source: &str,+) {+ let config = if concurrent {+ r#"pre-merge = [{ check = "exit 7", sibling = "true" }]"#+ } else {+ r#"pre-merge = [{ check = "exit 7" }]"#+ };+ if source == "project" {+ repo.write_project_config(config);+ } else {+ repo.write_test_config(config);+ }+ let output = repo+ .wt_command()+ .args(["hook", "pre-merge", "--yes"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert_eq!(output.status.code(), Some(7), "{stderr}");+ setup_snapshot_settings(&repo).bind(|| {+ assert_snapshot!(format!("hook_failure_status_{source}"), stderr);+ });+}++/// A hook moves its worktree, so the next spawn fails. Serial and concurrent+/// paths retain the failing command and OS cause under Warn and FailFast.+#[rstest]+#[cfg(unix)]+#[case::warn_serial(true, false)]+#[case::warn_concurrent(true, true)]+#[case::failfast_serial(false, false)]+#[case::failfast_concurrent(false, true)]+fn test_foreground_hook_spawn_failure_has_one_io_detail(+ mut repo: TestRepo,+ #[case] warn: bool,+ #[case] concurrent: bool,+) {+ let worktree = repo.add_worktree("move-away");+ let hook = if warn { "post-start" } else { "pre-merge" };+ let config = if concurrent {+ r#"[+ { move = "mv {{ worktree_path }} {{ worktree_path }}.moved" },+ { check = "true", sibling = "true" },+]+"#+ } else {+ r#"[+ { move = "mv {{ worktree_path }} {{ worktree_path }}.moved" },+ { check = "true" },+]+"#+ };+ repo.write_test_config(&format!("{hook} = {config}"));+ let output = repo+ .wt_command()+ .args(["hook", hook, "--foreground", "--yes"])+ .current_dir(&worktree)+ .output()+ .unwrap();+ assert_eq!(+ output.status.code(),+ Some(if warn { 0 } else { 1 }),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ !worktree.exists(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(worktree.with_file_name("repo.move-away.moved").exists());+ assert!(repo.root_path().exists());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert_eq!(+ stderr.matches("Failed to execute").count(),+ if warn && concurrent { 2 } else { 1 },+ "{stderr}"+ );+ assert_eq!(+ stderr.matches("os error 2").count(),+ if warn && concurrent { 2 } else { 1 },+ "{stderr}"+ );+ setup_snapshot_settings(&repo).bind(|| {+ assert_snapshot!(+ match (warn, concurrent) {+ (true, false) => "foreground_hook_spawn_failure_has_one_io_detail",+ (true, true) => "foreground_concurrent_hook_spawn_failure_has_one_io_detail",+ (false, false) => "foreground_hook_failfast_spawn_failure_has_one_io_detail",+ (false, true) =>+ "foreground_concurrent_hook_failfast_spawn_failure_has_one_io_detail",+ },+ stderr+ );+ });+}+/// Sibling count must not change access to /dev/tty. Exercise the reported/// terminal-settings failure, input allocation, and restoration after the job.#[rstest]diff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_command_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_command_fails.snapindex 9fc309f87..9024ff785 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_command_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_command_fails.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mAdding plugin from marketplace...[39m-[31m✗[39m [31mclaude plugin marketplace add max-sixty/worktrunk failed (exit 1)[39m+[31m✗[39m [31mclaude plugin marketplace add max-sixty/worktrunk failed (exit code 1)[39m[107m [0m error: network timeoutdiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_second_step_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_second_step_fails.snapindex df263b2b6..ddd5fca13 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_second_step_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_install_second_step_fails.snap@@ -64,5 +64,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mAdding plugin from marketplace...[39m[36m◎[39m [36mInstalling plugin...[39m-[31m✗[39m [31mclaude plugin install worktrunk@worktrunk failed (exit 1)[39m+[31m✗[39m [31mclaude plugin install worktrunk@worktrunk failed (exit code 1)[39m[107m [0m error: install faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_command_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_command_fails.snapindex d1f84979a..a01b6bb1c 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_command_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_command_fails.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mUninstalling plugin...[39m-[31m✗[39m [31mclaude plugin uninstall worktrunk@worktrunk failed (exit 1)[39m+[31m✗[39m [31mclaude plugin uninstall worktrunk@worktrunk failed (exit code 1)[39m[107m [0m error: uninstall faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_second_step_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_second_step_fails.snapindex 0b3f4b191..15d66bae9 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_second_step_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_claude_uninstall_second_step_fails.snap@@ -64,5 +64,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mUninstalling plugin...[39m[36m◎[39m [36mRemoving Claude Code plugin marketplace...[39m-[31m✗[39m [31mclaude plugin marketplace remove worktrunk failed (exit 1)[39m+[31m✗[39m [31mclaude plugin marketplace remove worktrunk failed (exit code 1)[39m[107m [0m error: marketplace remove faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_command_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_command_fails.snapindex 8ea27ced4..f6557e0e7 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_command_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_command_fails.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mAdding Codex plugin marketplace...[39m-[31m✗[39m [31mcodex plugin marketplace add max-sixty/worktrunk failed (exit 1)[39m+[31m✗[39m [31mcodex plugin marketplace add max-sixty/worktrunk failed (exit code 1)[39m[107m [0m error: marketplace add faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_plugin_add_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_plugin_add_fails.snapindex fc6d4be2a..bd06f9fb5 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_plugin_add_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_install_plugin_add_fails.snap@@ -64,5 +64,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mAdding Codex plugin marketplace...[39m[36m◎[39m [36mInstalling plugin...[39m-[31m✗[39m [31mcodex plugin add worktrunk@worktrunk failed (exit 1)[39m+[31m✗[39m [31mcodex plugin add worktrunk@worktrunk failed (exit code 1)[39m[107m [0m error: plugin add faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_plugin_remove_fails.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_plugin_remove_fails.snapindex 4772a99a2..87e0a5302 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_plugin_remove_fails.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_plugin_remove_fails.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mUninstalling plugin...[39m-[31m✗[39m [31mcodex plugin remove worktrunk@worktrunk failed (exit 1)[39m+[31m✗[39m [31mcodex plugin remove worktrunk@worktrunk failed (exit code 1)[39m[107m [0m error: plugin remove faileddiff --git a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_surfaces_marketplace_remove_failure.snap b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_surfaces_marketplace_remove_failure.snapindex e5134b06d..a634c945c 100644--- a/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_surfaces_marketplace_remove_failure.snap+++ b/tests/snapshots/integration__integration_tests__config_show__plugins_codex_uninstall_surfaces_marketplace_remove_failure.snap@@ -64,5 +64,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mUninstalling plugin...[39m[36m◎[39m [36mRemoving Codex plugin marketplace...[39m-[31m✗[39m [31mcodex plugin marketplace remove worktrunk failed (exit 1)[39m+[31m✗[39m [31mcodex plugin marketplace remove worktrunk failed (exit code 1)[39m[107m [0m error: marketplace remove faileddiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snapindex e40bba2be..d1632070c 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap@@ -64,19 +64,19 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m[0m[31m✗[39m [31mFailed in [1m[1mmain[22m[22m (spawn failed)[39m-[107m [0m [31m✗[39m [31mFailed to execute command (direct): [SPAWN_FAIL][39m+[107m [0m Failed to execute nonexistent-command-12345 @ ~/repo: [SPAWN_FAIL][36m◎[39m [36mRunning in [1mfeature[22m...[39m[0m[31m✗[39m [31mFailed in [1m[1mfeature[22m[22m (spawn failed)[39m-[107m [0m [31m✗[39m [31mFailed to execute command (direct): [SPAWN_FAIL][39m+[107m [0m Failed to execute nonexistent-command-12345 @ ~/repo.feature: [SPAWN_FAIL][36m◎[39m [36mRunning in [1mfeature-a[22m...[39m[0m[31m✗[39m [31mFailed in [1m[1mfeature-a[22m[22m (spawn failed)[39m-[107m [0m [31m✗[39m [31mFailed to execute command (direct): [SPAWN_FAIL][39m+[107m [0m Failed to execute nonexistent-command-12345 @ ~/repo.feature-a: [SPAWN_FAIL][36m◎[39m [36mRunning in [1mfeature-b[22m...[39m[0m[31m✗[39m [31mFailed in [1m[1mfeature-b[22m[22m (spawn failed)[39m-[107m [0m [31m✗[39m [31mFailed to execute command (direct): [SPAWN_FAIL][39m+[107m [0m Failed to execute nonexistent-command-12345 @ ~/repo.feature-b: [SPAWN_FAIL][36m◎[39m [36mRunning in [1mfeature-c[22m...[39m[0m[31m✗[39m [31mFailed in [1m[1mfeature-c[22m[22m (spawn failed)[39m-[107m [0m [31m✗[39m [31mFailed to execute command (direct): [SPAWN_FAIL][39m+[107m [0m Failed to execute nonexistent-command-12345 @ ~/repo.feature-c: [SPAWN_FAIL][33m▲[39m [33m5 of 5 worktrees failed[39m[107m [0m [1mmain[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snapindex 0ea520567..d4d496ce1 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-commit project hook[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-commit command failed: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-commit project hook[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-commit hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_failure.snapindex 1d6475254..adc9b8220 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_failure.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-merge project hook[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-merge command failed: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-merge project hook[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snapindex 0ea520567..d4d496ce1 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-commit project hook[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-commit command failed: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-commit project hook[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-commit hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snapindex 31a99b82f..878e75a6a 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-start project hook @ [1m_REPO_.feature[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-start command failed: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-start project hook[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-start hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snapindex 6d7238ee8..3088c45ff 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap@@ -61,6 +61,6 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mFailed to expand project pre-start hook: undefined value @ line 1[39m+[31m✗[39m [31mFailed to expand pre-start project hook: undefined value @ line 1[39m[107m [0m echo 'Upstream: {{ upstream }}' > upstream.txt[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snapindex 1d53e9af3..98997f547 100644--- a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.feature-fail[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-remove command failed: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-remove project hook[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_background.snap b/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_background.snapindex 670517264..cdc531f58 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_background.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_background.snap@@ -4,14 +4,14 @@ expression: stderr---[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.failed-a[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'failed-a'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m-[0m[31m✗[39m [31mpre-remove command failed: exit status: 7[39m+[0m[31m✗[39m [31m[1mpre-remove project hook[22m failed (exit code 7)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22m[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.valid[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'valid'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m[0m[36m◎[39m [36mRemoving [1mvalid[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.failed-b[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'failed-b'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m-[0m[31m✗[39m [31mpre-remove command failed: exit status: 7[39m+[0m[31m✗[39m [31m[1mpre-remove project hook[22m failed (exit code 7)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22m[2m○[22m No worktree found for branch [1mbranch-only[22m[32m✓ Removed branch [1mbranch-only[22m (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_foreground.snap b/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_foreground.snapindex cea41b4b6..2ffe7d7a3 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_foreground.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_continues_hook_foreground.snap@@ -4,7 +4,7 @@ expression: stderr---[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.failed-a[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'failed-a'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m-[0m[31m✗[39m [31mpre-remove command failed: exit status: 7[39m+[0m[31m✗[39m [31m[1mpre-remove project hook[22m failed (exit code 7)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22m[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.valid[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'valid'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m@@ -12,7 +12,7 @@ expression: stderr[32m✓[39m [32mRemoved [1mvalid[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39m[36m◎[39m [36mRunning pre-remove project hook @ [1m_REPO_.failed-b[22m[39m[107m [0m [2m[0m[2m[35mcase[0m[2m [0m[2m[32m'failed-b'[0m[2m [0m[2m[35min[0m[2m failed-*) [0m[2m[34mexit[0m[2m 7 ;; [0m[2m[35mesac[0m-[0m[31m✗[39m [31mpre-remove command failed: exit status: 7[39m+[0m[31m✗[39m [31m[1mpre-remove project hook[22m failed (exit code 7)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22m[2m○[22m No worktree found for branch [1mbranch-only[22m[32m✓ Removed branch [1mbranch-only[22m (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39mdiff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_bash.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_bash.snapindex c00c45dee..b8f0e2a44 100644--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_bash.snap+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_bash.snap@@ -9,6 +9,6 @@ expression: "&output.combined"[36m◎[39m [36mRunning pre-merge [1mproject:test[22m[39m[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'✗ Test suite failed: 3 tests failing'[0m[2m [0m[2m[36m&&[0m[2m [0m[2m[34mexit[0m[2m 1[0m[0m✗ Test suite failed: 3 tests failing-[31m✗[39m [31mpre-merge command failed: [1mtest[22m: exit status: 1[39m+[31m✗[39m [31m[1mpre-merge project:test[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22m[0mdiff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_zsh.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_zsh.snapindex c00c45dee..b8f0e2a44 100644--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_zsh.snap+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge_with_pre_merge_failure_zsh.snap@@ -9,6 +9,6 @@ expression: "&output.combined"[36m◎[39m [36mRunning pre-merge [1mproject:test[22m[39m[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'✗ Test suite failed: 3 tests failing'[0m[2m [0m[2m[36m&&[0m[2m [0m[2m[34mexit[0m[2m 1[0m[0m✗ Test suite failed: 3 tests failing-[31m✗[39m [31mpre-merge command failed: [1mtest[22m: exit status: 1[39m+[31m✗[39m [31m[1mpre-merge project:test[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22m[0mdiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_concurrent_spawn_failure_has_one_source_detail.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_concurrent_spawn_failure_has_one_source_detail.snapnew file mode 100644index 000000000..b093a544a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_concurrent_spawn_failure_has_one_source_detail.snap@@ -0,0 +1,8 @@+---+source: tests/integration_tests/step_alias.rs+expression: stderr+---+[36m◎[39m [36mRunning alias [1mmove-away[22m: [1mcheck[22m & [1msibling[22m[39m+[0m[31m✗[39m [31mFailed to run alias 'move-away' command 'check'[39m+[107m [0m Failed to execute sh @ _REPO_+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_spawn_failure_has_one_source_detail.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_spawn_failure_has_one_source_detail.snapnew file mode 100644index 000000000..8d5fa59f9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_spawn_failure_has_one_source_detail.snap@@ -0,0 +1,7 @@+---+source: tests/integration_tests/step_alias.rs+expression: stderr+---+[0m[0m[31m✗[39m [31mFailed to run alias 'move-away'[39m+[107m [0m Failed to execute sh @ _REPO_+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_failfast_spawn_failure_has_one_io_detail.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_failfast_spawn_failure_has_one_io_detail.snapnew file mode 100644index 000000000..09ebabe65--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_failfast_spawn_failure_has_one_io_detail.snap@@ -0,0 +1,13 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning pre-merge [1muser:move[22m[39m+[107m [0m [2m[0m[2m[34mmv[0m[2m _REPO_.move-away _REPO_.move-away.moved[0m+[0m[36m◎[39m [36mRunning pre-merge [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[36m◎[39m [36mRunning pre-merge [1muser:sibling[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[31m✗[39m [31m[1mpre-merge user:check[22m failed[39m+[107m [0m Failed to execute sh @ _REPO_.move-away+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_spawn_failure_has_one_io_detail.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_spawn_failure_has_one_io_detail.snapnew file mode 100644index 000000000..82c3749e3--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_concurrent_hook_spawn_failure_has_one_io_detail.snap@@ -0,0 +1,16 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning post-start [1muser:move[22m[39m+[107m [0m [2m[0m[2m[34mmv[0m[2m _REPO_.move-away _REPO_.move-away.moved[0m+[0m[36m◎[39m [36mRunning post-start [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[36m◎[39m [36mRunning post-start [1muser:sibling[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[31m✗[39m [31m[1mpost-start user:check[22m failed[39m+[107m [0m Failed to execute sh @ _REPO_.move-away+[107m [0m No such file or directory (os error 2)+[31m✗[39m [31m[1mpost-start user:sibling[22m failed[39m+[107m [0m Failed to execute sh @ _REPO_.move-away+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_failfast_spawn_failure_has_one_io_detail.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_failfast_spawn_failure_has_one_io_detail.snapnew file mode 100644index 000000000..2ecc5ea4a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_failfast_spawn_failure_has_one_io_detail.snap@@ -0,0 +1,11 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning pre-merge [1muser:move[22m[39m+[107m [0m [2m[0m[2m[34mmv[0m[2m _REPO_.move-away _REPO_.move-away.moved[0m+[0m[36m◎[39m [36mRunning pre-merge [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[0m[31m✗[39m [31m[1mpre-merge user:check[22m failed[39m+[107m [0m Failed to execute sh @ _REPO_.move-away+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_spawn_failure_has_one_io_detail.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_spawn_failure_has_one_io_detail.snapnew file mode 100644index 000000000..dd22a43fb--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_hook_spawn_failure_has_one_io_detail.snap@@ -0,0 +1,11 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning post-start [1muser:move[22m[39m+[107m [0m [2m[0m[2m[34mmv[0m[2m _REPO_.move-away _REPO_.move-away.moved[0m+[0m[36m◎[39m [36mRunning post-start [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[0m[31m✗[39m [31m[1mpost-start user:check[22m failed[39m+[107m [0m Failed to execute sh @ _REPO_.move-away+[107m [0m No such file or directory (os error 2)diff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_project.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_project.snapnew file mode 100644index 000000000..6cd441343--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_project.snap@@ -0,0 +1,7 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning pre-merge [1mproject:check[22m[39m+[107m [0m [2m[0m[2m[34mexit[0m[2m 7[0m+[0m[31m✗[39m [31m[1mpre-merge project:check[22m failed (exit code 7)[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_user.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_user.snapnew file mode 100644index 000000000..c0a631aa7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_failure_status_user.snap@@ -0,0 +1,9 @@+---+source: tests/integration_tests/user_hooks.rs+expression: stderr+---+[36m◎[39m [36mRunning pre-merge [1muser:check[22m[39m+[107m [0m [2m[0m[2m[34mexit[0m[2m 7[0m+[36m◎[39m [36mRunning pre-merge [1muser:sibling[22m[39m+[107m [0m [2m[0m[2m[34mtrue[0m+[31m✗[39m [31m[1mpre-merge user:check[22m failed (exit code 7)[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_commit_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_commit_failure.snapindex c2502137e..1645e5e2d 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_commit_failure.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_commit_failure.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-commit [1muser:lint[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-commit command failed: [1mlint[22m: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-commit user:lint[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-commit hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_failure.snapindex 286ae47d1..a43224b32 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_failure.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_merge_failure.snap@@ -63,5 +63,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-merge [1muser:check[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-merge command failed: [1mcheck[22m: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-merge user:check[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-merge hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_remove_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_remove_failure.snapindex 4c51bfcad..f03a4ba23 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_remove_failure.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_remove_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-remove [1muser:block[22m @ [1m_REPO_.feature[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-remove command failed: [1mblock[22m: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-remove user:block[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-remove hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_start_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_start_failure.snapindex 846575673..e31dfa552 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_start_failure.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_start_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-start [1muser:failing[22m @ [1m_REPO_.feature[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-start command failed: [1mfailing[22m: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-start user:failing[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-start hooks, re-run with [4m--no-hooks[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snapindex 6b1f00089..d15da8332 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__user_pre_switch_failure.snap@@ -62,5 +62,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-switch [1muser:block[22m[39m[107m [0m [2m[0m[2m[34mexit[0m[2m 1[0m-[0m[31m✗[39m [31mpre-switch command failed: [1mblock[22m: exit status: 1[39m+[0m[31m✗[39m [31m[1mpre-switch user:block[22m failed (exit code 1)[39m[2m↳[22m [2mTo skip pre-switch hooks, re-run with [4m--no-hooks[24m[22m