Skip to content

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

fix(hooks): scrub inherited GIT_* discovery vars from user hooks (#3374)

Worktrunk Bot89e858e9c34a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0418bba6..d14de5108 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@
### Fixed
+- **User hooks no longer inherit `wt`'s `GIT_*` discovery vars**: A user hook that shells out to `git` now discovers its repository from the worktree `wt` sets as its cwd, rather than an inherited `GIT_DIR`/`GIT_WORK_TREE` (e.g. from `wt` run as a `!wt` git alias, or nested under another tool's git hook). `wt` now scrubs the `GIT_*` discovery vars at every hook spawn site — foreground, background, and concurrent. Previously the inherited context leaked into hooks: with both `GIT_DIR` and `GIT_WORK_TREE` present, a hook that ran `git init` would write `core.worktree` into the inherited repo's config, silently redirecting later plain git commands there. `wt`'s own internal git plumbing keeps the inherited context (the absolutize-and-forward behavior from [#1914](https://github.com/max-sixty/worktrunk/pull/1914)); aliases keep it too, since a top-level `wt <alias>` is the user's own command. ([#3374](https://github.com/max-sixty/worktrunk/pull/3374), closes [#3373](https://github.com/max-sixty/worktrunk/issues/3373), thanks @silvanshade for reporting)
+
- **`wt remove` preserves your subdirectory position**: Removing a worktree from a subdirectory (e.g. `apps/gateway/`) now lands you in the equivalent subdirectory of the destination worktree rather than at its root — matching how `wt switch` already behaves, and falling back to the root when that subdirectory doesn't exist there. `wt merge` lands through the same handler, so it gains the same behavior. ([#3344](https://github.com/max-sixty/worktrunk/pull/3344), closes [#3343](https://github.com/max-sixty/worktrunk/issues/3343), thanks @caillou for reporting)
## 0.64.0
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 73ecf96e8..7bf2b21a2 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -107,6 +107,14 @@ impl PipelineKind {
Self::Alias { .. } => None,
}
}
+
+ /// Whether this pipeline is a hook (vs an alias). Hooks scrub inherited
+ /// git-discovery env vars from their children so a hook's `git` commands
+ /// resolve against the worktree wt targets, not an inherited `GIT_DIR`
+ /// (issue #3373).
+ fn is_hook(&self) -> bool {
+ matches!(self, Self::Hook { .. })
+ }
}
/// A pipeline step ready for foreground execution, with rendering / error policy.
@@ -522,6 +530,7 @@ fn run_concurrent_group(
.map(|cmd| fg_step.announce.log_label(cmd))
.collect();
+ let scrub_git_discovery = fg_step.announce.is_hook();
let specs: Vec<ConcurrentCommand<'_>> = (0..cmds.len())
.map(|i| ConcurrentCommand {
label: labels[i],
@@ -530,6 +539,7 @@ fn run_concurrent_group(
context_json: &context_jsons[i],
log_label: log_labels[i].as_deref(),
directives,
+ scrub_git_discovery,
})
.collect();
@@ -581,6 +591,7 @@ fn run_one_command(
log_label.as_deref(),
directives.clone(),
fg_step.redirect_stdout_to_stderr,
+ fg_step.announce.is_hook(),
);
match result {
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 0fc85e58b..9dd276c03 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -64,7 +64,7 @@ use std::process::{Child, ExitStatus, Stdio};
use anyhow::Context;
use worktrunk::git::{Repository, WorktrunkError};
-use worktrunk::shell_exec::ShellConfig;
+use worktrunk::shell_exec::{ShellConfig, scrub_git_discovery_env_vars};
use worktrunk::trace::CommandTrace;
use super::command_executor::{expand_shell_template, wait_first_error};
@@ -166,14 +166,17 @@ fn spawn_shell_command(
// `context_json` on stdin, so mark it stdin-reading — the same command
// across worktrees isn't a duplicate (different per-worktree input).
let mut trace = CommandTrace::new(None, expanded).reads_stdin(true);
- let mut child = match shell
- .command(expanded)
+ let mut command = shell.command(expanded);
+ command
.current_dir(worktree_path)
.stdin(Stdio::piped())
.stdout(Stdio::from(log_file))
- .stderr(Stdio::from(log_err))
- .spawn()
- {
+ .stderr(Stdio::from(log_err));
+ // Background hooks, like foreground ones, discover their repo from the
+ // worktree cwd, not an inherited GIT_DIR/GIT_WORK_TREE (issue #3373). This
+ // runner only ever executes hook pipelines, so the scrub is unconditional.
+ scrub_git_discovery_env_vars(&mut command);
+ let mut child = match command.spawn() {
Ok(child) => child,
Err(e) => {
trace.fail(&e);
diff --git a/src/output/concurrent.rs b/src/output/concurrent.rs
index 55e579a70..fb67870fb 100644
--- a/src/output/concurrent.rs
+++ b/src/output/concurrent.rs
@@ -47,7 +47,7 @@ use worktrunk::command_log::log_command;
use worktrunk::git::WorktrunkError;
use worktrunk::shell_exec::{
DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR, ShellConfig,
- scrub_directive_env_vars,
+ scrub_directive_env_vars, scrub_git_discovery_env_vars,
};
#[cfg(unix)]
use worktrunk::signal_forwarder::ForegroundSignals;
@@ -72,6 +72,10 @@ pub struct ConcurrentCommand<'a> {
/// Directive file env vars to pass through to the child. See
/// `DirectivePassthrough` for the trust model (CD passthrough, EXEC scrub).
pub directives: &'a DirectivePassthrough,
+ /// Scrub inherited git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`/…) from the
+ /// child. `true` for hooks (they operate on the worktree wt targets), `false`
+ /// for aliases (they keep wt's inherited context). See issue #3373.
+ pub scrub_git_discovery: bool,
}
/// Run every command concurrently and return each per-child result in input
@@ -292,6 +296,12 @@ fn spawn_child(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // User hooks discover their repo from the cwd wt sets, not an inherited
+ // GIT_DIR/GIT_WORK_TREE (issue #3373). Aliases keep the inherited context.
+ if cmd.scrub_git_discovery {
+ scrub_git_discovery_env_vars(&mut command);
+ }
+
// Scrub all directive env vars, then re-add the passthroughs.
scrub_directive_env_vars(&mut command);
if let Some(path) = &cmd.directives.cd_file {
@@ -494,6 +504,7 @@ mod tests {
context_json: "{}",
log_label,
directives,
+ scrub_git_discovery: false,
}];
run_concurrent_commands(&specs).expect("spawn failed")
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 5222858eb..2fe4a2393 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1938,6 +1938,16 @@ fn remove_removed_worktree_silently(
/// maintain a single rendering state machine — if stdout writes color codes
/// but stderr's output arrives next, the terminal applies stdout's color
/// state to stderr's text. The reset to stderr prevents this.
+///
+/// ## Git discovery
+///
+/// `scrub_git_discovery` removes inherited `GIT_DIR`/`GIT_WORK_TREE` (and the
+/// rest of [`INHERITED_GIT_PATH_VARS`]) from the child so its `git` commands
+/// discover the repo from `working_dir`. Hooks pass `true` (they operate on the
+/// worktree wt targets); aliases pass `false` (they keep wt's inherited context,
+/// like a top-level command the user typed). See issue #3373.
+///
+/// [`INHERITED_GIT_PATH_VARS`]: worktrunk::shell_exec::INHERITED_GIT_PATH_VARS
pub fn execute_shell_command(
working_dir: &std::path::Path,
command: &str,
@@ -1945,6 +1955,7 @@ pub fn execute_shell_command(
command_log_label: Option<&str>,
directives: DirectivePassthrough,
redirect_stdout_to_stderr: bool,
+ scrub_git_discovery: bool,
) -> anyhow::Result<()> {
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
@@ -1960,6 +1971,12 @@ pub fn execute_shell_command(
.current_dir(working_dir)
.forward_signals();
+ // User hooks discover their repo from the cwd wt sets, not an inherited
+ // GIT_DIR/GIT_WORK_TREE (issue #3373). Aliases keep the inherited context.
+ if scrub_git_discovery {
+ cmd = cmd.scrub_git_discovery_env();
+ }
+
if redirect_stdout_to_stderr {
cmd = cmd.stdout(Stdio::from(std::io::stderr()));
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 7b619417a..cce519da7 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -361,6 +361,28 @@ pub fn scrub_directive_env_vars(cmd: &mut std::process::Command) {
cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
}
+/// Scrub the git-discovery path vars ([`INHERITED_GIT_PATH_VARS`]) from a child
+/// `Command`, so the spawned process discovers its repository from its working
+/// directory rather than a `GIT_DIR`/`GIT_WORK_TREE` that `wt` inherited.
+///
+/// Applied when spawning **user hooks**: `wt` sets a hook's working directory to
+/// the worktree it is operating on, so the hook's own `git` commands must
+/// resolve against that worktree — not a git-discovery context `wt` happened to
+/// inherit (e.g. `wt` run as a `!wt` git alias, or nested under another tool's
+/// git hook). Forwarding the inherited context into a hook is a footgun: with
+/// both `GIT_DIR` and `GIT_WORK_TREE` present, a hook that runs `git init`
+/// writes `core.worktree` into the *inherited* repo's config, silently
+/// redirecting every later plain git command there. See issue #3373.
+///
+/// `wt`'s *own* internal git plumbing ([`Cmd`] via `Repository::run_command`)
+/// keeps the inherited context on purpose (relative values absolutized, see
+/// issue #1914), so this scrub is applied only at the hook spawn sites.
+pub fn scrub_git_discovery_env_vars(cmd: &mut std::process::Command) {
+ for var in INHERITED_GIT_PATH_VARS {
+ cmd.env_remove(var);
+ }
+}
+
// ============================================================================
// Directive-Payload Shell Escaping
// ============================================================================
@@ -1081,6 +1103,22 @@ impl Cmd {
self
}
+ /// Scrub inherited git-discovery vars ([`INHERITED_GIT_PATH_VARS`]) from the
+ /// child environment. Applied by user-hook spawn sites so a hook's `git`
+ /// commands discover the repository from the working directory `wt` sets,
+ /// not a `GIT_DIR`/`GIT_WORK_TREE` `wt` inherited. See
+ /// [`scrub_git_discovery_env_vars`] for the rationale (issue #3373).
+ ///
+ /// Applied after the inherited-`GIT_*` absolutization in
+ /// `apply_common_settings` (env-removes run last), so it also overrides the
+ /// relative-path absolutization that would otherwise re-add these vars.
+ pub fn scrub_git_discovery_env(mut self) -> Self {
+ for var in INHERITED_GIT_PATH_VARS {
+ self.env_removes.push(OsString::from(*var));
+ }
+ self
+ }
+
/// Set stdout configuration for `.stream()`.
///
/// Defaults to `Stdio::inherit()`. Use `Stdio::from(io::stderr())` to redirect
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index ee9b54065..183a6ad98 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -3898,3 +3898,110 @@ lint = "cargo clippy"
});
});
}
+
+// ============================================================================
+// Git-discovery env scrubbing (issue #3373)
+// ============================================================================
+//
+// wt forwards inherited `GIT_*` discovery vars (GIT_DIR, GIT_WORK_TREE, …)
+// into the commands it spawns. For wt's own internal git plumbing that is
+// intentional (#1914), but a *user hook* is meant to operate on the worktree
+// wt sets as its cwd — so a hook that shells out to `git` must discover the
+// repo from that cwd, not from a `GIT_DIR`/`GIT_WORK_TREE` wt happened to
+// inherit (e.g. wt run as a `!wt` git alias, or nested under another tool's
+// git hook). The concrete harm: with both `GIT_DIR` and `GIT_WORK_TREE`
+// present, a hook that runs `git init` (common in test-harness fixtures)
+// writes `core.worktree` into the inherited repo's config, silently
+// redirecting every later plain git command in that repo.
+//
+// These tests set a git-discovery context that is *consistent* with the repo
+// wt operates on (GIT_DIR = repo's gitdir, GIT_WORK_TREE = repo root), so wt
+// itself runs normally, then assert the spawned hook does not see the vars.
+// The hook records `$GIT_DIR`/`$GIT_WORK_TREE` — empty once scrubbed — as
+// `[<git_dir>][<work_tree>]`; a fully-scrubbed environment yields `[][]`.
+
+/// Hook body recording the `GIT_DIR`/`GIT_WORK_TREE` it sees to `marker`.
+/// Unset vars expand to empty, so a scrubbed environment writes `[][]`.
+fn record_git_env_cmd(marker: &str) -> String {
+ format!(r#"printf '[%s][%s]' \"$GIT_DIR\" \"$GIT_WORK_TREE\" > {marker}"#)
+}
+
+/// Assert a `record_git_env_cmd` marker shows both discovery vars scrubbed.
+fn assert_git_env_scrubbed(marker: &std::path::Path) {
+ let seen = fs::read_to_string(marker).unwrap();
+ assert_eq!(
+ seen, "[][]",
+ "hook inherited git-discovery vars ([GIT_DIR][GIT_WORK_TREE]): {seen}"
+ );
+}
+
+/// Run `wt hook <args>` with an inherited (but repo-consistent) git-discovery
+/// context, matching what a `!wt` git alias leaves in the environment.
+fn run_hook_with_inherited_git_env(repo: &TestRepo, args: &[&str]) -> std::process::Output {
+ repo.wt_command()
+ .args(args)
+ .env("GIT_DIR", repo.root_path().join(".git"))
+ .env("GIT_WORK_TREE", repo.root_path())
+ .output()
+ .unwrap()
+}
+
+#[rstest]
+fn test_foreground_hook_does_not_inherit_git_discovery_vars(repo: TestRepo) {
+ repo.write_test_config(&format!(
+ "[pre-merge]\nrecord = \"{}\"\n",
+ record_git_env_cmd("env_seen.txt")
+ ));
+
+ let output = run_hook_with_inherited_git_env(&repo, &["hook", "pre-merge", "--yes"]);
+ assert!(
+ output.status.success(),
+ "pre-merge hook run failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let marker = repo.root_path().join("env_seen.txt");
+ assert!(marker.exists(), "foreground hook did not run");
+ assert_git_env_scrubbed(&marker);
+}
+
+#[rstest]
+fn test_background_hook_does_not_inherit_git_discovery_vars(repo: TestRepo) {
+ repo.write_test_config(&format!(
+ "[post-merge]\nrecord = \"{}\"\n",
+ record_git_env_cmd("env_seen.txt")
+ ));
+
+ let output = run_hook_with_inherited_git_env(&repo, &["hook", "post-merge", "--yes"]);
+ assert!(
+ output.status.success(),
+ "post-merge hook dispatch failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // post-* hooks run detached; poll for the marker before reading it.
+ let marker = repo.root_path().join("env_seen.txt");
+ wait_for_file_content(&marker);
+ assert_git_env_scrubbed(&marker);
+}
+
+#[rstest]
+fn test_concurrent_hook_does_not_inherit_git_discovery_vars(repo: TestRepo) {
+ // A multi-command hook table runs as a concurrent group (foreground for a
+ // pre-* hook), exercising the separate concurrent spawn path.
+ repo.write_test_config(&format!(
+ "[pre-merge]\nrecord = \"{}\"\nnoop = \"true\"\n",
+ record_git_env_cmd("env_seen.txt")
+ ));
+
+ let output = run_hook_with_inherited_git_env(&repo, &["hook", "pre-merge", "--yes"]);
+ assert!(
+ output.status.success(),
+ "concurrent pre-merge hook run failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let marker = repo.root_path().join("env_seen.txt");
+ assert!(marker.exists(), "concurrent hook did not run");
+ assert_git_env_scrubbed(&marker);
+}