Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Unify hook and alias shell execution (#2089)
Maximilian Roos73b4f8305da8
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex a61bd187e..c6e42f233 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -1,12 +1,26 @@-//! Alias command implementation+//! Alias command implementation.//!-//! Runs user-defined command aliases configured in `[aliases]` sections-//! of user config or project config. Aliases are command templates that-//! support the same template variables as hooks.+//! Aliases are user-defined commands configured in `[aliases]` sections of user+//! or project config. They share execution infrastructure with hooks:+//! `execute_shell_command` (signal forwarding, ANSI reset, `Cmd` tracing),+//! `CommandConfig` (pipeline steps), template expansion, and the approval system.//!-//! Project-config aliases require command approval (same as project hooks).-//! User-config aliases are trusted and skip approval. When an alias exists-//! in both configs, both run — user first, then project (with approval).+//! ## Execution model+//!+//! Aliases iterate `CommandConfig::steps()`, preserving pipeline structure:+//! - `HookStep::Single` — serial execution, fail-fast+//! - `HookStep::Concurrent` — commands spawn via `thread::scope`, all run to+//! completion, first error propagated+//!+//! In pipelines, templates referencing `vars.*` use lazy expansion — deferred+//! until execution time so prior steps can set vars via git config.+//!+//! ## Trust model+//!+//! User-config aliases are trusted (skip approval). Project-config aliases+//! require command approval. When both define the same alias, both run — user+//! first, then project. The directive file is passed through to child processes+//! (same trust profile as foreground hooks).use std::collections::HashMap;use std::path::PathBuf;@@ -14,7 +28,8 @@ use std::path::PathBuf;use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::{- CommandConfig, ProjectConfig, UserConfig, append_aliases, expand_template,+ CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases, expand_template,+ template_references_var,};use worktrunk::git::{Repository, WorktrunkError};use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;@@ -24,7 +39,7 @@ use worktrunk::styling::{use crate::commands::command_approval::approve_alias_commands;use crate::commands::command_executor::{CommandContext, build_hook_context};-use crate::commands::for_each::{CommandError, run_command_streaming};+use crate::output::execute_shell_command;/// Built-in `wt step` subcommand names. Aliases with these names are/// shadowed by the built-in and will never run.@@ -254,11 +269,9 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {let context_json = serde_json::to_string(&context_map).expect("HashMap<String, String> serialization should never fail");- let commands: Vec<_> = cmd_config.commands().collect();-if opts.dry_run {- let expanded: Vec<_> = commands- .iter()+ let expanded: Vec<_> = cmd_config+ .commands().map(|cmd| expand_template(&cmd.template, &vars, true, &repo, &opts.name)).collect::<Result<_, _>>()?;eprintln!(@@ -281,47 +294,35 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {progress_message(cformat!("Running alias <bold>{}</>", opts.name)));- // Pass the parent shell's directive file through to the alias subprocess- // so inner `wt` invocations (e.g. `wt switch --create` inside an alias- // body) can write shell integration directives like `cd '/path'` that the- // parent shell wrapper will source after `wt` exits. Without this the- // inner `wt` would see a scrubbed env var, print the "shell integration- // not installed" hint, and drop the `cd`.- //- // This is a deliberate relaxation of the usual env scrub: aliases are- // explicit, named, user-authorised commands (user-config aliases are- // trusted; project-config aliases require approval), and an alias body is- // already arbitrary shell that can `cd`/`rm`/`exec` anything locally, so- // letting it ask the parent shell to `cd` is strictly less powerful than- // what the body can already do.- //- // TODO: unify hook and alias execution so both pass the directive file- // through. Hooks currently scrub it (see `process.rs` and the `None`- // branch in `for_each::run_command_streaming`), so an inner `wt switch`- // inside a hook body still drops its `cd`. Foreground `pre-*` hooks have- // the same trust profile as aliases and could pass through too;- // background `post-*` hooks outlive the parent shell, so any unification- // needs to keep scrubbing in the detached spawn paths.+ // Pass the parent shell's directive file through so inner `wt` invocations+ // (e.g. `wt switch --create`) can write shell directives that the parent+ // shell wrapper will source after `wt` exits. The Cmd builder scrubs the+ // env var by default; `.directive_file()` re-adds it for trusted contexts.let parent_directive_file: Option<PathBuf> =std::env::var_os(DIRECTIVE_FILE_ENV_VAR).map(PathBuf::from);- for cmd in commands {- let command = expand_template(&cmd.template, &vars, true, &repo, &opts.name)?;- match run_command_streaming(- &command,- &wt_path,- Some(&context_json),- parent_directive_file.as_deref(),- ) {- Ok(()) => {}- Err(CommandError::SpawnFailed(err)) => {- bail!("Failed to run alias '{}': {}", opts.name, err);- }- Err(CommandError::ExitCode(exit_code)) => {- return Err(WorktrunkError::AlreadyDisplayed {- exit_code: exit_code.unwrap_or(1),- }- .into());+ let exec = AliasExecCtx {+ vars: &vars,+ repo: &repo,+ alias_name: &opts.name,+ wt_path: &wt_path,+ context_json: &context_json,+ directive_file: parent_directive_file.as_deref(),+ is_pipeline: cmd_config.is_pipeline(),+ };++ for step in cmd_config.steps() {+ match step {+ HookStep::Single(cmd) => exec.run(cmd)?,+ HookStep::Concurrent(cmds) => {+ std::thread::scope(|s| {+ let handles: Vec<_> =+ cmds.iter().map(|cmd| s.spawn(|| exec.run(cmd))).collect();+ for handle in handles {+ handle.join().expect("alias command thread panicked")?;+ }+ Ok::<(), anyhow::Error>(())+ })?;}}}@@ -329,6 +330,52 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {Ok(())}+/// Shared state for executing alias commands within a pipeline.+struct AliasExecCtx<'a> {+ vars: &'a HashMap<&'a str, &'a str>,+ repo: &'a Repository,+ alias_name: &'a str,+ wt_path: &'a std::path::Path,+ context_json: &'a str,+ directive_file: Option<&'a std::path::Path>,+ is_pipeline: bool,+}++impl AliasExecCtx<'_> {+ /// Expand and execute a single alias command.+ ///+ /// In pipelines, templates referencing `vars.*` are deferred to execution+ /// time so that vars set by earlier steps are available.+ fn run(&self, cmd: &worktrunk::config::Command) -> anyhow::Result<()> {+ let command = if self.is_pipeline && template_references_var(&cmd.template, "vars") {+ let fresh_context: HashMap<String, String> = serde_json::from_str(self.context_json)+ .context("failed to deserialize context_json")?;+ let fresh_vars: HashMap<&str, &str> = fresh_context+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();+ expand_template(&cmd.template, &fresh_vars, true, self.repo, self.alias_name)?+ } else {+ expand_template(&cmd.template, self.vars, true, self.repo, self.alias_name)?+ };+ if let Err(err) = execute_shell_command(+ self.wt_path,+ &command,+ Some(self.context_json),+ None,+ self.directive_file,+ ) {+ if let Some(WorktrunkError::ChildProcessExited { code, .. }) =+ err.downcast_ref::<WorktrunkError>()+ {+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: *code }.into());+ }+ bail!("Failed to run alias '{}': {}", self.alias_name, err);+ }+ Ok(())+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex e6dfa3ab6..6e76d7be9 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -22,21 +22,17 @@//! For now, we keep `for-each` under `step` as a pragmatic choice.use std::collections::HashMap;-use std::io::Write;-use std::path::Path;-use std::process::Stdio;use color_print::cformat;use worktrunk::config::{UserConfig, expand_template};-use worktrunk::git::Repository;-use worktrunk::git::WorktrunkError;-use worktrunk::shell_exec::ShellConfig;+use worktrunk::git::{Repository, WorktrunkError};use worktrunk::styling::{eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,};use crate::commands::command_executor::{CommandContext, build_hook_context};use crate::commands::worktree_display_name;+use crate::output::execute_shell_command;/// Run a command in each worktree sequentially.///@@ -87,12 +83,11 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anylet context_json = serde_json::to_string(&context_map).expect("HashMap<String, String> serialization should never fail");- // Execute command: stream both stdout and stderr in real-time+ // Execute command: stream both stdout and stderr in real-time.// Pipe context JSON to stdin for scripts that want structured data.- // `for-each` scrubs the directive file env var (see `run_command_streaming`- // docs) so commands run in each worktree cannot influence the parent- // shell's working directory.- match run_command_streaming(&command, &wt.path, Some(&context_json), None) {+ // Directive file is scrubbed — commands run in other worktrees should+ // not influence the parent shell's working directory.+ match execute_shell_command(&wt.path, &command, Some(&context_json), None, None) {Ok(()) => {if json_mode {json_results.push(serde_json::json!({@@ -104,34 +99,40 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any}}Err(err) => {- match &err {- CommandError::SpawnFailed(e) => {- eprintln!(- "{}",- error_message(cformat!(- "Failed in <bold>{display_name}</> (spawn failed)"- ))- );- eprintln!("{}", format_with_gutter(e, None));- }- CommandError::ExitCode(code) => {- let exit_info = code- .map(|c| format!(" (exit code {c})"))- .unwrap_or_default();- eprintln!(- "{}",- error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))- );- }+ let (exit_info, exit_code, error_msg, show_detail) =+ if let Some(WorktrunkError::ChildProcessExited { code, message }) =+ err.downcast_ref::<WorktrunkError>()+ {+ (+ format!(" (exit code {code})"),+ serde_json::json!(code),+ message.clone(),+ false,+ )+ } else {+ let msg = err.to_string();+ (+ " (spawn failed)".to_string(),+ serde_json::json!(null),+ msg,+ true,+ )+ };+ eprintln!(+ "{}",+ error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))+ );+ if show_detail {+ eprintln!("{}", format_with_gutter(&error_msg, None));}failed.push(display_name.to_string());if json_mode {json_results.push(serde_json::json!({"branch": wt.branch,"path": wt.path,- "exit_code": err.exit_code(),+ "exit_code": exit_code,"success": false,- "error": err.to_string(),+ "error": error_msg,}));}}@@ -173,138 +174,3 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anyErr(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())}}--/// Error from running a command in a worktree-pub(crate) enum CommandError {- /// Command failed to spawn (e.g., command not found, permission denied)- SpawnFailed(String),- /// Command exited with non-zero status- ExitCode(Option<i32>),-}--impl CommandError {- fn exit_code(&self) -> Option<i32> {- match self {- CommandError::SpawnFailed(_) => None,- CommandError::ExitCode(code) => *code,- }- }-}--impl std::fmt::Display for CommandError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- CommandError::SpawnFailed(e) => write!(f, "spawn failed: {e}"),- CommandError::ExitCode(Some(c)) => write!(f, "exit code {c}"),- CommandError::ExitCode(None) => write!(f, "killed by signal"),- }- }-}--/// Run a shell command, streaming both stdout and stderr in real-time.-///-/// Returns `Ok(())` on success, or `Err(CommandError)` on failure.-/// Both stdout and stderr stream to the terminal (stderr) in real-time.-/// If `stdin_content` is provided, it's piped to the command's stdin.-///-/// `directive_file` controls whether the child process can write shell-/// integration directives back to the parent shell:-///-/// - `None` — the `WORKTRUNK_DIRECTIVE_FILE` env var is removed from the-/// child's environment. Inner `wt` invocations will print the "shell-/// integration not installed" hint and drop any `cd` directives. This is-/// the default for sandboxed contexts like `wt step for-each`.-/// - `Some(path)` — the env var is set to `path`, so inner `wt` invocations-/// (and any child they spawn) can write directives that the parent shell-/// wrapper will source after `wt` exits. `wt step alias` uses this to let-/// aliases wrapping `wt switch --create` land the user in the new worktree.-///-/// # TODO: Streaming vs Gutter Tradeoff-///-/// Currently stderr streams directly without gutter formatting, same as hooks.-/// This means error output appears inline rather than in a visual gutter block.-/// Options to consider:-/// - Tee stderr (stream + capture) for gutter display on failure-/// - Add `--gutter` flag to capture and format output-/// - Accept current behavior as consistent with hooks-pub(crate) fn run_command_streaming(- command: &str,- working_dir: &Path,- stdin_content: Option<&str>,- directive_file: Option<&Path>,-) -> Result<(), CommandError> {- let shell = ShellConfig::get().map_err(|e| CommandError::SpawnFailed(e.to_string()))?;-- log::debug!("$ {} (streaming)", command);-- let stdin_mode = if stdin_content.is_some() {- Stdio::piped()- } else {- Stdio::inherit() // Allow interactive commands when no stdin content- };-- let mut cmd = shell.command(command);- cmd.current_dir(working_dir)- .stdin(stdin_mode)- // Redirect stdout to stderr to keep stdout reserved for data output- // Note: Stdio::from(Stderr) works since Rust 1.74 (impl From<Stderr> for Stdio)- .stdout(Stdio::from(std::io::stderr()))- // Stream stderr to terminal in real-time- .stderr(Stdio::inherit());-- match directive_file {- // Propagate the parent's directive file so inner `wt` calls can write- // shell integration directives (e.g. `wt switch --create` inside a- // user alias body).- Some(path) => {- cmd.env(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR, path);- }- // Default: prevent subprocesses from writing to the directive file.- None => {- cmd.env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR);- }- }-- let mut child = cmd- .spawn()- .map_err(|e| CommandError::SpawnFailed(e.to_string()))?;-- // Write stdin content if provided (JSON context for scripts)- if let Some(content) = stdin_content- && let Some(mut stdin) = child.stdin.take()- {- // Ignore write errors - command may not read stdin- let _ = stdin.write_all(content.as_bytes());- // stdin is dropped here, closing the pipe- }-- let status = child- .wait()- .map_err(|e| CommandError::SpawnFailed(e.to_string()))?;-- if status.success() {- Ok(())- } else {- Err(CommandError::ExitCode(status.code()))- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_command_error_display_and_exit_code() {- let spawn = CommandError::SpawnFailed("no such file".into());- assert_eq!(spawn.to_string(), "spawn failed: no such file");- assert_eq!(spawn.exit_code(), None);-- let exit = CommandError::ExitCode(Some(42));- assert_eq!(exit.to_string(), "exit code 42");- assert_eq!(exit.exit_code(), Some(42));-- let signal = CommandError::ExitCode(None);- assert_eq!(signal.to_string(), "killed by signal");- assert_eq!(signal.exit_code(), None);- }-}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 8ce047c2f..e6ca945db 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -14,7 +14,8 @@ use super::command_executor::{CommandContext, PreparedCommand, PreparedStep, prepare_commands, prepare_steps,};use crate::commands::process::{HookLog, spawn_detached_exec};-use crate::output::execute_command_in_worktree;+use crate::output::execute_shell_command;+use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;/// A prepared command with its source information.pub struct SourcedCommand {@@ -506,7 +507,13 @@ pub fn run_hook_with_filter(return Ok(());}- // Track first failure's exit code for Warn strategy (to propagate after all commands run)+ // Foreground hooks have the same trust profile as aliases — the hook body+ // is already arbitrary shell. Pass the directive file through so inner `wt`+ // invocations (e.g. `wt switch --create` in a pre-start hook) can write+ // shell directives back to the parent shell.+ let directive_file: Option<PathBuf> =+ std::env::var_os(DIRECTIVE_FILE_ENV_VAR).map(PathBuf::from);+for cmd in commands {cmd.announce()?;@@ -520,11 +527,12 @@ pub fn run_hook_with_filter(};let log_label = format!("{} {}", cmd.hook_type, cmd.summary_name());- if let Err(err) = execute_command_in_worktree(+ if let Err(err) = execute_shell_command(ctx.worktree_path,&expanded,Some(&cmd.prepared.context_json),Some(&log_label),+ directive_file.as_deref(),) {// Extract raw message and exit code from errorlet (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 846e4c89f..62d770bb4 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -1362,35 +1362,43 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh}}-/// Execute a command in a worktree directory+/// Run a shell command with streaming output, signal forwarding, and ANSI reset.///-/// Redirects child stdout to stderr (via `.stdout(Stdio::from(std::io::stderr()))`) for-/// deterministic output ordering. Per CLAUDE.md guidelines: child process output goes to-/// stderr, worktrunk output goes to stdout.+/// Unified entry point for all foreground command execution — hooks, aliases,+/// and `for-each` all call this. The background pipeline runner+/// (`run_pipeline.rs`) has its own spawning logic since it redirects to log+/// files and runs detached.///-/// If `stdin_content` is provided, it will be piped to the command's stdin. This is used to pass-/// hook context as JSON to hook commands.+/// Capabilities: stdout→stderr redirect for deterministic ordering,+/// SIGINT/SIGTERM forwarding to child process group, ANSI reset before child+/// runs, `Cmd` tracing/logging, and directive file control.///-/// ## Color Bleeding Prevention+/// ## Directive file///-/// This function explicitly resets ANSI codes on stderr before executing child commands.+/// `directive_file` controls whether the child can write shell integration+/// directives (e.g. `cd`) back to the parent shell:///-/// Root cause: Terminal emulators maintain a single rendering state machine. When stdout-/// and stderr both connect to the same TTY, output from both streams passes through this-/// state machine in arrival order. If stdout writes color codes but stderr's output arrives-/// next, the terminal applies stdout's color state to stderr's text. The flush ensures stdout-/// completes, but doesn't reset the terminal state - hence this explicit reset to stderr.+/// - `None` — scrubs `WORKTRUNK_DIRECTIVE_FILE` from the child (default;+/// used by `for-each` which runs in other worktrees, and hooks prior to+/// Phase 3).+/// - `Some(path)` — passes the env var through. Used by aliases and+/// foreground hooks, which have the same trust profile: the command body+/// is already arbitrary shell, so letting it write a `cd` directive is+/// strictly less powerful than what it can already do. Background hooks+/// must never pass through (they outlive the parent shell).///-/// We write the reset to stderr (not stdout) because:-/// 1. Child process output goes to stderr (per CLAUDE.md guidelines)-/// 2. The reset must reach the terminal before child output-/// 3. Writing to stdout could arrive after stderr due to buffering+/// ## ANSI reset///-pub fn execute_command_in_worktree(- worktree_path: &std::path::Path,+/// Resets ANSI codes on stderr before the child runs. Terminal emulators+/// maintain a single rendering state machine — if stdout writes color codes+/// but stderr's output arrives next, the terminal applies stdout's color+/// state to stderr's text. The reset to stderr prevents this.+pub fn execute_shell_command(+ working_dir: &std::path::Path,command: &str,stdin_content: Option<&str>,command_log_label: Option<&str>,+ directive_file: Option<&std::path::Path>,) -> anyhow::Result<()> {// Flush stdout before executing command to ensure all our messages appear// before the child process output@@ -1404,7 +1412,7 @@ pub fn execute_command_in_worktree(// Execute with stdout→stderr redirect for deterministic orderinglet mut cmd = Cmd::shell(command)- .current_dir(worktree_path)+ .current_dir(working_dir).stdout(Stdio::from(std::io::stderr())).forward_signals();@@ -1416,6 +1424,10 @@ pub fn execute_command_in_worktree(cmd = cmd.stdin_bytes(content);}+ if let Some(path) = directive_file {+ cmd = cmd.directive_file(path);+ }+cmd.stream()?;// Flush to ensure all output appears before we continuediff --git a/src/output/mod.rs b/src/output/mod.rsindex f3b3618b2..41dd83e97 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -43,7 +43,7 @@ pub(crate) use global::{};// Re-export output handlerspub(crate) use handlers::{- execute_command_in_worktree, execute_user_command, handle_remove_output, handle_switch_output,+ execute_shell_command, execute_user_command, handle_remove_output, handle_switch_output,};// Re-export shell integration functionspub(crate) use shell_integration::{diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex ce4a16376..c3ef0d9b2 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -463,6 +463,10 @@ pub struct Cmd {/// When set, log this command to the command log after execution./// The label identifies what triggered the command (e.g., "pre-merge user:lint").external_label: Option<String>,+ /// When set, re-adds the directive file env var after the security scrub in+ /// `apply_common_settings`. This is a privileged opt-in for contexts where+ /// pass-through is safe (aliases, foreground hooks).+ directive_file: Option<std::path::PathBuf>,}struct ExternalCommandLog {@@ -505,6 +509,7 @@ impl Cmd {stdin_cfg: None,forward_signals: false,external_label: None,+ directive_file: None,}}@@ -685,6 +690,16 @@ impl Cmd {self}+ /// Pass the directive file through to the child process.+ ///+ /// By default, `Cmd` scrubs `WORKTRUNK_DIRECTIVE_FILE` from all child+ /// processes (security). This re-adds it for trusted contexts where the+ /// child should be able to write shell directives (aliases, foreground hooks).+ pub fn directive_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {+ self.directive_file = Some(path.into());+ self+ }+/// Execute the command and return its output.////// Captures stdout/stderr and returns them in `Output`. For interactive@@ -700,6 +715,10 @@ impl Cmd {!self.shell_wrap,"Cmd::shell() commands must use .stream(), not .run()");+ debug_assert!(+ self.directive_file.is_none(),+ "directive_file is only applied by .stream(), not .run()"+ );let cmd_str = self.command_string();let external_log = ExternalCommandLog::new(self.external_label.clone(), cmd_str.clone());@@ -843,6 +862,11 @@ impl Cmd {self.log_stream_start(&cmd_str, &exec_mode);self.apply_common_settings(&mut cmd);+ // Re-add directive file after security scrub if explicitly opted in.+ if let Some(ref path) = self.directive_file {+ cmd.env(DIRECTIVE_FILE_ENV_VAR, path);+ }+#[cfg(not(unix))]let _ = self.forward_signals;diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex ec5c94937..cf3970147 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -92,6 +92,70 @@ fn test_for_each_spawn_fails(mut repo: TestRepo) {));}+/// Force the shell spawn itself to fail (rather than the command inside the+/// shell exiting non-zero) by setting `PATH` to a directory that contains+/// only `git` (so wt can still operate) but no `sh` (so the child shell+/// spawn fails). This is the only branch in the failure handler that does+/// NOT downcast to `WorktrunkError::ChildProcessExited`, and it appears in+/// JSON mode as `exit_code: null`. Without this test the spawn-failed JSON+/// path is unreachable from the integration suite (#2089 review).+#[rstest]+#[cfg(unix)]+fn test_for_each_json_spawn_failure(repo: TestRepo) {+ use std::path::PathBuf;++ // Locate a real `git` so we can symlink it into the minimal PATH dir.+ // wt itself shells out to git constantly; clearing PATH entirely makes+ // wt fail before it ever reaches the shell-spawn branch we want to test.+ let git_path: PathBuf = std::env::var_os("PATH")+ .iter()+ .flat_map(std::env::split_paths)+ .map(|p| p.join("git"))+ .find(|p| p.is_file())+ .expect("git must be in PATH for tests");++ let tmp = tempfile::tempdir().expect("create tmpdir for minimal PATH");+ std::os::unix::fs::symlink(&git_path, tmp.path().join("git"))+ .expect("symlink git into minimal PATH");+ // Deliberately do NOT symlink `sh` — that's what makes the shell spawn fail.++ let mut cmd = repo.wt_command();+ cmd.env("PATH", tmp.path());+ cmd.args(["step", "for-each", "--format=json", "--", "true"]);+ let output = cmd.output().unwrap();++ assert!(+ !output.status.success(),+ "for-each should fail when shell spawn fails: stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8_lossy(&output.stdout);+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {+ panic!(+ "for-each --format=json should emit valid JSON on spawn failure: {e}\nstdout: {stdout}"+ )+ });+ let items = json.as_array().expect("JSON output should be an array");+ assert!(!items.is_empty(), "expected at least one worktree result");+ for item in items {+ assert_eq!(item["success"], false);+ // Spawn failure ⇒ no exit code (vs. exit-code path which uses an integer)+ assert!(+ item["exit_code"].is_null(),+ "spawn failure should report exit_code: null, got {item}"+ );+ let error = item["error"]+ .as_str()+ .expect("error field should be a string");+ assert!(+ !error.is_empty(),+ "spawn failure error message should be non-empty"+ );+ }+}+#[rstest]fn test_for_each_skips_prunable_worktrees(mut repo: TestRepo) {let worktree_path = repo.add_worktree("feature");@@ -167,7 +231,7 @@ fn test_for_each_json_with_failure(repo: TestRepo) {for item in items {assert_eq!(item["success"], false);assert_eq!(item["exit_code"], 1);- // error field is always present on failure (both ExitCode and SpawnFailed)- assert_eq!(item["error"], "exit code 1");+ // error field contains the raw message from the child process+ assert_eq!(item["error"], "exit status: 1");}}diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 6717c724b..91b4c26d5 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -575,6 +575,96 @@ new-branch = "'{wt_toml}' switch --create alias-created");}+/// Concurrent alias steps (named table) execute all commands+#[rstest]+fn test_alias_concurrent_steps(mut repo: TestRepo) {+ // Named table form: commands run concurrently within the step+ repo.write_test_config(+ r#"+[aliases.build]+lint = "echo LINT"+test = "echo TEST"+"#,+ );+ repo.commit("initial");+ let feature_path = repo.add_worktree("feature");++ let mut cmd = repo.wt_command();+ cmd.args(["step", "build"]).current_dir(&feature_path);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "concurrent alias failed: stderr={}",+ String::from_utf8_lossy(&output.stderr),+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ // Both commands should have run (order may vary due to concurrency)+ assert!(stderr.contains("LINT"), "expected LINT in output: {stderr}");+ assert!(stderr.contains("TEST"), "expected TEST in output: {stderr}");+}++/// A failing concurrent step causes the alias to fail. Covers the error+/// propagation path in the `HookStep::Concurrent` join loop, complementing+/// the happy-path `test_alias_concurrent_steps` above.+#[rstest]+fn test_alias_concurrent_step_failure(repo: TestRepo) {+ repo.write_test_config(+ r#"+[aliases.check]+ok = "true"+fail = "exit 1"+"#,+ );+ repo.commit("initial");++ let mut cmd = repo.wt_command();+ cmd.args(["step", "check"]);+ let output = cmd.output().expect("wt step check failed to spawn");+ assert!(+ !output.status.success(),+ "wt step check should fail when a concurrent step exits non-zero"+ );+}++/// Pipeline-form aliases (list of steps) run sequentially. A later step+/// referencing `{{ vars.X }}` must see vars set by an earlier step. Exercises+/// the lazy re-expansion path in `AliasExecCtx::run` (which only triggers+/// when `is_pipeline && template references vars.`).+#[rstest]+fn test_alias_pipeline_lazy_vars(repo: TestRepo) {+ repo.write_test_config(+ r#"+[aliases]+deploy = [+ "git config worktrunk.state.main.vars.target 'staging'",+ { publish = "echo target={{ vars.target }} > alias_lazy.txt" },+]+"#,+ );+ repo.commit("initial");++ let mut cmd = repo.wt_command();+ cmd.args(["step", "deploy"]);+ let output = cmd.output().expect("wt step deploy failed to spawn");+ assert!(+ output.status.success(),+ "wt step deploy failed: stdout={}\nstderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let marker = repo.root_path().join("alias_lazy.txt");+ let content = std::fs::read_to_string(&marker)+ .unwrap_or_else(|e| panic!("missing marker {marker:?}: {e}"));+ assert_eq!(+ content.trim(),+ "target=staging",+ "lazy step should see var set by prior serial step"+ );+}+/// Declining approval prevents alias execution#[rstest]fn test_alias_approval_decline(mut repo: TestRepo) {diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex f69e7360a..28d3b2d8e 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -2790,3 +2790,60 @@ cleanup = "echo done"Some(repo.root_path()),);}++/// Foreground hooks pass the directive file through to child processes,+/// so inner `wt switch --create` can write shell directives back to the+/// parent shell.+#[rstest]+fn test_foreground_hook_passes_directive_file(repo: TestRepo) {+ use crate::common::{configure_directive_file, directive_file, wt_bin};++ repo.commit("initial");++ let wt = wt_bin();+ let wt_str = wt.to_string_lossy();+ assert!(+ !wt_str.contains('\''),+ "wt binary path should not contain single quotes: {wt_str}"+ );+ let wt_toml = wt_str.replace('\\', "\\\\");++ // Pre-start hook that creates a new worktree via `wt switch --create`.+ // If the directive file is passed through, the inner wt will write a+ // `cd` directive. If scrubbed, it prints the "shell integration not+ // installed" hint instead.+ repo.write_test_config(&format!(+ r#"+[pre-start]+setup = "'{wt_toml}' switch --create hook-created --no-hooks"+"#,+ ));++ let (directive_path, _guard) = directive_file();++ let mut cmd = repo.wt_command();+ configure_directive_file(&mut cmd, &directive_path);+ // Run the pre-start hook manually in foreground+ cmd.args(["hook", "pre-start", "setup"]);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "hook failed: stdout={}\nstderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();+ assert!(+ directives.contains("cd '"),+ "foreground hook running `wt switch --create` should write a cd directive \+ to the parent directive file, got: {directives:?}"+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !stderr.contains("shell integration"),+ "inner wt should not warn about shell integration being uninstalled, got: {stderr}",+ );+}diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails_in_one.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails_in_one.snapindex a15f56c0a..c91105400 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails_in_one.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_command_fails_in_one.snap@@ -49,27 +49,27 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.+[0mfatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'[31m✗[39m [31mFailed in [1m[1mmain[22m[22m (exit code 128)[39m[36m◎[39m [36mRunning in [1mfeature[22m...[39m-fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.+[0mfatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'[31m✗[39m [31mFailed in [1m[1mfeature[22m[22m (exit code 128)[39m[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.+[0mfatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'[31m✗[39m [31mFailed in [1m[1mfeature-a[22m[22m (exit code 128)[39m[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.+[0mfatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'[31m✗[39m [31mFailed in [1m[1mfeature-b[22m[22m (exit code 128)[39m[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-fatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.+[0mfatal: ambiguous argument 'nonexistent-ref': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'[31m✗[39m [31mFailed in [1m[1mfeature-c[22m[22m (exit code 128)[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snapindex 159352dea..1b24b49de 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap@@ -48,14 +48,14 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-Branch: main+[0mBranch: main[36m◎[39m [36mRunning in [1mrepo.detached-test[22m (detached)...[39m-Branch: HEAD+[0mBranch: HEAD[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-Branch: feature-a+[0mBranch: feature-a[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-Branch: feature-b+[0mBranch: feature-b[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-Branch: feature-c+[0mBranch: feature-c[32m✓[39m [32mCompleted in 5 worktrees[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_multiple_worktrees.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_multiple_worktrees.snapindex ee999f0c8..0a538ae29 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_multiple_worktrees.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_multiple_worktrees.snap@@ -49,12 +49,12 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-main+[0mmain[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-feature-a+[0mfeature-a[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-feature-b+[0mfeature-b[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-feature-c+[0mfeature-c[32m✓[39m [32mCompleted in 4 worktrees[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_single_worktree.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_single_worktree.snapindex b9c8d28fb..842337a10 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_single_worktree.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_single_worktree.snap@@ -49,12 +49,12 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[32m✓[39m [32mCompleted in 4 worktrees[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snapindex 6d2c92b0e..699d50af5 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snap@@ -48,12 +48,12 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-Running in main+[0mRunning in main[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-Running in feature-a+[0mRunning in feature-a[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-Running in feature-b+[0mRunning in feature-b[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-Running in feature-c+[0mRunning in feature-c[32m✓[39m [32mCompleted in 4 worktrees[39mdiff --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 f4b2ad79a..9d9338f34 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@@ -48,19 +48,19 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-sh: nonexistent-command-12345: command not found+[0msh: nonexistent-command-12345: command not found[31m✗[39m [31mFailed in [1m[1mmain[22m[22m (exit code 127)[39m[36m◎[39m [36mRunning in [1mfeature[22m...[39m-sh: nonexistent-command-12345: command not found+[0msh: nonexistent-command-12345: command not found[31m✗[39m [31mFailed in [1m[1mfeature[22m[22m (exit code 127)[39m[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-sh: nonexistent-command-12345: command not found+[0msh: nonexistent-command-12345: command not found[31m✗[39m [31mFailed in [1m[1mfeature-a[22m[22m (exit code 127)[39m[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-sh: nonexistent-command-12345: command not found+[0msh: nonexistent-command-12345: command not found[31m✗[39m [31mFailed in [1m[1mfeature-b[22m[22m (exit code 127)[39m[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-sh: nonexistent-command-12345: command not found+[0msh: nonexistent-command-12345: command not found[31m✗[39m [31mFailed in [1m[1mfeature-c[22m[22m (exit code 127)[39m[33m▲[39m [33m5 of 5 worktrees failed[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached_head.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached_head.snapindex 03a8762af..7d52c6fcf 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached_head.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_with_detached_head.snap@@ -49,13 +49,13 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mrepo.detached-test[22m (detached)...[39m-[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-warning: untracked cache is disabled on this system or location+[0m[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-warning: untracked cache is disabled on this system or location+[0mwarning: untracked cache is disabled on this system or location[32m✓[39m [32mCompleted in 5 worktrees[39mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_with_template.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_with_template.snapindex 189969388..5a3663efd 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_with_template.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_with_template.snap@@ -48,12 +48,12 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-Branch: main+[0mBranch: main[36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-Branch: feature-a+[0mBranch: feature-a[36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-Branch: feature-b+[0mBranch: feature-b[36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-Branch: feature-c+[0mBranch: feature-c[32m✓[39m [32mCompleted in 4 worktrees[39mdiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snapindex 85566ffcd..043801c92 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap@@ -46,5 +46,5 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mgreet[22m[39m-USER-PROJECT+[0mUSER+[0mPROJECTdiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_already_approved.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_already_approved.snapindex 3ae0ba904..b284373b1 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_already_approved.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_already_approved.snap@@ -45,4 +45,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mdeploy[22m[39m-deploying feature+[0mdeploying featurediff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_and_project_both_need_approval.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_and_project_both_need_approval.snapindex e72b83261..ff606d25a 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_and_project_both_need_approval.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_and_project_both_need_approval.snap@@ -46,5 +46,5 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mdeploy[22m[39m-user deploy-project deploy+[0muser deploy+[0mproject deploydiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_config_skips.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_config_skips.snapindex e2544230f..fcb703123 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_config_skips.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_user_config_skips.snap@@ -45,4 +45,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mdeploy[22m[39m-deploying from user config+[0mdeploying from user configdiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_yes_first_run.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_yes_first_run.snapindex 658912724..b4fb27c8c 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_approval_yes_first_run.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_approval_yes_first_run.snap@@ -46,4 +46,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mdeploy[22m[39m-deploying+[0mdeployingdiff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_project_config.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_project_config.snapindex 5b8377b3d..7f9a74752 100644--- a/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_project_config.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_project_config.snap@@ -46,4 +46,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mhello[22m[39m-Hello from feature+[0mHello from featurediff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_user_config.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_user_config.snapindex 7d478a358..184669662 100644--- a/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_user_config.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_from_user_config.snap@@ -45,4 +45,4 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning alias [1mgreet[22m[39m-Greetings from feature+[0mGreetings from feature