Skip to content

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

Run --execute in the worktree even under --no-cd (#4179)

Maximilian Roos5b2d3c05bf3a
diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.md
index 5632cd6a7..aa384be08 100644
--- a/docs/src/content/docs/switch.md
+++ b/docs/src/content/docs/switch.md
@@ -206,7 +206,10 @@ Options:
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there. With --no-cd, the program starts in the invoking directory instead.
+ there.
+
+ The program starts in the worktree the switch selected, whether or not your shell follows
+ it there: --no-cd governs only the shell.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -236,8 +239,10 @@ Options:
--no-cd
Skip directory change after switching
- Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
+ Hooks still run normally, and an --execute program still starts in the worktree — only
+ your shell stays put, so wt switch feature --no-cd -x code -- . opens the worktree in an
+ editor and leaves your terminal where it was. Useful when hooks handle navigation (e.g.,
+ tmux workflows) or for CI/automation. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.md
index f8988bc89..0ab06ad78 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md
@@ -178,7 +178,10 @@ Options:
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there. With --no-cd, the program starts in the invoking directory instead.
+ there.
+
+ The program starts in the worktree the switch selected, whether or not your shell follows
+ it there: --no-cd governs only the shell.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -208,8 +211,10 @@ Options:
--no-cd
Skip directory change after switching
- Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
+ Hooks still run normally, and an --execute program still starts in the worktree — only
+ your shell stays put, so wt switch feature --no-cd -x code -- . opens the worktree in an
+ editor and leaves your terminal where it was. Useful when hooks handle navigation (e.g.,
+ tmux workflows) or for CI/automation. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index f8988bc89..0ab06ad78 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -178,7 +178,10 @@ Options:
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there. With --no-cd, the program starts in the invoking directory instead.
+ there.
+
+ The program starts in the worktree the switch selected, whether or not your shell follows
+ it there: --no-cd governs only the shell.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -208,8 +211,10 @@ Options:
--no-cd
Skip directory change after switching
- Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
+ Hooks still run normally, and an --execute program still starts in the worktree — only
+ your shell stays put, so wt switch feature --no-cd -x code -- . opens the worktree in an
+ editor and leaves your terminal where it was. Useful when hooks handle navigation (e.g.,
+ tmux workflows) or for CI/automation. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index c20928e30..d7cab06d4 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -384,8 +384,10 @@ pub(crate) struct SwitchArgs {
///
/// Without a branch argument, the interactive picker opens and the
/// command runs against the selected worktree — so `wt switch -x claude`
- /// picks a worktree, then launches Claude Code there. With `--no-cd`, the
- /// program starts in the invoking directory instead.
+ /// picks a worktree, then launches Claude Code there.
+ ///
+ /// The program starts in the worktree the switch selected, whether or not
+ /// your shell follows it there: `--no-cd` governs only the shell.
///
/// Supports [hook template variables](https://worktrunk.dev/hook/#template-variables)
/// (`{{ branch }}`, `{{ worktree_path }}`, etc.) and filters.
@@ -432,9 +434,12 @@ pub(crate) struct SwitchArgs {
/// Skip directory change after switching
///
- /// Hooks still run normally. Useful when hooks handle navigation
- /// (e.g., tmux workflows) or for CI/automation. `--execute` also starts in
- /// the invoking directory. Use --cd to override.
+ /// Hooks still run normally, and an `--execute` program still starts in
+ /// the worktree — only your shell stays put, so
+ /// `wt switch feature --no-cd -x code -- .` opens the worktree in an
+ /// editor and leaves your terminal where it was. Useful when hooks handle
+ /// navigation (e.g., tmux workflows) or for CI/automation. Use --cd to
+ /// override.
#[arg(long, overrides_with = "cd")]
pub(crate) no_cd: bool,
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 3c696d038..1766dcbab 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1978,9 +1978,13 @@ impl SwitchPipeline<'_> {
.collect();
let argv: Vec<String> = std::iter::once(program).chain(args?).collect();
// The header names where the program starts, which is the
- // directory the switch cd'd to and not the worktree the hooks
+ // directory the switch selected and not the worktree the hooks
// announce (#4042).
- execute_user_command(&argv, display_paths.execute.as_deref())?;
+ execute_user_command(
+ &argv,
+ display_paths.execute.as_deref(),
+ &display_paths.execute_dir,
+ )?;
}
Ok(())
diff --git a/src/output/global.rs b/src/output/global.rs
index e16255e0e..dfdc22325 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -70,8 +70,6 @@ enum DirectiveMode {
struct OutputState {
/// How directory changes are communicated.
mode: DirectiveMode,
- /// Target directory for a subsequent `execute()` call.
- target_dir: Option<PathBuf>,
/// Mapping from canonical path prefix to logical (symlink) prefix.
/// Computed once at init from `$PWD` vs `std::env::current_dir()`.
symlink_mapping: Option<SymlinkMapping>,
@@ -197,7 +195,6 @@ fn state() -> &'static Mutex<OutputState> {
Mutex::new(OutputState {
mode,
- target_dir: None,
symlink_mapping,
cwd_removed: false,
})
@@ -287,17 +284,18 @@ fn write_cd_path_io(file: &Path, path: &Path) -> io::Result<()> {
/// Request directory change (for shell integration).
///
-/// Stores the target for a later `execute()` call and, when shell integration
-/// is active, also writes it to the CD directive file.
+/// Moves the user's shell, and nothing else: where a relocated child program
+/// runs is its caller's own argument (see [`execute`]). When shell integration
+/// is inactive there is no shell to move and the call is a no-op.
///
/// A write failure names the file it couldn't write.
pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
let path = path.as_ref();
- let mode = {
- let mut guard = state().lock().expect("OUTPUT_STATE lock poisoned");
- guard.target_dir = Some(path.to_path_buf());
- guard.mode.clone()
- };
+ let mode = state()
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .mode
+ .clone();
match mode {
DirectiveMode::Interactive | DirectiveMode::Retired => Ok(()),
@@ -335,37 +333,28 @@ pub(crate) fn format_exec_argv(argv: &[String]) -> String {
.join(" ")
}
-/// Run an external program in the directory selected by the preceding switch.
-pub fn execute(argv: Vec<String>) -> anyhow::Result<()> {
+/// Run an external program in `dir`, with the terminal attached.
+///
+/// The caller names the directory rather than reading one the shell directive
+/// left behind: the program goes where the switch pointed, whether or not the
+/// user's shell follows it there.
+pub fn execute(argv: Vec<String>, dir: &Path) -> anyhow::Result<()> {
if argv.first().is_none_or(String::is_empty) {
anyhow::bail!("--execute requires a non-empty program");
}
- let target_dir = state()
- .lock()
- .expect("OUTPUT_STATE lock poisoned")
- .target_dir
- .clone();
- execute_command(argv, target_dir.as_deref())
-}
-
-/// Execute an argv in the given directory, with the terminal attached.
-fn execute_command(argv: Vec<String>, target_dir: Option<&Path>) -> anyhow::Result<()> {
let mut argv = argv.into_iter();
let program = argv.next().context("--execute requires a program")?;
- let mut cmd = Cmd::new(program)
+ // wt relocated the payload into a worktree it selected; its `git` calls
+ // must discover that worktree from the cwd, not an inherited `GIT_DIR`
+ // (issue #3373; see `scrub_git_discovery_env_vars`).
+ let cmd = Cmd::new(program)
.args(argv)
.inherit_stdin()
- .forward_signals();
+ .forward_signals()
+ .current_dir(dir)
+ .scrub_git_discovery_env();
#[cfg(unix)]
- {
- cmd = cmd.propagate_sigpipe();
- }
- if let Some(dir) = target_dir {
- // wt relocated the payload into a worktree it selected; its `git`
- // calls must discover that worktree from the cwd, not an inherited
- // `GIT_DIR` (issue #3373; see `scrub_git_discovery_env_vars`).
- cmd = cmd.current_dir(dir).scrub_git_discovery_env();
- }
+ let cmd = cmd.propagate_sigpipe();
suppress_child_exit_message(cmd.stream())
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 6ecded615..31dd63854 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1025,20 +1025,23 @@ pub(crate) fn resolve_subdir_in_target(
target_root.to_path_buf()
}
-/// The "@ path" annotations a switch's follow-on output should carry.
+/// Where a switch's follow-on work runs, and which of those directories its
+/// output should annotate with "@ path".
///
-/// Both are `Some` only when the user's shell won't be where the annotated work
-/// runs; the two paths differ because the work doesn't share one directory.
-/// Background hooks always run at the worktree root, while the `--execute`
-/// program runs wherever the switch cd'd — the root, or the subdirectory
-/// position [`resolve_subdir_in_target`] preserved — and nowhere at all under
-/// `--no-cd`, which leaves it in the invoking directory (#4042).
+/// The `--execute` program always starts in the switch target — the worktree
+/// root, or the subdirectory position [`resolve_subdir_in_target`] preserved —
+/// so `execute_dir` is unconditional. The two `Option`s are the annotations,
+/// `Some` only when the user's shell won't be where that work runs: background
+/// hooks always run at the worktree root, and `--no-cd` leaves the shell behind
+/// while the program still goes to the worktree (#4042).
pub struct SwitchDisplayPaths {
/// Where the background `post-switch` / `post-start` hooks run, when that
/// isn't where the user's shell is (or will be).
pub hooks: Option<PathBuf>,
- /// Where the `--execute` program starts, when that isn't where the user's
- /// shell is (or will be).
+ /// Where the `--execute` program starts.
+ pub execute_dir: PathBuf,
+ /// [`Self::execute_dir`], when that isn't where the user's shell is (or
+ /// will be).
pub execute: Option<PathBuf>,
}
@@ -1081,16 +1084,15 @@ pub fn handle_switch_output(
source_worktree_root: Option<&Path>,
cwd: &Path,
) -> anyhow::Result<SwitchDisplayPaths> {
- // Set target directory for command execution, preserving subdirectory position.
- // If the user is in apps/gateway/ in the source worktree and that directory exists
- // in the target, cd to apps/gateway/ in the target instead of the root.
- let cd_target = if change_dir {
- let cd_target = resolve_subdir_in_target(result.path(), source_worktree_root, cwd);
- super::change_directory(&cd_target)?;
- Some(cd_target)
- } else {
- None
- };
+ // Where the switch points, preserving subdirectory position: if the user is
+ // in apps/gateway/ in the source worktree and that directory exists in the
+ // target, that's apps/gateway/ in the target rather than its root. The
+ // `--execute` program starts there either way; `--no-cd` only declines to
+ // take the user's shell along.
+ let destination = resolve_subdir_in_target(result.path(), source_worktree_root, cwd);
+ if change_dir {
+ super::change_directory(&destination)?;
+ }
// Translate to the user's logical (symlink-preserved) path for display messages.
// The cd directive (above) handles its own translation internally.
@@ -1112,32 +1114,36 @@ pub fn handle_switch_output(
),
};
- // The `--execute` program runs in `cd_target`, which is the worktree root
- // only when the user was at the source worktree's root: otherwise
+ // The program runs in `destination`, which is the worktree root only when
+ // the user was at the source worktree's root: otherwise
// `resolve_subdir_in_target` kept their subdirectory position, and the
// hooks' path names a directory one level out from the program's. Annotate
- // it only when the user's shell won't be there — `--no-cd` leaves the
- // program where the shell already stands, and shell integration takes the
- // shell to `cd_target` too (#4042).
- let display_path_for_execute = cd_target.filter(|target| {
- !super::is_shell_integration_active()
- && super::global::compute_hooks_display_path(target, cwd).is_some()
- });
+ // it only when the user's shell won't be there — it follows the program
+ // only when the switch cd'd and shell integration carried it (#4042).
+ let shell_follows = change_dir && super::is_shell_integration_active();
+ let display_path_for_execute = (!shell_follows)
+ .then(|| destination.clone())
+ .filter(|dir| super::global::compute_hooks_display_path(dir, cwd).is_some());
stderr().flush()?;
Ok(SwitchDisplayPaths {
hooks: display_path_for_hooks,
- execute: display_path_for_execute.map(|target| super::to_logical_path(&target)),
+ execute_dir: destination,
+ execute: display_path_for_execute.map(|dir| super::to_logical_path(&dir)),
})
}
/// Execute the --execute command after hooks have run.
///
-/// `display_path` names the directory the program starts in
-/// ([`SwitchDisplayPaths::execute`]), and is `Some` only when the user's shell
-/// won't be there — otherwise the header has nothing to annotate.
-///
-pub fn execute_user_command(argv: &[String], display_path: Option<&Path>) -> anyhow::Result<()> {
+/// The program runs in `dir` ([`SwitchDisplayPaths::execute_dir`]).
+/// `display_path` is that same directory ([`SwitchDisplayPaths::execute`]), and
+/// is `Some` only when the user's shell won't be there — otherwise the header
+/// has nothing to annotate.
+pub fn execute_user_command(
+ argv: &[String],
+ display_path: Option<&Path>,
+ dir: &Path,
+) -> anyhow::Result<()> {
super::global::print_outdated_execute_wrapper_warning();
let command = super::global::format_exec_argv(argv);
@@ -1153,7 +1159,7 @@ pub fn execute_user_command(argv: &[String], display_path: Option<&Path>) -> any
eprintln!("{}", progress_message(header));
eprintln!("{}", format_bash_with_gutter(&command));
- super::execute(argv.to_vec())?;
+ super::execute(argv.to_vec(), dir)?;
Ok(())
}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 2c113f4ca..1badb2e81 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -14,7 +14,7 @@
//!
//! eprintln!("{}", success_message("Operation complete"));
//! output::change_directory(&path);
-//! output::execute(vec!["git".into(), "pull".into()]);
+//! output::execute(vec!["git".into(), "pull".into()], &path);
//! ```
//!
//! ## Shell Integration
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index a235cae4f..5878ea244 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -516,8 +516,8 @@ fn test_switch_no_cd_execute_does_not_emit_cd(#[from(repo_with_remote)] repo: Te
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
configure_directive_file(&mut cmd, &cd_path);
- // The wrapper will launch pwd from the invoking directory because
- // --no-cd deliberately leaves its shell there.
+ // pwd runs in the new worktree — --no-cd suppresses the cd directive,
+ // so the wrapper leaves the shell behind, not the program.
cmd.args([
"switch",
"--create",
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 5b6546766..d27e88f1c 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -939,14 +939,14 @@ fn test_switch_execute_does_not_inherit_git_discovery_vars(mut repo: TestRepo) {
);
}
-/// `--no-cd` starts the `--execute` program in the invoking directory, so the
-/// "Executing (--execute) @ …" header must not name the new worktree. The path
-/// it renders is the one the background hooks run in; the program never enters
-/// it, and naming it there sent a reporter looking for a broken template
-/// variable instead of the directory the flag moved (issue #4042).
+/// `--no-cd` governs where the user's shell lands, not where the `--execute`
+/// program runs: the program starts in the worktree the switch selected either
+/// way, so `wt switch feature --no-cd -x code -- .` opens the worktree while
+/// the terminal stays put (issue #4042). The header names that worktree,
+/// because the shell won't be there.
#[rstest]
-fn test_switch_no_cd_execute_header_omits_worktree_path(mut repo: TestRepo) {
- repo.add_worktree("feature");
+fn test_switch_no_cd_execute_runs_in_worktree(mut repo: TestRepo) {
+ let worktree = repo.add_worktree("feature");
let output = repo
.wt_command()
@@ -961,14 +961,21 @@ fn test_switch_no_cd_execute_header_omits_worktree_path(mut repo: TestRepo) {
String::from_utf8_lossy(&output.stderr)
);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert_eq!(
+ dunce::canonicalize(stdout.trim()).unwrap(),
+ dunce::canonicalize(&worktree).unwrap(),
+ "--no-cd ran the program outside the worktree: {stdout}"
+ );
+
let stderr = String::from_utf8_lossy(&output.stderr);
let header = stderr
.lines()
.find(|line| line.contains("Executing (--execute)"))
.unwrap_or_else(|| panic!("no --execute header in stderr:\n{stderr}"));
assert!(
- !header.contains('@'),
- "--no-cd runs the program in the invoking directory, but the header named a path: {header}"
+ header.contains('@'),
+ "--no-cd leaves the shell behind, so the header must name the program's directory: {header}"
);
}
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
index 6364e11b5..852bbd974 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
@@ -62,11 +62,11 @@ info:
success: true
exit_code: 0
----- stdout -----
-_REPO_
+_REPO_.exec-test
----- stderr -----
✓ Created branch exec-test from main and worktree @ _REPO_.exec-test
↳ To customize worktree locations, run wt config create
-◎ Executing (--execute):
+◎ Executing (--execute) @ _REPO_.exec-test:
  pwd

diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index 3ac0bec1c..6f05f3dec 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -71,7 +71,9 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Runs one external program after switching, with full terminal control. Arguments after -- go directly to that program without Worktrunk shell parsing. Program lookup and argument decoding follow the operating system. Shell syntax requires an explicit shell, for example -x sh -- -c 'npm install && npm test'. On Windows, shell shims need their extension (-x code.cmd) or an explicit shell such as -x cmd.exe -- /C code.
- Without a branch argument, the interactive picker opens and the command runs against the selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code there. With --no-cd, the program starts in the invoking directory instead.
+ Without a branch argument, the interactive picker opens and the command runs against the selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code there.
+
+ The program starts in the worktree the switch selected, whether or not your shell follows it there: --no-cd governs only the shell.
Supports ]8;;https://worktrunk.dev/hook/#template-variables\hook template variables]8;;\ ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{ base }} and {{ base_worktree_path }} describe the source: the selected base with --create, or the invoking worktree when switching to an existing worktree.
@@ -94,7 +96,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--no-cd
Skip directory change after switching
- Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
+ Hooks still run normally, and an --execute program still starts in the worktree — only your shell stays put, so wt switch feature --no-cd -x code -- . opens the worktree in an editor and leaves your terminal where it was. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation. Use --cd to override.
-h, --help
Print help (see a summary with '-h')