Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: pass directive file through `wt step` aliases (#2077)
Worktrunk Botd8897382586e
diff --git a/docs/content/step.md b/docs/content/step.mdindex 1e98fd7e3..9170eaaec 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -826,6 +826,8 @@ port = "echo http://localhost:{{ branch | hash_port }}"When defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](@/hook.md#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.+Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.+Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run.<!-- END AUTO-GENERATED from `wt step --help-page` -->diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex b5a625538..35c79c827 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -876,4 +876,6 @@ $ wt step deploy --yes # skip approval promptWhen defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](https://worktrunk.dev/hook/#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.+Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.+Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run.diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 52a194d86..70ad9037c 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1166,6 +1166,8 @@ $ wt step deploy --yes # skip approval promptWhen defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](@/hook.md#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.+Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.+Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run."#)]Step {diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex c7d486663..a61bd187e 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -9,6 +9,7 @@//! in both configs, both run — user first, then project (with approval).use std::collections::HashMap;+use std::path::PathBuf;use anyhow::{Context, bail};use color_print::cformat;@@ -16,6 +17,7 @@ use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig, append_aliases, expand_template,};use worktrunk::git::{Repository, WorktrunkError};+use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;use worktrunk::styling::{eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,};@@ -279,9 +281,38 @@ 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.+ 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)) {+ 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);diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 6cc604aa9..e6dfa3ab6 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -23,6 +23,7 @@use std::collections::HashMap;use std::io::Write;+use std::path::Path;use std::process::Stdio;use color_print::cformat;@@ -87,8 +88,11 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any.expect("HashMap<String, String> serialization should never fail");// Execute command: stream both stdout and stderr in real-time- // Pipe context JSON to stdin for scripts that want structured data- match run_command_streaming(&command, &wt.path, Some(&context_json)) {+ // 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) {Ok(()) => {if json_mode {json_results.push(serde_json::json!({@@ -203,6 +207,18 @@ impl std::fmt::Display for CommandError {/// 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.@@ -213,8 +229,9 @@ impl std::fmt::Display for CommandError {/// - Accept current behavior as consistent with hookspub(crate) fn run_command_streaming(command: &str,- working_dir: &std::path::Path,+ 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()))?;@@ -226,17 +243,29 @@ pub(crate) fn run_command_streaming(Stdio::inherit() // Allow interactive commands when no stdin content};- let mut child = shell- .command(command)- .current_dir(working_dir)+ 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())- // Prevent subprocesses from writing to the directive file- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)+ .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()))?;diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 9e6e8613a..6717c724b 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -1,6 +1,9 @@//! Integration tests for `wt step <alias>`-use crate::common::{TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings};+use crate::common::{+ TestRepo, configure_directive_file, directive_file, make_snapshot_cmd, repo,+ setup_snapshot_settings, wt_bin,+};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;use std::io::Write;@@ -500,6 +503,78 @@ deploy = "echo deploying");}+// ============================================================================+// Directive file passthrough+// ============================================================================++/// `wt step <alias>` passes the parent's `WORKTRUNK_DIRECTIVE_FILE` through to+/// the alias subprocess so inner `wt switch --create` calls can land the user+/// in the new worktree.+///+/// Regression test for #2075: without the passthrough, an alias that wraps+/// `wt switch --create` prints the "shell integration not installed" hint and+/// the parent shell never `cd`s into the new worktree.+#[rstest]+fn test_alias_passes_directive_file_to_subprocess(repo: TestRepo) {+ repo.commit("initial");++ // Escape the wt binary path for embedding in a sh -c command string.+ // Test temp paths never contain single quotes.+ 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}"+ );+ // Double backslashes so the Windows path (e.g. `D:\a\worktrunk\...\wt.exe`)+ // parses as literal characters inside a TOML basic string rather than+ // being interpreted as escape sequences (`\a`, `\w`, ...).+ let wt_toml = wt_str.replace('\\', "\\\\");++ // Alias body invokes the test wt binary directly (PATH lookup in the+ // subprocess shell wouldn't find it).+ repo.write_test_config(&format!(+ r#"+[aliases]+new-branch = "'{wt_toml}' switch --create alias-created"+"#+ ));++ let (directive_path, _guard) = directive_file();++ let mut cmd = repo.wt_command();+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["step", "new-branch"]);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "wt step new-branch 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 '"),+ "alias wrapping `wt switch --create` should write a cd directive to the \+ parent directive file, got: {directives:?}"+ );+ assert!(+ directives.contains("alias-created"),+ "cd directive should target the new worktree (alias-created), got: {directives:?}"+ );++ // Stderr should NOT contain the "shell integration not installed" hint+ // — that hint is what appears when the inner wt can't find the directive+ // file, which is exactly the bug this test guards against.+ 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}",+ );+}+/// Declining approval prevents alias execution#[rstest]fn test_alias_approval_decline(mut repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snapindex b8d4ae008..53e38a861 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap@@ -114,4 +114,6 @@ Custom command templates configured in user config ([2m~/.config/worktrunk/confWhen defined in both user and project config, both run — user first, then project. Project-config aliases require command approval on first run, same as project hooks. User-config aliases are trusted.+Inside an alias body, an inner [2mwt switch[0m (or [2mwt switch --create[0m) passes its [2mcd[0m through to the parent shell, so an alias wrapping [2mwt switch --create[0m lands the shell in the new worktree just like running it directly.+Alias names that match a built-in step command ([2mcommit[0m, [2msquash[0m, etc.) are shadowed by the built-in and will never run.