Skip to content

fix(wsl): resolve sparse-checkout and diff-stamp gitdirs through the caller's distro - #17932

Merged
nwparker merged 1 commit into
mainfrom
nwparker/wsl-remaining-distro-threading
Sep 1, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/wsl-remaining-distro-threading

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

fix(wsl): resolve sparse-checkout and diff-stamp gitdirs through the caller's distro

Two main-process resolveGitDir call sites dropped the WSL distro their caller
already held, so they could only resolve a gitdir pointer whose spelling carries
its own translation: a //wsl.localhost/<Distro>/... base, or a /mnt/<letter>
drvfs pointer that maps to a drive letter on its own.

The layout that needs the third case is a repo inside the distro's filesystem
with its worktrees on the Windows drive. git worktree list reports the worktree
as /mnt/c/wt/x, which the listing translates to C:\wt\x — a base that no
longer names a distro — while the .git gitfile beside it points at
/home/me/repo/.git/worktrees/x, which has no drive to derive. Win32 then treats
that pointer as absolute and reads a path that names nothing:

  • detectSparseCheckout stats info/sparse-checkout under the fabricated path,
    always misses, and reports the worktree as non-sparse — no sparse badge, and
    the file list claims files that are not on disk.
  • readWorktreeDiffStamp reads HEAD under the same path, gets nothing, and
    returns null. Null is the safe answer ("cannot prove unchanged"), but it
    retires the settled-diff cache for every file in that worktree, so each diff
    respawns Git.

Both callers already have the distro: the listing threads its
GitWorktreeExecOptions to annotateSparseCheckoutStatus, on through
detectSparseCheckoutCached (the annotation cache added by #17859) and its
background revalidation probe, and finally to detectSparseCheckout; and
file-diff already forwards its GitRuntimeOptions to readWorktreeDiffStamp,
which now forwards it to resolveGitDir as well.

resolveGitMetadataPath still prefers a UNC base's distro and still tries drvfs
before the caller-named distro, so nothing that resolved before resolves
differently.

The cache hop matters twice over. It is the only remaining caller of
detectSparseCheckout, so without threading it the fix would not reach the
probe at all. And the cache is where the bug turns sticky. #17859 keyed entries
on repoPath + worktreePath alone, on the reasoning that the distro is a
property of the repo and so every read for a given repoPath carries the same
one. That invariant does not hold. listRepoWorktrees(repo) is called with no
options at all from the filesystem-auth root rebuild
(registered-worktree-roots-cache.ts, reached from ensureAuthorizedRootsCache
on any auth check with a dirty cache) and from the local worktree-ownership
check in filesystem-worktree-helpers.ts. Both land on the same key as the
distro-carrying listing, because translateWslOutputPaths derives the distro
from the cwd spelling before falling back to options.wslDistro, so a
UNC-spelled repo path yields the identical C:\... worktree row either way.
Measured on Windows in one process, branch build: a distro-less read followed by
a distro-carrying read reported the sparse worktree as non-sparse both times.

So wslDistro now joins the cache key -- trimmed and lowercased, matching how
the rest of the codebase compares distro names, and appended last so the
repo-scoped prefix delete still matches every variant. The per-path invalidate
becomes a prefix delete for the same reason, dropping every distro variant of a
removed or moved worktree.

Keying on it closes both halves of the defect. A correct caller can no longer be
served an answer derived without the distro it supplied. And because the entry a
reader reaches is now selected by the same distro it would re-probe with,
revalidateInBackground can no longer re-derive a warm entry under weaker
options -- which mattered on its own: a distro-less reader crossing the
five-minute window would otherwise flip a correct true to false, and the
resulting change notification runs the registered invalidator, clearing the
whole repo's cache and re-probing every worktree cold, on a five-minute loop.

Cost of the extra key dimension is bounded by the number of distinct distros a
given repo is actually read under: one where a distro is threaded everywhere,
two while the distro-less callers above still exist. Entries are still
repo-scoped, and both clears already sweep by prefix.

Per-platform delta:

  • macOS/Linux: no change. Guest-pointer translation is gated to win32 and a
    caller-named distro is ignored off Windows; no caller supplies one there, so
    the cache keys and probes exactly as before.
  • native Windows, no WSL: no change. wslDistro is undefined, so the resolver
    takes exactly the branches it took before and every read keys on the same
    empty distro component, so the cache behaves exactly as it did.
  • Windows + WSL, UNC-spelled worktree: no change. The base already names the
    distro and outranks the caller's.
  • Windows + WSL, drvfs-spelled worktree with a drvfs pointer: no change. The
    drive-letter derivation still runs first.
  • Windows + WSL, drvfs-spelled worktree with a non-drvfs pointer: the sparse
    badge appears and the settled-diff cache starts hitting. Both previously
    failed toward "not sparse" / "do not cache", so neither can now serve a stale
    answer, and the distro-less listings no longer share the badge's cache entry.
  • SSH/relay: none. Those paths return through the provider branch before
    reaching either function.
  • folder workspaces, GitLab: none. Neither is on these code paths.

Not in this change:

  • readRepoCommonDirFromDisk (worktree-listing). Passing the distro there is
    inert: a repo root's .git is a directory, so the gitfile-pointer branch never
    runs, and when repoPath itself is guest-spelled the preceding stat already
    fails — which no resolveGitDir option can fix.
  • The two findExistingWorktreeSymlinkPaths calls on the removal paths. Both
    receive registeredWorktree.path from listWorktreesStrict, which already
    translates every row out of the guest namespace, so the distro would be a
    no-op. The removeWorktreeLinkedPaths unlink beside them is untranslated too,
    so a half-threaded fix would only move the refusal from Orca's preflight to
    git worktree remove.
  • An absolute commondir payload, which resolveGitCommonDir still resolves
    untranslated. Git writes that file relative in the layouts above, and the
    failure direction is unchanged.
  • Giving the two distro-less listRepoWorktrees(repo) callers a distro. Neither
    reads isSparse -- both use only worktree.path -- so the distro would buy
    them nothing they consume, while resolving a project runtime inside the
    filesystem-auth rebuild would put a call that throws on repair-required
    behind a catch that skips the whole repo's authorized roots. The cache key
    makes their reads harmless; skipping the annotation for callers that never
    read it is a separate, larger change. The third no-options call in
    hosted-review.ts is inside the repo.connectionId branch and returns
    through the SSH provider, so it never reaches this cache.

Runtime exercise on real Windows + WSL (awin)

Fixture built by WSL's own git (Ubuntu-24.04, git 2.43.0) — repo inside the distro, linked worktree on the Windows drive, so the .git gitfile genuinely contained gitdir: /home/neil/prex932/repo/.git/worktrees/wt (verified byte-level with cat -A; commondir = ../.. relative, as claimed). Sparse-checkout enabled for real. Run through the repo's own vitest with no fs or child_process mocking. Baseline origin/main = f176e494780, this branch's own parent, so it is a clean one-commit delta.

Probe origin/main this branch
detectSparseCheckout(wt, {wslDistro}) false (arity 1, arg ignored) true
detectSparseCheckoutCached(repo, wt, {wslDistro}) false true
listWorktreesStrict(...) row (really spawns wsl.exe git) no isSparse field isSparse: true
readWorktreeDiffStamp(wt, file, true, {wslDistro}) null non-null, real loose tip
resolved gitdir existsSync false — /home/neil/... true — \\wsl.localhost\Ubuntu-24.04\...

Also confirmed on hardware: even when the caller passes /mnt/c/... directly, main returns null, because toWindowsWslPath prefers the drvfs drive form so hostWorktreePath collapses to C:\... and the distro is lost before resolveGitDir.

The exercise found a defect, now fixed in this PR

An earlier revision left wslDistro out of the sparse-annotation cache key. Reproduced live, same process:

firstNoDistro:     C:\Users\neil\prex932\wt isSparse=undefined
secondWithDistro:  C:\Users\neil\prex932\wt isSparse=undefined   <- poisoned

A distro-less false was cached for 5 minutes and served to the correct caller, and the background revalidation could flip a correct true back to false, firing notifyWorktreesChanged -> clearSparseCheckoutStateCacheForRepo and cold-re-probing the whole repo every ~5 minutes. Fixed by putting the distro in the key; see the "cache" section above. Mutation-verified: reverting cacheKey to ignore options fails 4 of 18 tests.

Not exercised

The renderer sparse badge and file-diff cache-hit counters in the running app (functions and the listing that feeds them were measured, not the UI); SSH/relay and folder-workspace paths (asserted no-delta by reading, since both return before these functions); Sta4593-Federated (everything ran on Ubuntu-24.04); describeCreatedWorktree end-to-end, though it shares annotateSparseCheckoutStatus with the exercised listWorktreesStrict.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9166817b-5017-45b5-8dc2-e3477ab52c79

📥 Commits

Reviewing files that changed from the base of the PR and between ddb2061 and 19b4482.

📒 Files selected for processing (2)
  • src/main/git/worktree-sparse-checkout-cache.test.ts
  • src/main/git/worktree-sparse-checkout-cache.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

Worktree gitdir resolution now receives the caller-provided WSL distro in diff-stamp and sparse-checkout paths. Sparse-checkout detection and its cache forward this option through initial and background probes. Worktree listing functions pass runtime options when annotating rows. New Vitest coverage validates Windows/WSL host-path resolution, sparse-checkout detection, listing propagation, cache isolation, invalidation, and diff-stamp generation.

Merge Risk: ⚪ Minimal · up to 19b44

This change preserves WSL distro context for sparse-checkout and diff metadata reads and separates cached results by distro, correcting incorrect sparse indicators and missed diff-cache hits without adding new deployment or security exposure. No actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed context, rationale, scope, and verification results, but it does not follow the required template. It omits the required section headings, linked issue, visual proof … Restructure the description using the repository template. Add the required headings and content, include a linked issue after "Fixes #", write "N/A" with a reason under Visual Proof, add a Testing section with the relevant test and platfor…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: resolving sparse-checkout and diff-stamp git directories through the caller's WSL distro.
Full details: Description check

Explanation

The description provides detailed context, rationale, scope, and verification results, but it does not follow the required template. It omits the required section headings, linked issue, visual proof declaration, testing checklist, AI disclosure, review sections, agent-skill boundary checklist, notes, and final checklist.

Resolution

Restructure the description using the repository template. Add the required headings and content, include a linked issue after "Fixes #", write "N/A" with a reason under Visual Proof, add a Testing section with the relevant test and platform results, complete applicable checkboxes, and address AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Thread wslDistro into sparse-checkout detection — detectSparseCheckout and its cache wrapper (detectSparseCheckoutCached, revalidateInBackground) now forward the caller's distro to resolveGitDir, so a drvfs-spelled worktree with a non-drvfs gitdir pointer resolves to the distro's UNC share instead of a fabricated Win32 path.
  • Thread wslDistro into the diff stamp — readWorktreeDiffStamp passes its existing options to resolveGitDir, restoring the settled-diff cache hit for the same layout.
  • Listing plumbing — annotateSparseCheckoutStatus and describeCreatedWorktree carry GitWorktreeExecOptions through to the cached probe.
  • Tests — three new win32-stubbed suites (sparse-state host paths, listing sparse distro, created-sparse distro, diff-stamp guest gitdir) plus one updated porcelain assertion pinning the distro argument.

The fix is correctly scoped: the drvfs pointer branch still runs before the caller-named distro (toWindowsWslPath tries toWindowsWslDrivePath first), non-Win32 hosts ignore the distro, and both previously-broken behaviors failed toward the safe answers (not-sparse / do-not-cache). The cache key excluding the distro is sound because the distro is a property of repoPath; the remaining call sites (readRepoCommonDirFromDisk, the two findExistingWorktreeSymlinkPaths removal calls) were audited and are either provably inert or fail-closed, matching the analysis in the PR body.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…caller's distro

Two main-process `resolveGitDir` call sites dropped the WSL distro their caller
already held, so they could only resolve a gitdir pointer whose spelling carries
its own translation: a `//wsl.localhost/<Distro>/...` base, or a `/mnt/<letter>`
drvfs pointer that maps to a drive letter on its own.

The layout that needs the third case is a repo inside the distro's filesystem
with its worktrees on the Windows drive. `git worktree list` reports the worktree
as `/mnt/c/wt/x`, which the listing translates to `C:\wt\x` — a base that no
longer names a distro — while the `.git` gitfile beside it points at
`/home/me/repo/.git/worktrees/x`, which has no drive to derive. Win32 then treats
that pointer as absolute and reads a path that names nothing:

- `detectSparseCheckout` stats `info/sparse-checkout` under the fabricated path,
  always misses, and reports the worktree as non-sparse — no sparse badge, and
  the file list claims files that are not on disk.
- `readWorktreeDiffStamp` reads HEAD under the same path, gets nothing, and
  returns null. Null is the safe answer ("cannot prove unchanged"), but it
  retires the settled-diff cache for every file in that worktree, so each diff
  respawns Git.

Both callers already have the distro: the listing threads its
`GitWorktreeExecOptions` to `annotateSparseCheckoutStatus`, on through
`detectSparseCheckoutCached` (the annotation cache added by #17859) and its
background revalidation probe, and finally to `detectSparseCheckout`; and
`file-diff` already forwards its `GitRuntimeOptions` to `readWorktreeDiffStamp`,
which now forwards it to `resolveGitDir` as well.

`resolveGitMetadataPath` still prefers a UNC base's distro and still tries drvfs
before the caller-named distro, so nothing that resolved before resolves
differently.

The cache hop matters twice over. It is the only remaining caller of
`detectSparseCheckout`, so without threading it the fix would not reach the
probe at all. And the cache is where the bug turns sticky. #17859 keyed entries
on `repoPath` + `worktreePath` alone, on the reasoning that the distro is a
property of the repo and so every read for a given `repoPath` carries the same
one. That invariant does not hold. `listRepoWorktrees(repo)` is called with no
options at all from the filesystem-auth root rebuild
(`registered-worktree-roots-cache.ts`, reached from `ensureAuthorizedRootsCache`
on any auth check with a dirty cache) and from the local worktree-ownership
check in `filesystem-worktree-helpers.ts`. Both land on the *same* key as the
distro-carrying listing, because `translateWslOutputPaths` derives the distro
from the cwd spelling before falling back to `options.wslDistro`, so a
UNC-spelled repo path yields the identical `C:\...` worktree row either way.
Measured on Windows in one process, branch build: a distro-less read followed by
a distro-carrying read reported the sparse worktree as non-sparse both times.

So `wslDistro` now joins the cache key -- trimmed and lowercased, matching how
the rest of the codebase compares distro names, and appended last so the
repo-scoped prefix delete still matches every variant. The per-path invalidate
becomes a prefix delete for the same reason, dropping every distro variant of a
removed or moved worktree.

Keying on it closes both halves of the defect. A correct caller can no longer be
served an answer derived without the distro it supplied. And because the entry a
reader reaches is now selected by the same distro it would re-probe with,
`revalidateInBackground` can no longer re-derive a warm entry under weaker
options -- which mattered on its own: a distro-less reader crossing the
five-minute window would otherwise flip a correct `true` to `false`, and the
resulting change notification runs the registered invalidator, clearing the
whole repo's cache and re-probing every worktree cold, on a five-minute loop.

Cost of the extra key dimension is bounded by the number of distinct distros a
given repo is actually read under: one where a distro is threaded everywhere,
two while the distro-less callers above still exist. Entries are still
repo-scoped, and both clears already sweep by prefix.

Per-platform delta:
- macOS/Linux: no change. Guest-pointer translation is gated to win32 and a
  caller-named distro is ignored off Windows; no caller supplies one there, so
  the cache keys and probes exactly as before.
- native Windows, no WSL: no change. `wslDistro` is undefined, so the resolver
  takes exactly the branches it took before and every read keys on the same
  empty distro component, so the cache behaves exactly as it did.
- Windows + WSL, UNC-spelled worktree: no change. The base already names the
  distro and outranks the caller's.
- Windows + WSL, drvfs-spelled worktree with a drvfs pointer: no change. The
  drive-letter derivation still runs first.
- Windows + WSL, drvfs-spelled worktree with a non-drvfs pointer: the sparse
  badge appears and the settled-diff cache starts hitting. Both previously
  failed toward "not sparse" / "do not cache", so neither can now serve a stale
  answer, and the distro-less listings no longer share the badge's cache entry.
- SSH/relay: none. Those paths return through the provider branch before
  reaching either function.
- folder workspaces, GitLab: none. Neither is on these code paths.

Not in this change:
- `readRepoCommonDirFromDisk` (worktree-listing). Passing the distro there is
  inert: a repo root's `.git` is a directory, so the gitfile-pointer branch never
  runs, and when `repoPath` itself is guest-spelled the preceding `stat` already
  fails — which no `resolveGitDir` option can fix.
- The two `findExistingWorktreeSymlinkPaths` calls on the removal paths. Both
  receive `registeredWorktree.path` from `listWorktreesStrict`, which already
  translates every row out of the guest namespace, so the distro would be a
  no-op. The `removeWorktreeLinkedPaths` unlink beside them is untranslated too,
  so a half-threaded fix would only move the refusal from Orca's preflight to
  `git worktree remove`.
- An absolute `commondir` payload, which `resolveGitCommonDir` still resolves
  untranslated. Git writes that file relative in the layouts above, and the
  failure direction is unchanged.
- Giving the two distro-less `listRepoWorktrees(repo)` callers a distro. Neither
  reads `isSparse` -- both use only `worktree.path` -- so the distro would buy
  them nothing they consume, while resolving a project runtime inside the
  filesystem-auth rebuild would put a call that throws on `repair-required`
  behind a catch that skips the whole repo's authorized roots. The cache key
  makes their reads harmless; skipping the annotation for callers that never
  read it is a separate, larger change. The third no-options call in
  `hosted-review.ts` is inside the `repo.connectionId` branch and returns
  through the SSH provider, so it never reaches this cache.
@nwparker
nwparker force-pushed the nwparker/wsl-remaining-distro-threading branch from ddb2061 to 19b4482 Compare September 1, 2026 11:14

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — since the prior review, this PR adds the caller's WSL distro to the sparse-checkout cache key and reworks the invalidation helpers to sweep all distro variants.

  • Distro joins the cache key — cacheKey now appends options.wslDistro (trimmed + lowercased), so a distro-less read no longer shares an entry with a distro-carrying one, and background revalidation is pinned to the options that produced the entry rather than whichever reader happened to win the dedupe race.
  • Prefix-based invalidation — invalidateSparseCheckoutState and clearSparseCheckoutStateCacheForRepo now delete by prefix, dropping every distro variant of a removed/moved worktree and preserving the repo-scoped sweep.
  • Regression coverage — six new cache-key cases (poisoning both orders, spelling normalization, windowed revalidation, invalidate-every-variant, no-distro caching) plus one updated porcelain assertion.

Verified locally: the six touched test files pass (31 tests) and pnpm tc:node is clean.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 26dfa46 into main Sep 1, 2026
28 checks passed
@nwparker
nwparker deleted the nwparker/wsl-remaining-distro-threading branch September 1, 2026 11:25
nwparker added a commit that referenced this pull request Sep 2, 2026
…d it (#18050)

Three main-process call sites list a repo's worktrees to read `worktree.path`
and nothing else, but went through the annotated listing, so each one paid a
sparse-checkout probe per worktree and cached the result nobody consumed:

- `registered-worktree-roots-cache.ts` rebuilds the filesystem-auth authorized
  roots. `invalidateAuthorizedRootsCache()` fires on every worktree create and
  remove, plus repo add/clone/settings changes, so this reruns constantly.
- `filesystem-source-control-ai-targets.ts` checks whether a local repo owns a
  worktree path.
- `hosted-review.ts` verifies a worktree belongs to the repo before granting
  access.

The probe is an `fs.stat` of the per-worktree `info/sparse-checkout` plus, when
that file is non-empty, a git config read. On a WSL-hosted repo both cross 9p.
#17859 cached it and #17932 keyed that cache on the distro, which fixed a wrong
answer but also meant the distro-less callers above populate a second entry per
worktree — probed cold, revalidated on their own five-minute loop, and read by
nobody. Worktree create/remove clears the sparse cache and dirties the roots
cache together, so both variants go cold at once and the discarded half is
re-probed in full on the next auth check.

`listRepoWorktreeGraph` routes those callers to `listWorktreeGraph`, which
already existed as the annotation-free listing (#17655).

Doing only that would have cost a second `git worktree list`. The scan cache
keys in-flight scans on a `kind`, and graph and lenient were separate kinds, so
a roots rebuild overlapping a sidebar refresh would spawn its own subprocess
where the two previously coalesced. That is a real regression on macOS, Linux
and native Windows, where `getLocalProjectWorktreeGitOptions` returns `{}` and
both callers land on the identical key; on WSL they already differ by distro and
never shared.

So the annotated listing is now the graph listing plus annotation, rather than a
parallel scan of its own: `listWorktrees` awaits `listWorktreeGraph` and
annotates the rows it returns. Both soften a Git failure to `[]`, so they can
share one listing; strict keeps its own because it must be able to reject. The
two kinds ran Git twice before and now run it once, so the overlap case gets
strictly faster instead of paying for the opt-out.

An annotated scan holds two in-flight entries now (its own, plus the graph
listing it shares). Keeping its own entry matters: `detectSparseCheckoutCached`
dedupes revalidation but not the initial fill, so two concurrent badge readers
sharing only the graph scan would both probe.

Per-platform delta:
- macOS/Linux: fewer probes on the three call sites; one `git worktree list`
  instead of two when a graph and an annotated scan overlap.
- native Windows, no WSL: same, and the saved subprocess is the expensive half.
- Windows + WSL: the largest win. The discarded probes were 9p round-trips
  re-paid cold after every worktree create/remove.
- SSH/relay: none. `listRepoWorktreeGraph` returns through the same provider
  branch as `listRepoWorktrees` before reaching local Git.
- folder workspaces: none. Both return the same synthetic folder worktree.

Not in this change:
- The badge listing itself. It still probes, still annotates, and still keys on
  the distro exactly as #17932 left it.
- The remaining `listRepoWorktrees` callers. They read `isSparse`, or feed rows
  to something that does.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…d it (stablyai#18050)

Three main-process call sites list a repo's worktrees to read `worktree.path`
and nothing else, but went through the annotated listing, so each one paid a
sparse-checkout probe per worktree and cached the result nobody consumed:

- `registered-worktree-roots-cache.ts` rebuilds the filesystem-auth authorized
  roots. `invalidateAuthorizedRootsCache()` fires on every worktree create and
  remove, plus repo add/clone/settings changes, so this reruns constantly.
- `filesystem-source-control-ai-targets.ts` checks whether a local repo owns a
  worktree path.
- `hosted-review.ts` verifies a worktree belongs to the repo before granting
  access.

The probe is an `fs.stat` of the per-worktree `info/sparse-checkout` plus, when
that file is non-empty, a git config read. On a WSL-hosted repo both cross 9p.
stablyai#17859 cached it and stablyai#17932 keyed that cache on the distro, which fixed a wrong
answer but also meant the distro-less callers above populate a second entry per
worktree — probed cold, revalidated on their own five-minute loop, and read by
nobody. Worktree create/remove clears the sparse cache and dirties the roots
cache together, so both variants go cold at once and the discarded half is
re-probed in full on the next auth check.

`listRepoWorktreeGraph` routes those callers to `listWorktreeGraph`, which
already existed as the annotation-free listing (stablyai#17655).

Doing only that would have cost a second `git worktree list`. The scan cache
keys in-flight scans on a `kind`, and graph and lenient were separate kinds, so
a roots rebuild overlapping a sidebar refresh would spawn its own subprocess
where the two previously coalesced. That is a real regression on macOS, Linux
and native Windows, where `getLocalProjectWorktreeGitOptions` returns `{}` and
both callers land on the identical key; on WSL they already differ by distro and
never shared.

So the annotated listing is now the graph listing plus annotation, rather than a
parallel scan of its own: `listWorktrees` awaits `listWorktreeGraph` and
annotates the rows it returns. Both soften a Git failure to `[]`, so they can
share one listing; strict keeps its own because it must be able to reject. The
two kinds ran Git twice before and now run it once, so the overlap case gets
strictly faster instead of paying for the opt-out.

An annotated scan holds two in-flight entries now (its own, plus the graph
listing it shares). Keeping its own entry matters: `detectSparseCheckoutCached`
dedupes revalidation but not the initial fill, so two concurrent badge readers
sharing only the graph scan would both probe.

Per-platform delta:
- macOS/Linux: fewer probes on the three call sites; one `git worktree list`
  instead of two when a graph and an annotated scan overlap.
- native Windows, no WSL: same, and the saved subprocess is the expensive half.
- Windows + WSL: the largest win. The discarded probes were 9p round-trips
  re-paid cold after every worktree create/remove.
- SSH/relay: none. `listRepoWorktreeGraph` returns through the same provider
  branch as `listRepoWorktrees` before reaching local Git.
- folder workspaces: none. Both return the same synthetic folder worktree.

Not in this change:
- The badge listing itself. It still probes, still annotates, and still keys on
  the distro exactly as stablyai#17932 left it.
- The remaining `listRepoWorktrees` callers. They read `isSparse`, or feed rows
  to something that does.

Mirror-Of: a7db6c3
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…caller's distro (stablyai#17932)

Two main-process `resolveGitDir` call sites dropped the WSL distro their caller
already held, so they could only resolve a gitdir pointer whose spelling carries
its own translation: a `//wsl.localhost/<Distro>/...` base, or a `/mnt/<letter>`
drvfs pointer that maps to a drive letter on its own.

The layout that needs the third case is a repo inside the distro's filesystem
with its worktrees on the Windows drive. `git worktree list` reports the worktree
as `/mnt/c/wt/x`, which the listing translates to `C:\wt\x` — a base that no
longer names a distro — while the `.git` gitfile beside it points at
`/home/me/repo/.git/worktrees/x`, which has no drive to derive. Win32 then treats
that pointer as absolute and reads a path that names nothing:

- `detectSparseCheckout` stats `info/sparse-checkout` under the fabricated path,
  always misses, and reports the worktree as non-sparse — no sparse badge, and
  the file list claims files that are not on disk.
- `readWorktreeDiffStamp` reads HEAD under the same path, gets nothing, and
  returns null. Null is the safe answer ("cannot prove unchanged"), but it
  retires the settled-diff cache for every file in that worktree, so each diff
  respawns Git.

Both callers already have the distro: the listing threads its
`GitWorktreeExecOptions` to `annotateSparseCheckoutStatus`, on through
`detectSparseCheckoutCached` (the annotation cache added by stablyai#17859) and its
background revalidation probe, and finally to `detectSparseCheckout`; and
`file-diff` already forwards its `GitRuntimeOptions` to `readWorktreeDiffStamp`,
which now forwards it to `resolveGitDir` as well.

`resolveGitMetadataPath` still prefers a UNC base's distro and still tries drvfs
before the caller-named distro, so nothing that resolved before resolves
differently.

The cache hop matters twice over. It is the only remaining caller of
`detectSparseCheckout`, so without threading it the fix would not reach the
probe at all. And the cache is where the bug turns sticky. stablyai#17859 keyed entries
on `repoPath` + `worktreePath` alone, on the reasoning that the distro is a
property of the repo and so every read for a given `repoPath` carries the same
one. That invariant does not hold. `listRepoWorktrees(repo)` is called with no
options at all from the filesystem-auth root rebuild
(`registered-worktree-roots-cache.ts`, reached from `ensureAuthorizedRootsCache`
on any auth check with a dirty cache) and from the local worktree-ownership
check in `filesystem-worktree-helpers.ts`. Both land on the *same* key as the
distro-carrying listing, because `translateWslOutputPaths` derives the distro
from the cwd spelling before falling back to `options.wslDistro`, so a
UNC-spelled repo path yields the identical `C:\...` worktree row either way.
Measured on Windows in one process, branch build: a distro-less read followed by
a distro-carrying read reported the sparse worktree as non-sparse both times.

So `wslDistro` now joins the cache key -- trimmed and lowercased, matching how
the rest of the codebase compares distro names, and appended last so the
repo-scoped prefix delete still matches every variant. The per-path invalidate
becomes a prefix delete for the same reason, dropping every distro variant of a
removed or moved worktree.

Keying on it closes both halves of the defect. A correct caller can no longer be
served an answer derived without the distro it supplied. And because the entry a
reader reaches is now selected by the same distro it would re-probe with,
`revalidateInBackground` can no longer re-derive a warm entry under weaker
options -- which mattered on its own: a distro-less reader crossing the
five-minute window would otherwise flip a correct `true` to `false`, and the
resulting change notification runs the registered invalidator, clearing the
whole repo's cache and re-probing every worktree cold, on a five-minute loop.

Cost of the extra key dimension is bounded by the number of distinct distros a
given repo is actually read under: one where a distro is threaded everywhere,
two while the distro-less callers above still exist. Entries are still
repo-scoped, and both clears already sweep by prefix.

Per-platform delta:
- macOS/Linux: no change. Guest-pointer translation is gated to win32 and a
  caller-named distro is ignored off Windows; no caller supplies one there, so
  the cache keys and probes exactly as before.
- native Windows, no WSL: no change. `wslDistro` is undefined, so the resolver
  takes exactly the branches it took before and every read keys on the same
  empty distro component, so the cache behaves exactly as it did.
- Windows + WSL, UNC-spelled worktree: no change. The base already names the
  distro and outranks the caller's.
- Windows + WSL, drvfs-spelled worktree with a drvfs pointer: no change. The
  drive-letter derivation still runs first.
- Windows + WSL, drvfs-spelled worktree with a non-drvfs pointer: the sparse
  badge appears and the settled-diff cache starts hitting. Both previously
  failed toward "not sparse" / "do not cache", so neither can now serve a stale
  answer, and the distro-less listings no longer share the badge's cache entry.
- SSH/relay: none. Those paths return through the provider branch before
  reaching either function.
- folder workspaces, GitLab: none. Neither is on these code paths.

Not in this change:
- `readRepoCommonDirFromDisk` (worktree-listing). Passing the distro there is
  inert: a repo root's `.git` is a directory, so the gitfile-pointer branch never
  runs, and when `repoPath` itself is guest-spelled the preceding `stat` already
  fails — which no `resolveGitDir` option can fix.
- The two `findExistingWorktreeSymlinkPaths` calls on the removal paths. Both
  receive `registeredWorktree.path` from `listWorktreesStrict`, which already
  translates every row out of the guest namespace, so the distro would be a
  no-op. The `removeWorktreeLinkedPaths` unlink beside them is untranslated too,
  so a half-threaded fix would only move the refusal from Orca's preflight to
  `git worktree remove`.
- An absolute `commondir` payload, which `resolveGitCommonDir` still resolves
  untranslated. Git writes that file relative in the layouts above, and the
  failure direction is unchanged.
- Giving the two distro-less `listRepoWorktrees(repo)` callers a distro. Neither
  reads `isSparse` -- both use only `worktree.path` -- so the distro would buy
  them nothing they consume, while resolving a project runtime inside the
  filesystem-auth rebuild would put a call that throws on `repair-required`
  behind a catch that skips the whole repo's authorized roots. The cache key
  makes their reads harmless; skipping the annotation for callers that never
  read it is a separate, larger change. The third no-options call in
  `hosted-review.ts` is inside the `repo.connectionId` branch and returns
  through the SSH provider, so it never reaches this cache.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…d it (stablyai#18050)

Three main-process call sites list a repo's worktrees to read `worktree.path`
and nothing else, but went through the annotated listing, so each one paid a
sparse-checkout probe per worktree and cached the result nobody consumed:

- `registered-worktree-roots-cache.ts` rebuilds the filesystem-auth authorized
  roots. `invalidateAuthorizedRootsCache()` fires on every worktree create and
  remove, plus repo add/clone/settings changes, so this reruns constantly.
- `filesystem-source-control-ai-targets.ts` checks whether a local repo owns a
  worktree path.
- `hosted-review.ts` verifies a worktree belongs to the repo before granting
  access.

The probe is an `fs.stat` of the per-worktree `info/sparse-checkout` plus, when
that file is non-empty, a git config read. On a WSL-hosted repo both cross 9p.
stablyai#17859 cached it and stablyai#17932 keyed that cache on the distro, which fixed a wrong
answer but also meant the distro-less callers above populate a second entry per
worktree — probed cold, revalidated on their own five-minute loop, and read by
nobody. Worktree create/remove clears the sparse cache and dirties the roots
cache together, so both variants go cold at once and the discarded half is
re-probed in full on the next auth check.

`listRepoWorktreeGraph` routes those callers to `listWorktreeGraph`, which
already existed as the annotation-free listing (stablyai#17655).

Doing only that would have cost a second `git worktree list`. The scan cache
keys in-flight scans on a `kind`, and graph and lenient were separate kinds, so
a roots rebuild overlapping a sidebar refresh would spawn its own subprocess
where the two previously coalesced. That is a real regression on macOS, Linux
and native Windows, where `getLocalProjectWorktreeGitOptions` returns `{}` and
both callers land on the identical key; on WSL they already differ by distro and
never shared.

So the annotated listing is now the graph listing plus annotation, rather than a
parallel scan of its own: `listWorktrees` awaits `listWorktreeGraph` and
annotates the rows it returns. Both soften a Git failure to `[]`, so they can
share one listing; strict keeps its own because it must be able to reject. The
two kinds ran Git twice before and now run it once, so the overlap case gets
strictly faster instead of paying for the opt-out.

An annotated scan holds two in-flight entries now (its own, plus the graph
listing it shares). Keeping its own entry matters: `detectSparseCheckoutCached`
dedupes revalidation but not the initial fill, so two concurrent badge readers
sharing only the graph scan would both probe.

Per-platform delta:
- macOS/Linux: fewer probes on the three call sites; one `git worktree list`
  instead of two when a graph and an annotated scan overlap.
- native Windows, no WSL: same, and the saved subprocess is the expensive half.
- Windows + WSL: the largest win. The discarded probes were 9p round-trips
  re-paid cold after every worktree create/remove.
- SSH/relay: none. `listRepoWorktreeGraph` returns through the same provider
  branch as `listRepoWorktrees` before reaching local Git.
- folder workspaces: none. Both return the same synthetic folder worktree.

Not in this change:
- The badge listing itself. It still probes, still annotates, and still keys on
  the distro exactly as stablyai#17932 left it.
- The remaining `listRepoWorktrees` callers. They read `isSparse`, or feed rows
  to something that does.
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.

1 participant