Skip to content

perf(git): cache sparse-checkout annotation on worktree listing - #17859

Merged
nwparker merged 4 commits into
mainfrom
nwparker/lazy-sparse-annotation
Sep 1, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/lazy-sparse-annotation

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​411 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​408
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​205 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​195

ELI5

Every time Orca lists a repo's worktrees, it also checks each one for whether it's a "sparse" checkout (partial working tree). That check was re-done from scratch, every single time, for every worktree -- even though the answer almost never changes. On a repo with ~1000 worktrees this dwarfed the cost of the actual git worktree list call it was decorating. This PR remembers the answer per worktree, scoped per repo, so repeat listings are nearly free, while still catching every real reason the answer could change (worktree removed/moved, sparse checkout toggled through Orca or externally, app restart) -- including a background self-correction if something changes it externally without Orca noticing right away.

What Changed

  • Added src/main/git/worktree-sparse-checkout-cache.ts: a cache (detectSparseCheckoutCached) wrapping the existing detectSparseCheckout, keyed by repo path + worktree path so entries from different repos never collide or evict each other.
  • Cache keys (and invalidation lookups) go through a new canonicalWorktreePath(), extracted from the existing areWorktreePathsEqual normalization (src/main/git/worktree-path-comparison.ts) -- resolved and case-folded on Windows syntax -- so two different spellings of the same path (trailing slash, . segment, drive-letter casing) always hit the same entry instead of silently diverging.
  • Replaced the original hard 5-minute cutoff with stale-while-revalidate: once an entry is past the reconcile window, a read still returns the cached value immediately, but also kicks a deduplicated background re-detect. If that re-detect flips the answer, it fires the same worktrees-changed notification other mutations already use, so the fix propagates on its own without waiting for the next explicit trigger.
  • src/main/git/worktree-listing.ts's annotateSparseCheckoutStatus now takes repoPath and calls the cached wrapper (with both the repo and worktree path) instead of hitting the filesystem on every listing.
  • Explicit invalidation on the two Orca-driven mutations that change a worktree's path: removeWorktree (worktree-removal.ts) and moveWorktree (worktree-move.ts), for both old and new paths, both now repo-scoped.
  • src/main/ipc/worktrees/listing/register-sparse-checkout-cache-invalidation.ts (rewritten): resolves the invalidator registry's repoId to a repo path via the Store and clears only that repo's entries (falling back to a full clear if the repo can't be resolved, e.g. it was already removed), and forwards a stale-while-revalidate flip to notifyWorktreesChanged by resolving the repo path back to a repoId. This needs both mainWindow and store, so registration moved from module-load time into registerWorktreeHandlers, with a disposer so re-invoking it (already-supported re-registration) doesn't stack duplicate listeners.
  • The background revalidation's write-back is now guarded by entry identity, not key presence: it captures the exact cache-entry object it started from and only writes its result back if that object is still the one at the key. A presence check (has(key)) can't distinguish "nothing touched this key" from "something invalidated it and a fresh cold read already repopulated it" -- a worktree removed and recreated at the same path while a stale re-detect is in flight would otherwise let the old result overwrite the new one.
  • Added/extended test-suite reset hooks (remove-worktree-test-harness.ts, worktree-test-harness.ts) so the new module-level cache doesn't leak state across test cases.

Why

git worktree list --porcelain predates sparse-checkout awareness on Orca's Git 2.25 compatibility baseline: newer Git versions do emit a sparse porcelain line (Orca's own parser handles it -- src/main/git/worktree-list-parser.ts:38-39 -- and annotateSparseCheckoutStatus already skips rows where it's set), but on the baseline we support, Orca still has to derive it itself via a per-worktree fs.stat + config read (detectSparseCheckout). On a real user's repo with 973 live worktrees, git worktree list --porcelain -z itself ran in 0.135s, but the sparse-checkout annotation pass over all worktrees (concurrency 8) took ~0.58-1.0s -- roughly 9x the cost of the git call it decorates. This runs on every listing (lenient and strict), so it directly slows down worktree-heavy operations at scale (see #17828).

Caching per-path is safe here because sparse-checkout state changes only through a small, enumerable set of triggers, all of which are covered:

  1. Worktree created -- new path, never cached, first read is always fresh.
  2. Worktree removed -- explicit invalidateSparseCheckoutState(repoPath, worktreePath).
  3. Worktree moved -- explicit invalidation of both old and new paths.
  4. External git sparse-checkout toggle with extensions.worktreeConfig on -- rewrites config.worktree, which the existing git-common-dir watcher already classifies as structural and routes through notifyWorktreesChanged -> the repo-scoped invalidator this module registers.
  5. External toggle with extensions.worktreeConfig off, or a bare pattern-file edit -- not observed by the watcher (this is the exact same blind spot readRepoWorktreeAdminFingerprint already documents and accepts). Rather than sitting stale for a fixed window, a read past the window now serves the cached value and kicks a background re-detect, so the visible staleness collapses from the full window down to one refresh cycle, at no added cost to the listing that noticed it.
  6. App cold start -- the cache is an empty in-memory Map, so the first read after launch is always a fresh detect.

I deliberately did not widen the file-watcher classifier to watch info/sparse-checkout directly or reclassify the shared config file as structural: git sparse-checkout disable never rewrites the pattern file at all (only flips config), so watching it alone wouldn't catch every mutation anyway, and reclassifying the shared config file as structural would reopen the "index-churn fanout" the existing classifier's own comments say it was designed to avoid. Similarly, true zero-staleness for the unwitnessed case (item 5) would require a dedicated watcher per repo's info/sparse-checkout file and config.worktree regardless of extensions.worktreeConfig -- 973 additional watchers on the motivating user's repo alone -- which is out of proportion to a cosmetic badge; stale-while-revalidate gets the practical benefit (bounded, self-correcting staleness) without that cost.

Benchmark (synthetic fixture, 1 main + 984 linked worktrees under /tmp, never touching a real checkout):

  • git worktree list --porcelain -z: ~207ms
  • Sparse annotation, uncached, per listing: ~140-300ms (paid every single listing)
  • Sparse annotation, cached, cold (first listing): ~199ms (comparable to before)
  • Sparse annotation, cached, warm (every subsequent listing within the reconcile window): ~0.3ms

So steady-state repeat listings -- which is what polling/refresh does in practice -- go from paying the full per-worktree stat+config-read fan-out every time to effectively free, a ~470x reduction for that specific cost on this fixture. The canonicalization, repo-scoping, and stale-while-revalidate changes above don't materially change these numbers (still O(1) map lookups on the warm path); they close correctness gaps in the caching layer itself, not its throughput.

User-Facing Regressions

One, and it is cosmetic.

  • The sparse-checkout badge can be one refresh cycle stale after an external git sparse-checkout toggle in a repo with extensions.worktreeConfig disabled — the one mutation no watcher signal witnesses. Modern sparse-checkout set enables worktreeConfig itself, so this needs old git or hand-edited config.

Nothing functional reads this cached value. Every consumer on this path is display-only (sidebar badge, status-bar row, metadata merge); the one behavioural gate — provisioned-root adoption refusing sparse checkouts — is SSH-only and reads sparse state through the SSH provider, not this cache.

Stale-while-revalidate replaced an earlier hard 5-minute window, so a flip now surfaces on the next refresh rather than after a timeout.

True zero staleness is out of scope: it would need a watcher per worktree gitdir (~973 on the motivating machine), which is exactly the fan-out this effort exists to remove.

Linked Issue

Refs #17828

Visual Proof

N/A -- pure backend performance change, no UI/behavior difference. Sparse badges in the sidebar render identically; only how fast (and how precisely) we compute them changes.

Testing

  • src/main/git/worktree-sparse-checkout-cache.test.ts: unit tests for caching, per-path independence, repo-scoping (same path under two repos cached independently), path-spelling canonicalization (trailing slash / . segment treated as the same entry), false-result caching, stale-while-revalidate past the reconcile window, and change-listener notification only on an actual flip. Includes two race regressions: a background revalidation resolving after its entry was explicitly invalidated must not resurrect it, and (the identity-guard fix) a background revalidation resolving after its entry was invalidated and repopulated with a different value by a fresh cold read must not clobber that fresh value -- verified this second test fails against the earlier has(key)-based guard and only passes with the reference-identity check.

  • Extended src/main/git/worktree-move.test.ts and src/main/git/remove-worktree.test.ts with cache-invalidation coverage for both success and failure paths (now passing repoPath explicitly).

  • Extended src/main/git/worktree-sparse-checkout.test.ts with a real-git end-to-end test proving a worktree recreated at a just-removed worktree's path never inherits a stale sparse badge.

  • New src/main/ipc/worktrees/listing/register-sparse-checkout-cache-invalidation.test.ts: unit tests for repo-scoped clearing, the full-clear fallback when a repo can't be resolved, forwarding a stale-while-revalidate flip to notifyWorktreesChanged, and listener cleanup on disposal.

  • Ran a synthetic ~1000-worktree benchmark under /tmp (see numbers above); never touched a real checkout.

  • pnpm tc:node, targeted pnpm test (src/main/git/worktree*, src/main/ipc/worktrees: 556 tests passing / 1 pre-existing skip), and pnpm run check:code-quality:changed all pass clean.

  • Tested platforms: macOS only (local dev machine). Sparse-checkout tests already skip on win32 per the existing repo convention (it.skipIf(process.platform === 'win32')) since sparse-checkout mechanics are POSIX-path-sensitive in this test file; I did not have Linux/Windows/WSL/SSH hardware to test against, so I relied on tracing the existing watcher/invalidation code paths, plus the new canonicalWorktreePath unit coverage, for cross-platform correctness rather than live verification there.

  • I manually tested these changes locally (macOS)

  • Automated tests added/updated (see above)

AI Disclosure

Claude Sonnet 5 (Claude Code)

Review

This PR was self-reviewed, unlike other PRs in this effort that went through adversarial review. An independent review pass was subsequently run against it and specifically checked for: an unbounded-staleness path, a functional (not just cosmetic) isSparse consumer on the cached path, and a sibling-repo cache-key bug -- and found none. Every isSparse consumer reached through this cache is cosmetic (sidebar badge, status-bar row, metadata merge); the one functional gate that refuses sparse checkouts (provisioned-root SSH adoption) reads sparse state through the SSH provider, not this cache, so it's unaffected. The review credited the double backstop -- the reconcile window/stale-while-revalidate plus the invalidator registry's clear-all fallback -- as what makes that verdict hold even before this round's repo-scoping and canonicalization landed.

That same review requested three concrete improvements over disclosing them as residual risk, which this revision implements: canonical (normalized, case-folded) cache keys on both read and invalidate; scoping cache reads/clears by repo path instead of one shared namespace; and stale-while-revalidate in place of the hard cutoff. While implementing the third, I found and flagged a new race it introduced -- a background revalidation resolving after its entry was explicitly invalidated could resurrect it -- and shipped a fix guarded by sparseCheckoutStateCache.has(key).

That fix was insufficient, and bot review caught it correctly. Both greptile (P1) and pullfrog independently flagged that a presence check can't distinguish "nothing touched this key" from "something invalidated it and a fresh, unrelated value already landed there" -- concretely, a worktree removed and recreated at the same generated path (Orca's own create flow does this, and the motivating user runs ~981 worktrees) while a stale re-detect is in flight would let the old result overwrite the new one for a full reconcile window. This is the second time this exact race was raised on this PR (I found the presence-vs-identity gap in principle during my own readiness pass but chose a guard that didn't actually close it); the corrected fix compares the map's current entry to the exact object the revalidation captured when it started, not just key presence -- the approach both bots independently suggested -- and a new regression test asserts the fresh value survives a stale write-back attempt, failing against the old guard and passing against the new one.

True zero-staleness for the one remaining unwitnessed case (external sparse-checkout toggle with extensions.worktreeConfig off, or a raw pattern-file edit, per Why item 5) would require a dedicated filesystem watcher per repo's info/sparse-checkout file -- 973 additional watchers on the motivating user's repo alone. That's intentionally out of scope for a cosmetic badge; stale-while-revalidate bounds the same staleness to one refresh cycle instead.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no new subprocess/network/eval surfaces; the cache wraps an existing filesystem-only detection function.
  • Cross-platform: underlying detection logic (detectSparseCheckout/resolveGitDir) is unchanged; the cache adds an in-memory layer keyed by canonicalWorktreePath(repoPath) + canonicalWorktreePath(worktreePath), the same normalization areWorktreePathsEqual already uses for Windows/WSL path-spelling differences, so the previously-disclosed path-spelling cache-key risk is closed rather than mitigated.
  • Remote/SSH: no new remote I/O; reuses the same locally-resolved resolveGitDir path resolution the uncached detector already used.
  • Backward compatibility: purely in-memory, ephemeral cache -- no persisted schema, no migration, no data-loss vector.
  • Performance: this is the primary target of the change; see benchmark numbers above.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

`git worktree list` never reports sparse-checkout state, so every listing paid a
per-worktree fs.stat + config read to detect it -- measured at ~9x the cost of
the `git worktree list` call it decorates on a 1000-worktree repo. Cache the
result per worktree path, invalidated by the existing worktree-change
invalidator registry plus explicit remove/move hooks, with a 5-minute
reconcile window bounding the one unwitnessed edge case (external
`git sparse-checkout` toggle with extensions.worktreeConfig off), matching the
precedent already accepted in readRepoWorktreeAdminFingerprint.
@greptile-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Greptile Summary

This PR caches sparse-checkout annotations by worktree path and invalidates them on worktree lifecycle and structural-change notifications to reduce repeated filesystem work.

  • Adds a five-minute sparse-state cache used during worktree listing.
  • Invalidates individual entries after moves and removals.
  • Registers full-cache clearing with worktree-change notifications.
  • Adds unit and lifecycle coverage for caching and invalidation.

Confidence Score: 4/5

The PR should not merge until cache invalidation also fences in-flight detections from restoring obsolete sparse-checkout state.

The cache unconditionally stores an asynchronous detection result even when a concurrent move, removal, or watcher notification has invalidated that path, allowing a stale sidebar annotation to persist for the reconciliation interval.

Files Needing Attention: src/main/git/worktree-sparse-checkout-cache.ts

Important Files Changed

Filename Overview
src/main/git/worktree-sparse-checkout-cache.ts Adds the read-through cache, but pending detections are not fenced against concurrent invalidation and can restore stale entries.
src/main/git/worktree-listing.ts Routes sparse annotation through the new cache; its correctness now depends on cache invalidation ordering.
src/main/git/worktree-move.ts Invalidates old and new paths after move attempts, but deletion alone cannot prevent late cache writes.
src/main/git/worktree-removal.ts Invalidates the removed path in cleanup, but deletion alone cannot prevent late cache writes.
src/main/ipc/worktrees/listing/register-sparse-checkout-cache-invalidation.ts Registers full-cache clearing with the existing worktree-change invalidator registry.

Sequence Diagram

sequenceDiagram
  participant L as Worktree listing
  participant C as Sparse cache
  participant D as Sparse detector
  participant M as Worktree mutation
  L->>C: detectSparseCheckoutCached(path)
  C->>D: detectSparseCheckout(path)
  M->>C: invalidate(path)
  D-->>C: old sparse state
  C->>C: set(path, old state)
  C-->>L: stale annotation
Loading

Reviews (1): Last reviewed commit: "perf(git): cache sparse-checkout annotat..." | Re-trigger Greptile

return cached.isSparse
}
const isSparse = await detectSparseCheckout(worktreePath)
sparseCheckoutStateCache.set(worktreePath, { isSparse, cachedAt: Date.now() })

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Invalidation permits stale cache writes

When sparse-checkout detection overlaps a move, removal, recreation, or watcher-driven invalidation, the pending detection unconditionally writes its earlier result after invalidation completes, causing the worktree to display stale sparse-checkout status for up to five minutes.

Knowledge Base Used: Workspace and worktree lifecycle

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 05411bb. The write-back guard now compares the map's current entry by reference to the exact entry object captured when the revalidation started (sparseCheckoutStateCache.get(key) === startingEntry), not just key presence -- so an entry invalidated and then repopulated by a fresh cold read (e.g. remove + recreate at the same path) can no longer be clobbered by the stale in-flight result. Added a regression test that fails against the old has(key) guard and passes with this fix (invalidate + repopulate with a different value mid-flight, then let the stale revalidation settle and assert the fresh value survives).

@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

  • worktree-sparse-checkout-cache.ts — new module-level Map keyed by worktree path caching detectSparseCheckout results behind a 5-minute reconcile window, with invalidateSparseCheckoutState/clearSparseCheckoutStateCache helpers.
  • worktree-listing.ts — annotateSparseCheckoutStatus now calls detectSparseCheckoutCached instead of re-running the filesystem probe on every listing.
  • worktree-removal.ts / worktree-move.ts — explicit invalidateSparseCheckoutState on the affected path(s) in finally, so removed/moved paths are re-detected on reuse.
  • register-sparse-checkout-cache-invalidation.ts + worktrees.ts — wires a full clear into the shared registerWorktreeChangeInvalidator registry, so structural notifyWorktreesChanged events clear stale entries.
  • Test-suite reset hooks — extended to clear the module-level cache between tests, plus unit and real-git lifecycle coverage.

Verified the load-bearing invalidation claim: config.worktree is classified structural in worktree-base-directory-event-filter.ts and routes through notifyWorktreesChanged → runWorktreeChangeInvalidators, so an external sparse toggle with extensions.worktreeConfig on does clear the cache. The unwitnessed cases (worktreeConfig off, pattern-file edits) are bounded by the reconcile window, matching the readRepoWorktreeAdminFingerprint precedent. The new tests assert concrete observables (call counts, stat counts, cache size) rather than tautologies, and all touched suites pass locally.

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

Address independent-review follow-ups on the sparse-checkout annotation
cache (#17859):

- Extract canonicalWorktreePath() from areWorktreePathsEqual and key/invalidate
  the cache through it on both read and write, closing the disclosed
  path-spelling P2 outright instead of leaving it as a residual risk.
- Scope cache entries and clears by repo path (derived from the invalidator
  registry's repoId via a store lookup, falling back to a full clear when the
  repo can't be resolved), so churn in one repo no longer evicts a sibling
  repo's warm cache.
- Replace the hard 5-minute cutoff with stale-while-revalidate: past the
  window, callers get the cached value immediately while a deduplicated
  background probe corrects it and, on a flip, drives the existing
  worktrees-changed notification -- collapsing visible staleness from the
  full window to one refresh cycle at zero added listing latency.

Also corrects a stale claim in the original PR description: newer Git does
emit a `sparse` porcelain line (which annotateSparseCheckoutStatus already
skips), but Orca's Git 2.25 compatibility baseline predates it, so the
fallback detection this caches remains necessary.
…nvalidated entries

Readiness-loop finding: a stale-while-revalidate probe in flight when a
worktree is removed/moved (or a repo's cache is cleared) would still write
its result back afterward, resurrecting an entry that was deliberately
dropped. Guard the write with a presence check so an invalidated key stays
absent until the next real read.

@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 critical issues — one minor suggestion inline.

Reviewed changes

  • Repo-scoped, canonicalized cache keys — detectSparseCheckoutCached now takes (repoPath, worktreePath) and keys by canonicalWorktreePath of both, so sibling repos and path-spelling variants (trailing slash, . segment, drive-case) can no longer collide or silently diverge.
  • Stale-while-revalidate — past the 5-minute reconcile window a read now serves the cached value immediately and kicks a deduplicated background re-detect; a flip fires the shared worktrees-changed notification instead of blocking the listing.
  • Repo-scoped invalidation rewired — registerSparseCheckoutCacheInvalidation resolves repoId to a repo path via the Store (full-clear fallback when unresolvable) and forwards SWR flips back to notifyWorktreesChanged; registration moved into registerWorktreeHandlers with a disposer.
  • Tests — repo-scoping, path-spelling, SWR dedup/flip, no-resurrection, and invalidation-registry coverage added, plus real-git lifecycle coverage.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

The has()/presence guard from the previous commit only proved some
entry existed at the key, not that it was the one this revalidation
started from. A worktree removed and re-created at the same path while
a background re-detect was in flight would repopulate the key with a
fresh cold read, and the stale in-flight result would then overwrite
it -- exactly the race greptile (P1) and pullfrog both flagged as
still open. Compare the map's current entry by reference to the entry
captured when the revalidation began; a mismatch means something else
(invalidate, clear, or a fresh cold read) replaced it, and the stale
result must not be written back.

Added a regression test that fails against the old has() guard and
passes with the identity check: invalidate and repopulate the key with
a different value mid-flight, then let the stale revalidation settle
and assert the fresh value survives.

@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

  • Identity-checked the stale-while-revalidate write-back — revalidateInBackground now captures the entry object it started from and only writes back when sparseCheckoutStateCache.get(key) === startingEntry, so a stale in-flight re-detect can no longer clobber a fresh value written by an invalidate + recreate at the same path (the previously flagged presence-only guard).
  • Regression test — added does not let a stale in-flight revalidation clobber a fresh value written after remove+recreate at the same path, which holds a re-detect open across an invalidate + fresh cold read and asserts the fresh value survives the stale result resolving.

The prior minor suggestion (identity-check the write-back guard) is addressed by this delta and its thread is resolved.

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

@nwparker
nwparker merged commit 84584b6 into main Sep 1, 2026
28 checks passed
@nwparker
nwparker deleted the nwparker/lazy-sparse-annotation branch September 1, 2026 10:44
nwparker added a commit that referenced this pull request Sep 1, 2026
…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.

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 it makes the bug stickier than the analysis below assumes: a
distro-less `false` is now cached for five minutes and served by
stale-while-revalidate, so the wrong "not sparse" answer persists rather than
being re-derived per listing. `wslDistro` is deliberately not part of the cache
key -- the distro is a property of the repo, so every read for a given
`repoPath` carries the same one -- which is an invariant of the current call
paths rather than something the types enforce.
`resolveGitMetadataPath` still prefers a UNC base's distro and still tries drvfs
before the caller-named distro, so nothing that resolved before resolves
differently.

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.
- native Windows, no WSL: no change. `wslDistro` is undefined, so the resolver
  takes exactly the branches it took before.
- 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.
- 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.
nwparker added a commit that referenced this pull request Sep 1, 2026
…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 added a commit that referenced this pull request Sep 1, 2026
…caller's distro (#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 #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 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
…lyai#17859)

* perf(git): cache sparse-checkout annotation on worktree listing

`git worktree list` never reports sparse-checkout state, so every listing paid a
per-worktree fs.stat + config read to detect it -- measured at ~9x the cost of
the `git worktree list` call it decorates on a 1000-worktree repo. Cache the
result per worktree path, invalidated by the existing worktree-change
invalidator registry plus explicit remove/move hooks, with a 5-minute
reconcile window bounding the one unwitnessed edge case (external
`git sparse-checkout` toggle with extensions.worktreeConfig off), matching the
precedent already accepted in readRepoWorktreeAdminFingerprint.

* perf(git): normalize/scope sparse-checkout cache keys, add SWR

Address independent-review follow-ups on the sparse-checkout annotation
cache (stablyai#17859):

- Extract canonicalWorktreePath() from areWorktreePathsEqual and key/invalidate
  the cache through it on both read and write, closing the disclosed
  path-spelling P2 outright instead of leaving it as a residual risk.
- Scope cache entries and clears by repo path (derived from the invalidator
  registry's repoId via a store lookup, falling back to a full clear when the
  repo can't be resolved), so churn in one repo no longer evicts a sibling
  repo's warm cache.
- Replace the hard 5-minute cutoff with stale-while-revalidate: past the
  window, callers get the cached value immediately while a deduplicated
  background probe corrects it and, on a flip, drives the existing
  worktrees-changed notification -- collapsing visible staleness from the
  full window to one refresh cycle at zero added listing latency.

Also corrects a stale claim in the original PR description: newer Git does
emit a `sparse` porcelain line (which annotateSparseCheckoutStatus already
skips), but Orca's Git 2.25 compatibility baseline predates it, so the
fallback detection this caches remains necessary.

* fix(git): stop background sparse-checkout revalidation resurrecting invalidated entries

Readiness-loop finding: a stale-while-revalidate probe in flight when a
worktree is removed/moved (or a repo's cache is cleared) would still write
its result back afterward, resurrecting an entry that was deliberately
dropped. Guard the write with a presence check so an invalidated key stays
absent until the next real read.

* fix(git): identity-check the sparse-checkout SWR write-back guard

The has()/presence guard from the previous commit only proved some
entry existed at the key, not that it was the one this revalidation
started from. A worktree removed and re-created at the same path while
a background re-detect was in flight would repopulate the key with a
fresh cold read, and the stale in-flight result would then overwrite
it -- exactly the race greptile (P1) and pullfrog both flagged as
still open. Compare the map's current entry by reference to the entry
captured when the revalidation began; a mismatch means something else
(invalidate, clear, or a fresh cold read) replaced it, and the stale
result must not be written back.

Added a regression test that fails against the old has() guard and
passes with the identity check: invalidate and repopulate the key with
a different value mid-flight, then let the stale revalidation settle
and assert the fresh value survives.
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