Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Split directive file into CD (raw path) and EXEC (shell) files (#2118)

Maximilian Roosb174658e29cd
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.md
index 5a2c850ba..bcb0cc563 100644
--- a/.claude/skills/writing-user-outputs/SKILL.md
+++ b/.claude/skills/writing-user-outputs/SKILL.md
@@ -9,14 +9,15 @@ metadata:
## Shell Integration
-Worktrunk uses file-based directive passing for shell integration:
+Worktrunk uses split file-based directive passing for shell integration:
-1. Shell wrapper creates a temp file via `mktemp`
-2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_FILE` env var to the file path
-3. wt writes shell commands (like `cd '/path'`) to that file
-4. Shell wrapper sources the file after wt exits
+1. Shell wrapper creates two temp files via `mktemp` (cd and exec)
+2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
+3. wt writes a raw path to the CD file; shell commands to the EXEC file (for `--execute`)
+4. Shell wrapper reads the CD file with `cd -- "$(< file)"` (no shell parsing)
+5. Shell wrapper sources the EXEC file if non-empty
-When `WORKTRUNK_DIRECTIVE_FILE` is not set (direct binary call), commands execute
+When neither directive env var is set (direct binary call), commands execute
directly and shell integration hints are shown.
## Output Functions
@@ -105,9 +106,18 @@ Examples:
## Security
-`WORKTRUNK_DIRECTIVE_FILE` is automatically removed from spawned subprocesses
-(via `shell_exec::Cmd`). This prevents hooks from writing to the directive
-file.
+The split-trust design enforces two trust levels:
+
+- `WORKTRUNK_DIRECTIVE_CD_FILE` holds a raw path (no shell parsing), so it's
+ safe to pass through to alias/hook child processes — a body that writes to it
+ can at worst redirect `cd`.
+- `WORKTRUNK_DIRECTIVE_EXEC_FILE` holds arbitrary shell that the wrapper
+ sources verbatim, so wt scrubs this env var from alias/hook child processes.
+ A hook body writing to it would inject shell into the parent session.
+
+All directive env vars are removed from spawned subprocesses by default via
+`shell_exec::scrub_directive_env_vars()`. `DirectivePassthrough::inherit_from_env()`
+re-adds only the CD file (and legacy compat file) for trusted contexts.
## Windows Compatibility (Git Bash / MSYS2)
diff --git a/docs/content/config.md b/docs/content/config.md
index 55fc7621b..bc355f450 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -479,7 +479,8 @@ Override the LLM command in CI to use a mock:
| `WORKTRUNK_CONFIG_PATH` | Override user config file location |
| `WORKTRUNK_SYSTEM_CONFIG_PATH` | Override system config file location |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
-| `WORKTRUNK_DIRECTIVE_FILE` | Internal: set by shell wrappers to enable directory changes |
+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 7eb64cd8a..e9ab1b4e1 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -482,7 +482,8 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_CONFIG_PATH` | Override user config file location |
| `WORKTRUNK_SYSTEM_CONFIG_PATH` | Override system config file location |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
-| `WORKTRUNK_DIRECTIVE_FILE` | Internal: set by shell wrappers to enable directory changes |
+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |
diff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.md
index b7ef50da0..10280d06d 100644
--- a/skills/worktrunk/reference/shell-integration.md
+++ b/skills/worktrunk/reference/shell-integration.md
@@ -8,15 +8,18 @@ Subprocesses cannot change the parent shell's current directory. When
`wt switch feature` runs, the `wt` binary runs as a child process and cannot
`cd` the terminal.
-Worktrunk solves this with **directive file passing**:
+Worktrunk solves this with **split directive file passing**:
-1. Shell wrapper creates a temp file via `mktemp`
-2. Shell sets `WORKTRUNK_DIRECTIVE_FILE` env var to the temp file path
-3. `wt` binary writes shell commands (like `cd '/path'`) to that file
-4. Shell sources the file after `wt` exits, executing the commands
-5. Shell removes the temp file
+1. Shell wrapper creates two temp files via `mktemp` (one for cd, one for exec)
+2. Shell sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
+3. `wt` binary writes a raw path to the CD file (no shell escaping needed)
+4. `wt` writes shell commands to the EXEC file (only for `--execute`)
+5. Shell reads the CD file with `cd -- "$(< file)"` — no shell parsing
+6. Shell sources the EXEC file if non-empty
+7. Shell removes both temp files
-This allows `wt switch` to change the terminal's directory.
+The split design eliminates shell injection from cd directives — the CD file
+holds a raw path that is never parsed as shell.
## Installation
@@ -117,25 +120,31 @@ suggested fix.
The shell wrapper (installed by `wt config shell install`) defines a shell
function that:
-1. Creates a temp file for directives
-2. Sets `WORKTRUNK_DIRECTIVE_FILE` to that path
+1. Creates two temp files (cd and exec)
+2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
3. Runs the real `wt` binary
-4. Sources the directive file (executes `cd` commands)
-5. Cleans up the temp file
+4. Reads the CD file with `cd -- "$(< file)"` (raw path, no shell parsing)
+5. Sources the EXEC file if non-empty (for `--execute` payloads)
+6. Cleans up both temp files
Simplified example (actual wrapper handles completions and edge cases):
```bash
wt() {
- local directive_file
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command wt "$@" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command wt "$@" || exit_code=$?
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ fi
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
fi
- rm -f "$directive_file"
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
```
@@ -187,24 +196,26 @@ grep -n "wt config shell init" ~/.config/fish/config.fish
Should show the `eval` line with line number.
-### 3. Check if directive file is set
+### 3. Check if directive files are set
```bash
-# After running any wt command, this should be unset (temp file deleted)
-echo $WORKTRUNK_DIRECTIVE_FILE
+# After running any wt command, these should be unset (temp files deleted)
+echo $WORKTRUNK_DIRECTIVE_CD_FILE
+echo $WORKTRUNK_DIRECTIVE_EXEC_FILE
-# During wt execution, this would be set to a temp file path
+# During wt execution, these would be set to temp file paths
```
-### 4. Test directive file manually
+### 4. Test directive files manually
```bash
-# Create a temp file and test
-export WORKTRUNK_DIRECTIVE_FILE=$(mktemp)
+# Create temp files and test
+export WORKTRUNK_DIRECTIVE_CD_FILE=$(mktemp)
+export WORKTRUNK_DIRECTIVE_EXEC_FILE=$(mktemp)
command wt switch feature
-cat $WORKTRUNK_DIRECTIVE_FILE # Should contain: cd '/path/to/worktree'
-source $WORKTRUNK_DIRECTIVE_FILE # Should cd you there
-rm $WORKTRUNK_DIRECTIVE_FILE
+cat $WORKTRUNK_DIRECTIVE_CD_FILE # Should contain: /path/to/worktree (raw path)
+cd -- "$(<$WORKTRUNK_DIRECTIVE_CD_FILE)" # Should cd you there
+rm -f $WORKTRUNK_DIRECTIVE_CD_FILE $WORKTRUNK_DIRECTIVE_EXEC_FILE
```
## Common Issues
@@ -239,7 +250,8 @@ If you see path issues, ensure you're using a recent Git for Windows version.
| Variable | Purpose |
|----------|---------|
-| `WORKTRUNK_DIRECTIVE_FILE` | Set by shell wrapper; path to temp file for directives |
+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Set by shell wrapper; wt writes a raw path, wrapper `cd`s to it |
+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Set by shell wrapper; wt writes shell commands, wrapper sources the file |
| `WORKTRUNK_BIN` | Override binary path (for testing dev builds) |
| `WORKTRUNK_SHELL` | Set by PowerShell wrapper to indicate shell type |
diff --git a/skills/worktrunk/reference/troubleshooting.md b/skills/worktrunk/reference/troubleshooting.md
index 067ed10a7..fcdacf651 100644
--- a/skills/worktrunk/reference/troubleshooting.md
+++ b/skills/worktrunk/reference/troubleshooting.md
@@ -104,7 +104,7 @@ session:
2. `(Get-Command git-wt -CommandType Function).ScriptBlock | Select-String
WORKTRUNK` — verifies the wrapper function body sets
- `WORKTRUNK_DIRECTIVE_FILE`. If this doesn't appear, the function is
+ `WORKTRUNK_DIRECTIVE_CD_FILE`. If this doesn't appear, the function is
incomplete or corrupted.
3. `Get-Command git-wt -CommandType Application | Select-Object Source` — shows
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index eb0550181..a972936aa 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -2129,7 +2129,8 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_CONFIG_PATH` | Override user config file location |
| `WORKTRUNK_SYSTEM_CONFIG_PATH` | Override system config file location |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
-| `WORKTRUNK_DIRECTIVE_FILE` | Internal: set by shell wrappers to enable directory changes |
+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index a029b9945..815d87930 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -40,17 +40,17 @@
//!
//! 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).
+//! first, then project. The CD directive file is passed through to child
+//! processes so inner `wt` invocations can redirect the parent shell's cwd;
+//! the EXEC directive file is scrubbed so alias bodies cannot inject
+//! arbitrary shell into the interactive session.
use std::collections::HashMap;
-use std::path::PathBuf;
use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::config::{CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases};
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,
};
@@ -61,7 +61,7 @@ use crate::commands::command_executor::{
};
use crate::commands::force_serial_concurrent;
use crate::commands::hooks::format_pipeline_summary_from_names;
-use crate::output::execute_shell_command;
+use crate::output::{DirectivePassthrough, execute_shell_command};
/// Built-in `wt step` subcommand names. Aliases with these names are
/// shadowed by the built-in and will never run.
@@ -355,12 +355,8 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
progress_message(format_alias_announcement(&opts.name, cmd_config))
);
- // 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);
+ // CD passed through, EXEC scrubbed (see `output::global` for rationale).
+ let directives = DirectivePassthrough::inherit_from_env();
let exec = AliasExecCtx {
context_map: &context_map,
@@ -368,7 +364,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
alias_name: &opts.name,
wt_path: &wt_path,
context_json: &context_json,
- directive_file: parent_directive_file.as_deref(),
+ directives: &directives,
};
for step in cmd_config.steps() {
@@ -405,7 +401,7 @@ struct AliasExecCtx<'a> {
alias_name: &'a str,
wt_path: &'a std::path::Path,
context_json: &'a str,
- directive_file: Option<&'a std::path::Path>,
+ directives: &'a DirectivePassthrough,
}
impl AliasExecCtx<'_> {
@@ -422,7 +418,7 @@ impl AliasExecCtx<'_> {
&command,
Some(self.context_json),
None,
- self.directive_file,
+ self.directives.clone(),
) {
if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
err.downcast_ref::<WorktrunkError>()
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 436c7a46b..b6de2b963 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -32,7 +32,7 @@ use crate::commands::command_executor::{
CommandContext, build_hook_context, expand_shell_template,
};
use crate::commands::worktree_display_name;
-use crate::output::execute_shell_command;
+use crate::output::{DirectivePassthrough, execute_shell_command};
/// Run a command in each worktree sequentially.
///
@@ -80,9 +80,15 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
// Execute command: stream both stdout and stderr in real-time.
// Pipe context JSON to stdin for scripts that want structured data.
- // Directive file is scrubbed — commands run in other worktrees should
+ // Directive files are 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) {
+ match execute_shell_command(
+ &wt.path,
+ &command,
+ Some(&context_json),
+ None,
+ DirectivePassthrough::none(),
+ ) {
Ok(()) => {
if json_mode {
json_results.push(serde_json::json!({
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 955ceacc2..bc3771628 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -14,8 +14,7 @@ use super::command_executor::{
CommandContext, PreparedCommand, PreparedStep, expand_shell_template, prepare_steps,
};
use crate::commands::process::{HookLog, spawn_detached_exec};
-use crate::output::execute_shell_command;
-use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;
+use crate::output::{DirectivePassthrough, execute_shell_command};
/// Short summary name: "user:name" for named commands, "user" otherwise.
pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> String {
@@ -545,13 +544,8 @@ pub fn run_hook_with_filter(
return Ok(());
}
- // 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);
- let directive_file_ref = directive_file.as_deref();
+ // CD passed through, EXEC scrubbed (see `output::global` for rationale).
+ let directives = DirectivePassthrough::inherit_from_env();
// Foreground hooks always execute serially, even when the prepared step is
// `Concurrent`. The documented contract is "for pre-* hooks, commands in a
@@ -566,7 +560,7 @@ pub fn run_hook_with_filter(
cmd,
sourced.source,
sourced.hook_type,
- directive_file_ref,
+ &directives,
failure_strategy,
)?;
}
@@ -581,7 +575,7 @@ fn execute_one_hook_command(
cmd: &PreparedCommand,
source: HookSource,
hook_type: HookType,
- directive_file: Option<&Path>,
+ directives: &DirectivePassthrough,
failure_strategy: HookFailureStrategy,
) -> anyhow::Result<()> {
let summary = command_summary_name(cmd.name.as_deref(), source);
@@ -604,7 +598,7 @@ fn execute_one_hook_command(
command_str,
Some(&cmd.context_json),
Some(&log_label),
- directive_file,
+ directives.clone(),
) else {
return Ok(());
};
diff --git a/src/commands/picker/pager.rs b/src/commands/picker/pager.rs
index ca5687a78..bcbe251bf 100644
--- a/src/commands/picker/pager.rs
+++ b/src/commands/picker/pager.rs
@@ -83,16 +83,15 @@ pub(super) fn pipe_through_pager(text: &str, pager_cmd: &str, width: usize) -> S
log::debug!("Piping through pager: {}", pager_cmd);
// Spawn pager with stdin piped
- let mut child = match Command::new("sh")
- .arg("-c")
+ let mut cmd = Command::new("sh");
+ cmd.arg("-c")
.arg(pager_cmd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
- .env("COLUMNS", width.to_string())
- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .spawn()
- {
+ .env("COLUMNS", width.to_string());
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
log::debug!("Failed to spawn pager: {}", e);
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 81338a8e1..a7ef5b5fc 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -286,8 +286,8 @@ fn spawn_detached_unix(
// Detachment via process_group(0): puts the spawned shell in its own process group.
// When the controlling PTY closes, SIGHUP is sent to the foreground process group.
// Since our process is in a different group, it doesn't receive the signal.
- let mut child = Command::new("sh")
- .arg("-c")
+ let mut cmd = Command::new("sh");
+ cmd.arg("-c")
.arg(&shell_cmd)
.current_dir(worktree_path)
.stdin(Stdio::null())
@@ -297,11 +297,10 @@ fn spawn_detached_unix(
.context("Failed to clone log file handle")?,
))
.stderr(Stdio::from(log_file))
- // Prevent hooks from writing to the directive file
- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .process_group(0) // New process group, not in PTY's foreground group
- .spawn()
- .context("Failed to spawn detached process")?;
+ .process_group(0); // New process group, not in PTY's foreground group
+ // Prevent hooks from writing to the directive file
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = cmd.spawn().context("Failed to spawn detached process")?;
// Wait for sh to exit (immediate, doesn't block on background command)
child
@@ -370,11 +369,10 @@ fn spawn_detached_windows(
.context("Failed to clone log file handle")?,
))
.stderr(Stdio::from(log_file))
- // Prevent hooks from writing to the directive file
- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
- .spawn()
- .context("Failed to spawn detached process")?;
+ .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
+ // Prevent hooks from writing to the directive file
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ cmd.spawn().context("Failed to spawn detached process")?;
// Windows: Process is fully detached via DETACHED_PROCESS flag,
// no need to wait (unlike Unix which waits for the outer shell)
@@ -432,8 +430,8 @@ fn spawn_detached_exec_unix(
use std::io::Write;
use std::os::unix::process::CommandExt;
- let mut child = Command::new(program)
- .args(args)
+ let mut cmd = Command::new(program);
+ cmd.args(args)
.current_dir(worktree_path)
.stdin(Stdio::piped())
.stdout(Stdio::from(
@@ -442,10 +440,9 @@ fn spawn_detached_exec_unix(
.context("Failed to clone log file handle")?,
))
.stderr(Stdio::from(log_file))
- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .process_group(0)
- .spawn()
- .context("Failed to spawn detached process")?;
+ .process_group(0);
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = cmd.spawn().context("Failed to spawn detached process")?;
if let Some(mut stdin) = child.stdin.take() {
// Ignore BrokenPipe — child may exit before reading all input.
@@ -469,8 +466,8 @@ fn spawn_detached_exec_windows(
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
const DETACHED_PROCESS: u32 = 0x00000008;
- let mut child = Command::new(program)
- .args(args)
+ let mut cmd = Command::new(program);
+ cmd.args(args)
.current_dir(worktree_path)
.stdin(Stdio::piped())
.stdout(Stdio::from(
@@ -479,10 +476,9 @@ fn spawn_detached_exec_windows(
.context("Failed to clone log file handle")?,
))
.stderr(Stdio::from(log_file))
- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
- .spawn()
- .context("Failed to spawn detached process")?;
+ .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = cmd.spawn().context("Failed to spawn detached process")?;
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(stdin_bytes);
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 5eafc7e89..058cd26d0 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -10,14 +10,17 @@
//! The binary can change *its own* working directory, but when it exits, the parent shell remains
//! in the original directory.
//!
-//! # Solution: File-Based Directive Passing
+//! # Solution: Split File-Based Directive Passing
//!
-//! Shell wrappers create a temp file and set `WORKTRUNK_DIRECTIVE_FILE` to its path:
+//! Shell wrappers create two temp files and set `WORKTRUNK_DIRECTIVE_CD_FILE`
+//! and `WORKTRUNK_DIRECTIVE_EXEC_FILE` to their paths:
//!
-//! 1. Shell wrapper creates temp file via `mktemp`
-//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_FILE=/path/to/temp`
-//! 3. wt binary writes commands like `cd '/path'` to that file
-//! 4. Shell wrapper sources the file after wt exits
+//! 1. Shell wrapper creates two temp files via `mktemp` (cd and exec)
+//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
+//! 3. wt binary writes a raw path to the CD file (no shell escaping)
+//! 4. wt writes arbitrary shell to the EXEC file (only for `--execute`)
+//! 5. Shell wrapper reads the CD file with `cd -- "$(< file)"` (no shell parsing)
+//! 6. Shell wrapper sources the EXEC file if non-empty
//!
//! ## Without Shell Integration (Direct Binary Call)
//!
@@ -46,9 +49,9 @@
//!
//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell wrapper:
//!
-//! 1. Creates a temp file and sets `WORKTRUNK_DIRECTIVE_FILE` to its path
-//! 2. Runs the wt binary (which writes `cd '/path'` to the temp file)
-//! 3. Sources the temp file after wt exits
+//! 1. Creates two temp files and sets the CD and EXEC directive env vars
+//! 2. Runs the wt binary (which writes a raw path to the CD file)
+//! 3. Reads the CD file with `cd -- "$(< file)"` after wt exits
//!
//! # Implementation Details
//!
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 35c456de6..33356e1ad 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -749,14 +749,14 @@ impl Repository {
/// waiting for EOF that never comes.
pub fn start_fsmonitor_daemon_at(&self, path: &Path) {
log::debug!("$ git fsmonitor--daemon start [{}]", path.display());
- let result = std::process::Command::new("git")
- .args(["fsmonitor--daemon", "start"])
+ let mut cmd = std::process::Command::new("git");
+ cmd.args(["fsmonitor--daemon", "start"])
.current_dir(path)
- .env_remove(crate::shell_exec::DIRECTIVE_FILE_ENV_VAR)
.stdin(Stdio::null())
.stdout(Stdio::null())
- .stderr(Stdio::null())
- .status();
+ .stderr(Stdio::null());
+ crate::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let result = cmd.status();
match result {
Ok(status) if !status.success() => {
log::debug!("fsmonitor daemon start exited {status} (usually fine)");
@@ -919,13 +919,14 @@ impl Repository {
delay_ms
);
- let mut child = std::process::Command::new("git")
- .args(args)
+ let mut cmd = std::process::Command::new("git");
+ cmd.args(args)
.current_dir(&self.discovery_path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .env_remove(crate::shell_exec::DIRECTIVE_FILE_ENV_VAR)
+ .stderr(Stdio::piped());
+ crate::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = cmd
.spawn()
.with_context(|| format!("Failed to spawn: {}", cmd_str))?;
diff --git a/src/help_pager.rs b/src/help_pager.rs
index 4df784486..8d1c563bf 100644
--- a/src/help_pager.rs
+++ b/src/help_pager.rs
@@ -126,8 +126,7 @@ pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) -> std::io::R
};
log::debug!("$ {} (pager)", pager_cmd);
let mut cmd = shell.command(&final_cmd);
- // Prevent subprocesses from writing to the directive file
- cmd.env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR);
+ worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
let mut child = match cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn() {
Ok(child) => child,
Err(e) => {
diff --git a/src/output/global.rs b/src/output/global.rs
index bc7607e11..55f810478 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -1,21 +1,47 @@
//! Global output context with file-based directive passing
//!
-//! This module handles shell integration directives (cd, exec) that need to be
-//! communicated to the parent shell. For regular output, use `eprintln!`/`println!`
-//! directly (from `worktrunk::styling` for color support).
+//! Shell integration directives (cd, exec) travel from wt to the parent shell
+//! through files named by environment variables. This module chooses the right
+//! file for each directive and escalates a warning when a trusted directive is
+//! refused. Regular output still uses `eprintln!`/`println!` directly (from
+//! `worktrunk::styling` for color support).
//!
-//! # Implementation
+//! # Protocol
//!
-//! Uses a simple global approach:
-//! - `OnceLock<Mutex<OutputState>>` stores the directive file path and accumulated state
-//! - If `WORKTRUNK_DIRECTIVE_FILE` env var is set, directives are written to that file
-//! - Otherwise, commands execute directly
+//! Shell integration uses two separate files with different trust levels:
//!
-//! # Shell Integration
+//! - `WORKTRUNK_DIRECTIVE_CD_FILE` holds a single raw path. The wrapper runs
+//! `cd -- "$(< file)"` after wt exits. There is no shell parsing, no
+//! escaping, and no injection surface, so the env var is safe to pass
+//! through to alias/hook shell bodies — a body that appends to it can at
+//! worst redirect `cd`.
//!
-//! When `WORKTRUNK_DIRECTIVE_FILE` is set (by the shell wrapper), wt writes shell commands
-//! (like `cd '/path'`) to that file. The shell wrapper sources the file after wt exits.
-//! This allows the parent shell to change directory.
+//! - `WORKTRUNK_DIRECTIVE_EXEC_FILE` holds arbitrary shell that the wrapper
+//! sources after the `cd`. This is how `wt switch --execute <cmd>` runs its
+//! payload in the user's interactive shell, inheriting functions and env.
+//! Because the contents are sourced verbatim, wt scrubs this env var from
+//! alias and foreground-hook child processes so a hook body cannot inject
+//! shell into the parent session.
+//!
+//! # Conservative scrub
+//!
+//! Because the EXEC env var is scrubbed from alias/hook child environments, a
+//! nested `wt` invocation inside an alias body (e.g. `wt step my-alias` where
+//! the alias runs `wt switch main --execute claude`) sees no EXEC file and
+//! refuses to run the `--execute` payload, emitting a warning and a link to
+//! <https://github.com/max-sixty/worktrunk/issues/2101> so users can report
+//! whether to relax the restriction.
+//!
+//! # Legacy compat
+//!
+//! Users who upgrade wt without restarting their shell still run the previous
+//! release's shell wrapper, which only sets `WORKTRUNK_DIRECTIVE_FILE`. When
+//! only that variable is set, wt falls back to the pre-split protocol (shell
+//! commands written to the single file) silently. For bash, zsh, fish, and
+//! PowerShell a shell restart picks up the new wrapper automatically; nushell
+//! is the only shell where users have to rerun `wt config shell install`
+//! because its wrapper is a static file. Remove the legacy path in the next
+//! breaking release.
use std::fs::OpenOptions;
use std::io::{self, Write};
@@ -24,7 +50,6 @@ use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
-#[cfg(unix)]
use color_print::cformat;
use std::sync::{Mutex, OnceLock};
@@ -32,9 +57,16 @@ use std::sync::{Mutex, OnceLock};
use worktrunk::git::WorktrunkError;
#[cfg(not(unix))]
use worktrunk::shell_exec::Cmd;
-use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;
#[cfg(unix)]
use worktrunk::shell_exec::ShellConfig;
+use worktrunk::shell_exec::{
+ DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR,
+};
+use worktrunk::styling::{hint_message, warning_message};
+
+/// Issue tracking whether to relax the conservative EXEC scrub for alias/hook
+/// bodies. Emitted in the warning so users can report use cases.
+pub const EXEC_SCRUB_ISSUE_URL: &str = "https://github.com/max-sixty/worktrunk/issues/2101";
// Re-export set_verbosity from the library's styling module.
// This ensures the binary and library share the same global state.
@@ -52,11 +84,34 @@ pub use worktrunk::styling::set_verbosity;
/// unreachable - the lock is only held for trivial Option assignments that cannot panic.
static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();
+/// Selects which directive files wt writes to based on environment.
+///
+/// Computed once during `state()` initialization from the process environment.
+/// Legacy mode only activates when no new-protocol vars are set — a fresh
+/// wrapper always wins over any leftover legacy var.
+#[derive(Debug, Clone, Default)]
+enum DirectiveMode {
+ /// Shell integration not active. `execute()` runs commands directly;
+ /// `change_directory()` is a no-op beyond updating the buffered target
+ /// dir used by `execute()`.
+ #[default]
+ Interactive,
+ /// New split protocol. `cd_file` is always a real path; `exec_file` is
+ /// `None` when the EXEC var was scrubbed from this process (we're
+ /// running inside an alias/hook shell body). `--execute` in the scrubbed
+ /// case warns and drops the command.
+ NewProtocol {
+ cd_file: PathBuf,
+ exec_file: Option<PathBuf>,
+ },
+ /// Legacy single-file protocol. Pre-split wrapper is still active.
+ Legacy { file: PathBuf },
+}
+
#[derive(Default)]
struct OutputState {
- /// Path to the directive file (from WORKTRUNK_DIRECTIVE_FILE env var)
- /// If None, we're in interactive mode (no shell wrapper)
- directive_file: Option<PathBuf>,
+ /// Which directive files wt writes to.
+ mode: DirectiveMode,
/// Buffered target directory for execute() in interactive mode
target_dir: Option<PathBuf>,
/// Mapping from canonical path prefix to logical (symlink) prefix.
@@ -174,19 +229,16 @@ pub fn to_logical_path(path: &Path) -> PathBuf {
/// Get or lazily initialize the global output state.
///
-/// Reads `WORKTRUNK_DIRECTIVE_FILE` from environment on first access.
-/// Empty or whitespace-only strings are treated as "not set" to handle edge cases.
+/// Reads directive file env vars from environment on first access and picks
+/// a `DirectiveMode`. Empty or whitespace-only strings are treated as "not
+/// set" to handle edge cases.
fn state() -> &'static Mutex<OutputState> {
OUTPUT_STATE.get_or_init(|| {
- let directive_file = std::env::var(DIRECTIVE_FILE_ENV_VAR)
- .ok()
- .filter(|s| !s.trim().is_empty())
- .map(PathBuf::from);
-
+ let mode = compute_directive_mode();
let symlink_mapping = SymlinkMapping::compute();
Mutex::new(OutputState {
- directive_file,
+ mode,
target_dir: None,
symlink_mapping,
cwd_removed: false,
@@ -194,65 +246,125 @@ fn state() -> &'static Mutex<OutputState> {
})
}
-/// Check if shell integration is active (directive file is set)
-fn has_directive_file() -> bool {
- state()
- .lock()
- .expect("OUTPUT_STATE lock poisoned")
- .directive_file
- .is_some()
+fn read_env_path(var: &str) -> Option<PathBuf> {
+ std::env::var(var)
+ .ok()
+ .filter(|s| !s.trim().is_empty())
+ .map(PathBuf::from)
}
-/// Write a directive to the directive file (if set)
-fn write_directive(directive: &str) -> io::Result<()> {
- // Copy path out of lock to avoid holding mutex during I/O
- let path = {
- let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
- guard.directive_file.clone()
- };
+fn compute_directive_mode() -> DirectiveMode {
+ let cd = read_env_path(DIRECTIVE_CD_FILE_ENV_VAR);
+ let exec = read_env_path(DIRECTIVE_EXEC_FILE_ENV_VAR);
+ let legacy = read_env_path(DIRECTIVE_FILE_ENV_VAR);
+
+ match cd {
+ Some(cd_file) => DirectiveMode::NewProtocol {
+ cd_file,
+ exec_file: exec,
+ },
+ None => match legacy {
+ // Silent fallback: bash/zsh/fish/PowerShell self-update on restart,
+ // and nushell is the only shell that needs a manual reinstall. A
+ // global "your wrapper is old" warning would hit everyone else with
+ // noise they can't avoid until their next terminal restart.
+ Some(file) => DirectiveMode::Legacy { file },
+ None => DirectiveMode::Interactive,
+ },
+ }
+}
- let Some(path) = path else {
- return Ok(());
- };
+/// Warn that `--execute` was refused because we're running inside an alias or
+/// hook body with the EXEC file scrubbed. Fires at most once per process so
+/// repeated refusals don't spam the terminal.
+fn warn_exec_scrubbed_once(command: &str) {
+ static WARNED: OnceLock<()> = OnceLock::new();
+ if WARNED.set(()).is_err() {
+ return;
+ }
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "<bold>--execute</> disabled inside alias/hook bodies for safety; skipping <bold>{command}</>"
+ ))
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "This is extremely conservative; comment at <underline>{EXEC_SCRUB_ISSUE_URL}</> if this affects you"
+ ))
+ );
+}
- let mut file = OpenOptions::new().append(true).open(&path)?;
- writeln!(file, "{}", directive)?;
+/// Append a line to a directive file.
+fn append_line(path: &Path, line: &str) -> io::Result<()> {
+ let mut file = OpenOptions::new().append(true).open(path)?;
+ writeln!(file, "{}", line)?;
file.flush()
}
-/// Request directory change (for shell integration)
+/// Truncate-write the given path to the CD directive file. The file holds one
+/// line: the absolute path the shell wrapper should `cd` to. Truncate-then-
+/// write semantics mean the last writer wins, which matches how overlapping
+/// `change_directory()` calls should resolve (hook emits a cd after switch
+/// emits its own → hook wins).
+fn write_cd_path(file: &Path, path: &Path) -> io::Result<()> {
+ let mut f = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(file)?;
+ // Lossy for non-UTF-8 paths (extremely rare in practice; worktrunk-
+ // managed paths are always valid UTF-8).
+ f.write_all(path.as_os_str().to_string_lossy().as_bytes())?;
+ f.write_all(b"\n")?;
+ f.flush()
+}
+
+/// Escape a path as a POSIX-shell (or PowerShell) single-quoted string. Only
+/// used in legacy mode where we still emit shell commands.
+fn escape_legacy_cd(path: &Path) -> String {
+ let path_str = path.to_string_lossy();
+ // POSIX and PowerShell both single-quote, but escape embedded quotes
+ // differently:
+ // POSIX: 'it'\''s'
+ // PSH: 'it''s'
+ let is_powershell = std::env::var("WORKTRUNK_SHELL")
+ .map(|v| v.eq_ignore_ascii_case("powershell"))
+ .unwrap_or(false);
+ let escaped = if is_powershell {
+ path_str.replace('\'', "''")
+ } else {
+ path_str.replace('\'', "'\\''")
+ };
+ format!("cd '{}'", escaped)
+}
+
+/// Request directory change (for shell integration).
///
-/// If shell integration is active (WORKTRUNK_DIRECTIVE_FILE set), writes `cd` command to the file.
-/// Also stores path for execute() to use as working directory.
+/// Writes the target path to the CD directive file (new protocol) or emits
+/// a shell `cd '...'` command to the legacy file (legacy compat). In
+/// interactive mode (no wrapper), just buffers the target so that a later
+/// `execute()` can use it as the child's working directory.
pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
let path = path.as_ref();
- let mut guard = state().lock().expect("OUTPUT_STATE lock poisoned");
-
- // Store for execute() to use as process cwd
- guard.target_dir = Some(path.to_path_buf());
-
- // Write to directive file if set
- if guard.directive_file.is_some() {
- drop(guard); // Release lock before I/O
-
- let directive_path = to_logical_path(path);
- let path_str = directive_path.to_string_lossy();
- // Escape based on shell type. Both shell families use single-quoted strings
- // where contents are literal, but they escape embedded quotes differently:
- // - PowerShell: double the quote ('it''s')
- // - POSIX (bash/zsh/fish): end quote, escaped quote, start quote ('it'\''s')
- let is_powershell = std::env::var("WORKTRUNK_SHELL")
- .map(|v| v.eq_ignore_ascii_case("powershell"))
- .unwrap_or(false);
- let escaped = if is_powershell {
- path_str.replace('\'', "''")
- } else {
- path_str.replace('\'', "'\\''")
- };
- write_directive(&format!("cd '{}'", escaped))?;
- }
+ let mode = {
+ let mut guard = state().lock().expect("OUTPUT_STATE lock poisoned");
+ guard.target_dir = Some(path.to_path_buf());
+ guard.mode.clone()
+ };
- Ok(())
+ match mode {
+ DirectiveMode::Interactive => Ok(()),
+ DirectiveMode::NewProtocol { cd_file, .. } => {
+ let directive_path = to_logical_path(path);
+ write_cd_path(&cd_file, &directive_path)
+ }
+ DirectiveMode::Legacy { file } => {
+ let directive_path = to_logical_path(path);
+ append_line(&file, &escape_legacy_cd(&directive_path))
+ }
+ }
}
/// Mark that the current working directory's worktree has been removed.
@@ -275,28 +387,61 @@ pub fn was_cwd_removed() -> bool {
.cwd_removed
}
-/// Request command execution
+/// Request command execution.
///
-/// In interactive mode (no directive file), executes the command directly (replacing process on Unix).
-/// In shell integration mode, writes the command to the directive file.
+/// Dispatches by directive mode:
+/// - Interactive: runs the command directly (replacing this process on Unix).
+/// - New protocol with EXEC file: appends the command to the EXEC file; the
+/// wrapper sources it after wt exits, so it runs in the user's interactive
+/// shell.
+/// - New protocol without EXEC file: refuses the command with a warning. We
+/// land here when running inside an alias or hook body, where `Cmd` scrubbed
+/// the EXEC var to keep arbitrary shell from reaching the parent session.
+/// - Legacy: appends the command to the single legacy directive file.
pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
let command = command.into();
- let (has_directive, target_dir) = {
+ let (mode, target_dir) = {
let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
- (guard.directive_file.is_some(), guard.target_dir.clone())
+ (guard.mode.clone(), guard.target_dir.clone())
};
- if has_directive {
- // Write to directive file
- write_directive(&command)?;
- Ok(())
- } else {
- // Execute directly
- execute_command(command, target_dir.as_deref())
+ match mode {
+ DirectiveMode::Interactive => execute_command(command, target_dir.as_deref()),
+ DirectiveMode::NewProtocol {
+ exec_file: Some(file),
+ ..
+ } => {
+ append_line(&file, &command)?;
+ Ok(())
+ }
+ DirectiveMode::NewProtocol {
+ exec_file: None, ..
+ } => {
+ warn_exec_scrubbed_once(&command);
+ Ok(())
+ }
+ DirectiveMode::Legacy { file } => {
+ append_line(&file, &command)?;
+ Ok(())
+ }
}
}
+/// Whether a call to `execute()` with a non-empty command would be refused
+/// by the conservative scrub. Callers can use this to suppress pre-exec
+/// output (e.g. "Executing (--execute):" headers) so the warning stands alone.
+pub fn exec_would_be_refused() -> bool {
+ let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
+ matches!(
+ guard.mode,
+ DirectiveMode::NewProtocol {
+ exec_file: None,
+ ..
+ }
+ )
+}
+
/// Execute a command in the given directory (Unix: exec, non-Unix: spawn)
#[cfg(unix)]
fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
@@ -351,7 +496,7 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result
/// In interactive mode (no shell wrapper), message formatting functions
/// already reset their own styles, so no global reset is needed.
pub fn terminate_output() -> io::Result<()> {
- if !has_directive_file() {
+ if !is_shell_integration_active() {
return Ok(());
}
@@ -362,11 +507,15 @@ pub fn terminate_output() -> io::Result<()> {
stderr.flush()
}
-/// Check if we're in shell integration mode (directive file is set)
+/// Check if we're in shell integration mode (any directive-file protocol active).
///
-/// This is useful for handlers that need to know whether shell integration is active.
+/// Useful for handlers that need to know whether shell integration is in effect,
+/// regardless of which protocol (new or legacy) is being used.
pub fn is_shell_integration_active() -> bool {
- has_directive_file()
+ !matches!(
+ state().lock().expect("OUTPUT_STATE lock poisoned").mode,
+ DirectiveMode::Interactive
+ )
}
/// Compute whether to show "@ path" in hook announcements.
@@ -528,7 +677,7 @@ mod tests {
fn test_lazy_init_does_not_panic() {
// Verify lazy initialization doesn't panic.
// State is lazily initialized on first access.
- let _ = has_directive_file();
+ let _ = is_shell_integration_active();
}
#[test]
@@ -558,38 +707,30 @@ mod tests {
rx.recv().unwrap();
}
- // Shell escaping tests
+ // Shell escaping tests (escape_legacy_cd)
#[test]
- fn test_shell_script_format() {
- // Test that POSIX quoting produces correct output
- let path = PathBuf::from("/test/path");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
- assert_eq!(cd_cmd, "cd '/test/path'");
+ fn test_escape_legacy_cd_simple_path() {
+ let result = escape_legacy_cd(Path::new("/test/path"));
+ assert_eq!(result, "cd '/test/path'");
}
#[test]
- fn test_path_with_single_quotes() {
- // Paths with single quotes need escaping: ' -> '\''
- let path = PathBuf::from("/test/it's/path");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
- assert_eq!(cd_cmd, "cd '/test/it'\\''s/path'");
+ fn test_escape_legacy_cd_single_quotes() {
+ let result = escape_legacy_cd(Path::new("/test/it's/path"));
+ assert_eq!(result, "cd '/test/it'\\''s/path'");
}
#[test]
- fn test_path_with_spaces() {
- // Paths with spaces are safely quoted
- let path = PathBuf::from("/test/my path/here");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
- assert_eq!(cd_cmd, "cd '/test/my path/here'");
+ fn test_escape_legacy_cd_spaces() {
+ let result = escape_legacy_cd(Path::new("/test/my path/here"));
+ assert_eq!(result, "cd '/test/my path/here'");
}
+ // PowerShell branch of escape_legacy_cd is exercised via integration
+ // test `test_switch_legacy_directive_file_powershell` which sets
+ // WORKTRUNK_SHELL=powershell on the subprocess.
+
/// Test that anstyle formatting is preserved
#[test]
fn test_success_preserves_anstyle() {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 62d770bb4..347a345b6 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -598,8 +598,8 @@ fn resolve_subdir_in_target(target_root: &Path, source_root: Option<&Path>, cwd:
/// Always warn when the shell's directory won't change. Users expect to be in
/// the target worktree after switching.
///
-/// **When to warn:** Shell integration is not active (`WORKTRUNK_DIRECTIVE_FILE`
-/// not set). This applies to both `Existing` and `Created` results.
+/// **When to warn:** Shell integration is not active (no directive files set).
+/// This applies to both `Existing` and `Created` results.
///
/// **When NOT to warn:**
/// - `AlreadyAt` — user is already in the target directory
@@ -664,11 +664,22 @@ pub fn handle_switch_output(
Ok(display_path_for_hooks)
}
-/// Execute the --execute command after hooks have run
+/// Execute the --execute command after hooks have run.
///
-/// `display_path` is shown when the user's shell won't be in the worktree directory
-/// (shell integration not active). This helps users understand where the command runs.
+/// `display_path` is shown when the user's shell won't be in the worktree
+/// directory (shell integration not active). This helps users understand where
+/// the command runs.
+///
+/// When the conservative EXEC scrub is in effect (nested `wt` inside an alias
+/// or hook body), no `Executing` header is printed — `execute()` emits its own
+/// warning explaining the skip, and a contradictory header would read as a
+/// broken promise. See `output::global::warn_exec_scrubbed_once`.
pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyhow::Result<()> {
+ if super::exec_would_be_refused() {
+ // execute() will emit the conservative-scrub warning and return Ok.
+ return super::execute(command);
+ }
+
// Show what command is being executed (section header + gutter content)
// Include path when user's shell won't be there (shell integration not active)
let header = match display_path {
@@ -1373,19 +1384,21 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh
/// SIGINT/SIGTERM forwarding to child process group, ANSI reset before child
/// runs, `Cmd` tracing/logging, and directive file control.
///
-/// ## Directive file
+/// ## Directive files
///
-/// `directive_file` controls whether the child can write shell integration
-/// directives (e.g. `cd`) back to the parent shell:
+/// `directives` controls whether the child can write shell-integration
+/// directives back to the parent shell. The CD file is always safe to pass
+/// through (raw path, no injection surface); the EXEC file is never passed
+/// through — only wt-internal Rust code writes arbitrary shell directives.
///
-/// - `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).
+/// - `DirectivePassthrough::none()` — scrubs all directive env vars from the
+/// child. Used by `for-each` (runs in other worktrees) and background hooks
+/// (outlive the parent shell).
+/// - `DirectivePassthrough::inherit_from_env()` — re-adds whichever directive
+/// env vars are currently set in this process. Used by aliases and
+/// foreground hooks, which may emit `cd` directives. In new-protocol mode
+/// only the CD file passes through; in legacy compat mode the single
+/// legacy file passes through to preserve pre-split behavior.
///
/// ## ANSI reset
///
@@ -1398,7 +1411,7 @@ pub fn execute_shell_command(
command: &str,
stdin_content: Option<&str>,
command_log_label: Option<&str>,
- directive_file: Option<&std::path::Path>,
+ directives: DirectivePassthrough,
) -> anyhow::Result<()> {
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
@@ -1424,8 +1437,11 @@ pub fn execute_shell_command(
cmd = cmd.stdin_bytes(content);
}
- if let Some(path) = directive_file {
- cmd = cmd.directive_file(path);
+ if let Some(path) = directives.cd_file {
+ cmd = cmd.directive_cd_file(path);
+ }
+ if let Some(path) = directives.legacy_file {
+ cmd = cmd.directive_legacy_file(path);
}
cmd.stream()?;
@@ -1436,6 +1452,42 @@ pub fn execute_shell_command(
Ok(())
}
+/// Selector for which directive file env vars to pass through to a child shell.
+///
+/// Constructed by callers via [`DirectivePassthrough::none`] or
+/// [`DirectivePassthrough::inherit_from_env`]. The EXEC file is intentionally
+/// never included — alias/hook shell bodies must not inject arbitrary shell
+/// into the parent session.
+#[derive(Debug, Default, Clone)]
+pub struct DirectivePassthrough {
+ pub cd_file: Option<std::path::PathBuf>,
+ pub legacy_file: Option<std::path::PathBuf>,
+}
+
+impl DirectivePassthrough {
+ /// Scrub all directive file env vars from the child process.
+ pub fn none() -> Self {
+ Self::default()
+ }
+
+ /// Pass CD and legacy directive files through to the child, reading the
+ /// current process environment. Used by trusted contexts (aliases,
+ /// foreground hooks) that may legitimately emit a `cd` directive. The
+ /// EXEC file is deliberately omitted.
+ pub fn inherit_from_env() -> Self {
+ use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR};
+ let read = |var: &str| {
+ std::env::var_os(var)
+ .map(std::path::PathBuf::from)
+ .filter(|p| !p.as_os_str().is_empty())
+ };
+ Self {
+ cd_file: read(DIRECTIVE_CD_FILE_ENV_VAR),
+ legacy_file: read(DIRECTIVE_FILE_ENV_VAR),
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 41dd83e97..7b75d6c77 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -18,14 +18,17 @@
//!
//! ## Shell Integration
//!
-//! When `WORKTRUNK_DIRECTIVE_FILE` env var is set (by shell wrapper):
-//! - Shell commands (cd, exec) are written to that file
-//! - Shell wrapper sources the file after wt exits
-//! - This allows the parent shell to change directory
+//! Two split directive files, one for each trust level:
+//! - `WORKTRUNK_DIRECTIVE_CD_FILE` — raw path; the wrapper `cd`s to it.
+//! - `WORKTRUNK_DIRECTIVE_EXEC_FILE` — arbitrary shell; the wrapper sources it.
//!
-//! When not set (direct binary call):
-//! - Commands execute directly
-//! - Shell hints are shown for missing integration
+//! The legacy single-file `WORKTRUNK_DIRECTIVE_FILE` env var is still honored
+//! for one release to bridge users who upgraded `wt` without restarting
+//! their shell. See `global` for the `DirectiveMode` selection logic.
+//!
+//! When no directive env vars are set (direct binary call):
+//! - Commands execute directly.
+//! - Shell hints are shown for missing integration.
//!
//! See [`shell_integration`] module for the complete spec of warning messages.
@@ -37,13 +40,14 @@ pub(crate) mod shell_integration;
// Re-export the public API
pub(crate) use global::{
- change_directory, execute, is_shell_integration_active, mark_cwd_removed,
- post_hook_display_path, pre_hook_display_path, set_verbosity, terminate_output,
- to_logical_path, was_cwd_removed,
+ change_directory, exec_would_be_refused, execute, is_shell_integration_active,
+ mark_cwd_removed, post_hook_display_path, pre_hook_display_path, set_verbosity,
+ terminate_output, to_logical_path, was_cwd_removed,
};
// Re-export output handlers
pub(crate) use handlers::{
- execute_shell_command, execute_user_command, handle_remove_output, handle_switch_output,
+ DirectivePassthrough, execute_shell_command, execute_user_command, handle_remove_output,
+ handle_switch_output,
};
// Re-export shell integration functions
pub(crate) use shell_integration::{
diff --git a/src/shell/detection.rs b/src/shell/detection.rs
index a81531700..d00f3ab9e 100644
--- a/src/shell/detection.rs
+++ b/src/shell/detection.rs
@@ -73,7 +73,7 @@ use super::paths::{home_dir_required, powershell_profile_paths};
///
/// Detection is ONLY used when shell integration is NOT active (i.e., user ran
/// the binary directly without the shell wrapper). Once the shell wrapper is
-/// active (after shell restart), `WORKTRUNK_DIRECTIVE_FILE` is set and no
+/// active (after shell restart), `WORKTRUNK_DIRECTIVE_CD_FILE` is set and no
/// detection is needed.
///
/// **When binary is run directly (wrapper not active):**
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
index 198621824..94c7cbe9b 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
@@ -7,8 +7,8 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override wt command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -18,7 +18,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -26,24 +26,38 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
index 8fd83aaa8..841ad889e 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
@@ -7,15 +7,9 @@ expression: output
# This is the full function definition, output by `wt config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/wt.fish.
-# Override wt command with file-based directive passing.
-# Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, evals it after.
+# Override wt command with split directive passing.
+# Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
-#
-# Note: We use `eval (string collect < file)` instead of `source` because
-# fish's `source` doesn't propagate exit codes to the parent function.
-# We read the directive with `string collect` (builtin) instead of `cat`
-# (external) to avoid spawning a subprocess whose CWD may have been renamed
-# by worktree removal.
function wt
set -l use_source false
set -l args
@@ -29,27 +23,41 @@ function wt
echo "wt: command not found" >&2
return 127
end
- set -l directive_file (mktemp)
+ set -l cd_file (mktemp)
+ set -l exec_file (mktemp)
# --source: use cargo run (builds from source)
if test $use_source = true
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file cargo run --bin wt --quiet -- $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ cargo run --bin wt --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file $WORKTRUNK_BIN $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ $WORKTRUNK_BIN $args
end
set -l exit_code $status
- if test -s "$directive_file"
- # Use fish builtin instead of cat to avoid spawning a subprocess
- # whose CWD may have been renamed by worktree removal.
- set -l directive (string collect < "$directive_file")
+ # cd file holds a raw path — read with fish builtin (no cat subprocess,
+ # safe even if CWD was removed by worktree removal).
+ if test -s "$cd_file"
+ set -l target (string trim < "$cd_file")
+ cd -- "$target"
+ set -l cd_exit $status
+ if test $exit_code -eq 0
+ set exit_code $cd_exit
+ end
+ end
+
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if test -s "$exec_file"
+ set -l directive (string collect < "$exec_file")
eval $directive
+ set -l src_exit $status
if test $exit_code -eq 0
- set exit_code $status
+ set exit_code $src_exit
end
end
- command rm -f "$directive_file"
+ command rm -f "$cd_file" "$exec_file"
return $exit_code
end
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
index c8d8951f7..c53dd70ac 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
@@ -39,13 +39,10 @@ export def "nu-complete wt" [context: string] {
}
}
-# Override wt command with file-based directive passing.
-# Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, executes directives after.
+# Override wt command with split directive passing.
+# Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
#
-# Note: Nushell's `source` is parse-time only, so we can't source dynamic paths.
-# Instead, we read the directive file and execute each line.
-#
# Nushell pipeline workaround (nushell/nushell#12643):
#
# In POSIX shells, pipes are file-descriptor plumbing — stdout flows through
@@ -62,7 +59,7 @@ export def "nu-complete wt" [context: string] {
# - `list`: Direct passthrough. The binary is the last expression, so stdout
# streams to the terminal (progressive rendering) and flows through pipes
# (`wt list --format json | from json`). No directive processing — `list`
-# never emits directives. No WORKTRUNK_DIRECTIVE_FILE is set.
+# never emits directives. No directive env vars are set.
#
# - Everything else: Stdout is redirected to a temp file via `o>`, then
# returned as the function's last expression after directive processing.
@@ -96,14 +93,15 @@ export def --env --wrapped wt [...args: string@"nu-complete wt"] {
# terminal and flows through nushell pipelines.
^$worktrunk_bin ...$args
} else {
- let directive_file = (mktemp --tmpdir)
+ let cd_file = (mktemp --tmpdir)
+ let exec_file = (mktemp --tmpdir)
let stdout_file = (mktemp --tmpdir)
# Capture stdout to file for pipeline passthrough; stderr flows to terminal.
# Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).
# `try` catches it so directive processing and temp file cleanup still run.
let exit_code = (try {
- with-env { WORKTRUNK_DIRECTIVE_FILE: $directive_file } {
+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file, WORKTRUNK_DIRECTIVE_EXEC_FILE: $exec_file } {
^$worktrunk_bin ...$args o> $stdout_file
}
0
@@ -111,30 +109,26 @@ export def --env --wrapped wt [...args: string@"nu-complete wt"] {
$env.LAST_EXIT_CODE
})
- # Process directive file line by line
- if ($directive_file | path exists) and (open $directive_file --raw | str trim | is-not-empty) {
- let directives = open $directive_file --raw | str trim | lines
+ # cd file holds a raw path — no shell parsing needed
+ if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {
+ let target_dir = open $cd_file --raw | str trim
+ cd $target_dir
+ }
+
+ # exec file holds arbitrary shell (e.g. from --execute).
+ # Execute via sh for POSIX shell expansion (globs, pipes, $VAR).
+ # Env changes (export) won't persist in the nushell session, but no
+ # worktrunk code emits export directives.
+ if ($exec_file | path exists) and (open $exec_file --raw | str trim | is-not-empty) {
+ let directives = open $exec_file --raw | str trim | lines
for directive in $directives {
- if ($directive | str starts-with "cd '") {
- # Parse cd command: worktrunk emits "cd '<path>'" with POSIX quoting.
- # Strip the "cd '" prefix and trailing "'" to extract the raw path.
- # Note: paths with embedded single quotes use POSIX '\'' escaping,
- # which this doesn't handle. A future improvement could have worktrunk
- # emit raw paths instead of POSIX shell commands, letting each shell
- # construct its native cd syntax.
- let target_dir = $directive | str substring 4..-2
- cd $target_dir
- } else if ($directive | is-not-empty) {
- # Execute via sh for POSIX shell expansion (globs, pipes, $VAR).
- # --execute commands are user-provided shell expressions that expect
- # this. Env changes (export) won't persist in the nushell session,
- # but no worktrunk code emits export directives.
+ if ($directive | is-not-empty) {
^sh -c $directive
}
}
}
- rm -f $directive_file
+ rm -f $cd_file $exec_file
let output = (open $stdout_file --raw)
rm -f $stdout_file
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
index cfb102059..78875998d 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
@@ -12,7 +12,7 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
- # wt wrapper function - uses temp file for directives
+ # wt wrapper function - uses split temp files for directives
#
# IMPORTANT: This function must remain a "simple function" (no [CmdletBinding()] or
# [Parameter()] attributes). Advanced functions add common parameters like -Debug,
@@ -29,28 +29,43 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
$wtBin = (Get-Command wt -CommandType Application | Select-Object -First 1).Source
}
- $directiveFile = [System.IO.Path]::GetTempFileName()
+ $cdFile = [System.IO.Path]::GetTempFileName()
+ $execFile = [System.IO.Path]::GetTempFileName()
try {
- # Run wt with WORKTRUNK_DIRECTIVE_FILE env var
- # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping
- $env:WORKTRUNK_DIRECTIVE_FILE = $directiveFile
+ # Run wt with split directive env vars
+ # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping (legacy compat)
+ $env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
+ $env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
$env:WORKTRUNK_SHELL = "powershell"
& $wtBin @args
$exitCode = $LASTEXITCODE
}
finally {
- Remove-Item Env:\WORKTRUNK_DIRECTIVE_FILE -ErrorAction SilentlyContinue
+ Remove-Item Env:\WORKTRUNK_DIRECTIVE_CD_FILE -ErrorAction SilentlyContinue
+ Remove-Item Env:\WORKTRUNK_DIRECTIVE_EXEC_FILE -ErrorAction SilentlyContinue
Remove-Item Env:\WORKTRUNK_SHELL -ErrorAction SilentlyContinue
}
- # Execute the directive script if it has content
+ # Process directive files and clean up in a single try/finally so both
+ # temp files are removed even if cd or exec throws.
try {
- if ((Test-Path $directiveFile) -and (Get-Item $directiveFile).Length -gt 0) {
- $script = Get-Content -Path $directiveFile -Raw
+ # cd file holds a raw path (no shell escaping needed)
+ if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
+ $target = (Get-Content -Path $cdFile -Raw).Trim()
+ if ($target) {
+ Set-Location -LiteralPath $target
+ if ($exitCode -eq 0) {
+ $exitCode = $LASTEXITCODE
+ }
+ }
+ }
+
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if ((Test-Path $execFile) -and (Get-Item $execFile).Length -gt 0) {
+ $script = Get-Content -Path $execFile -Raw
if ($script.Trim()) {
Invoke-Expression $script
- # If wt succeeded, use the directive script's exit code
if ($exitCode -eq 0) {
$exitCode = $LASTEXITCODE
}
@@ -58,8 +73,8 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
}
}
finally {
- # Cleanup even if Invoke-Expression throws
- Remove-Item $directiveFile -ErrorAction SilentlyContinue
+ Remove-Item $cdFile -ErrorAction SilentlyContinue
+ Remove-Item $execFile -ErrorAction SilentlyContinue
}
# Propagate exit code so $? and $LASTEXITCODE are consistent for scripts/CI
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
index 9dc5ab6ca..d6a97effe 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
@@ -10,8 +10,8 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override wt command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -21,7 +21,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -29,24 +29,38 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
index 5cee88fac..c1e864cac 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
@@ -7,8 +7,8 @@ expression: "init.generate().expect(\"Should generate with custom prefix\")"
# Only initialize if custom is available (in PATH or via WORKTRUNK_BIN)
if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override custom command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override custom command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
custom() {
local use_source=false
@@ -18,7 +18,7 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -26,24 +26,38 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin custom --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ cargo run --bin custom --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-custom}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command "${WORKTRUNK_BIN:-custom}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/src/shell/utils.rs b/src/shell/utils.rs
index 4e26ae59c..eaf746eb4 100644
--- a/src/shell/utils.rs
+++ b/src/shell/utils.rs
@@ -123,8 +123,8 @@ pub fn detect_zsh_compinit() -> Option<bool> {
log::debug!("$ zsh -ic '{}' (probe)", probe_cmd);
- let mut child = Command::new("zsh")
- .arg("-ic")
+ let mut cmd = Command::new("zsh");
+ cmd.arg("-ic")
.arg(probe_cmd)
.stdin(Stdio::null()) // Prevent compinit from prompting interactively
.stdout(Stdio::piped())
@@ -146,11 +146,9 @@ pub fn detect_zsh_compinit() -> Option<bool> {
//
// Safe to suppress because we're only probing shell state, not doing anything
// security-sensitive, and this only affects our subprocess.
- .env("ZSH_DISABLE_COMPFIX", "true")
- // Prevent subprocesses from writing to the directive file
- .env_remove(crate::shell_exec::DIRECTIVE_FILE_ENV_VAR)
- .spawn()
- .ok()?;
+ .env("ZSH_DISABLE_COMPFIX", "true");
+ crate::shell_exec::scrub_directive_env_vars(&mut cmd);
+ let mut child = cmd.spawn().ok()?;
let timeout = Duration::from_secs(2);
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index c3ef0d9b2..8f2192271 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -270,10 +270,42 @@ fn find_git_bash() -> Option<PathBuf> {
None
}
-/// Environment variable removed from spawned subprocesses for security.
-/// Hooks and other child processes should not be able to write to the directive file.
+/// Environment variable naming the directive file for `cd` path changes.
+///
+/// Shell wrappers set this to a temp file; wt writes a raw absolute path to
+/// it (one line, no shell escaping). The wrapper `cd`s to that path after wt
+/// exits. Because the file contents are a literal path, there is no shell
+/// injection surface — this is safe to pass through to alias/hook shell bodies.
+pub const DIRECTIVE_CD_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_CD_FILE";
+
+/// Environment variable naming the directive file for arbitrary exec commands.
+///
+/// Shell wrappers set this to a temp file; wt writes shell commands (e.g. the
+/// body of `wt switch --execute`) to it and the wrapper sources the file after
+/// wt exits, so the command runs in the user's interactive shell. Because the
+/// file contents are arbitrary shell, wt scrubs this from alias/hook child
+/// environments — a hook body writing to this file could inject shell into
+/// the parent shell. Only trusted wt-internal callers write to it.
+pub const DIRECTIVE_EXEC_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_EXEC_FILE";
+
+/// Legacy pre-split directive file env var. Honored for one release so users
+/// who upgraded `wt` without restarting their shell still get shell integration
+/// from their current session's old wrapper. When only this is set (no new
+/// vars), wt writes shell-format directives to it. Remove in the next breaking
+/// release.
pub const DIRECTIVE_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_FILE";
+/// Scrub all directive file env vars from a `std::process::Command`.
+///
+/// Prevents child processes from writing to the parent shell's directive
+/// files. Called by every code path that spawns external commands (Cmd,
+/// help pager, picker pager, background hooks, git credential helpers).
+pub fn scrub_directive_env_vars(cmd: &mut std::process::Command) {
+ cmd.env_remove(DIRECTIVE_CD_FILE_ENV_VAR);
+ cmd.env_remove(DIRECTIVE_EXEC_FILE_ENV_VAR);
+ cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
+}
+
// ============================================================================
// Thread-Local Command Timeout
// ============================================================================
@@ -463,10 +495,16 @@ 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>,
+ /// When set, re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` after the security scrub
+ /// in `apply_common_settings`. Used by aliases and foreground hooks — their
+ /// shell bodies may emit cd directives (the file holds a raw path, no shell
+ /// injection surface). `WORKTRUNK_DIRECTIVE_EXEC_FILE` is NEVER re-added,
+ /// so alias/hook bodies cannot inject arbitrary shell into the parent.
+ directive_cd_file: Option<std::path::PathBuf>,
+ /// When set, re-adds the legacy `WORKTRUNK_DIRECTIVE_FILE` env var. Used in
+ /// legacy-wrapper compat mode to preserve pre-split behavior for alias/hook
+ /// bodies running under an old shell wrapper.
+ directive_legacy_file: Option<std::path::PathBuf>,
}
struct ExternalCommandLog {
@@ -509,7 +547,8 @@ impl Cmd {
stdin_cfg: None,
forward_signals: false,
external_label: None,
- directive_file: None,
+ directive_cd_file: None,
+ directive_legacy_file: None,
}
}
@@ -566,8 +605,11 @@ impl Cmd {
}
// Prevent subprocesses from writing shell directives (security).
- // Applied last to ensure it can't be re-added by user-provided envs.
- cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
+ // Applied last so it can't be re-added by user-provided envs.
+ // `stream()` selectively re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` (and
+ // the legacy var, in compat mode) for trusted contexts — but never
+ // `WORKTRUNK_DIRECTIVE_EXEC_FILE`, which carries arbitrary shell.
+ scrub_directive_env_vars(cmd);
}
fn log_run_start(&self, cmd_str: &str) {
@@ -690,13 +732,30 @@ impl Cmd {
self
}
- /// Pass the directive file through to the child process.
+ /// Pass the CD 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());
+ /// By default, `Cmd` scrubs all directive file env vars from child
+ /// processes. This re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` for trusted
+ /// contexts (aliases, foreground hooks) where the child should be able
+ /// to request a directory change. It is always safe to pass through: the
+ /// file holds a raw path, not shell, so there is no injection surface.
+ ///
+ /// `WORKTRUNK_DIRECTIVE_EXEC_FILE` is intentionally *not* exposed by any
+ /// `Cmd` method — only wt-internal Rust code writes arbitrary shell
+ /// directives, so no child process ever needs the env var.
+ pub fn directive_cd_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
+ self.directive_cd_file = Some(path.into());
+ self
+ }
+
+ /// Pass the legacy (pre-split) directive file through to the child process.
+ ///
+ /// Used only in legacy-wrapper compat mode. Preserves pre-split behavior
+ /// for alias/hook bodies running under an old shell wrapper that still
+ /// sets `WORKTRUNK_DIRECTIVE_FILE`. Remove together with the legacy env
+ /// var in the next breaking release.
+ pub fn directive_legacy_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
+ self.directive_legacy_file = Some(path.into());
self
}
@@ -716,8 +775,8 @@ impl Cmd {
"Cmd::shell() commands must use .stream(), not .run()"
);
debug_assert!(
- self.directive_file.is_none(),
- "directive_file is only applied by .stream(), not .run()"
+ self.directive_cd_file.is_none() && self.directive_legacy_file.is_none(),
+ "directive_*_file is only applied by .stream(), not .run()"
);
let cmd_str = self.command_string();
@@ -862,8 +921,13 @@ 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 {
+ // Re-add directive files after security scrub for trusted contexts.
+ // CD file is always safe to pass through (raw path, no shell). EXEC
+ // file is never re-added — alias/hook bodies must not inject shell.
+ if let Some(ref path) = self.directive_cd_file {
+ cmd.env(DIRECTIVE_CD_FILE_ENV_VAR, path);
+ }
+ if let Some(ref path) = self.directive_legacy_file {
cmd.env(DIRECTIVE_FILE_ENV_VAR, path);
}
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index 2a68f95af..5b227540d 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -505,32 +505,58 @@ pub trait TestRepoBase {
}
}
-/// Create a temporary file for directive output.
+/// Create a pair of temporary files for directive output (cd + exec).
///
-/// The shell wrapper sets WORKTRUNK_DIRECTIVE_FILE to a temp file before running wt.
-/// Use `configure_directive_file()` to set this on a Command for testing.
+/// The shell wrapper creates temp files and sets `WORKTRUNK_DIRECTIVE_CD_FILE`
+/// and `WORKTRUNK_DIRECTIVE_EXEC_FILE` before running wt. Use
+/// `configure_directive_files()` to set these on a Command for testing.
///
-/// Returns a tuple of (path, guard). The guard must be kept alive for the duration
-/// of the test - when dropped, the temp file is cleaned up.
-pub fn directive_file() -> (PathBuf, tempfile::TempPath) {
- // Create temp file that persists until guard is dropped
- let file = tempfile::NamedTempFile::new().expect("failed to create temp file");
+/// Returns `(cd_path, exec_path, guards)`. The guards must be kept alive for
+/// the duration of the test — when dropped the temp files are cleaned up.
+pub fn directive_files() -> (PathBuf, PathBuf, (tempfile::TempPath, tempfile::TempPath)) {
+ let cd = tempfile::NamedTempFile::new().expect("failed to create cd temp file");
+ let exec = tempfile::NamedTempFile::new().expect("failed to create exec temp file");
+ let cd_path = cd.path().to_path_buf();
+ let exec_path = exec.path().to_path_buf();
+ (
+ cd_path,
+ exec_path,
+ (cd.into_temp_path(), exec.into_temp_path()),
+ )
+}
- // Get the path before we persist
- let path = file.path().to_path_buf();
+/// Configure a Command to use the new split directive-file protocol.
+///
+/// Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE` env
+/// vars so the wt binary writes a raw path to the cd file and arbitrary shell
+/// to the exec file.
+pub fn configure_directive_files(cmd: &mut Command, cd_path: &Path, exec_path: &Path) {
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
+ cmd.env("WORKTRUNK_DIRECTIVE_EXEC_FILE", exec_path);
+}
- // Convert to TempPath - file persists until TempPath is dropped
- let guard = file.into_temp_path();
+/// Configure a Command to use the split directive-file protocol with only the
+/// CD file (EXEC scrubbed). This simulates running inside an alias/hook body
+/// where the EXEC env var was stripped.
+pub fn configure_directive_cd_only(cmd: &mut Command, cd_path: &Path) {
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
+}
- (path, guard)
+/// Create a temporary file for legacy single-file directive output.
+///
+/// Used to test the legacy fallback path where an old shell wrapper sets
+/// `WORKTRUNK_DIRECTIVE_FILE`. Returns `(path, guard)`.
+pub fn legacy_directive_file() -> (PathBuf, tempfile::TempPath) {
+ let file = tempfile::NamedTempFile::new().expect("failed to create temp file");
+ let path = file.path().to_path_buf();
+ (path, file.into_temp_path())
}
-/// Configure a Command to use directive file mode.
+/// Configure a Command to use the legacy single-file directive protocol.
///
-/// Sets the WORKTRUNK_DIRECTIVE_FILE environment variable to the given path.
-/// The wt binary will write shell directives (like cd) to this file instead of
-/// executing them directly.
-pub fn configure_directive_file(cmd: &mut Command, path: &Path) {
+/// Sets `WORKTRUNK_DIRECTIVE_FILE` env var (no new vars) to simulate an
+/// outdated shell wrapper that hasn't been updated to the split protocol.
+pub fn configure_legacy_directive_file(cmd: &mut Command, path: &Path) {
cmd.env("WORKTRUNK_DIRECTIVE_FILE", path);
}
diff --git a/templates/bash.sh b/templates/bash.sh
index 4a37faf60..b6521c683 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -3,8 +3,8 @@
# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override {{ cmd }} command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override {{ cmd }} command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
{{ cmd }}() {
local use_source=false
@@ -14,7 +14,7 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -22,24 +22,38 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/templates/fish.fish b/templates/fish.fish
index e4d3e1f15..fb9e31b78 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -3,15 +3,9 @@
# This is the full function definition, output by `{{ cmd }} config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/{{ cmd }}.fish.
-# Override {{ cmd }} command with file-based directive passing.
-# Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, evals it after.
+# Override {{ cmd }} command with split directive passing.
+# Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
-#
-# Note: We use `eval (string collect < file)` instead of `source` because
-# fish's `source` doesn't propagate exit codes to the parent function.
-# We read the directive with `string collect` (builtin) instead of `cat`
-# (external) to avoid spawning a subprocess whose CWD may have been renamed
-# by worktree removal.
function {{ cmd }}
set -l use_source false
set -l args
@@ -25,27 +19,41 @@ function {{ cmd }}
echo "{{ cmd }}: command not found" >&2
return 127
end
- set -l directive_file (mktemp)
+ set -l cd_file (mktemp)
+ set -l exec_file (mktemp)
# --source: use cargo run (builds from source)
if test $use_source = true
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file cargo run --bin {{ cmd }} --quiet -- $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ cargo run --bin {{ cmd }} --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file $WORKTRUNK_BIN $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ $WORKTRUNK_BIN $args
end
set -l exit_code $status
- if test -s "$directive_file"
- # Use fish builtin instead of cat to avoid spawning a subprocess
- # whose CWD may have been renamed by worktree removal.
- set -l directive (string collect < "$directive_file")
+ # cd file holds a raw path — read with fish builtin (no cat subprocess,
+ # safe even if CWD was removed by worktree removal).
+ if test -s "$cd_file"
+ set -l target (string trim < "$cd_file")
+ cd -- "$target"
+ set -l cd_exit $status
+ if test $exit_code -eq 0
+ set exit_code $cd_exit
+ end
+ end
+
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if test -s "$exec_file"
+ set -l directive (string collect < "$exec_file")
eval $directive
+ set -l src_exit $status
if test $exit_code -eq 0
- set exit_code $status
+ set exit_code $src_exit
end
end
- command rm -f "$directive_file"
+ command rm -f "$cd_file" "$exec_file"
return $exit_code
end
diff --git a/templates/nushell.nu b/templates/nushell.nu
index 2e023f353..eab12095d 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -35,13 +35,10 @@ export def "nu-complete {{ cmd }}" [context: string] {
}
}
-# Override {{ cmd }} command with file-based directive passing.
-# Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, executes directives after.
+# Override {{ cmd }} command with split directive passing.
+# Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
#
-# Note: Nushell's `source` is parse-time only, so we can't source dynamic paths.
-# Instead, we read the directive file and execute each line.
-#
# Nushell pipeline workaround (nushell/nushell#12643):
#
# In POSIX shells, pipes are file-descriptor plumbing — stdout flows through
@@ -58,7 +55,7 @@ export def "nu-complete {{ cmd }}" [context: string] {
# - `list`: Direct passthrough. The binary is the last expression, so stdout
# streams to the terminal (progressive rendering) and flows through pipes
# (`{{ cmd }} list --format json | from json`). No directive processing — `list`
-# never emits directives. No WORKTRUNK_DIRECTIVE_FILE is set.
+# never emits directives. No directive env vars are set.
#
# - Everything else: Stdout is redirected to a temp file via `o>`, then
# returned as the function's last expression after directive processing.
@@ -92,14 +89,15 @@ export def --env --wrapped {{ cmd }} [...args: string@"nu-complete {{ cmd }}"] {
# terminal and flows through nushell pipelines.
^$worktrunk_bin ...$args
} else {
- let directive_file = (mktemp --tmpdir)
+ let cd_file = (mktemp --tmpdir)
+ let exec_file = (mktemp --tmpdir)
let stdout_file = (mktemp --tmpdir)
# Capture stdout to file for pipeline passthrough; stderr flows to terminal.
# Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).
# `try` catches it so directive processing and temp file cleanup still run.
let exit_code = (try {
- with-env { WORKTRUNK_DIRECTIVE_FILE: $directive_file } {
+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file, WORKTRUNK_DIRECTIVE_EXEC_FILE: $exec_file } {
^$worktrunk_bin ...$args o> $stdout_file
}
0
@@ -107,30 +105,26 @@ export def --env --wrapped {{ cmd }} [...args: string@"nu-complete {{ cmd }}"] {
$env.LAST_EXIT_CODE
})
- # Process directive file line by line
- if ($directive_file | path exists) and (open $directive_file --raw | str trim | is-not-empty) {
- let directives = open $directive_file --raw | str trim | lines
+ # cd file holds a raw path — no shell parsing needed
+ if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {
+ let target_dir = open $cd_file --raw | str trim
+ cd $target_dir
+ }
+
+ # exec file holds arbitrary shell (e.g. from --execute).
+ # Execute via sh for POSIX shell expansion (globs, pipes, $VAR).
+ # Env changes (export) won't persist in the nushell session, but no
+ # worktrunk code emits export directives.
+ if ($exec_file | path exists) and (open $exec_file --raw | str trim | is-not-empty) {
+ let directives = open $exec_file --raw | str trim | lines
for directive in $directives {
- if ($directive | str starts-with "cd '") {
- # Parse cd command: worktrunk emits "cd '<path>'" with POSIX quoting.
- # Strip the "cd '" prefix and trailing "'" to extract the raw path.
- # Note: paths with embedded single quotes use POSIX '\'' escaping,
- # which this doesn't handle. A future improvement could have worktrunk
- # emit raw paths instead of POSIX shell commands, letting each shell
- # construct its native cd syntax.
- let target_dir = $directive | str substring 4..-2
- cd $target_dir
- } else if ($directive | is-not-empty) {
- # Execute via sh for POSIX shell expansion (globs, pipes, $VAR).
- # --execute commands are user-provided shell expressions that expect
- # this. Env changes (export) won't persist in the nushell session,
- # but no worktrunk code emits export directives.
+ if ($directive | is-not-empty) {
^sh -c $directive
}
}
}
- rm -f $directive_file
+ rm -f $cd_file $exec_file
let output = (open $stdout_file --raw)
rm -f $stdout_file
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index 13b422f94..a3091d899 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -8,7 +8,7 @@
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
- # wt wrapper function - uses temp file for directives
+ # wt wrapper function - uses split temp files for directives
#
# IMPORTANT: This function must remain a "simple function" (no [CmdletBinding()] or
# [Parameter()] attributes). Advanced functions add common parameters like -Debug,
@@ -25,28 +25,43 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
$wtBin = (Get-Command {{ cmd }} -CommandType Application | Select-Object -First 1).Source
}
- $directiveFile = [System.IO.Path]::GetTempFileName()
+ $cdFile = [System.IO.Path]::GetTempFileName()
+ $execFile = [System.IO.Path]::GetTempFileName()
try {
- # Run wt with WORKTRUNK_DIRECTIVE_FILE env var
- # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping
- $env:WORKTRUNK_DIRECTIVE_FILE = $directiveFile
+ # Run wt with split directive env vars
+ # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping (legacy compat)
+ $env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
+ $env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
$env:WORKTRUNK_SHELL = "powershell"
& $wtBin @args
$exitCode = $LASTEXITCODE
}
finally {
- Remove-Item Env:\WORKTRUNK_DIRECTIVE_FILE -ErrorAction SilentlyContinue
+ Remove-Item Env:\WORKTRUNK_DIRECTIVE_CD_FILE -ErrorAction SilentlyContinue
+ Remove-Item Env:\WORKTRUNK_DIRECTIVE_EXEC_FILE -ErrorAction SilentlyContinue
Remove-Item Env:\WORKTRUNK_SHELL -ErrorAction SilentlyContinue
}
- # Execute the directive script if it has content
+ # Process directive files and clean up in a single try/finally so both
+ # temp files are removed even if cd or exec throws.
try {
- if ((Test-Path $directiveFile) -and (Get-Item $directiveFile).Length -gt 0) {
- $script = Get-Content -Path $directiveFile -Raw
+ # cd file holds a raw path (no shell escaping needed)
+ if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
+ $target = (Get-Content -Path $cdFile -Raw).Trim()
+ if ($target) {
+ Set-Location -LiteralPath $target
+ if ($exitCode -eq 0) {
+ $exitCode = $LASTEXITCODE
+ }
+ }
+ }
+
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if ((Test-Path $execFile) -and (Get-Item $execFile).Length -gt 0) {
+ $script = Get-Content -Path $execFile -Raw
if ($script.Trim()) {
Invoke-Expression $script
- # If wt succeeded, use the directive script's exit code
if ($exitCode -eq 0) {
$exitCode = $LASTEXITCODE
}
@@ -54,8 +69,8 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
}
}
finally {
- # Cleanup even if Invoke-Expression throws
- Remove-Item $directiveFile -ErrorAction SilentlyContinue
+ Remove-Item $cdFile -ErrorAction SilentlyContinue
+ Remove-Item $execFile -ErrorAction SilentlyContinue
}
# Propagate exit code so $? and $LASTEXITCODE are consistent for scripts/CI
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index 1ef4ce12c..53a01ab49 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -6,8 +6,8 @@
# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override {{ cmd }} command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override {{ cmd }} command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
{{ cmd }}() {
local use_source=false
@@ -17,7 +17,7 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -25,24 +25,38 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 7e0325d2b..194c0e67d 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -531,6 +531,11 @@ pub fn add_standard_env_redactions(settings: &mut insta::Settings) {
settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");
settings.add_redaction(".env.WORKTRUNK_SYSTEM_CONFIG_PATH", "[TEST_SYSTEM_CONFIG]");
settings.add_redaction(".env.WORKTRUNK_APPROVALS_PATH", "[TEST_APPROVALS]");
+ settings.add_redaction(".env.WORKTRUNK_DIRECTIVE_CD_FILE", "[DIRECTIVE_CD_FILE]");
+ settings.add_redaction(
+ ".env.WORKTRUNK_DIRECTIVE_EXEC_FILE",
+ "[DIRECTIVE_EXEC_FILE]",
+ );
settings.add_redaction(".env.WORKTRUNK_DIRECTIVE_FILE", "[DIRECTIVE_FILE]");
settings.add_redaction(".env.HOME", "[TEST_HOME]");
// Windows: the `home` crate uses USERPROFILE for home_dir()
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index db1f8bb20..4173ec3cd 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -1,6 +1,6 @@
use crate::common::{
- BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_file,
- configure_git_cmd, configure_git_env, directive_file, repo, setup_temp_snapshot_settings,
+ BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_files,
+ configure_git_cmd, configure_git_env, directive_files, repo, setup_temp_snapshot_settings,
wait_for, wait_for_file, wait_for_file_content, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
@@ -64,10 +64,10 @@ fn test_bare_repo_switch_creates_worktree() {
// Run wt switch --create to create a new worktree
// Config uses {{ branch }} template, so worktrees are created inside bare repo
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
@@ -111,10 +111,10 @@ fn test_bare_repo_switch_with_configured_naming() {
test.commit_in(&main_worktree, "Initial commit");
// Config uses "{{ branch }}" template, so worktrees are created inside bare repo
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
@@ -149,10 +149,10 @@ fn test_bare_repo_remove_worktree() {
test.commit_in(&feature_worktree, "Feature work");
// Remove feature worktree from main worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["remove", "feature", "--foreground"])
.current_dir(&main_worktree);
@@ -208,10 +208,10 @@ fn test_bare_repo_path_used_for_worktree_paths() {
// Create new worktree - config uses {{ branch }} template
// Worktrees are created inside the bare repo directory
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "dev"])
.current_dir(&main_worktree);
@@ -252,10 +252,10 @@ fn test_bare_repo_with_repo_path_variable() {
test.commit_in(&main_worktree, "Initial commit");
// Create new worktree using wt switch
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature/auth"])
.current_dir(&main_worktree);
@@ -613,10 +613,10 @@ fn test_bare_repo_merge_workflow() {
// Create feature branch worktree using wt switch
// Config uses {{ branch }} template, so worktrees are inside bare repo
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -629,10 +629,10 @@ fn test_bare_repo_merge_workflow() {
test.commit_in(&feature_worktree, "Feature work");
// Merge feature into main (explicitly specify target)
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args([
"merge",
"main", // Explicitly specify target branch
@@ -686,10 +686,10 @@ fn test_bare_repo_background_logs_location() {
test.commit_in(&feature_worktree, "Feature work");
// Run remove in background to test log file location
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["remove", "feature"]).current_dir(&main_worktree);
let output = cmd.output().unwrap();
@@ -765,10 +765,10 @@ fn test_bare_repo_project_config_found_from_bare_root() {
// Now run `wt switch --create feature` from the bare repo root (NOT from main worktree)
// This is the scenario described in #1691
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(test.bare_repo_path());
@@ -827,10 +827,10 @@ fn test_bare_repo_project_config_found_with_dash_c_flag() {
// Run from a completely unrelated directory using -C to point at the bare repo
let unrelated_dir = tempfile::tempdir().unwrap();
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args([
"-C",
test.bare_repo_path().to_str().unwrap(),
@@ -885,10 +885,10 @@ fn test_bare_repo_ignores_config_in_bare_root() {
.unwrap();
// Run `wt switch --create feature` from the bare repo root
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(test.bare_repo_path());
@@ -926,10 +926,10 @@ fn test_bare_repo_slashed_branch_with_sanitize() {
test.commit_in(&main_worktree, "Initial commit");
// Create feature branch with slash using wt switch
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature/auth"])
.current_dir(&main_worktree);
@@ -1138,10 +1138,10 @@ fn test_nested_bare_repo_worktree_path() {
let test = NestedBareRepoTest::new();
// Create first worktree using wt switch --create
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
@@ -1176,10 +1176,10 @@ fn test_nested_bare_repo_full_workflow() {
let test = NestedBareRepoTest::new();
// Create main worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
cmd.output().unwrap();
@@ -1189,10 +1189,10 @@ fn test_nested_bare_repo_full_workflow() {
test.commit_in(&main_worktree, "Initial");
// Create feature worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1215,10 +1215,10 @@ fn test_nested_bare_repo_full_workflow() {
assert!(stdout.contains("feature"), "Should list feature worktree");
// Remove feature worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["remove", "feature", "--foreground"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1235,10 +1235,10 @@ fn test_nested_bare_repo_list_snapshot() {
let test = NestedBareRepoTest::new();
// Create main worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
cmd.output().unwrap();
@@ -1247,10 +1247,10 @@ fn test_nested_bare_repo_list_snapshot() {
test.commit_in(&main_worktree, "Initial");
// Create feature worktree
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1276,10 +1276,10 @@ fn test_bare_repo_bootstrap_first_worktree() {
// Unlike other tests, we do NOT create any worktrees first.
// We run wt switch --create directly on the bare repo.
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
@@ -1427,10 +1427,10 @@ fn test_bare_repo_merge_preserves_default_branch_worktree() {
// Run `wt merge feature` from the main (default branch) worktree.
// This attempts to merge main into feature — the important thing is that
// the main worktree must NOT be removed even though is_linked() returns true.
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args([
"merge",
"feature", // Target = feature branch
@@ -1472,10 +1472,10 @@ fn setup_unconfigured_nested_bare_repo() -> NestedBareRepoTest {
.unwrap();
// Create main worktree with a commit (needed as a starting point for switch)
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "main", "--yes"])
.current_dir(test.bare_repo_path());
let output = cmd.output().unwrap();
@@ -1501,10 +1501,10 @@ fn test_bare_repo_worktree_path_prompt_auto_accept() {
let settings = setup_temp_snapshot_settings(test.temp_path());
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(&main_worktree);
@@ -1535,10 +1535,10 @@ fn test_bare_repo_worktree_path_prompt_non_interactive_warning() {
let settings = setup_temp_snapshot_settings(test.temp_path());
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// No --yes, but stdin is piped (non-interactive) since assert_cmd_snapshot
// doesn't attach a TTY
cmd.args(["switch", "--create", "feature"])
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index bf605eece..950ba14ac 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -2047,7 +2047,7 @@ fn test_config_show_shell_integration_active(mut repo: TestRepo, temp_home: Temp
set_temp_home_env(&mut cmd, temp_home.path());
set_xdg_config_path(&mut cmd, temp_home.path());
// Set WORKTRUNK_DIRECTIVE_FILE to simulate shell integration being active
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
assert_cmd_snapshot!(cmd);
});
@@ -2083,7 +2083,7 @@ fn test_config_show_shell_active_but_not_in_config_file(mut repo: TestRepo, temp
cmd.arg("config").arg("show").current_dir(repo.root_path());
set_temp_home_env(&mut cmd, temp_home.path());
set_xdg_config_path(&mut cmd, temp_home.path());
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
// Set SHELL to zsh so current_shell() returns Some(Zsh)
cmd.env("SHELL", "/bin/zsh");
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index fab6c8cac..1515c3c70 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -1,6 +1,8 @@
use crate::common::{
- TestRepo, configure_directive_file, directive_file, repo, repo_with_feature_worktree,
- repo_with_remote, repo_with_remote_and_feature, setup_snapshot_settings, wt_command,
+ TestRepo, configure_directive_cd_only, configure_directive_files,
+ configure_legacy_directive_file, directive_files, legacy_directive_file, repo,
+ repo_with_feature_worktree, repo_with_remote, repo_with_remote_and_feature,
+ setup_snapshot_settings, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -10,15 +12,24 @@ use std::os::unix::fs as unix_fs;
use std::path::Path;
// ============================================================================
-// Directive File Tests
+// Directive File Tests (split protocol)
// ============================================================================
-// These tests verify that WORKTRUNK_DIRECTIVE_FILE env var causes directives to be
-// written to the file. The shell wrapper sources this file after wt exits.
+// These tests verify the split directive-file protocol:
+// - WORKTRUNK_DIRECTIVE_CD_FILE: wt writes a raw path (no `cd ` prefix, no quotes).
+// The shell wrapper runs `cd -- "$(< file)"`.
+// - WORKTRUNK_DIRECTIVE_EXEC_FILE: wt writes arbitrary shell (e.g. from --execute).
+// The shell wrapper sources the file.
+
+// ============================================================================
+// Legacy Directive File Tests (single WORKTRUNK_DIRECTIVE_FILE)
+// ============================================================================
+// These tests verify the legacy single-file protocol still works for users
+// who haven't restarted their shell after upgrading.
#[rstest]
-fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
+fn test_switch_legacy_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (directive_path, _guard) = legacy_directive_file();
let mut settings = setup_snapshot_settings(&repo);
// Normalize the directive file cd path
@@ -27,46 +38,176 @@ fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_legacy_directive_file(&mut cmd, &directive_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- // Verify directive file contains cd command
+ // Verify directive file contains cd command (legacy format)
let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
assert!(
directives.contains("cd '"),
- "Directive file should contain cd command, got: {}",
+ "Legacy directive file should contain cd command, got: {}",
directives
);
});
}
+/// Legacy directive file in PowerShell mode: single quotes are doubled
+/// instead of using POSIX escaping.
+#[rstest]
+fn test_switch_legacy_directive_file_powershell(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (directive_path, _guard) = legacy_directive_file();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_legacy_directive_file(&mut cmd, &directive_path);
+ cmd.env("WORKTRUNK_SHELL", "powershell");
+ cmd.arg("switch")
+ .arg("feature")
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ directives.contains("cd '"),
+ "Legacy directive file should contain cd command, got: {directives}",
+ );
+ });
+}
+
+/// Legacy directive file with --execute: both cd and execute commands
+/// should be written to the single file.
+#[rstest]
+fn test_switch_legacy_directive_file_with_execute(#[from(repo_with_remote)] repo: TestRepo) {
+ let (directive_path, _guard) = legacy_directive_file();
+
+ let mut settings = setup_snapshot_settings(&repo);
+ settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_legacy_directive_file(&mut cmd, &directive_path);
+ cmd.args([
+ "switch",
+ "--create",
+ "exec-legacy",
+ "--execute",
+ "echo hello",
+ ])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ directives.contains("cd '"),
+ "Legacy directive file should contain cd command, got: {directives}",
+ );
+ assert!(
+ directives.contains("echo hello"),
+ "Legacy directive file should contain execute command, got: {directives}",
+ );
+ });
+}
+
+/// When only the CD file is set (EXEC scrubbed — running inside an alias/hook),
+/// --execute commands are refused with a warning.
+#[rstest]
+fn test_switch_exec_scrubbed_warns(#[from(repo_with_remote)] repo: TestRepo) {
+ let (cd_path, _exec_path, _guard) = directive_files();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ // Only set CD file, not EXEC — simulates running inside alias/hook body
+ configure_directive_cd_only(&mut cmd, &cd_path);
+ cmd.args([
+ "switch",
+ "--create",
+ "scrub-test",
+ "--execute",
+ "echo should-not-run",
+ ])
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+// ============================================================================
+// Split Protocol Tests
+// ============================================================================
+
+#[rstest]
+fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (cd_path, exec_path, _guard) = directive_files();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ cmd.arg("switch")
+ .arg("feature")
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ // Verify cd file contains a raw path (no `cd ` prefix, no quotes)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
+ assert!(
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path, got: {}",
+ cd_content
+ );
+ assert!(
+ !cd_content.contains("cd "),
+ "CD file should contain a raw path (no cd prefix), got: {}",
+ cd_content
+ );
+ });
+}
+
#[rstest]
fn test_merge_directive_file(mut repo_with_remote_and_feature: TestRepo) {
let repo = &mut repo_with_remote_and_feature;
let feature_wt = &repo.worktrees["feature"];
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
- let mut settings = setup_snapshot_settings(repo);
- settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
+ let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("merge").arg("main").current_dir(feature_wt);
assert_cmd_snapshot!(cmd);
- // Verify directive file contains cd command (back to main)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file contains a raw path (back to main)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Directive file should contain cd command, got: {}",
- directives
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path, got: {}",
+ cd_content
+ );
+ assert!(
+ !cd_content.contains("cd "),
+ "CD file should contain a raw path (no cd prefix), got: {}",
+ cd_content
);
});
}
@@ -74,25 +215,29 @@ fn test_merge_directive_file(mut repo_with_remote_and_feature: TestRepo) {
#[rstest]
fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
- let mut settings = setup_snapshot_settings(&repo);
- settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
+ let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("remove").current_dir(&feature_wt);
assert_cmd_snapshot!(cmd);
- // Verify directive file contains cd command (back to main)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file contains a raw path (back to main)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Directive file should contain cd command, got: {}",
- directives
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path, got: {}",
+ cd_content
+ );
+ assert!(
+ !cd_content.contains("cd "),
+ "CD file should contain a raw path (no cd prefix), got: {}",
+ cd_content
);
});
}
@@ -105,7 +250,7 @@ fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
#[rstest]
fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create the same subdirectory in both worktrees
let subdir = "apps/gateway";
@@ -114,7 +259,7 @@ fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path().join(subdir));
@@ -122,16 +267,16 @@ fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let output = cmd.output().unwrap();
assert!(output.status.success(), "wt switch failed: {:?}", output);
- // Verify directive file contains cd to the subdirectory, not the root.
+ // Verify cd file contains path to the subdirectory, not the root.
// Use Path::join for each component so separators are native on Windows.
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
let expected_subdir = feature_wt.join(Path::new("apps").join("gateway"));
let expected_str = expected_subdir.to_string_lossy();
assert!(
- directives.contains(&*expected_str),
- "Directive should cd to subdirectory {}, got: {}",
+ cd_content.contains(&*expected_str),
+ "CD file should contain subdirectory path {}, got: {}",
expected_str,
- directives
+ cd_content
);
}
@@ -140,7 +285,7 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create subdirectory only in the source worktree, not in the target
let subdir = "apps/gateway";
@@ -149,7 +294,7 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path().join(subdir));
@@ -157,30 +302,30 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
let output = cmd.output().unwrap();
assert!(output.status.success(), "wt switch failed: {:?}", output);
- // Verify directive file contains cd to worktree root (not the missing subdir)
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file contains path to worktree root (not the missing subdir)
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
let feature_str = feature_wt.to_string_lossy();
assert!(
- directives.contains(&*feature_str),
- "Directive should cd to worktree root {}, got: {}",
+ cd_content.contains(&*feature_str),
+ "CD file should contain worktree root {}, got: {}",
feature_str,
- directives
+ cd_content
);
// Make sure it doesn't contain the subdir path.
// Use Path::join for each component so separators are native on Windows.
let subdir_path = feature_wt.join(Path::new("apps").join("gateway"));
let subdir_str = subdir_path.to_string_lossy();
assert!(
- !directives.contains(&*subdir_str),
- "Directive should NOT cd to missing subdirectory {}, got: {}",
+ !cd_content.contains(&*subdir_str),
+ "CD file should NOT contain missing subdirectory path {}, got: {}",
subdir_str,
- directives
+ cd_content
);
}
#[rstest]
fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create a subdirectory in the source worktree and commit it so it appears in the new branch
let subdir = "apps/gateway";
@@ -191,7 +336,7 @@ fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo)
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "new-feature"])
.current_dir(repo.root_path().join(subdir));
@@ -200,13 +345,13 @@ fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo)
// The subdirectory was committed, so the new worktree should have it.
// Use Path to construct the expected substring so separators match on Windows.
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
let subdir_suffix = Path::new("apps").join("gateway");
let subdir_str = subdir_suffix.to_string_lossy();
assert!(
- directives.contains(&*subdir_str),
- "New worktree should cd to preserved subdirectory, got: {}",
- directives
+ cd_content.contains(&*subdir_str),
+ "CD file should contain preserved subdirectory path, got: {}",
+ cd_content
);
}
@@ -218,57 +363,57 @@ fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo)
#[rstest]
fn test_switch_no_cd_suppresses_directive(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "feature", "--no-cd"])
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file is empty (no path written with --no-cd)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd, got: {}",
+ cd_content
);
});
}
#[rstest]
fn test_switch_no_cd_create_suppresses_directive(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "--create", "new-feature", "--no-cd"])
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file is empty (no path written with --no-cd)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd, got: {}",
+ cd_content
);
});
}
#[rstest]
fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create project config with a post-switch hook
let config_dir = repo.root_path().join(".config");
@@ -286,33 +431,33 @@ fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo:
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// Use --yes to auto-approve the hook command
cmd.args(["switch", "--create", "hook-test", "--no-cd", "--yes"])
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file is empty (no path written with --no-cd)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd, got: {}",
+ cd_content
);
});
}
#[rstest]
fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// pwd should print the target worktree path, even with --no-cd
cmd.args([
"switch",
@@ -326,12 +471,12 @@ fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] r
assert_cmd_snapshot!(cmd);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file is empty (no path written with --no-cd)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd, got: {}",
+ cd_content
);
});
}
@@ -340,7 +485,7 @@ fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] r
#[rstest]
fn test_switch_no_cd_config_suppresses_directive(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Set up config with cd = false
repo.write_test_config(
@@ -356,18 +501,18 @@ cd = false
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["switch", "feature"])
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file is empty (no path written with cd=false config)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with no-cd config, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with no-cd config, got: {}",
+ cd_content
);
});
}
@@ -408,14 +553,14 @@ fn test_remove_without_directive_file(repo: TestRepo) {
fn test_merge_directive_no_remove(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
let feature_wt = &repo.worktrees["feature"];
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("merge")
.arg("main")
.arg("--no-remove")
@@ -429,25 +574,29 @@ fn test_merge_directive_no_remove(mut repo_with_feature_worktree: TestRepo) {
fn test_merge_directive_remove(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
let feature_wt = &repo.worktrees["feature"];
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
- let mut settings = setup_snapshot_settings(repo);
- settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
+ let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("merge").arg("main").current_dir(feature_wt);
assert_cmd_snapshot!(cmd);
- // Verify directive file contains cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify cd file contains a raw path
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Directive file should contain cd command, got: {}",
- directives
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path, got: {}",
+ cd_content
+ );
+ assert!(
+ !cd_content.contains("cd "),
+ "CD file should contain a raw path (no cd prefix), got: {}",
+ cd_content
);
});
}
@@ -462,7 +611,7 @@ fn test_merge_directive_remove(mut repo_with_feature_worktree: TestRepo) {
#[rstest]
fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create a symlink to the repo's parent directory
let real_parent = repo.root_path().parent().unwrap();
@@ -476,7 +625,7 @@ fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRe
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// Set PWD to the logical (symlink) path — this is what the shell sets
cmd.env("PWD", &logical_cwd);
cmd.arg("switch").arg("feature").current_dir(&logical_cwd);
@@ -488,25 +637,25 @@ fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRe
String::from_utf8_lossy(&output.stderr)
);
- // The directive should use the logical (symlink) path, not the canonical one
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ // The cd file should use the logical (symlink) path, not the canonical one
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
- // The symlink prefix should appear in the directive
+ // The symlink prefix should appear in the cd path
let symlink_prefix = symlink_path.to_string_lossy();
assert!(
- directives.contains(&*symlink_prefix),
- "Directive should use symlink path (containing {}), got: {}",
+ cd_content.contains(&*symlink_prefix),
+ "CD file should use symlink path (containing {}), got: {}",
symlink_prefix,
- directives
+ cd_content
);
// The canonical (real) parent path should NOT appear
let real_prefix = real_parent.to_string_lossy();
assert!(
- !directives.contains(&*real_prefix),
- "Directive should NOT contain canonical path {}, got: {}",
+ !cd_content.contains(&*real_prefix),
+ "CD file should NOT contain canonical path {}, got: {}",
real_prefix,
- directives
+ cd_content
);
// Display messages (stderr) should also use the logical path
@@ -528,7 +677,7 @@ fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRe
#[cfg(unix)]
#[rstest]
fn test_switch_create_preserves_symlink_path(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create a symlink to the repo's parent directory
let real_parent = repo.root_path().parent().unwrap();
@@ -541,7 +690,7 @@ fn test_switch_create_preserves_symlink_path(#[from(repo_with_remote)] repo: Tes
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.env("PWD", &logical_cwd);
cmd.args(["switch", "--create", "new-feature"])
.current_dir(&logical_cwd);
@@ -553,13 +702,13 @@ fn test_switch_create_preserves_symlink_path(#[from(repo_with_remote)] repo: Tes
String::from_utf8_lossy(&output.stderr)
);
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
let symlink_prefix = symlink_path.to_string_lossy();
assert!(
- directives.contains(&*symlink_prefix),
- "Directive should use symlink path (containing {}), got: {}",
+ cd_content.contains(&*symlink_prefix),
+ "CD file should use symlink path (containing {}), got: {}",
symlink_prefix,
- directives
+ cd_content
);
// Display messages (stderr) should also use the logical path
@@ -585,7 +734,7 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
// Create subdirectory in both worktrees
let subdir = "apps/gateway";
@@ -603,7 +752,7 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.env("PWD", &logical_cwd);
cmd.arg("switch").arg("feature").current_dir(&logical_cwd);
@@ -614,24 +763,24 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
String::from_utf8_lossy(&output.stderr)
);
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
// Should use symlink prefix AND preserve subdirectory
let symlink_prefix = symlink_path.to_string_lossy();
assert!(
- directives.contains(&*symlink_prefix),
- "Directive should use symlink path (containing {}), got: {}",
+ cd_content.contains(&*symlink_prefix),
+ "CD file should use symlink path (containing {}), got: {}",
symlink_prefix,
- directives
+ cd_content
);
let subdir_suffix = Path::new("apps").join("gateway");
let subdir_str = subdir_suffix.to_string_lossy();
assert!(
- directives.contains(&*subdir_str),
- "Directive should preserve subdirectory {}, got: {}",
+ cd_content.contains(&*subdir_str),
+ "CD file should preserve subdirectory {}, got: {}",
subdir_str,
- directives
+ cd_content
);
}
@@ -640,13 +789,13 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
fn test_switch_no_symlink_uses_canonical(#[from(repo_with_remote)] mut repo: TestRepo) {
// When PWD matches current_dir (no symlink), canonical path is used as before
let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let canonical_cwd = dunce::canonicalize(repo.root_path()).unwrap();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// Set PWD to canonical (same as current_dir — no symlink)
cmd.env("PWD", &canonical_cwd);
cmd.arg("switch").arg("feature").current_dir(&canonical_cwd);
@@ -658,11 +807,11 @@ fn test_switch_no_symlink_uses_canonical(#[from(repo_with_remote)] mut repo: Tes
String::from_utf8_lossy(&output.stderr)
);
- // Should still have a cd directive (just with canonical path)
- let directives = fs::read_to_string(&directive_path).unwrap_or_default();
+ // Should still have a path in the cd file (just with canonical path)
+ let cd_content = fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Directive file should contain cd command, got: {}",
- directives
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path, got: {}",
+ cd_content
);
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index a0048d15b..230984a70 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -1945,7 +1945,7 @@ fn mock_summary_cache(
/// Generate Quick Start example: `wt switch --create feature-auth` output
///
/// Shows the switch output when creating a new worktree from main.
-/// Sets WORKTRUNK_DIRECTIVE_FILE to simulate shell integration being active,
+/// Sets WORKTRUNK_DIRECTIVE_CD_FILE to simulate shell integration being active,
/// which suppresses the "Cannot change directory" warning.
/// Output: tests/snapshots/integration__integration_tests__list__quickstart_switch.snap
#[rstest]
@@ -1960,7 +1960,7 @@ fn test_quickstart_switch(mut repo: TestRepo) {
std::fs::write(&directive_file, "").unwrap();
assert_cmd_snapshot!("quickstart_switch", {
let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature-auth"], None);
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
cmd
});
}
@@ -1981,7 +1981,7 @@ fn test_quickstart_list(mut repo: TestRepo) {
/// Generate Quick Start example: `wt merge` output
///
/// Shows merge output when merging feature-auth into main.
-/// Sets WORKTRUNK_DIRECTIVE_FILE to simulate shell integration being active,
+/// Sets WORKTRUNK_DIRECTIVE_CD_FILE to simulate shell integration being active,
/// which suppresses the "Cannot change directory" warning.
/// Output: tests/snapshots/integration__integration_tests__list__quickstart_merge.snap
#[rstest]
@@ -2084,7 +2084,7 @@ mod tests {
// Merge feature-auth into main
assert_cmd_snapshot!("quickstart_merge", {
let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_auth));
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
// Set MOCK_CONFIG_DIR so mock-stub can find llm.json
cmd.env("MOCK_CONFIG_DIR", &mock_bin_dir);
// Use to_slash_lossy() for Windows compatibility - bash can't handle backslash paths
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index 6e63adbe7..63d93f3c4 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -1,8 +1,8 @@
//! Guard test to prevent stdout leaks in command code
//!
//! stdout is reserved for data output (e.g., JSON). User-visible messages go to stderr.
-//! When shell integration is active (`WORKTRUNK_DIRECTIVE_FILE` is set), directives are written
-//! to the file, not stdout.
+//! When shell integration is active (directive env vars set), directives are written
+//! to files, not stdout.
//!
//! This test enforces: **No accidental stdout writes in command code**
//!
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 574f41a01..88cc29239 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1,5 +1,5 @@
use crate::common::{
- BareRepoTest, TestRepo, TestRepoBase, configure_directive_file, directive_file,
+ BareRepoTest, TestRepo, TestRepoBase, configure_directive_files, directive_files,
make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
setup_temp_snapshot_settings, wt_command,
};
@@ -41,11 +41,11 @@ fn test_remove_from_worktree(mut repo: TestRepo) {
fn test_remove_internal_mode(mut repo: TestRepo) {
let worktree_path = repo.add_worktree("feature-internal");
- // Directive file guard must live through command execution
- let (directive_path, _guard) = directive_file();
+ // Directive file guards must live through command execution
+ let (cd_path, exec_path, _guard) = directive_files();
assert_cmd_snapshot!({
let mut cmd = make_snapshot_cmd(&repo, "remove", &[], Some(&worktree_path));
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd
});
}
@@ -1683,14 +1683,14 @@ approved-commands = ["exit 1"]
// Create a worktree to remove
let worktree_path = repo.add_worktree("feature-cd-test");
- // Set up directive file
- let (directive_path, _guard) = directive_file();
+ // Set up directive files
+ let (cd_path, exec_path, _guard) = directive_files();
// Run remove from within the worktree (which would trigger cd to main if it worked)
let mut cmd = repo.wt_command();
cmd.args(["remove", "--foreground"]);
cmd.current_dir(&worktree_path);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
let output = cmd.output().unwrap();
// Command should have failed (hook failure)
@@ -1699,12 +1699,12 @@ approved-commands = ["exit 1"]
"Remove should fail when pre-remove hook fails"
);
- // Directive file should be empty (no cd written)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // CD file should be empty (no path written when hook fails)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd "),
- "Directive file should NOT contain cd when hook fails, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty when hook fails, got: {}",
+ cd_content
);
// Worktree should still exist
diff --git a/tests/integration_tests/security.rs b/tests/integration_tests/security.rs
index 1e9c81d98..8fe5ccbb3 100644
--- a/tests/integration_tests/security.rs
+++ b/tests/integration_tests/security.rs
@@ -1,105 +1,57 @@
-//! Security tests for shell script injection vulnerabilities
+//! Security tests for shell injection vulnerabilities
//!
-//! # Attack Surface Analysis
+//! # Security Model: Split Directive Protocol
//!
-//! Worktrunk uses a file-based directive protocol for shell integration. When `WORKTRUNK_DIRECTIVE_FILE`
-//! env var is set (pointing to a temp file), the wt binary:
-//! - Streams all user-visible output (progress, errors, hints) to stderr in real-time
-//! - Writes shell directives (cd commands, exec commands) to the directive file
+//! Worktrunk uses two directive files with different trust levels:
//!
-//! The shell wrapper sources the directive file after wt exits:
-//! ```bash
-//! directive_file="$(mktemp)"
-//! WORKTRUNK_DIRECTIVE_FILE="$directive_file" wt ... || exit_code=$?
-//! source "$directive_file"
-//! ```
+//! - **CD file** (`WORKTRUNK_DIRECTIVE_CD_FILE`): Contains a raw path. The shell
+//! wrapper runs `cd -- "$(< file)"`. Because the file is never sourced as
+//! shell, there is **no injection surface** — even a malicious path cannot
+//! inject commands. This file is safe to pass through to alias/hook bodies.
//!
-//! ## Vulnerability: Shell Injection
+//! - **EXEC file** (`WORKTRUNK_DIRECTIVE_EXEC_FILE`): Contains arbitrary shell
+//! (from `--execute`). The wrapper sources it. Only wt-internal Rust code
+//! writes to this file — it is scrubbed from alias/hook child environments.
//!
-//! If external content (branch names, file paths, git output) can inject malicious shell
-//! code into the directive file, the shell wrapper will execute it. This is analogous to SQL injection
-//! or command injection vulnerabilities.
+//! ## Defense in Depth
//!
-//! ## Attack Vectors
+//! Multiple layers prevent injection even if one layer fails:
//!
-//! ### 1. Path Injection via Single Quote Escaping (HIGH RISK if not escaped)
+//! 1. **Protocol separation**: CD file is a raw path (no shell parsing); EXEC
+//! file is only written by Rust code, never by external content.
//!
-//! Paths are emitted in single quotes: `cd '/path/to/worktree'`
-//! Single quotes prevent most shell metacharacter expansion, but embedded single quotes
-//! could break out of the quoting if not properly escaped.
+//! 2. **Channel separation**: User messages go to stderr; directive files are
+//! separate. Malicious content in stderr cannot reach the directive files.
//!
-//! **Example attack (if unescaped):**
-//! ```bash
-//! # Create directory with malicious name
-//! mkdir "test'; rm -rf /; echo '"
-//! WORKTRUNK_DIRECTIVE_FILE=/tmp/d wt switch branch # If cd emits: cd 'test'; rm -rf /; echo ''
-//! ```
+//! 3. **Git layer**: Git REJECTS invalid characters in ref names (NUL, most
+//! control characters, shell metacharacters like backtick).
//!
-//! **Protection:** All paths are escaped using `replace('\'', "'\\''")` pattern,
-//! which is the standard POSIX approach for embedding single quotes in single-quoted strings.
+//! 4. **Filesystem layer**: OS enforces valid path characters (NUL is
+//! universally invalid in paths).
//!
-//! ### 2. Execute Command Injection (LOW RISK - user-controlled)
+//! 5. **Legacy escaping** (compat path only): When the pre-split legacy
+//! wrapper is active, paths use POSIX single-quote escaping (`'\''`),
+//! which handles `$`, `` ` ``, `;`, `&`, `|`, spaces, etc.
//!
-//! The `--execute` flag lets users specify shell commands to run. This is intentionally
-//! user-controlled and not an injection vector (users can already run arbitrary commands).
+//! ## What These Tests Verify
//!
-//! ### 3. Branch Name in Output (NO RISK)
+//! The CD file holds a raw path, so path-based shell injection is structurally
+//! impossible. These tests verify the remaining attack surface:
//!
-//! Branch names appear in stderr messages, not in the stdout shell script.
-//! The shell wrapper only evals stdout, so stderr content cannot be executed.
+//! 1. Branch names with shell metacharacters don't corrupt the cd path
+//! 2. Malicious branch names don't create unexpected files
+//! 3. The EXEC file only contains user-provided `--execute` content
+//! 4. Git's ref-name validation rejects the most dangerous characters
//!
-//! ## Current Protections
+//! ## Testing Limitations
//!
-//! **Shell script protocol with proper escaping:**
-//!
-//! 1. **Channel separation**: User messages go to stderr, shell directives go to a temp file
-//! - Shell wrapper only sources the directive file
-//! - Malicious content in stderr cannot be executed
-//!
-//! 2. **Path escaping**: All paths use single quotes with `'\''` escape pattern
-//! ```rust
-//! let escaped = path_str.replace('\'', "'\\''");
-//! writeln!(stdout, "cd '{}'", escaped)?;
-//! ```
-//! This handles all shell metacharacters: `$`, `` ` ``, `;`, `&`, `|`, spaces, etc.
-//!
-//! 3. **Git layer**: Git REJECTS invalid characters in ref names
-//!
-//! 4. **Filesystem layer**: OS enforces valid path characters
-//!
-//! ## Vulnerabilities We Test
-//!
-//! This test suite verifies that user-controlled content CANNOT inject shell commands:
-//!
-//! 1. ✅ Branch names with shell metacharacters
-//! 2. ✅ Branch names with single quotes
-//! 3. ✅ Paths with special characters
-//! 4. ✅ Git output with shell commands
-//!
-//! ## Security Model
-//!
-//! The file-based directive protocol is secure:
-//!
-//! 1. **Simpler parsing**: Just source a file, no command substitution needed
-//! 2. **Channel separation**: Messages on stderr, directives in temp file
-//! 3. **Standard escaping**: Uses well-understood POSIX single-quote escaping
-//! 4. **Smaller attack surface**: Only cd and exec commands in directive file
-//!
-//! ### Testing Limitations
-//!
-//! These tests verify that:
-//! - Path escaping is correct for shell metacharacters
-//! - Branch names with special characters don't break quoting
-//!
-//! However, they DON'T fully test shell execution security because:
-//! - Tests run the Rust binary, not the shell wrapper
-//! - Full end-to-end tests with malicious shell wrapper input are in `shell_wrapper.rs`
-//!
-//! For comprehensive security testing, see `tests/integration_tests/shell_wrapper.rs` which
-//! tests the full shell integration pipeline.
+//! These tests run the Rust binary, not the shell wrapper. They verify that
+//! directive file contents are safe, but they don't test that the wrapper
+//! handles the files correctly. Full end-to-end tests with the shell wrapper
+//! are in `tests/integration_tests/shell_wrapper.rs`.
use crate::common::{
- TestRepo, configure_directive_file, directive_file, repo, setup_snapshot_settings, wt_command,
+ TestRepo, configure_directive_files, directive_files, repo, setup_snapshot_settings, wt_command,
};
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
@@ -204,10 +156,10 @@ fn test_branch_name_is_directive_not_executed(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -241,10 +193,10 @@ fn test_branch_name_with_newline_directive_not_executed(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -340,10 +292,10 @@ fn test_branch_name_with_cd_directive_not_executed(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -364,10 +316,10 @@ fn test_error_message_with_directive_not_executed(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg(malicious_branch)
.current_dir(repo.root_path());
@@ -406,10 +358,10 @@ fn test_execute_flag_with_directive_like_branch_name(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 55a9caa15..1d1863543 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -1,7 +1,7 @@
//! Tests for the shell integration first-run prompt
//!
//! These tests verify that `prompt_shell_integration` behaves correctly across scenarios:
-//! - Skips when shell integration is active (WORKTRUNK_DIRECTIVE_FILE set)
+//! - Skips when shell integration is active (WORKTRUNK_DIRECTIVE_CD_FILE set)
//! - Skips when already prompted (config flag true)
//! - Skips when already installed (config line exists in shell config)
//! - Shows hint when not a TTY (non-interactive)
@@ -13,7 +13,7 @@ use std::fs;
use worktrunk::config::UserConfig;
///
-/// When WORKTRUNK_DIRECTIVE_FILE is set (shell integration active), we should:
+/// When WORKTRUNK_DIRECTIVE_CD_FILE is set (shell integration active), we should:
/// 1. Never call prompt_shell_integration()
/// 2. Have zero overhead from the prompt feature
#[rstest]
@@ -30,12 +30,15 @@ fn test_switch_with_active_shell_integration_no_prompt(repo: TestRepo) {
String::from_utf8_lossy(&create_output.stderr)
);
- // Now switch with shell integration "active" (directive file set)
- // The directive file must exist (shell wrapper creates it before calling wt)
- let directive_file = repo.root_path().join("directive.txt");
- fs::write(&directive_file, "").unwrap();
+ // Now switch with shell integration "active" (CD directive file set)
+ // The file must exist (shell wrapper creates it before calling wt)
+ let cd_file = repo.root_path().join("directive_cd.txt");
+ let exec_file = repo.root_path().join("directive_exec.txt");
+ fs::write(&cd_file, "").unwrap();
+ fs::write(&exec_file, "").unwrap();
let mut cmd = repo.wt_command();
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &cd_file);
+ cmd.env("WORKTRUNK_DIRECTIVE_EXEC_FILE", &exec_file);
let output = cmd.args(["switch", "feature"]).output().unwrap();
@@ -46,11 +49,11 @@ fn test_switch_with_active_shell_integration_no_prompt(repo: TestRepo) {
"Switch should succeed.\nstderr: {stderr}\nstdout: {stdout}"
);
- // The directive file should have cd command (shell integration active)
- let directive = fs::read_to_string(&directive_file).unwrap_or_default();
+ // The CD file should have a path (shell integration active)
+ let cd_content = fs::read_to_string(&cd_file).unwrap_or_default();
assert!(
- directive.contains("cd "),
- "Directive should contain cd command when shell integration active"
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path when shell integration active"
);
// No install prompt in output (would contain "Install shell integration")
@@ -228,7 +231,7 @@ mod pty_tests {
/// Test: Already installed (config line exists) → skip prompt
///
/// This covers the "installed but shell not restarted" scenario where:
- /// - Shell integration is not active (no WORKTRUNK_DIRECTIVE_FILE)
+ /// - Shell integration is not active (no directive env vars)
/// - But the config line is already in shell config files
/// - We should detect this and skip the prompt (not show interactive prompt)
/// - We should NOT mark as prompted (no interactive prompt shown)
@@ -245,8 +248,12 @@ mod pty_tests {
fs::write(&bashrc, format!("{config_line}\n")).unwrap();
let mut env_vars = repo.test_env_vars();
- // Remove WORKTRUNK_DIRECTIVE_FILE if present (ensure shell integration not active)
- env_vars.retain(|(k, _)| k != "WORKTRUNK_DIRECTIVE_FILE");
+ // Remove directive env vars (ensure shell integration not active)
+ env_vars.retain(|(k, _)| {
+ k != "WORKTRUNK_DIRECTIVE_CD_FILE"
+ && k != "WORKTRUNK_DIRECTIVE_EXEC_FILE"
+ && k != "WORKTRUNK_DIRECTIVE_FILE"
+ });
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 9b5de4472..24d8b7e50 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -595,8 +595,8 @@ fn exec_bash_truly_interactive(
///
/// This simulates what actually happens when users run `wt switch`, etc. in their shell:
/// 1. The `wt` function is defined (from shell integration)
-/// 2. It calls `wt_exec` which sets WORKTRUNK_DIRECTIVE_FILE and runs the binary
-/// 3. The wrapper sources the directive file after wt exits (for cd, exec commands)
+/// 2. It calls `wt_exec` which sets WORKTRUNK_DIRECTIVE_CD_FILE + WORKTRUNK_DIRECTIVE_EXEC_FILE
+/// 3. The wrapper reads the cd file and sources the exec file after wt exits
/// 4. Users see stdout/stderr output in real-time
///
/// Now uses PTY interactive mode for consistent behavior and potential input echoing.
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index 65637aef1..4d9639bdf 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -282,10 +282,10 @@ fn test_statusline_claude_code_missing_context_window(repo: TestRepo) {
}
// --- Directive Mode Tests ---
-// Note: With the new WORKTRUNK_DIRECTIVE_FILE architecture, data output (like statusline)
-// still goes to stdout. The directive file is only used for shell directives like
-// `cd '/path'`. So this test is no longer needed - statusline behavior is the same
-// regardless of whether WORKTRUNK_DIRECTIVE_FILE is set.
+// Note: With the split directive file architecture, data output (like statusline)
+// still goes to stdout. The directive files are only used for cd paths and exec
+// commands. So this test is no longer needed - statusline behavior is the same
+// regardless of whether directive env vars are set.
// --- Branch Display Tests ---
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 9a818fb54..c29f8b070 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -1,7 +1,7 @@
//! Integration tests for `wt step <alias>`
use crate::common::{
- TestRepo, configure_directive_file, directive_file, make_snapshot_cmd, repo,
+ TestRepo, configure_directive_files, directive_files, make_snapshot_cmd, repo,
setup_snapshot_settings, wt_bin,
};
use insta_cmd::assert_cmd_snapshot;
@@ -530,9 +530,9 @@ 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.
+/// `wt step <alias>` passes the parent's `WORKTRUNK_DIRECTIVE_CD_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
@@ -563,10 +563,10 @@ new-branch = "'{wt_toml}' switch --create alias-created"
"#
));
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = repo.wt_command();
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
cmd.args(["step", "new-branch"]);
let output = cmd.output().unwrap();
@@ -577,15 +577,15 @@ new-branch = "'{wt_toml}' switch --create alias-created"
String::from_utf8_lossy(&output.stderr),
);
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = std::fs::read_to_string(&cd_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:?}"
+ !cd_content.trim().is_empty(),
+ "alias wrapping `wt switch --create` should write a path to the \
+ CD directive file, got: {cd_content:?}"
);
assert!(
- directives.contains("alias-created"),
- "cd directive should target the new worktree (alias-created), got: {directives:?}"
+ cd_content.contains("alias-created"),
+ "cd directive should target the new worktree (alias-created), got: {cd_content:?}"
);
// Stderr should NOT contain the "shell integration not installed" hint
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 87366c230..8bd4dce7b 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1,5 +1,5 @@
use crate::common::{
- TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,
+ TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,
make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,
setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wt_command,
};
@@ -39,16 +39,16 @@ fn snapshot_switch_impl(
) {
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
- // Directive file guard - declared at closure scope to live through command execution
+ // Directive file guards - declared at closure scope to live through command execution
let maybe_directive = if with_directive_file {
- Some(directive_file())
+ Some(directive_files())
} else {
None
};
let mut cmd = make_snapshot_cmd(repo, "switch", args, cwd);
- if let Some((ref directive_path, ref _guard)) = maybe_directive {
- configure_directive_file(&mut cmd, directive_path);
+ if let Some((ref cd_path, ref exec_path, ref _guard)) = maybe_directive {
+ configure_directive_files(&mut cmd, cd_path, exec_path);
}
if let Some(shell_path) = shell {
cmd.env("SHELL", shell_path);
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index f26efe1b6..088de6744 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1062,13 +1062,18 @@ fn test_switch_picker_switch_to_existing_worktree(mut repo: TestRepo) {
);
}
-/// Helper to create a temporary directive file for PTY tests.
-/// Returns (path, guard) — the guard keeps the temp file alive until dropped.
-fn directive_file_for_pty() -> (PathBuf, tempfile::TempPath) {
- let file = tempfile::NamedTempFile::new().expect("failed to create temp file");
- let path = file.path().to_path_buf();
- let guard = file.into_temp_path();
- (path, guard)
+/// Helper to create temporary directive files for PTY tests.
+/// Returns (cd_path, exec_path, guards) — guards keep the temp files alive.
+fn directive_files_for_pty() -> (PathBuf, PathBuf, (tempfile::TempPath, tempfile::TempPath)) {
+ let cd = tempfile::NamedTempFile::new().expect("failed to create cd temp file");
+ let exec = tempfile::NamedTempFile::new().expect("failed to create exec temp file");
+ let cd_path = cd.path().to_path_buf();
+ let exec_path = exec.path().to_path_buf();
+ (
+ cd_path,
+ exec_path,
+ (cd.into_temp_path(), exec.into_temp_path()),
+ )
}
#[rstest]
@@ -1079,12 +1084,16 @@ fn test_switch_picker_no_cd_suppresses_directive(mut repo: TestRepo) {
// Create a worktree to switch to
repo.add_worktree("target-branch");
- let (directive_path, _guard) = directive_file_for_pty();
+ let (cd_path, exec_path, _guard) = directive_files_for_pty();
let mut env_vars = repo.test_env_vars();
env_vars.push((
- "WORKTRUNK_DIRECTIVE_FILE".to_string(),
- directive_path.display().to_string(),
+ "WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
+ cd_path.display().to_string(),
+ ));
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
+ exec_path.display().to_string(),
));
// Run `wt switch --no-cd`, select "target-branch" via picker, press Enter
@@ -1104,12 +1113,12 @@ fn test_switch_picker_no_cd_suppresses_directive(mut repo: TestRepo) {
"Expected exit code 0 for successful switch"
);
- // Verify directive file does NOT contain cd command
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify CD file is empty (no path written with --no-cd)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd via picker, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd via picker, got: {}",
+ cd_content
);
}
@@ -1121,12 +1130,16 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
// Create a worktree to switch to
repo.add_worktree("target-branch");
- let (directive_path, _guard) = directive_file_for_pty();
+ let (cd_path, exec_path, _guard) = directive_files_for_pty();
let mut env_vars = repo.test_env_vars();
env_vars.push((
- "WORKTRUNK_DIRECTIVE_FILE".to_string(),
- directive_path.display().to_string(),
+ "WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
+ cd_path.display().to_string(),
+ ));
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
+ exec_path.display().to_string(),
));
// Run `wt switch` (without --no-cd), select "target-branch" via picker
@@ -1146,12 +1159,12 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
"Expected exit code 0 for successful switch"
);
- // Verify directive file DOES contain cd command (default behavior)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ // Verify CD file DOES contain a path (default behavior)
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Directive file should contain cd command without --no-cd, got: {}",
- directives
+ !cd_content.trim().is_empty(),
+ "CD file should contain a path without --no-cd, got: {}",
+ cd_content
);
}
@@ -1163,12 +1176,16 @@ fn test_switch_picker_no_cd_prints_branch_without_switching(mut repo: TestRepo)
// Create a worktree to select
repo.add_worktree("target-branch");
- let (directive_path, _guard) = directive_file_for_pty();
+ let (cd_path, exec_path, _guard) = directive_files_for_pty();
let mut env_vars = repo.test_env_vars();
env_vars.push((
- "WORKTRUNK_DIRECTIVE_FILE".to_string(),
- directive_path.display().to_string(),
+ "WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
+ cd_path.display().to_string(),
+ ));
+ env_vars.push((
+ "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
+ exec_path.display().to_string(),
));
// Run `wt switch --no-cd`, filter to "target", press Enter to select
@@ -1198,10 +1215,10 @@ fn test_switch_picker_no_cd_prints_branch_without_switching(mut repo: TestRepo)
);
// --no-cd should NOT emit a cd directive (read-only operation)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
assert!(
- !directives.contains("cd '"),
- "Directive file should NOT contain cd command with --no-cd, got: {}",
- directives
+ cd_content.trim().is_empty(),
+ "CD file should be empty with --no-cd, got: {}",
+ cd_content
);
}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 968f71ae3..96b8090b7 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -2995,11 +2995,11 @@ cleanup = "echo done"
}
/// Foreground hooks pass the directive file through to child processes,
-/// so inner `wt switch --create` can write shell directives back to the
-/// parent shell.
+/// so inner `wt switch --create` can write cd directives back to the
+/// parent shell via the CD directive file.
#[rstest]
fn test_foreground_hook_passes_directive_file(repo: TestRepo) {
- use crate::common::{configure_directive_file, directive_file, wt_bin};
+ use crate::common::{configure_directive_files, directive_files, wt_bin};
repo.commit("initial");
@@ -3012,8 +3012,8 @@ fn test_foreground_hook_passes_directive_file(repo: TestRepo) {
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
+ // If the CD directive file is passed through, the inner wt will write a
+ // path to it. If scrubbed, it prints the "shell integration not
// installed" hint instead.
repo.write_test_config(&format!(
r#"
@@ -3022,10 +3022,10 @@ setup = "'{wt_toml}' switch --create hook-created --no-hooks"
"#,
));
- let (directive_path, _guard) = directive_file();
+ let (cd_path, exec_path, _guard) = directive_files();
let mut cmd = repo.wt_command();
- configure_directive_file(&mut cmd, &directive_path);
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
// Run the pre-start hook manually in foreground
cmd.args(["hook", "pre-start", "setup"]);
let output = cmd.output().unwrap();
@@ -3037,11 +3037,11 @@ setup = "'{wt_toml}' switch --create hook-created --no-hooks"
String::from_utf8_lossy(&output.stderr),
);
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ let cd_content = std::fs::read_to_string(&cd_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:?}"
+ !cd_content.trim().is_empty(),
+ "foreground hook running `wt switch --create` should write a path to \
+ the CD directive file, got: {cd_content:?}"
);
let stderr = String::from_utf8_lossy(&output.stderr);
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
index b38e3a227..5f650b320 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
@@ -25,7 +25,8 @@ info:
TERM: alacritty
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
index 22749dc64..f0260b59f 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
@@ -24,7 +24,8 @@ info:
TERM: alacritty
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_shell_active_but_not_in_config_file.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_shell_active_but_not_in_config_file.snap
index 456b80c37..bb50673fb 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_shell_active_but_not_in_config_file.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_shell_active_but_not_in_config_file.snap
@@ -29,7 +29,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_shell_integration_active.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_shell_integration_active.snap
index 23f0e9d79..c21dd30f4 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_shell_integration_active.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_shell_integration_active.snap
@@ -29,7 +29,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
index 6d14cc3be..edc7b2eae 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
index 4f867491c..cc592de2b 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
@@ -30,7 +30,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
index 6d14cc3be..edc7b2eae 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
index 5c553f601..fca8acf77 100644
--- a/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
@@ -28,7 +28,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
index eecbd21b2..84d763518 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap b/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap
new file mode 100644
index 000000000..a590aa63f
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap
@@ -0,0 +1,54 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - scrub-test
+ - "--execute"
+ - echo should-not-run
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch scrub-test from main and worktree @ _REPO_.scrub-test
+↳ To customize worktree locations, run wt config create
+▲ --execute disabled inside alias/hook bodies for safety; skipping echo should-not-run
+↳ This is extremely conservative; comment at https://github.com/max-sixty/worktrunk/issues/2101 if this affects you
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap
new file mode 100644
index 000000000..eecbd21b2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Switched to worktree for feature @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap
new file mode 100644
index 000000000..43c1b3619
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap
@@ -0,0 +1,49 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_SHELL: powershell
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Switched to worktree for feature @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap
new file mode 100644
index 000000000..ff8bf406d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap
@@ -0,0 +1,54 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - exec-legacy
+ - "--execute"
+ - echo hello
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch exec-legacy from main and worktree @ _REPO_.exec-legacy
+↳ To customize worktree locations, run wt config create
+◎ Executing (--execute):
+  echo hello
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
index eecbd21b2..84d763518 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
index e187e8e8b..6b931089c 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
@@ -31,7 +31,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
index 6d424d813..f05fbfffa 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
@@ -33,7 +33,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
index 8e9dbdd5e..aaef384cd 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
@@ -32,7 +32,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
index c131dd7f5..9dadc4b4a 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
@@ -30,7 +30,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 513f09855..d2d863775 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -8,7 +8,7 @@ info:
env:
CLICOLOR_FORCE: "1"
COLUMNS: "500"
- GIT_PAGER: ""
+ GIT_EDITOR: ""
LANG: C
LC_ALL: C
NO_COLOR: ""
@@ -456,14 +456,15 @@ Override the LLM command in CI to use a mock:
Other environment variables
- Variable Purpose
- ───────────────────────────────── ─────────────────────────────────────────────────────────────────────────────────
- WORKTRUNK_BIN Override binary path for shell wrappers; useful for testing dev builds
- WORKTRUNK_CONFIG_PATH Override user config file location
- WORKTRUNK_SYSTEM_CONFIG_PATH Override system config file location
- XDG_CONFIG_DIRS Colon-separated system config directories (default: /etc/xdg)
- WORKTRUNK_DIRECTIVE_FILE Internal: set by shell wrappers to enable directory changes
- WORKTRUNK_SHELL Internal: set by shell wrappers to indicate shell type (e.g., powershell)
- WORKTRUNK_MAX_CONCURRENT_COMMANDS Max parallel git commands (default: 32). Lower if hitting file descriptor limits.
- NO_COLOR Disable colored output (standard)
+ Variable Purpose
+ ───────────────────────────────── ───────────────────────────────────────────────────────────────────────────────────────
+ WORKTRUNK_BIN Override binary path for shell wrappers; useful for testing dev builds
+ WORKTRUNK_CONFIG_PATH Override user config file location
+ WORKTRUNK_SYSTEM_CONFIG_PATH Override system config file location
+ XDG_CONFIG_DIRS Colon-separated system config directories (default: /etc/xdg)
+ WORKTRUNK_DIRECTIVE_CD_FILE Internal: set by shell wrappers. wt writes a raw path; the wrapper cds to it
+ WORKTRUNK_DIRECTIVE_EXEC_FILE Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file
+ WORKTRUNK_SHELL Internal: set by shell wrappers to indicate shell type (e.g., powershell)
+ WORKTRUNK_MAX_CONCURRENT_COMMANDS Max parallel git commands (default: 32). Lower if hitting file descriptor limits.
+ NO_COLOR Disable colored output (standard)
CLICOLOR_FORCE Force colored output even when not a TTY
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 7fae1f503..bea40abed 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -49,8 +49,8 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override wt command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -60,7 +60,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -68,24 +68,38 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" /
+ cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" /
+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 319a91bb6..542deec5a 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -49,15 +49,9 @@ exit_code: 0
# This is the full function definition, output by `wt config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/wt.fish.
-# Override wt command with file-based directive passing.
-# Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, evals it after.
+# Override wt command with split directive passing.
+# Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
-#
-# Note: We use `eval (string collect < file)` instead of `source` because
-# fish's `source` doesn't propagate exit codes to the parent function.
-# We read the directive with `string collect` (builtin) instead of `cat`
-# (external) to avoid spawning a subprocess whose CWD may have been renamed
-# by worktree removal.
function wt
set -l use_source false
set -l args
@@ -71,27 +65,41 @@ function wt
echo "wt: command not found" >&2
return 127
end
- set -l directive_file (mktemp)
+ set -l cd_file (mktemp)
+ set -l exec_file (mktemp)
# --source: use cargo run (builds from source)
if test $use_source = true
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file cargo run --bin wt --quiet -- $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file /
+ cargo run --bin wt --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_FILE=$directive_file $WORKTRUNK_BIN $args
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file /
+ $WORKTRUNK_BIN $args
end
set -l exit_code $status
- if test -s "$directive_file"
- # Use fish builtin instead of cat to avoid spawning a subprocess
- # whose CWD may have been renamed by worktree removal.
- set -l directive (string collect < "$directive_file")
+ # cd file holds a raw path — read with fish builtin (no cat subprocess,
+ # safe even if CWD was removed by worktree removal).
+ if test -s "$cd_file"
+ set -l target (string trim < "$cd_file")
+ cd -- "$target"
+ set -l cd_exit $status
+ if test $exit_code -eq 0
+ set exit_code $cd_exit
+ end
+ end
+
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if test -s "$exec_file"
+ set -l directive (string collect < "$exec_file")
eval $directive
+ set -l src_exit $status
if test $exit_code -eq 0
- set exit_code $status
+ set exit_code $src_exit
end
end
- command rm -f "$directive_file"
+ command rm -f "$cd_file" "$exec_file"
return $exit_code
end
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index d3446dc1b..09e5ac905 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -52,8 +52,8 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with file-based directive passing.
- # Creates a temp file, passes path via WORKTRUNK_DIRECTIVE_FILE, sources it after.
+ # Override wt command with split directive passing.
+ # Creates two temp files: one for cd (raw path) and one for exec (shell).
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -63,7 +63,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
if [[ "$arg" == "--source" ]]; then use_source=true; else args+=("$arg"); fi
done
- # Completion mode: call binary directly, no directive file needed.
+ # Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
@@ -71,24 +71,38 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local directive_file exit_code=0
- directive_file="$(mktemp)"
+ local cd_file exec_file exit_code=0
+ cd_file="$(mktemp)"
+ exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" /
+ cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_FILE="$directive_file" command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" /
+ command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
- if [[ -s "$directive_file" ]]; then
- source "$directive_file"
+ # cd file holds a raw path (no shell escaping needed)
+ if [[ -s "$cd_file" ]]; then
+ cd -- "$(<"$cd_file")"
+ local cd_exit=$?
if [[ $exit_code -eq 0 ]]; then
- exit_code=$?
+ exit_code=$cd_exit
fi
fi
- rm -f "$directive_file"
+ # exec file holds arbitrary shell (e.g. from --execute)
+ if [[ -s "$exec_file" ]]; then
+ source "$exec_file"
+ local src_exit=$?
+ if [[ $exit_code -eq 0 ]]; then
+ exit_code=$src_exit
+ fi
+ fi
+
+ rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
diff --git a/tests/snapshots/integration__integration_tests__list__quickstart_merge.snap b/tests/snapshots/integration__integration_tests__list__quickstart_merge.snap
index 3bc477047..f0ef564fd 100644
--- a/tests/snapshots/integration__integration_tests__list__quickstart_merge.snap
+++ b/tests/snapshots/integration__integration_tests__list__quickstart_merge.snap
@@ -28,9 +28,9 @@ info:
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_COMMIT__GENERATION__COMMAND: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0bwkvo/mock-bin/llm
+ WORKTRUNK_COMMIT__GENERATION__COMMAND: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6TDTYE/mock-bin/llm
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__list__quickstart_switch.snap b/tests/snapshots/integration__integration_tests__list__quickstart_switch.snap
index a9d6e3f09..2d32abc1e 100644
--- a/tests/snapshots/integration__integration_tests__list__quickstart_switch.snap
+++ b/tests/snapshots/integration__integration_tests__list__quickstart_switch.snap
@@ -30,7 +30,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
index c97d5bf45..b4fe2265a 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
@@ -28,7 +28,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
index a7045dfd8..528ef82ce 100644
--- a/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
@@ -30,7 +30,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
index 3d7329a11..1a83b87f1 100644
--- a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap
index b6d4dae33..6cf6f388e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch_shows_hint.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap b/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
index 5fda7e918..39f0373cf 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
index f5823eb49..c5dcd5ae4 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
index 66dfa2f67..0b38f3914 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
index 23ce2f40e..3c4e37a58 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
index 9093964b6..9a1468a87 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
@@ -32,7 +32,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
index c9d0263eb..d728c8382 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
@@ -32,7 +32,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
index 9e96cdb03..e56e8b4c4 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
@@ -30,7 +30,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
index 44354dc6a..53fdcfc2f 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
@@ -32,7 +32,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
index 9d8f40fb8..0b8162f9f 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
index 7ebc4004a..caf913176 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
@@ -29,7 +29,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
index 91026b79d..db82051ae 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
@@ -31,7 +31,8 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"