Repository navigation
perf(git): cache sparse-checkout annotation on worktree listing - #17859
Conversation
`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 SummaryThis PR caches sparse-checkout annotations by worktree path and invalidates them on worktree lifecycle and structural-change notifications to reduce repeated filesystem work.
Confidence Score: 4/5The 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
|
| 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
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() }) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
worktree-sparse-checkout-cache.ts— new module-levelMapkeyed by worktree path cachingdetectSparseCheckoutresults behind a 5-minute reconcile window, withinvalidateSparseCheckoutState/clearSparseCheckoutStateCachehelpers.worktree-listing.ts—annotateSparseCheckoutStatusnow callsdetectSparseCheckoutCachedinstead of re-running the filesystem probe on every listing.worktree-removal.ts/worktree-move.ts— explicitinvalidateSparseCheckoutStateon the affected path(s) infinally, so removed/moved paths are re-detected on reuse.register-sparse-checkout-cache-invalidation.ts+worktrees.ts— wires a full clear into the sharedregisterWorktreeChangeInvalidatorregistry, so structuralnotifyWorktreesChangedevents 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.
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.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Repo-scoped, canonicalized cache keys —
detectSparseCheckoutCachednow takes(repoPath, worktreePath)and keys bycanonicalWorktreePathof 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 —
registerSparseCheckoutCacheInvalidationresolvesrepoIdto a repo path via theStore(full-clear fallback when unresolvable) and forwards SWR flips back tonotifyWorktreesChanged; registration moved intoregisterWorktreeHandlerswith a disposer. - Tests — repo-scoping, path-spelling, SWR dedup/flip, no-resurrection, and invalidation-registry coverage added, plus real-git lifecycle coverage.
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.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Identity-checked the stale-while-revalidate write-back —
revalidateInBackgroundnow captures the entry object it started from and only writes back whensparseCheckoutStateCache.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.
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.
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.
…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.
…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.
…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.
…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
…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.
…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.
…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.

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 listcall 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
src/main/git/worktree-sparse-checkout-cache.ts: a cache (detectSparseCheckoutCached) wrapping the existingdetectSparseCheckout, keyed by repo path + worktree path so entries from different repos never collide or evict each other.canonicalWorktreePath(), extracted from the existingareWorktreePathsEqualnormalization (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.src/main/git/worktree-listing.ts'sannotateSparseCheckoutStatusnow takesrepoPathand calls the cached wrapper (with both the repo and worktree path) instead of hitting the filesystem on every listing.removeWorktree(worktree-removal.ts) andmoveWorktree(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'srepoIdto a repo path via theStoreand 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 tonotifyWorktreesChangedby resolving the repo path back to arepoId. This needs bothmainWindowandstore, so registration moved from module-load time intoregisterWorktreeHandlers, with a disposer so re-invoking it (already-supported re-registration) doesn't stack duplicate listeners.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.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 --porcelainpredates sparse-checkout awareness on Orca's Git 2.25 compatibility baseline: newer Git versions do emit asparseporcelain line (Orca's own parser handles it --src/main/git/worktree-list-parser.ts:38-39-- andannotateSparseCheckoutStatusalready skips rows where it's set), but on the baseline we support, Orca still has to derive it itself via a per-worktreefs.stat+ config read (detectSparseCheckout). On a real user's repo with 973 live worktrees,git worktree list --porcelain -zitself 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:
invalidateSparseCheckoutState(repoPath, worktreePath).git sparse-checkouttoggle withextensions.worktreeConfigon -- rewritesconfig.worktree, which the existing git-common-dir watcher already classifies as structural and routes throughnotifyWorktreesChanged-> the repo-scoped invalidator this module registers.extensions.worktreeConfigoff, or a bare pattern-file edit -- not observed by the watcher (this is the exact same blind spotreadRepoWorktreeAdminFingerprintalready 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.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-checkoutdirectly or reclassify the sharedconfigfile as structural:git sparse-checkout disablenever rewrites the pattern file at all (only flips config), so watching it alone wouldn't catch every mutation anyway, and reclassifying the sharedconfigfile 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'sinfo/sparse-checkoutfile andconfig.worktreeregardless ofextensions.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: ~207msSo 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.
git sparse-checkouttoggle in a repo withextensions.worktreeConfigdisabled — the one mutation no watcher signal witnesses. Modernsparse-checkout setenablesworktreeConfigitself, 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 earlierhas(key)-based guard and only passes with the reference-identity check.Extended
src/main/git/worktree-move.test.tsandsrc/main/git/remove-worktree.test.tswith cache-invalidation coverage for both success and failure paths (now passingrepoPathexplicitly).Extended
src/main/git/worktree-sparse-checkout.test.tswith 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 tonotifyWorktreesChanged, and listener cleanup on disposal.Ran a synthetic ~1000-worktree benchmark under
/tmp(see numbers above); never touched a real checkout.pnpm tc:node, targetedpnpm test(src/main/git/worktree*,src/main/ipc/worktrees: 556 tests passing / 1 pre-existing skip), andpnpm run check:code-quality:changedall pass clean.Tested platforms: macOS only (local dev machine). Sparse-checkout tests already skip on
win32per 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 newcanonicalWorktreePathunit 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)
isSparseconsumer on the cached path, and a sibling-repo cache-key bug -- and found none. EveryisSparseconsumer 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.worktreeConfigoff, or a raw pattern-file edit, per Why item 5) would require a dedicated filesystem watcher per repo'sinfo/sparse-checkoutfile -- 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
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
detectSparseCheckout/resolveGitDir) is unchanged; the cache adds an in-memory layer keyed bycanonicalWorktreePath(repoPath) + canonicalWorktreePath(worktreePath), the same normalizationareWorktreePathsEqualalready uses for Windows/WSL path-spelling differences, so the previously-disclosed path-spelling cache-key risk is closed rather than mitigated.resolveGitDirpath resolution the uncached detector already used.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)