Skip to content

fix(git): tolerate non-git paths in WorkingTree::is_linked - #2625

Merged
max-sixty merged 5 commits into
mainfrom
fix/issue-2624
May 7, 2026
Merged

max-sixty merged 5 commits into
mainfrom
fix/issue-2624

Conversation

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Problem

branch_diff_empty_when_no_commits_ahead and branch_diff_shows_diff_when_commits_ahead (and any other test path that resolves the default branch) fail when the test binary's process CWD isn't inside a git repository — exactly the case the Nix build sandbox creates by extracting the source tarball without .git.

infer_default_branch_locally calls self.current_worktree().is_linked()?. current_worktree() uses the process-wide base_path(), which in the sandbox is /build/source/. is_linked() runs git rev-parse --git-dir there, exits non-zero, and the ? propagates the error so default_branch() returns None. Reproduction confirmed locally:

cd /tmp/notgit && /path/to/wt-<hash> branch_diff
# branch_diff_empty_when_no_commits_ahead ... FAILED
# branch_diff_shows_diff_when_commits_ahead ... FAILED

Solution

Treat a path that isn't inside any git repo as unambiguously not a linked worktree (Ok(false) rather than Err). Genuine git_dir() failures elsewhere still surface — is_linked() is the narrow place where "no repo here" is a definitive answer rather than an unknown.

Testing

  • New unit test is_linked_returns_false_for_path_outside_any_git_repo fails before the fix (git rev-parse --git-dir failed (exit 128)) and passes after.
  • The reporter's reproduction (cd /tmp/notgit && wt-<hash> branch_diff) now passes both branch_diff_* tests.
  • cargo test --lib clean apart from testing::mock_commands::tests::test_mock_config_write, which fails identically on main without this change (local-env flake, not this PR).

Closes #2624 — automated triage

`infer_default_branch_locally` calls `current_worktree().is_linked()?` to
decide whether HEAD inspection is meaningful. When the process CWD isn't
inside any git repo (e.g. the Nix build sandbox extracts source tarballs
without `.git`), `git rev-parse --git-dir` exits non-zero, the error
propagated up, and `default_branch()` returned None — breaking unit tests
that called it transitively (`branch_diff_empty_when_no_commits_ahead`,
`branch_diff_shows_diff_when_commits_ahead`).

Treat a path outside any git repo as unambiguously not a linked worktree.
The error path is still preserved for genuine failures since `git_dir()`
itself remains fallible elsewhere.

Closes #2624

Co-Authored-By: Claude <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The fix itself is small and correct — treating "path outside any git repo" as Ok(false) for is_linked is the right answer. One blocker on the new test: clippy bool_assert_comparison is failing the lint job (see run 25458360318). Inline suggestion below.

Comment thread src/git/repository/working_tree.rs Resolved
@max-sixty

Copy link
Copy Markdown
Owner

why are the tests exposed to anything about the cwd? let's fix that

… CWD

Replaces the band-aid `is_linked` change with the underlying fix max-sixty
flagged in review: tests (and other `Repository::at(p)` callers) shouldn't
be exposed to process CWD at all. `infer_default_branch_locally` was probing
`self.current_worktree().is_linked()`, which uses the process-wide
`base_path()` rather than `self.discovery_path()` — so a `Repository::at(test_repo)`
would consult the test binary's CWD when answering a question about the
test repo.

Anchor the linked-worktree probe to `self.discovery_path()` instead. For
production callers (`Repository::current()`) the two paths are identical;
for `Repository::at(p)` the probe now correctly uses `p`. Reverts the
`is_linked` early-return on non-repo paths and removes its test — the
function's contract (caller has a real worktree path) is restored.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Agreed — the band-aid in is_linked masked the real problem instead of fixing it. Pushed 1e0dfb3c which:

  • Anchors the linked-worktree probe in infer_default_branch_locally to self.discovery_path() instead of self.current_worktree() (which falls back to the process-wide base_path()). For Repository::current() the two are identical; for Repository::at(p) (tests, wt list pipeline workers, recovery) the probe now correctly uses p.
  • Reverts the is_linked early-return on non-repo paths and drops its unit test — the function's original contract is restored.

The branch_diff_* tests still pass when run from /tmp/notgit, which was the Nix-sandbox repro.

@max-sixty

Copy link
Copy Markdown
Owner

ok, it seems like there's likely a bug here regardless of the specific issue. add a test that -C works, and anywhere else that might have a gap.

Presumably if we were in a bare worktree with -C in a linked worktree, the existing code would be wrong? or that's not how the -C works?

max-sixty asked in #2625 review: "add a test that `-C` works, and anywhere
else that might have a gap. Presumably if we were in a bare worktree with
`-C` in a linked worktree, the existing code would be wrong?"

Two regression tests:

1. `wt -C <repo> config state default-branch` invoked from a directory
   that isn't inside any git repo, with origin removed so the call falls
   into `infer_default_branch_locally` (the formerly-buggy probe).

2. The bare-repo flavor: `wt -C <linked-worktree-of-bare>` from the same
   non-repo CWD. Pins down the answer to max-sixty's specific concern
   (it isn't wrong) so the combination stays covered.

`-C` itself doesn't trigger the original bug — it sets `base_path()` to
the same path `Repository::current()` adopts as `discovery_path()`, so
`current_worktree()` (the old probe) and `worktree_at(discovery_path())`
(the new one) resolve to the same directory. The bug only fires for
`Repository::at(p)` where `p \!= base_path()`, which is the test code
path the unit tests in `picker/items.rs` already cover. These are
end-to-end coverage on top of that.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Pushed b74f8a71 with two -C regression tests in tests/integration_tests/default_branch.rs:

  1. wt -C <repo> config state default-branch invoked from a non-repo CWD, with origin removed so the call lands in infer_default_branch_locally (the formerly-buggy probe).
  2. The bare-repo flavor: wt -C <linked-worktree-of-bare> from the same non-repo CWD.

On the question itself: -C is the CWD shortcut (it calls set_base_path(path) in apply_global_options), and Repository::current() then uses that same base_path() as its discovery_path. So for the binary's normal flow, current_worktree() (old probe) and worktree_at(self.discovery_path()) (new probe) resolve to the same directory — bare repo + -C linked-worktree gives the same answer either way. The bare-repo test pins that down so we don't regress it.

Where the fix actually buys us something is Repository::at(p) where p != base_path(). That's the test-code path (Repository::at(t.path()) from a process CWD that isn't itself a repo, which is what the Nix sandbox creates), already covered by the existing branch_diff_* tests in picker/items.rs.

For "anywhere else that might have a gap": I audited the other self.current_worktree() callers inside Repository:

  • project_config_path() / project_config() (src/git/repository/config.rs) use self.current_worktree() to locate the worktree's .config/wt.toml. Same shape as the original bug — Repository::at(p) would consult the process CWD's worktree instead of p. Not triggered today (production Repository::at callers in output/handlers.rs and commands/run_pipeline.rs don't load project config), but it's the same latent issue. Happy to anchor those to discovery_path() in this PR if you'd like, or split it out.
  • resolve_worktree_name("@") and require_current_branch() are intentionally CWD-relative — @ semantically means "the worktree the user is currently in", so current_worktree() is the right thing there.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The fix is correct: worktree_at(self.discovery_path()) decouples the linked-worktree probe from process CWD, which is the right answer for Repository::at(p) callers. One nit on test_default_branch_via_c_flag_to_linked_worktree_of_bare_repo — the explicit write+add before commit_in duplicates what commit_in already does (writes file.txt, stages, commits).

`commit_in` already writes `file.txt` and stages it before committing,
so the explicit setup was rewriting "hello" then immediately overwriting
it with "init".

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@max-sixty
max-sixty merged commit ab45e00 into main May 7, 2026
27 checks passed
@max-sixty
max-sixty deleted the fix/issue-2624 branch May 7, 2026 08:12
max-sixty pushed a commit that referenced this pull request May 8, 2026
)

## Summary

PR #2633 was a bad triage outcome — closed by the maintainer with
[feedback asking what changes we could make to
tend](#2633 (comment)):

> this was bad: it should have avoided creating a PR assuming the
outstanding PR would have fix the issue / and the change was ti change
the tests! but we should have fixed the code! / consider what changes we
could make to tend

Two distinct mistakes from that run, each addressed by a new H3 under
`## Issue Triage` in `running-tend`:

1. **Don't fix tests by adding skip guards.** Tend's "fix" was `let
Ok(_) = Repository::current() else { return };` so the test would
silently bail in the Nix flake build sandbox. That removes coverage
instead of fixing the real issue. The new section gives a smell list
(early-return skips, newly-added `#[ignore]`, `if !path.exists() {
return; }`) and tells the run to stop and look at production code or
test setup instead.
2. **Same-root-cause-class triage.** PR #2625 was open ~10 hours fixing
the same root-cause class ("process CWD outside any git repo") via
production code. The triage PR's own body acknowledged "Same root-cause
class as #2624" but proceeded with a parallel narrow test-skip PR. The
new section says: when multiple failing tests share a root-cause class
and an outstanding PR addresses any of them, wait for it to merge and
re-run, or mirror its approach for the additional sites.

Both rules anchored to PR #2633 / PR #2625 / issue #2632 so future runs
can see the incident they were distilled from.

The "don't fix tests by adding skip guards" rule may also generalize
beyond worktrunk — happy to file a follow-up issue against the bundled
`triage` skill if you think it belongs there too.

## Test plan

- [ ] Maintainer review of wording / placement under `## Issue Triage`

---------

Co-authored-by: worktrunk-bot <[email protected]>
Co-authored-by: Claude <[email protected]>
max-sixty pushed a commit to max-sixty/tend that referenced this pull request May 8, 2026
…oot-cause PRs (#394)

## Problem

Triage feedback from a run in `max-sixty/worktrunk` (PR
[#2633](max-sixty/worktrunk#2633)) surfaced two
patterns the bundled `triage` skill doesn't currently guard against:

1. The triage run "fixed" a failing test by inserting an early-return
that silently bailed when the bug fired, removing coverage instead of
restoring the assertion.
2. An outstanding PR ([worktrunk
#2625](max-sixty/worktrunk#2625)) had been
merged ~3 minutes earlier with a production-code fix for the same
root-cause class. The triage PR's own body even named it as
same-root-cause — but Step 3's duplicate check only catches identical
fixes, not the *same root cause class, different surface* pattern, so
the run shipped a parallel narrow workaround anyway.

worktrunk's overlay captured both rules in [worktrunk PR
#2639](max-sixty/worktrunk#2639); both look
generalizable to every tend consumer, hence promoting them to the
bundled skill.

## Solution

Two new subsections under Step 6 of
`plugins/tend-ci-runner/skills/triage/SKILL.md`:

- **Don't "fix" tests by adding skip guards** — names the smell patterns
(newly-added early-returns, fresh `#[ignore]`, `pytest.skip` keyed on
the failing condition).
- **Defer to in-flight same-root-cause PRs** — when triage analysis
itself names an existing PR as same-root-cause, that's the signal to
wait, not to ship a parallel workaround.

Both are strict additions. Step 3's existing duplicate-check guidance
and Step 6's "Fix the root cause (not just the symptom)" remain in
place; the new rules fill gaps neither covered.

## Testing

`pre-commit run --files plugins/tend-ci-runner/skills/triage/SKILL.md`
passes (trim trailing whitespace, fix end of files, typos, forbid
bang-backtick).

---
Closes #393 — automated triage

Co-authored-by: tend-agent <[email protected]>
Co-authored-by: Claude <[email protected]>
max-sixty added a commit that referenced this pull request May 9, 2026
…2652)

## Summary

`Repository::current_worktree()` resolved against the process-global
`base_path()` (CWD or `-C`), not against the Repository's own
`discovery_path`. The two coincide for `Repository::current()` (the
common case), but `Repository::at(p)` callers — output handlers, picker,
run_pipeline, tests, recovery — silently got a WorkingTree at the
*process CWD* instead of at `p`.

PR #2625 patched one symptom inline (`infer_default_branch_locally` was
calling `current_worktree().is_linked()` and reaching for the wrong
path). This change fixes the helper itself, which subsumes that
workaround and the sibling sites identified in the audit (Pass B from
the structural audit done in PR #2649's session): `project_config_path`,
`project_config`, `require_current_branch`,
`resolve_worktree_name("@")`, `resolve_worktree("@")`.

## Why structural over per-site

Five sibling sites use `self.current_worktree()` with the same intent:
"operate on the worktree this Repository represents." Patching each
individually would leave the helper as a footgun — the next sibling
added would re-introduce the bug. Fixing `current_worktree()` itself
matches what its name has always promised. Audited production callers;
none rely on the old "use process CWD even though `self` was constructed
elsewhere" semantics.

## What's in this diff

- `src/git/repository/mod.rs`: `current_worktree()` →
`worktree_at(self.discovery_path.clone())`. Docstring explains the dual
semantics.
- `src/git/repository/config.rs`: revert PR #2625's per-method
workaround (now redundant).
- `src/git/repository/working_tree.rs`: update `WorkingTree::path`
docstring that referenced `base_path()`.
- `src/git/repository/tests.rs`: regression test pins both directions —
matches `discovery_path()`, *not* process CWD.
- `src/commands/worktree/switch.rs`: gate the source-worktree capture on
`!is_recovered`. Without this, `current_worktree()` in recovery mode
would resolve to the *recovered ancestor* (typically the main worktree)
and expand `{{ base }}` / `{{ base_worktree_path }}` to main's identity
instead of empty strings. Mirrors the existing `!is_recovered` gate on
pre-switch hooks at line 1264. Caught by code review.
- `tests/integration_tests/repository.rs`: remove three stale "use
worktree_at, not current_worktree() which uses base_path()" comments.

## Test plan

- [x] All 1740 unit tests pass
- [x] Full integration suite (1632 tests) passes
- [x] PR #2625's two regression tests still pass (the structural fix
preserves the original bug-fix's behavior)
- [x] `pre-commit run --all-files` clean

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <[email protected]>
@max-sixty max-sixty mentioned this pull request May 10, 2026
3 tasks done
max-sixty added a commit that referenced this pull request May 10, 2026
Bump worktrunk to **0.49.0** — minor bump (semver-checks reports a
breaking change in `GitError::UncommittedChanges`, which gained a
`dirty_files: Vec<String>` field).

## Highlights

**Improved**
- New `codename(n)` template filter — deterministic friendly worktree
names from a ~1.26M-combo pool (`{{ branch | codename(2) }}` →
`malleable-opah`).
[#2641](#2641), thanks
@endigma
- Picker preview disk cache for Log / BranchDiff / UpstreamDiff, with
background refresh for stale Log decorations.
[#2628](#2628),
[#2646](#2646)
- Picker shares one `default_branch_sha` lookup across BranchDiff items
instead of forking N rev-parse subprocesses.
[#2658](#2658)
- "X has uncommitted changes" errors now list the dirty files inline.
[#2653](#2653)

**Fixed**
- `wt switch` integrates with `cd` aliases like zoxide (uses `builtin
cd`). [#2644](#2644), thanks
@xkumiyu for reporting
- Empty hook tables no longer panic during `wt switch --create`.
[#2635](#2635), thanks @topit
for reporting
- `Repository::current_worktree()` and five sibling helpers no longer
silently leak the process CWD when called via `Repository::at(p)`.
[#2652](#2652)
- `WorkingTree::is_linked` tolerates non-git CWDs (e.g. Nix sandbox).
[#2625](#2625), thanks
@DArtagan for reporting
- Picker no longer overlays `collect` warnings on the active TUI; clears
its frame on exit in inline mode.
[#2627](#2627),
[#2626](#2626)
- Failed `git log` no longer poisons the picker's preview disk cache.
[#2651](#2651)
- `wt step prune` says "removing branch" for branch-only candidates.
[#2619](#2619)
- Claude Code Windows integration uses a `wt.sh` wrapper to avoid
colliding with Windows Terminal's `wt.exe`.
[#1754](#1754), thanks
@lucaspimentel

**Documentation**
- cmux workspace integration recipe.
[#1907](#1907), thanks
@alvistar

See
[CHANGELOG.md](https://github.com/max-sixty/worktrunk/blob/release/CHANGELOG.md)
for the full list including internal CI / test-isolation changes.

## Test plan

- [x] `cargo run -- hook pre-merge --yes` (tests + lints clean)
- [x] `cargo semver-checks check-release -p worktrunk` (one breaking
change confirmed → minor bump)
- [x] CHANGELOG entries verified by subagent against actual diffs

🤖 Generated with [Claude Code](https://claude.com/claude-code)
max-sixty added a commit that referenced this pull request Jul 24, 2026
`-C` sets the repository discovery path but never chdir's the process,
so anything reading `std::env::current_dir()` silently ignores it. Two
places did.

## `wt list statusline` described the wrong worktree

`wt -C /path/to/other/worktree list statusline` printed the statusline
for the *cwd's* worktree, and from a directory outside any repo it
printed nothing at all.

Both formats now resolve their worktree through
`Repository::current_worktree()`, which anchors to the discovery path.
That accessor already exists for this bug class (its docstring cites
#2625), so this is routing the statusline onto the canonical path rather
than adding a new one.

Details worth knowing while reading the diff:

- `--format=json` was mostly right already. It picked its worktree via
`current_worktree()` and only its "are we in a worktree" gate read the
cwd, so it misbehaved just when the process cwd sat outside a repo
(printed `[]`). That gate moves to `current_worktree()` and the `cwd`
binding is gone.
- `git_status_segments` now takes a `WorkingTree` instead of
`(&Repository, &Path)`. That also settles a split inside it: the
worktree lookup used the cwd while the no-worktree fallback used
`repo.current_worktree()`.
- `--format=claude-code` is unchanged where it matters. The directory
Claude Code sends on stdin still wins, since that names the session's
directory rather than wt's. With no stdin it falls back to the same
worktree as the other formats, so it honours `-C` too.

Four integration tests. Three run from the main worktree with `-C`
pointed at a `feature` worktree, one per format; the existing statusline
tests all set the child's cwd, which is the route that already worked.
The fourth pins the claude-code split: when stdin names a directory in a
*different* repository, the worktree comes from stdin while
`list_worktrees` comes from wt's discovery path, so nothing matches and
only the branch is reported. That fallback previously had no test, which
is what `codecov/patch` caught on the first push.

Discovering the `Repository` from the stdin directory instead would
remove that split, but it would miss the `prewarm` cache (keyed on the
base path) that this prompt-redraw hot path depends on, so the split
stays and is now asserted rather than incidental.

## Supplied paths resolved from the shell, not from `-C`

`wt switch ../repo.feature` and `wt remove ../repo.feature` joined the
argument onto the process cwd. With `-C` in play that split the
invocation in two — wt chose the repository, the shell chose the path —
and the combination resolved to nothing, so `switch` reported "No branch
named ../repo.feature". `--config`, `WORKTRUNK_CONFIG_PATH`,
`WORKTRUNK_SYSTEM_CONFIG_PATH`, and the trace file of `wt config state
logs profile` name a file the same way and had the same gap: `wt -C repo
--config mycfg.toml config show` reported "Config file not found" for a
file sitting in `repo/`.

Git resolves the paths in its command line against its own `-C`, because
it chdir's there before doing anything else. wt's `-C` sets a discovery
path instead, so `resolve_input_path` joins onto that — one resolution
point for all five, so they cannot drift apart. It returns the path
untouched when `-C` was not given, rather than joining `.` onto it: the
process cwd already resolves those, and the join would surface as a
stray `./` in output. `Path::join` leaves an absolute path alone, which
drops an `is_absolute` branch and, in `resolve.rs`, a fallible
`current_dir()` call.

Three neighbours are deliberately outside the rule, and the docstring
says why:

- Paths wt derives itself — a worktree root from `git worktree list`, an
XDG config directory — arrive absolute.
- `WORKTRUNK_PROJECT_CONFIG_PATH` resolves from the worktree root, its
documented base, because the project config is per-worktree.
- `WORKTRUNK_BIN` and `XDG_CONFIG_DIRS` are never opened by wt: the
first is expanded later by the generated shell wrapper, and the XDG spec
already requires the second to be absolute.

Four integration tests, one per surface, each running from *outside* the
repo with `-C` pointed into it — the neighbouring tests run from a cwd
inside the repo, which is the route that works under either rule. All
four fail against the old code: `switch` with "No branch named
../repo.feature-detached", `remove` by leaving the worktree standing,
and the two config paths by not finding their file.

The `set_base_path` docstring picks up the rule, so the next reader has
one place to find it: `-C` is the base for the two things git takes from
its chdir — the repository discovered, and every path the user names —
while the process cwd stays the answer to where the user's shell
physically is.

## Noticed, not touched

`run_json` and `git_status_segments` duplicate the
worktree-lookup-and-populate sequence (`list_worktrees` → find by root →
`is_home` → `build_worktree_item` → `populate_item` with identical
`CollectOptions`). Worth collapsing separately.

> _This was written by Claude Code on behalf of max_
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.

branch_diff tests fail when test binary CWD is not a git repo (e.g. Nix build sandbox)

2 participants