Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(alias): carry the shell's cwd into alias and hook bodies (#3724)
Worktrunk Botd4538f204740
diff --git a/docs/content/config.md b/docs/content/config.mdindex b47caaeff..0e554bcee 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -665,6 +665,7 @@ Override the LLM command in CI to use a mock:| `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 `cd`s to it || `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |+| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `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. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex 83836512d..2f91dd0d9 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -662,6 +662,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `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 `cd`s to it || `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |+| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `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. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex 83836512d..2f91dd0d9 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -662,6 +662,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `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 `cd`s to it || `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |+| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `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. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 862799a12..c27d0effb 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -2548,6 +2548,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `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 `cd`s to it || `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |+| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `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. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rsindex b91b59b5a..9ff8f7faa 100644--- a/src/commands/step/relocate.rs+++ b/src/commands/step/relocate.rs@@ -133,7 +133,10 @@ pub fn step_relocate(// Phase 3 & 4: Create executor (classifies targets) and execute relocationslet mut executor = RelocationExecutor::new(&repo, validated, clobber)?;- let cwd = std::env::current_dir().ok();+ // Where the user's shell stands — inherited from the parent `wt` when this+ // runs inside an alias or hook body, whose process cwd is the worktree+ // root (#3723).+ let cwd = worktrunk::shell_exec::shell_cwd();executor.execute(&default_branch, cwd.as_deref())?;if json_mode {diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 44dee1d78..7f55a8b67 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -23,7 +23,9 @@ use worktrunk::git::remote_ref::{use worktrunk::git::{ForgeKind, GitError, GitRemoteUrl, RefType, Repository, SwitchSuggestionCtx, current_or_recover,};-use worktrunk::shell_exec::{ShellEscapeMode, directive_shell_escape_mode, shell_escape_for};+use worktrunk::shell_exec::{+ ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,+};use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,warning_message,@@ -1676,13 +1678,17 @@ impl SwitchPipeline<'_> {// user's shell won't be in the worktree, and shows the worktree-path// hint on first --create (before the shell integration warning).//- // When the user's CWD has been deleted, `std::env::current_dir()`- // fails — fall back to `repo_path()` (the main worktree root).- // `current_worktree().root()` resolves against the Repository's+ // `shell_cwd()` is where the user's shell stands: the process cwd,+ // unless a parent `wt` passed its own down (an alias or hook body runs+ // from the worktree root, so a nested switch would otherwise resolve+ // the user to that root — #3723). When the shell's CWD was already+ // gone when `wt` started, `startup_cwd()` never captured one and this+ // reads as absent — fall back to `repo_path()` (the main worktree+ // root). `current_worktree().root()` resolves against the Repository's// discovery path, which is alive even after recovery, but we keep the// same fallback for any pathological case where rev-parse fails.let fallback_path = repo.repo_path()?.to_path_buf();- let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());+ let cwd = shell_cwd().unwrap_or(fallback_path.clone());let source_root = repo.current_worktree().root().unwrap_or(fallback_path);let hooks_display_path =handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 8be02acd3..6a8f13e2b 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -46,7 +46,7 @@ use anyhow::Context;use worktrunk::command_log::log_command;use worktrunk::git::WorktrunkError;use worktrunk::shell_exec::{- DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, ShellConfig, scrub_directive_env_vars,+ DIRECTIVE_EXEC_FILE_ENV_VAR, ShellConfig, apply_cd_directive_env, scrub_directive_env_vars,scrub_git_discovery_env_vars,};#[cfg(unix)]@@ -305,7 +305,7 @@ fn spawn_child(// Scrub all directive env vars, then re-add the passthroughs.scrub_directive_env_vars(&mut command);if let Some(path) = &cmd.directives.cd_file {- command.env(DIRECTIVE_CD_FILE_ENV_VAR, path);+ apply_cd_directive_env(&mut command, path);}if let Some(path) = &cmd.directives.exec_file {command.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 595ef5a9f..36148cf11 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -6,7 +6,7 @@ use std::process::Stdio;use anstyle::AnsiColor;use color_print::cformat;-use worktrunk::shell_exec::Cmd;+use worktrunk::shell_exec::{Cmd, shell_cwd};use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};use crate::commands::command_executor::CommandContext;@@ -1752,9 +1752,12 @@ fn prepare_remove_directory_change(// `worktree/apps/gateway/` and `main/apps/gateway/` exists, cd there// instead of the main worktree root. Falls back to the root when the// subdir is absent in the destination or the cwd can't be read.- let cd_target = std::env::current_dir()+ // `shell_cwd()` rather than the process cwd, so the preservation+ // survives a `wt remove` nested in an alias or hook body, whose+ // process cwd is the worktree root (#3723).+ let cd_target = shell_cwd().map(|cwd| resolve_subdir_in_target(main_path, Some(worktree_path), &cwd))- .unwrap_or_else(|_| main_path.to_path_buf());+ .unwrap_or_else(|| main_path.to_path_buf());super::change_directory(&cd_target)?;stderr().flush()?; // Force flush to ensure shell processes the cd// Mark that the CWD worktree is being removed, so the error handlerdiff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 77d1ce105..bd29e4110 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -514,15 +514,81 @@ pub const DIRECTIVE_EXEC_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_EXEC_FILE";/// that its parent shell will source.pub const RETIRED_DIRECTIVE_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_FILE";+/// Environment variable carrying the directory the user's shell is in.+///+/// A top-level `wt` reads that directory from its own process cwd, which is+/// what subdirectory preservation resolves the user's position against (from+/// `monorepo.feature/subproject/`, `wt switch main` lands in+/// `monorepo/subproject/`). A `wt` nested inside an alias or hook body cannot:+/// those bodies run with a wt-chosen working directory (the worktree root), so+/// the nested process would resolve the user to that root and drop them there.+///+/// [`apply_cd_directive_env`] therefore sets this alongside the CD directive+/// file — the same children that are allowed to move the user's shell are the+/// ones that need to know where it currently is. Nesting composes because+/// [`shell_cwd`] prefers the inherited value over the process cwd, so each+/// layer forwards the shell's directory rather than its own. See issue #3723.+///+/// Private, unlike the directive-file vars above: the setter, the scrubber and+/// the reader all live in this module, and a name spells the coupling between+/// them that a repeated literal would leave to a spelling match.+const SHELL_CWD_ENV_VAR: &str = "WORKTRUNK_SHELL_CWD";++/// The directory the user's shell is in: the inherited `WORKTRUNK_SHELL_CWD`+/// when a parent `wt` set it, otherwise this process's own startup cwd.+///+/// Callers that ask "where is the user physically standing?" use this rather+/// than [`std::env::current_dir`]. `-C` is deliberately not consulted: it sets+/// git's discovery path without moving the shell.+pub fn shell_cwd() -> Option<PathBuf> {+ shell_cwd_from(std::env::var_os(SHELL_CWD_ENV_VAR), startup_cwd())+}++/// Pure form of [`shell_cwd`], split out so the relative-value fall-through is+/// unit-testable without mutating process-wide state — the same split+/// [`compute_git_env_overrides`] makes for [`inherited_git_env_overrides`].+fn shell_cwd_from(inherited: Option<OsString>, fallback: Option<&PathBuf>) -> Option<PathBuf> {+ if let Some(value) = inherited {+ let path = PathBuf::from(value);+ // A relative value can't name the shell's position from a child that+ // runs elsewhere, so fall through to the process cwd. A stale absolute+ // one needs no guard here: the subdirectory it resolves to has to exist+ // in the destination before anything `cd`s there.+ if path.is_absolute() {+ return Some(path);+ }+ }+ fallback.cloned()+}+/// 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).+///+/// `WORKTRUNK_SHELL_CWD` goes with them: it is meaningful only to a child that+/// can act on the shell's position, and those children get it back from+/// [`apply_cd_directive_env`].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(RETIRED_DIRECTIVE_FILE_ENV_VAR);+ cmd.env_remove(SHELL_CWD_ENV_VAR);+}++/// Re-add the CD directive file to a trusted child's environment, together+/// with the shell cwd that makes its `cd` land where the user actually is.+///+/// The two travel together by construction: a child that can redirect the+/// parent shell resolves the user's subdirectory against [`shell_cwd`], and+/// without it every nested `wt switch` / `wt remove` inside an alias or hook+/// body would `cd` to a worktree root (issue #3723).+pub fn apply_cd_directive_env(cmd: &mut std::process::Command, cd_file: &std::path::Path) {+ cmd.env(DIRECTIVE_CD_FILE_ENV_VAR, cd_file);+ if let Some(cwd) = shell_cwd() {+ cmd.env(SHELL_CWD_ENV_VAR, cwd);+ }}/// Scrub the git-discovery path vars ([`INHERITED_GIT_PATH_VARS`]) from a child@@ -1854,7 +1920,7 @@ impl Cmd {// aliases and hooks leave it scrubbed so their bodies cannot inject// shell into the parent session.if let Some(ref path) = self.directive_cd_file {- cmd.env(DIRECTIVE_CD_FILE_ENV_VAR, path);+ apply_cd_directive_env(&mut cmd, path);}if let Some(ref path) = self.directive_exec_file {cmd.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);@@ -2227,7 +2293,7 @@ mod tests {use super::*;#[test]- fn test_scrub_directive_env_vars_includes_retired_variable() {+ fn test_scrub_directive_env_vars_covers_every_directive_variable() {assert_eq!(RETIRED_DIRECTIVE_FILE_ENV_VAR, "WORKTRUNK_DIRECTIVE_FILE");let mut cmd = std::process::Command::new("child");@@ -2235,6 +2301,7 @@ mod tests {DIRECTIVE_CD_FILE_ENV_VAR,DIRECTIVE_EXEC_FILE_ENV_VAR,RETIRED_DIRECTIVE_FILE_ENV_VAR,+ SHELL_CWD_ENV_VAR,] {cmd.env(var, "directive");}@@ -2245,6 +2312,7 @@ mod tests {DIRECTIVE_CD_FILE_ENV_VAR,DIRECTIVE_EXEC_FILE_ENV_VAR,RETIRED_DIRECTIVE_FILE_ENV_VAR,+ SHELL_CWD_ENV_VAR,] {assert!(cmd.get_envs()@@ -2254,6 +2322,37 @@ mod tests {}}+ #[test]+ fn test_shell_cwd_from_prefers_absolute_inherited_value() {+ // Built from `temp_dir()` rather than platform literals: `/shell/cwd`+ // isn't absolute on Windows (no prefix), and a `cfg!(windows)` pair+ // would leave whichever arm this platform didn't take uncovered.+ // Neither path is touched — the predicate only inspects its shape.+ let root = std::env::temp_dir();+ let fallback = root.join("wt-shell-cwd-fallback");+ let absolute = root.join("wt-shell-cwd");+ assert!(absolute.is_absolute(), "temp_dir() should be absolute");++ // An absolute inherited value wins over the process cwd.+ assert_eq!(+ shell_cwd_from(Some(OsString::from(&absolute)), Some(&fallback)),+ Some(absolute.clone())+ );+ // A relative one names nothing from a child that runs elsewhere.+ assert_eq!(+ shell_cwd_from(Some(OsString::from("apps/gateway")), Some(&fallback)),+ Some(fallback.clone())+ );+ assert_eq!(+ shell_cwd_from(None, Some(&fallback)),+ Some(fallback.clone())+ );+ assert_eq!(+ shell_cwd_from(Some(OsString::from("apps/gateway")), None),+ None+ );+ }+/// The only test allowed to set `FOREGROUND_THREAD` (a process-wide/// set-once): with it unset, `is_foreground_thread()` is false everywhere,/// which is the state every other test runs under.diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex dee582e56..3922b1eee 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -2,7 +2,7 @@use crate::common::{TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,- make_snapshot_cmd_with_global_flags, repo, setup_snapshot_settings, wt_bin,+ make_snapshot_cmd_with_global_flags, repo, repo_with_remote, setup_snapshot_settings, wt_bin,};// Used only by the `#[cfg(unix)]` signal tests below; gate the import to match,// or it reads as unused on Windows under `-D warnings`.@@ -789,26 +789,11 @@ deploy = "echo deploying"fn test_alias_passes_directive_file_to_subprocess(repo: TestRepo) {repo.commit("initial");- // Escape the wt binary path for embedding in a sh -c command string.- // Test temp paths never contain single quotes.- let wt = wt_bin();- let wt_str = wt.to_string_lossy();- assert!(- !wt_str.contains('\''),- "wt binary path should not contain single quotes: {wt_str}"- );- // Double backslashes so the Windows path (e.g. `D:\a\worktrunk\...\wt.exe`)- // parses as literal characters inside a TOML basic string rather than- // being interpreted as escape sequences (`\a`, `\w`, ...).- let wt_toml = wt_str.replace('\\', r"\\");-// Alias body invokes the test wt binary directly (PATH lookup in the// subprocess shell wouldn't find it).- repo.write_test_config(&format!(- r#"-[aliases]-new-branch = "'{wt_toml}' switch --create alias-created"-"#+ repo.write_test_config(&wt_alias_config(+ "new-branch",+ "switch --create alias-created",));let (cd_path, exec_path, _guard) = directive_files();@@ -846,16 +831,15 @@ new-branch = "'{wt_toml}' switch --create alias-created");}-/// User-source aliases pass the EXEC directive file through to the body, so a-/// nested `wt switch --execute X` writes the payload back to the parent-/// shell's EXEC file the same as a top-level `wt switch --execute X` would.+/// Build an `[aliases]` config whose single alias body invokes the test `wt`+/// binary. Suits either config source — pass it to `write_test_config` for a+/// user alias or `write_project_config` for a project one.///-/// Regression test for #2101: the conservative scrub used to refuse `--execute`-/// inside any alias body, breaking workflows like `issue = "wt switch --create-/// {{ args[0] }} --execute claude"` even when the alias lived in user config.-#[rstest]-fn test_user_alias_passes_exec_directive(repo: TestRepo) {- repo.commit("initial");+/// The binary path has to be embedded in a TOML basic string inside a shell+/// command, so single quotes must be absent (they'd terminate the shell+/// quoting) and backslashes doubled (a Windows path like `D:\a\wt.exe` would+/// otherwise parse `\a` as a TOML escape).+fn wt_alias_config(name: &str, args: &str) -> String {let wt = wt_bin();let wt_str = wt.to_string_lossy();assert!(@@ -863,12 +847,109 @@ fn test_user_alias_passes_exec_directive(repo: TestRepo) {"wt binary path should not contain single quotes: {wt_str}");let wt_toml = wt_str.replace('\\', r"\\");-- repo.write_test_config(&format!(+ format!(r#"[aliases]-exec-passthrough = "'{wt_toml}' switch --create user-alias-target --execute 'echo from-user-alias'"+{name} = "'{wt_toml}' {args}""#+ )+}++/// `wt switch` inside an alias body preserves the user's subdirectory position,+/// the same as a top-level `wt switch` does.+///+/// Regression test for #3723: alias steps run with the worktree root as their+/// working directory, so the nested `wt` used to see the root as the user's+/// cwd and land the shell at the target worktree's root instead of the+/// matching subdirectory.+#[rstest]+fn test_alias_wrapping_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");++ // The same subdirectory exists in both worktrees.+ let subdir = std::path::Path::new("apps").join("gateway");+ std::fs::create_dir_all(repo.root_path().join(&subdir)).unwrap();+ std::fs::create_dir_all(feature_wt.join(&subdir)).unwrap();++ repo.write_test_config(&wt_alias_config("go", "switch feature"));++ let (cd_path, exec_path, _guard) = directive_files();++ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ cmd.args(["step", "go"])+ .current_dir(repo.root_path().join(&subdir));+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt step go failed: stdout={}\nstderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();+ let expected = feature_wt.join(&subdir);+ let expected_str = expected.to_string_lossy();+ assert!(+ cd_content.contains(&*expected_str),+ "CD file should preserve the subdirectory ({expected_str}), got: {cd_content:?}"+ );+}++/// `wt remove` inside an alias body preserves the user's subdirectory position.+///+/// Regression test for #3723: the reported case is a `remove`-wrapping alias+/// (`[aliases] finish = "wt remove -y"`) in a monorepo, which used to drop the+/// user at the primary worktree root instead of their sub-project.+#[rstest]+fn test_alias_wrapping_remove_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");++ // The same subdirectory exists in the worktree being removed (where the+ // user is) and in the main worktree (where removal lands).+ let subdir = std::path::Path::new("apps").join("gateway");+ std::fs::create_dir_all(repo.root_path().join(&subdir)).unwrap();+ std::fs::create_dir_all(feature_wt.join(&subdir)).unwrap();++ repo.write_test_config(&wt_alias_config("finish", "remove -y"));++ let (cd_path, exec_path, _guard) = directive_files();++ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ cmd.args(["step", "finish"])+ .current_dir(feature_wt.join(&subdir));+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt step finish failed: stdout={}\nstderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();+ let expected = repo.root_path().join(&subdir);+ let expected_str = expected.to_string_lossy();+ assert!(+ cd_content.contains(&*expected_str),+ "CD file should preserve the subdirectory ({expected_str}), got: {cd_content:?}"+ );+}++/// User-source aliases pass the EXEC directive file through to the body, so a+/// nested `wt switch --execute X` writes the payload back to the parent+/// shell's EXEC file the same as a top-level `wt switch --execute X` would.+///+/// Regression test for #2101: the conservative scrub used to refuse `--execute`+/// inside any alias body, breaking workflows like `issue = "wt switch --create+/// {{ args[0] }} --execute claude"` even when the alias lived in user config.+#[rstest]+fn test_user_alias_passes_exec_directive(repo: TestRepo) {+ repo.commit("initial");++ repo.write_test_config(&wt_alias_config(+ "exec-passthrough",+ "switch --create user-alias-target --execute 'echo from-user-alias'",));let (cd_path, exec_path, _guard) = directive_files();@@ -903,19 +984,10 @@ exec-passthrough = "'{wt_toml}' switch --create user-alias-target --execute 'ech#[rstest]fn test_project_alias_scrubs_exec_directive(repo: TestRepo) {repo.commit("initial");- let wt = wt_bin();- let wt_str = wt.to_string_lossy();- assert!(- !wt_str.contains('\''),- "wt binary path should not contain single quotes: {wt_str}"- );- let wt_toml = wt_str.replace('\\', r"\\");- repo.write_project_config(&format!(- r#"-[aliases]-exec-blocked = "'{wt_toml}' switch --create project-alias-target --execute 'echo should-not-pass'"-"#+ repo.write_project_config(&wt_alias_config(+ "exec-blocked",+ "switch --create project-alias-target --execute 'echo should-not-pass'",));let (cd_path, exec_path, _guard) = directive_files();@@ -959,27 +1031,16 @@ exec-blocked = "'{wt_toml}' switch --create project-alias-target --execute 'echo#[rstest]fn test_user_and_project_alias_collision_scrubs_only_project_step(repo: TestRepo) {repo.commit("initial");- let wt = wt_bin();- let wt_str = wt.to_string_lossy();- assert!(- !wt_str.contains('\''),- "wt binary path should not contain single quotes: {wt_str}"- );- let wt_toml = wt_str.replace('\\', r"\\");- repo.write_test_config(&format!(- r#"-[aliases]-shared = "'{wt_toml}' switch --create user-step-target --execute 'echo from-user-step'"-"#+ repo.write_test_config(&wt_alias_config(+ "shared",+ "switch --create user-step-target --execute 'echo from-user-step'",));// Project step also tries `--execute` so we can assert its payload is// scrubbed even though the user step's payload passes through.- repo.write_project_config(&format!(- r#"-[aliases]-shared = "'{wt_toml}' switch --create project-step-target --execute 'echo from-project-step'"-"#,+ repo.write_project_config(&wt_alias_config(+ "shared",+ "switch --create project-step-target --execute 'echo from-project-step'",));let (cd_path, exec_path, _guard) = directive_files();diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 4002bac08..c0fe08fef 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -646,6 +646,7 @@ Override the LLM command in CI to use a mock:[2mXDG_CONFIG_DIRS[0m Colon-separated system config directories (default: [2m/etc/xdg[0m)[2mWORKTRUNK_DIRECTIVE_CD_FILE[0m Internal: set by shell wrappers. wt writes a raw path; the wrapper [2mcd[0ms to it[2mWORKTRUNK_DIRECTIVE_EXEC_FILE[0m Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file+ [2mWORKTRUNK_SHELL_CWD[0m Internal: set by wt on alias and hook bodies, so a nested [2mwt[0m preserves the user's subdirectory[2mWORKTRUNK_SHELL[0m Internal: set by shell wrappers to indicate shell type (e.g., [2mpowershell[0m)[2mWORKTRUNK_MAX_CONCURRENT_COMMANDS[0m Max parallel git commands (default: 32). Lower if hitting file descriptor limits.[2mWORKTRUNK_VERBOSE[0m Verbosity level ([2m0[0m/[2m1[0m/[2m2[0m), like [2m-v[0m/[2m-vv[0m but applied everywhere — including shell completion, which no flag can reach