Skip to content

fix(git): scrub inherited GIT_DIR on worktree-local commands - #4075

Closed
Duang777 wants to merge 3 commits into
max-sixty:mainfrom
Duang777:fix/working-tree-scrubs-inherited-git-dir
Closed

Duang777 wants to merge 3 commits into
max-sixty:mainfrom
Duang777:fix/working-tree-scrubs-inherited-git-dir

Conversation

@Duang777

Copy link
Copy Markdown
Contributor

Summary

  • A !wt git alias from a linked worktree exports GIT_DIR pinned to that worktree's private gitdir (git wt merge from feature → GIT_DIR=.git/worktrees/feature).
  • WorkingTree::run_command relocated git with current_dir but still forwarded that GIT_DIR, so status / read-tree / rev-parse --git-dir used the invoking worktree's index.
  • wt merge's target conflict check then compared the feature index to the main worktree and refused a clean merge (Can't push to local main branch: conflicting uncommitted changes naming the feature's own files).
  • Worktree-local git now drops the discovery vars that pick a worktree. Repository::run_command still keeps the inherited context so the alias finds the repository (repo_path differs when invoked via git alias (git wt ...) in bare-layout repositories #1914).

Test plan

  • cargo test --test integration test_merge_syncs_target_when_git_dir_names_the_source (red before the scrub: false conflict on feature.txt; green after)
  • cargo test --test integration test_merge_fast_forward
  • cargo test --test integration test_merge_as_git_subcommand
  • cargo test --lib -- working_tree:: git::remove::
  • git wt merge from a feature worktree (alias.wt = "!wt") — merge succeeds, main is clean and has the feature files

Made with Cursor

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The WorkingTree::run_command_output scrub is the right fix for the path this targets. I reproduced the mechanism outside worktrunk to be sure of it: with GIT_DIR pinned to a linked worktree's private gitdir, git status --porcelain run in the main worktree reports D feature.txt — exactly the phantom overlap ensure_no_target_conflicts turns into Can't push to local main branch: conflicting uncommitted changes. One gap to resolve before this lands.

WorkingTree::prepare_diff is the same class of call site and is still unscrubbed. In src/git/repository/diff.rs, PreparedDiff::command's DiffSource::Repository arm builds Cmd::new("git") … .current_dir(path) with the identical with_object_store_env + path_to_logging_context shape as run_command_output, and WorkingTree::prepare_diff hands it self.path. Two consumers produce wrong output under a !wt alias from a linked worktree:

  • compute_live_worktree_diff in src/commands/picker/items.rs takes WorktreeDiffState::TrackedOnly => worktree.prepare_diff([base]), while the sibling arm HasUntracked | Unknown => worktree.prepare_diff_with_untracked(…) routes through TempIndex, which this PR does scrub. After this change the two arms of one match read different worktrees.
  • src/summary.rs's "Working tree diff: uncommitted changes" block (repo.worktree_at(wt_path).prepare_diff(["HEAD"])) would feed the invoking worktree's uncommitted diff into the branch summary for a different branch.

It isn't a one-liner: Repository::prepare_diff shares that same DiffSource::Repository arm and must keep the inherited context per the split you documented, so the variant has to carry which side it is on. I'm happy to push that as a commit on this branch if you'd prefer not to.

Worth deciding together with it: once the diff site is fixed the same way, three sites hand-roll the same env_remove list, where CLAUDE.md asks for Cmd::scrub_git_discovery_env or scrub_git_discovery_env_vars. The existing helper genuinely can't be reused as-is — apply_common_settings applies env-removes after envs, so it would strip both the object-store env and TempIndex's own GIT_INDEX_FILE — so the shape that does work is a helper for the worktree-selection trio (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR), leaving GIT_INDEX_FILE to each call site.

One process note: this changes which index every worktree-level git status reads, including the dirty gates wt remove and wt merge cleanup consult before deleting a worktree (WorkingTree::ensure_clean and is_dirty both route through run_command_output). The direction is toward correctness — the pre-fix behavior could mask a genuinely dirty target — but this repo's review guidance holds changes reaching that surface for a human, so I'm not approving; requesting @max-sixty.

Comment thread src/shell_exec.rs Resolved
Comment thread tests/integration_tests/merge.rs Resolved
@Duang777

Copy link
Copy Markdown
Contributor Author

Addressed the review in 482b825:

  • WorkingTree::prepare_diff now relocates through PreparedDiff::for_worktree; Repository::prepare_diff still keeps the inherited context. DiffSource::Repository carries that split as relocate.
  • The three worktree-local sites share Cmd::scrub_worktree_selection_env (GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR). GIT_INDEX_FILE is removed or set at each call site so the object-store env and TempIndex survive.
  • Test comment names ensure_no_target_conflicts as the gate that actually fires.

Still waiting on @max-sixty for the dirty-gate surface (ensure_clean / is_dirty go through run_command_output).

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both prior findings are resolved, and I verified the substance rather than the description: WorkingTree::prepare_diff now goes through PreparedDiff::for_worktree, Repository::prepare_diff still routes through PreparedDiff::new with relocate: false (its path is discovery_path(), so the alias context is the right one to keep), and the env_remove/env ordering holds — apply_common_settings applies env_removes after envs, and the removes list never names GIT_OBJECT_DIRECTORY/GIT_ALTERNATE_OBJECT_DIRECTORIES, so with_object_store_env survives the scrub at all three sites and TempIndex's own GIT_INDEX_FILE survives at the fourth. I also checked the two #1914 regression tests in tests/integration_tests/bare_repository.rs against the new scrub: both compare an aliased invocation to a baseline with no GIT_* set, so the scrub makes the aliased path converge on the baseline rather than diverge from it.

One same-class site the split leaves behind, outside this diff. stop_fsmonitor_daemon in src/git/remove.rs runs Cmd::new("git").args(["fsmonitor--daemon", "stop"]).current_dir(worktree.path()) with no scrub, and start_fsmonitor_daemon_at in src/git/repository/mod.rs does the same with a bare std::process::Command (it applies apply_hermetic_test_env and scrub_directive_env_vars, but not the git-discovery scrub). Both relocate git into a wt-chosen worktree, so under git wt remove <other-branch> from a linked worktree the stop IPC goes to the invoking worktree's daemon and the one being removed is never asked to exit. On Unix this PR incidentally papers over it: worktree.git_dir() now resolves correctly, so force_kill_fsmonitor_via_socket finds the target's still-live socket and escalates. On Windows that function is fn force_kill_fsmonitor_via_socket(_socket: &Path) {}, so nothing catches it — which is the leaked-forever daemon the function's own doc comment exists to prevent. Pre-existing rather than introduced here, and a one-call fix at each site; happy to push it onto this branch if you'd rather keep the PR scoped as-is.

Verdict is unchanged from the last round — the dirty-gate surface is still @max-sixty's call, not mine.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Adding one more same-class site to the review I just posted — a different subsystem from the fsmonitor pair, and the one with a user-visible wrong result rather than a leaked process.

run_git_capture in src/llm.rs builds Cmd::new("git") … .current_dir(cwd) with no scrub, and that cwd is always wt.path() — a worktree wt chose, not necessarily the invoking one. Both ends of the call chain already say so in as many words: generate_commit_message's doc ("It is not always the invoking worktree: wt step commit --branch <b> and wt step relocate --commit commit somewhere else, and reading the diff from the cwd instead handed the LLM an empty diff") and the call site in src/commands/commit.rs ("the prompt must describe the diff that is about to be committed"). That bug was fixed from the cwd angle; the GIT_DIR angle is still open. So under a !wt alias, git wt step commit --branch other builds the commit prompt from the invoking worktree's staged diff, and with no commit.generation command configured the fallback names the invoking worktree's files in the message it writes. Unlike the fsmonitor case nothing downstream catches it — the commit lands with a message describing the wrong tree.

The fix is the shape this PR already established: scrub_worktree_selection_env(), then env_remove("GIT_INDEX_FILE") when index_override is None, keeping the existing .env(…) when it's Some so --dry-run's temp index still works.

Whether this and the fsmonitor sites land here or as follow-ups is your call — but I'd not ship the classification ahead of them. The CLAUDE.md paragraph and the scrub_git_discovery_env_vars doc now both name "worktree-local plumbing" as scrubbed, and a reader grepping that rule would conclude the commit-prompt path is covered. Same over-broad-invariant problem I raised on src/shell_exec.rs in the first round, one file over, and you fixed it there the right way — by naming the two covered methods. Either extend the scrub or keep the wording enumerative.

Minor and separable, this one inside the diff: list_ignored_entries went from scrub_git_discovery_env() in 1d8d472 to scrub_worktree_selection_env() + env_remove("GIT_INDEX_FILE") in 482b825. That call site has no object-store env and no TempIndex, so it has nothing for the narrower helper to preserve — the full scrub it had in the first commit is both stronger and one call shorter.

Reproduction of the run_git_capture mechanism (plain git, no worktrunk)

Stage a file only in the feature worktree, then ask the main worktree what's staged, with GIT_DIR pinned to feature's private gitdir the way a !wt alias exports it:

$ git init -q -b main repo && cd repo && echo base > base.txt && git add . && git commit -qm base
$ git worktree add -q ../feature -b feature
$ cd ../feature && echo secret > feature-only.txt && git add feature-only.txt && cd ../repo

$ git diff --staged --name-only                      # main worktree: nothing staged
$ GIT_DIR="$PWD/.git/worktrees/feature" git diff --staged --name-only
feature-only.txt
$ env -u GIT_DIR git diff --staged --name-only       # scrubbed: correct, prints nothing

git diff --staged --name-only -z is the argv the no-LLM fallback passes to run_git_capture; build_commit_prompt's --no-pager diff --staged and --staged --stat go through the same helper with the same cwd.

mjfuddel-eng

This comment was marked as spam.

mjfuddel-eng

This comment was marked as spam.

Duang777 and others added 3 commits September 13, 2026 10:42
A !wt alias from a linked worktree pins GIT_DIR to that worktree's
admin dir. WorkingTree::run_command forwarded it, so merge's target
conflict check compared the feature index to the main worktree and
refused a clean merge.

Co-authored-by: Cursor <[email protected]>
The same inherited GIT_DIR that fooled status also reaches the picker
and branch-summary diffs. Carry relocate on DiffSource so repository
diffs keep the alias context, and share the worktree-selection trio
instead of repeating env_remove.

Co-authored-by: Cursor <[email protected]>
Same relocate class as WorkingTree::run_command: run_git_capture,
fsmonitor stop/start, and list_ignored_entries (full scrub — nothing
to preserve). Extend the classification docs to name them.

Co-authored-by: Cursor <[email protected]>
@Duang777
Duang777 force-pushed the fix/working-tree-scrubs-inherited-git-dir branch from 482b825 to f87f615 Compare September 13, 2026 02:45
@Duang777

Copy link
Copy Markdown
Contributor Author

Rebased onto main (clears the #4073 conflict) and addressed the follow-up sites in f87f615:

  • run_git_capture now uses scrub_worktree_selection_env() and drops GIT_INDEX_FILE unless --dry-run supplies an override — regression: test_step_commit_branch_prompt_follows_target_not_git_dir.
  • stop_fsmonitor_daemon and start_fsmonitor_daemon_at scrub the same way (raw Command uses scrub_git_discovery_env_vars).
  • list_ignored_entries restored to the full scrub_git_discovery_env() — nothing for the narrower helper to preserve.
  • Classification docs name the commit-prompt and fsmonitor sites so they match the scrub.

Still waiting on @max-sixty for the dirty-gate surface.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codecov/patch is red on exactly one line, and that line can't be reached by the job that measures it. 50 of 51 patch lines are hit — 98.03% against a 98.29% target — and the single miss is the new scrub_git_discovery_env_vars(&mut cmd) call in start_fsmonitor_daemon_at. That function's only caller is macOS-gated: in src/commands/list/collect/mod.rs, fsmonitor_worktrees is built under #[cfg(target_os = "macos")] from repo.is_builtin_fsmonitor_enabled(), and the #[cfg(not(target_os = "macos"))] arm hard-codes an empty vec. So on the Linux code-coverage runner the whole function is unreachable — every line of it already misses there, and this PR added one more. Two ways out, each with a cost worth weighing against simply approving the red: a unit test calling it directly would cover the line but starts a real fsmonitor daemon against the test repo, and putting #[cfg(target_os = "macos")] on the function (plus its call site) would drop the line from instrumentation entirely, at the price of no longer compile-checking it on Linux and Windows. Root CLAUDE.md → Coverage makes this check a merge gate needing explicit approval, so it is @max-sixty's call either way — recording the arithmetic so it doesn't have to be re-derived.

Separately, the fsmonitor pair ended up scrubbing two different ways: stop_fsmonitor_daemon removes the selection trio plus GIT_INDEX_FILE, start_fsmonitor_daemon_at removes all five. The two spawns are equivalent in effect — neither carries an object-store env or a TempIndex — so the split buys nothing, and it is what makes the new classification prose wrong in two places. The inline suggestions collapse it to one rule, full scrub at both fsmonitor sites, which is the same reasoning you applied when restoring list_ignored_entries to scrub_git_discovery_env().

Verdict stays COMMENT for the reason the last two rounds gave.

Comment thread src/git/remove.rs Resolved
Comment thread src/git/repository/mod.rs Resolved
Comment thread src/shell_exec.rs Resolved
Comment thread CLAUDE.md Resolved
@max-sixty

Copy link
Copy Markdown
Owner

this changes way too many core fields

@Duang777 additional PRs need more care, please

@max-sixty max-sixty closed this Sep 13, 2026
@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot was there actually an underlying issue here? Make a concise issue with a reproduction if so

@worktrunk-bot

worktrunk-bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Yes — filed as #4081 with a reproduction.

Corrected 2026-09-13: this comment originally attributed the failure to git wt merge. That was wrong — worktrunk's git wt is the git-wt binary dispatched as a git subcommand, and git exports no GIT_DIR to an external subcommand, so that path merges cleanly. The trigger is an inherited GIT_DIR; a !-alias and a git hook are two ways to acquire one. #4081 carries the corrected reproduction. The paragraph below is otherwise unchanged.

Confirmed on main (28399c2) with the built binary, not by inspection: wt merge from a linked worktree with GIT_DIR inherited fails with Can't push to local main branch: conflicting uncommitted changes against a main that is clean, while wt merge run directly on the identical state merges fine. Git exports GIT_DIR to a ! alias pinned to the invoking worktree's gitdir, WorkingTree::run_command_output forwards it past its own current_dir, and the target-conflict gate's git status then reads the source worktree's index. The phantom entries are exactly the push range, so any branch that touches a file hits it, and env -u GIT_DIR doesn't help — git re-supplies the variable when it spawns the alias.

The issue is diagnosis and reproduction only. I left the fix scope open rather than proposing one: ensure_clean and is_dirty route through the same method, so it isn't additive, and that's the surface I'd already flagged as your call in the review rounds here.

@Duang777

Copy link
Copy Markdown
Contributor Author

Resubmitted as a narrower PR that only touches the #4081 path (WorkingTree::run_command / TempIndex / one ignored-file listing), without the prepare_diff / commit-prompt / fsmonitor follow-ups from this closed branch: https://github.com/max-sixty/worktrunk/pulls?q=is%3Apr+author%3ADuang777+4081

Sorry for the oversized first attempt.

@Duang777

Copy link
Copy Markdown
Contributor Author

Narrow follow-up: #4082

max-sixty pushed a commit that referenced this pull request Nov 22, 2026
`WorkingTree::prepare_diff`, `prepare_staged_diff` and
`prepare_commit_diff` run `diff-index`/`diff-tree` in a worktree
Worktrunk picked, but they kept inherited `GIT_DIR`, `GIT_WORK_TREE` and
`GIT_INDEX_FILE`. When `wt` runs from a Git hook or a `!wt` alias in a
different worktree, those diffs read the invoking worktree's index and
HEAD. So `wt step commit --branch <b>` built its stats line and LLM
prompt from the wrong worktree's staged changes. The picker's diff
preview and the summary diff had the same problem.

AGENTS.md requires this scrub for worktree-local plumbing, and the
sibling paths already apply it (`WorkingTree::run_command` and
`TempIndex::command`). This PR applies `scrub_git_discovery_env()` to
the three `WorkingTree` diff constructors. `Repository::prepare_diff` is
repo-level and keeps the inherited context, as `Repository::run_command`
does. `with_object_store_env` still runs after the scrub, so a
redirected repository's own `GIT_OBJECT_DIRECTORY` survives.

The new
`test_step_commit_show_prompt_branch_ignores_inherited_git_context`
stages a file in each of two worktrees. It runs `wt step commit
--show-prompt --branch feature` with the primary worktree's
`GIT_DIR`/`GIT_WORK_TREE`/`GIT_INDEX_FILE`. Before the fix, the preview
diffed `caller_only.txt`, the invoking worktree's file. Now it diffs
`feature_only.txt`.

The closed #4075 included this change in a much broader diff. It was
dropped there for scope, not on approach. The narrower #4082 that landed
instead covered only `WorkingTree::run_command`, `TempIndex` and the
ignored-file listing.

Co-authored-by: worktrunk-bot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants