Repository navigation
perf(git): bound ref and worktree scans - #17655
Conversation
Greptile SummaryThe PR replaces broad remote-ref enumeration with bounded exact probes and introduces generation-aware sharing for compatible worktree scans.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/main/git/exact-ref-probe.ts | Adds validated, concurrency-bounded exact ref probes with explicit present, absent, and unknown outcomes. |
| src/main/git/repo-base-ref-search.ts | Bounds ref-search scans and narrows remote HEAD exclusion while preserving nested branch names. |
| src/main/git/worktree-scan-cache.ts | Separates graph, lenient, and strict in-flight scan identities and fences internal mutations by generation. |
| src/main/git/worktree.ts | Restores unshared strict listing for post-mutation verification and exposes shared strict scans only through explicit opt-in. |
| src/main/source-control/hosted-review-creation-git-state.ts | Replaces broad remote-ref enumeration with bounded exact probes and a bounded stale-ref fallback. |
| src/main/text-generation/pull-request-remote-ref-probes.ts | Centralizes bounded PR-context remote-ref discovery and conservative handling of inconclusive probes. |
| src/main/git/command-runner/git-exec-file.ts | Avoids retrying quiet Git control-flow exits through the WSL login-shell fallback. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
Caller[Branch, review, or worktree caller] --> RefProbe[Bounded exact ref probes]
RefProbe --> GitRefs[Git show-ref]
Caller --> ScanKind{Worktree scan kind}
ScanKind -->|Graph or lenient| Shared[Generation-fenced shared scan]
ScanKind -->|Strict verification| Isolated[Unshared strict scan]
Shared --> GitWorktrees[Git worktree list]
Isolated --> GitWorktrees
Reviews (4): Last reviewed commit: "fix(git): separate a proven absent ref f..." | Re-trigger Greptile
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Exact ref probes — new
src/main/git/exact-ref-probe.ts(probeExactRefs/probeAnyExactRef, concurrency 8,isShowRefNoMatchError), replacing broad ref enumeration across branch-conflict, hosted-review eligibility, and PR-context paths withshow-ref --verifylookups. - Bounded search excludes —
repo-base-ref-search.tsswaps--exclude=refs/remotes/**/HEADfor--exclude=refs/remotes/*/HEADplus exact slash-remote excludes, andparseAndFilterSearchRefDetailspreserves nestedfeature/HEADbranch names viaisRemoteHeadRef. - Worktree probes/caching —
worktree-base-ref-probe.tsmoves to an exactshow-ref --verifyprobe;worktree-scan-cache.tskeys the in-flight map by an explicitkind(bundler-safe) and shareslistWorktreeGraph. - Adapter plumbing —
filesystem.ts,worktree-remote.ts, andruntime-git-generation-commands.tsthreadmaxBuffer/timeoutMs/timeoutthrough the local and SSH exec adapters. - Docs —
AGENTS.mdgains a Git Scan Safety section codifying the no-ref×tree rule.
I read the full diff end-to-end and traced the new probe/fallback logic against the actual Git binary. The two load-bearing assumptions check out empirically: --exclude=refs/remotes/*/HEAD does not cross / (so nested feature/HEAD branches survive while the symbolic <remote>/HEAD slot is excluded), and show-ref --verify --quiet -- <ref> exits 0 for present refs (including symbolic origin/HEAD) and 1 for absent refs. The numeric-only isShowRefNoMatchError correctly preserves "absent vs. inconclusive" across the SSH relay, which surfaces a git exit 1 as a numeric code. The 10 MiB maxBuffer cap on the show-ref -- <base> suffix fallback bounds the remaining stale-ref scan without recreating the original unbounded allocation. Tests use exact assertions (specific argv arrays, exit-code code: 1, concurrency ≤ 8) and a real-binary compatibility case, so they are genuinely fail-able rather than theatre.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Shared ref-search limit constants — new
src/shared/repo-search-limits.tsdefinesREPO_SEARCH_REFS_DEFAULT_LIMIT(25),REPO_SEARCH_REFS_MAX_LIMIT(1000), andREPO_SEARCH_REFS_MAX_SCAN_LIMIT(1001), withis…guards plusclamp…/getRepoSearchRefsProbeLimithelpers. - Bounded
for-each-ref --count—buildSearchBaseRefsArgvclamps the scan limit before computing the candidate count, so an oversized request stops at--count=4004instead of multiplying an unbounded limit into the argv. - Forgiving-but-bounded IPC/runtime surfaces — local, SSH-relay, and runtime ref-search paths clamp oversized limits (and return
[]/ throwinvalid_limitfor malformed ones), reporting oversized runtime requests astruncated. - Truncation sentinel preserved —
getRepoSearchRefsProbeLimitkeeps the+1probe row (capped atMAX_SCAN_LIMIT) so the runtimetruncatedflag still fires without overflowing atMAX_SAFE_INTEGER.
I traced the new clamping through searchBaseRefs → searchBaseRefDetails → runSearchBaseRefsGit → buildSearchBaseRefsArgv, plus the SSH relay path (searchBaseRefDetailsForRepo) and the runtime path (searchRemoteRepoRefs/searchBaseRefDetails(…, probeLimit)). Every caller now passes a validated/clamped limit into buildSearchBaseRefsArgv, so the new invalid_limit throw can't surface on a production path, and the slice(0, limit) in parseAndFilterSearchRefDetails is consistently the retained-result cap rather than the scan cap. Tests assert exact --count values (4000/4004), reject Number.MAX_VALUE, and pin the truncation contract with real Git state, so they fail on a regression.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The shared-scan re-export flipped every `listWorktreesStrict` caller from an isolated subprocess to the coalesced scan. `git worktree prune` in the removal recovery path does not bump the scan generation, so a post-prune verification could join a pre-prune scan, see the stale row, and report a successful removal as a stale registration. The same gap defeats the post-archive-hook rechecks that exist to catch an external Git client locking the row. Restore the unshared export and make coalescing opt-in via `listWorktreesSharedStrict`, which existing callers already use deliberately.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Restored unshared
listWorktreesStrict— removed thelistWorktreesSharedStrict as listWorktreesStrictre-export so verification-after-mutation callers (local-worktree-removal-recovery.ts,execute-worktree-removal.ts, etc.) return to an isolated subprocess, with a comment documenting why coalescing must stay opt-in. - Added a mutation-verified regression test — asserts two concurrent
listWorktreesStrictcalls spawn two Git subprocesses, failing if the alias is reintroduced.
The fix is correct and complete. listWorktreesStrict now resolves to the unshared worktree-listing implementation with no export collision, and the only caller that wants coalescing for strict scans (created-worktree-reconciliation.ts) already uses listWorktreesSharedStrict explicitly. The git worktree prune generation-blindspot the commit message describes is real: the removal-recovery path runs prune raw without bumping the scan generation, so a coalesced post-prune read could report a successful removal as stale. The new test is exact (subprocess count === 2), so it fails on the regression rather than absorbing it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
`show-ref --verify --quiet` exits 1 for a missing ref, but so does `wsl.exe` when its own launch fails, so reading any exit 1 as absence collapsed `unverifiable` into `exited`. A genuine miss prints nothing while a wrapper failure always explains itself, so require empty stderr alongside the exit code; a runner that reports no stderr at all keeps its exit-code contract. That same signal removes a spawn regression: `show-ref` is a direct-git read under WSL, and the runner retried any numeric exit through the user's interactive login shell. The replaced `for-each-ref` exited 0 on a miss, so absence never retried; every absent probe now would. Treat a quiet exit 1 as Git control flow and skip the fallback. Also narrow the hosted-review suffix fallback: the replaced `refs/remotes/*/<base>` could not cross a slash, but `show-ref -- <base>` matches at any depth, so `origin/feature/main` answered a query for `main` and submitted a review against a base the provider rejects. Refresh the real-binary compatibility contract to the shipped excludes, and assert exact probe concurrency rather than an upper bound so a regression to serial probing fails.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — the 5dcc8ec commit separates a proven-absent ref from a failed probe and narrows the hosted-review suffix fallback:
- Empty-stderr absence discriminator —
isShowRefNoMatchErrornow requires empty (or missing) stderr alongside a numeric exit 1, so awsl.exelaunch failure reads asunknowninstead of a proven miss, while a genuineshow-ref --verify --quietmiss (exit 1, 0 bytes on stderr) still resolves as absent. - WSL retry suppression — new
isQuietGitControlFlowExitskips the interactive-login-shell fallback for quiet exit-1 control flow, removing the per-absent-probe spawn regression on the always-readshow-refpath. - Single-segment suffix match —
parseSuffixRemoteRefsrequires the remote component to be exactly one segment, so a nestedorigin/feature/mainno longer answers a baremainbase query. - Compat + concurrency contract — the real-binary test pins the shipped
*/HEAD+ per-remote excludes, and the concurrency tests assert exact pool saturation (8) rather than an upper bound.
I verified the load-bearing claim against the real binary (git 2.55): show-ref --verify --quiet -- <missing> exits 1 with empty stderr, and the suffix pattern form show-ref -- <base> matches a ref at any depth — exactly the case the new single-segment guard rejects. The three new error-shape tests and the mutation-verified concurrency equality assertions are genuinely fail-able.
ℹ️ The same depth-insensitive suffix match remains in the PR-context path
The single-segment guard was applied only to hosted-review-creation-git-state.ts. The parallel implementation in src/main/text-generation/pull-request-remote-ref-probes.ts:126 (shortRef.endsWith(\/${base}`)) and the resolveComparisonBasefilter insrc/main/text-generation/pull-request-context.ts:132 (.filter((ref) => ref.endsWith(`/${base}`))) still match a suffix at any depth, so PR-body generation can select a nested orphan/feature/mainas the base whenorigin/upstreamare unconfigured. This is pre-existing behavior — the oldfor-each-ref+endsWith` path was equally depth-insensitive — so it is not a regression from this PR. Flagging for a scope decision rather than as a blocker.
Technical details
# Unify the depth guard across the two suffix-remote-ref parsers
## Affected sites
- src/main/text-generation/pull-request-remote-ref-probes.ts:126 — `parseSuffixRemoteRefs` accepts `orphan/feature/main` for a bare `main` query.
- src/main/text-generation/pull-request-context.ts:132 — `resolveComparisonBase` filters `refs.endsWith('/'+base)`, which a nested truncated ref satisfies.
## Required outcome
- Decide whether the PR-context path should reject nested suffix matches with the same `isSingleRemoteSegmentMatch` guard added to `hosted-review-creation-git-state.ts`, or whether the pre-existing depth-insensitivity is acceptable there.
## Open questions for the human
- Is the PR-context `show-ref -- <base>` suffix fallback reachable in a case where a nested branch would be selected as the base (no `origin`/`upstream` configured, `refs.length < 2`)?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…-refactor main advanced 45 commits, six of them landing inside the orca-runtime.ts this branch splits apart. Git resolves that as a plain "take one side", and either side silently loses work, so each was ported into the module that now owns the code: - stablyai#17655 bound ref and worktree scans -> runtime-repository-ref-queries - stablyai#17448 preserve user-set workspace names -> the worktree-create modules - stablyai#17667 cut cold worktree-switch attach latency -> the mutation lock, including the deletion half (worktree-terminal-mutation-wait.ts is gone) - stablyai#17718 preserve large agent prompt pastes -> the agent-prompt write path - stablyai#17486 unblock targeted SSH session tab refresh -> the mobile refresh modules - stablyai#17159 close readiness gaps -> 34 runtime hunks and 5 test hunks Every added line of the six was checked against the merged tree; the unmatched ones are all renames or line splits, verified individually. Two defects surfaced while porting, both predating this merge: - isMobileSessionSurfaceMembershipAllowed read a session accessor that answers null where main's answers undefined, so main's `session !== undefined` guard was always true and the fence stopped fencing. Three clauses found in neither main nor the split base had been added ahead of it to compensate, and one of them dropped a freshly published split leaf out of syncWindowGraph. Restored to main's control flow with the sentinel normalized; stablyai#17159's two new tests cover it from both directions. - retiredMobileSessionPtyIds was write-only state this branch invented. Its only reader was the clause above, and it exists in neither main nor the split base. - RuntimeTerminalWriter.writeAgentPrompt had no callers and still carried the chunked-paste shape stablyai#17718 replaced.
…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
* perf(git): bound ref and worktree scans * fix(repo-search): clamp oversized ref limits * fix(worktree): keep strict worktree listing unshared The shared-scan re-export flipped every `listWorktreesStrict` caller from an isolated subprocess to the coalesced scan. `git worktree prune` in the removal recovery path does not bump the scan generation, so a post-prune verification could join a pre-prune scan, see the stale row, and report a successful removal as a stale registration. The same gap defeats the post-archive-hook rechecks that exist to catch an external Git client locking the row. Restore the unshared export and make coalescing opt-in via `listWorktreesSharedStrict`, which existing callers already use deliberately. * fix(git): separate a proven absent ref from a failed probe `show-ref --verify --quiet` exits 1 for a missing ref, but so does `wsl.exe` when its own launch fails, so reading any exit 1 as absence collapsed `unverifiable` into `exited`. A genuine miss prints nothing while a wrapper failure always explains itself, so require empty stderr alongside the exit code; a runner that reports no stderr at all keeps its exit-code contract. That same signal removes a spawn regression: `show-ref` is a direct-git read under WSL, and the runner retried any numeric exit through the user's interactive login shell. The replaced `for-each-ref` exited 0 on a miss, so absence never retried; every absent probe now would. Treat a quiet exit 1 as Git control flow and skip the fallback. Also narrow the hosted-review suffix fallback: the replaced `refs/remotes/*/<base>` could not cross a slash, but `show-ref -- <base>` matches at any depth, so `origin/feature/main` answered a query for `main` and submitted a review against a base the provider rejects. Refresh the real-binary compatibility contract to the shipped excludes, and assert exact probe concurrency rather than an upper bound so a regression to serial probing fails.
…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.

Summary
git show-ref --verifyprobes.ELI5
Orca used to answer small yes/no questions by reading the repository's entire phone book.
To find out "does the branch
mainalready exist on a remote?", it rangit for-each-ref refs/remotes— list every remote-tracking ref in the repo — and then scanned that list in JS for one name. On a normal repo that's cheap. On a repo with tens of thousands of refs, it's seconds of Git work plus a large string held in memory, and Orca did it repeatedly: once per worktree create, once per branch-name conflict check, once per PR-body generation, once per "can I open a PR?" check.Now Orca asks the exact question instead. It builds the handful of ref names that could actually answer it (
refs/remotes/origin/main,refs/remotes/upstream/main, one per configured remote) and runsgit show-ref --verify --quiet -- <ref>on each. Git looks those up directly, prints nothing, and exits 0 (present) or 1 (absent). At most 8 run at a time, so the subprocess fan-out is bounded too.The second half is the same idea for
git worktree list. Orca already de-duplicated concurrent worktree scans, but the cache key usedrun.name— the JavaScript function's name — to keep "strict" callers from joining a "lenient" scan. Production bundlers rename functions, so in packaged builds those keys could collide. Now the kind is passed explicitly ('graph' | 'lenient' | 'strict'), and the graph scan joins the shared cache instead of always spawning its own Git process.Benefit
Worktree create, branch-name conflict checks, PR body generation, and "create PR" eligibility stop doing repo-wide ref scans. On the affected repository those paths took roughly 6–38 s; the replacement is 56 exact probes at concurrency 8 in about 392 ms. The win scales with ref count — repos with few refs see little change, repos with many see most of it.
Three secondary wins:
refs/remoteslisting any more. The one remaining fallback scan is capped at 10 MiB and stops after it has found 2 candidates (all the caller needs to distinguish "none / one / ambiguous").run.namecache key is a real bug under minification: a strict worktree-list caller could inherit a lenient scan's softened[]and see an empty worktree list. The explicit-kind key removes that.listWorktreeGraphnow shares scans too, which removes duplicategit worktree listprocesses (expensive on Windows)..../HEADare no longer hidden. The old exclude was--exclude=refs/remotes/**/HEAD, where**crosses/— so a real branchorigin/feature/HEADwas filtered out of branch search along with the symbolicorigin/HEADslot. Now only the direct<remote>/HEADslot is excluded, and the display name is de-DWIM'd soorigin/feature/HEADno longer renders asorigin/feature.User-facing trade-offs
Items 1, 2 and 6 are genuine behavior changes; the rest are listed because a reviewer will reasonably wonder about them, and each note explains why it is not a regression.
1. Repo ref search is clamped to 1,000 results, and
truncatedgets looser.searchBaseRefs/searchBaseRefDetailspreviously passed the caller's limit straight to--count. It is now clamped byREPO_SEARCH_REFS_MAX_LIMIT = 1_000. The branch picker asks for 20 and the API default is 25, so no UI surface changes; an API or CLI caller asking for more than 1,000 rows now gets 1,000 and loses the tail. Separately,orca-runtime.tssetstruncated: limit > effectiveLimit || refDetails.length > effectiveLimit, so a request for 5,000 in a repo with 3 refs reportstruncated: true. A consumer readingtruncatedas "more data exists" will be misled.2. Branches literally named
<something>/HEADnow appear in the picker.The old
--exclude=refs/remotes/**/HEADplus a/^refs\/remotes\/.+\/HEAD$/post-filter hid a real branchorigin/feature/HEAD;isRemoteHeadRefnow excludes only the direct<remote>/HEADsymbolic slot. Their display name is also corrected — Git'srefname:shortDWIM was renderingorigin/feature/HEADasorigin/feature. This is a fix, but it does change what the picker lists.3. The PR-context suffix fallback is skipped when
origin/upstreamis configured.shouldSearchSuffixRemoteRefs(pull-request-remote-ref-probes.ts:157-172) skips the boundedshow-ref -- <base>scan in that case. This is not a behavior change:resolveComparisonBase(pull-request-context.ts:124-129) checks preferred remotes before suffix matching, and that check passes onstate.remotes.includes(parsed.remote)alone — origin merely being configured is enough, no ref required. So the suffix results would be discarded anyway, exactly as they were under the old full enumeration. The skip is a pure optimization.baseRefExistsOnRemoteruns its fallback unconditionally because it has no preferred-remote shortcut to fall back on.4. Timeout/maxBuffer plumbing is now correct, but no caller sets a timeout yet.
runtime-git-generation-commands.tsandfilesystem.tspreviously spread...optionsintogitExecFileAsync, so atimeoutMskey was passed as an unrecognized option and silently ignored; the SSH path dropped options entirely. Both now normalizetimeoutMs/timeout→timeoutand forwardmaxBuffer. No live behavior change today — every probe site passes onlymaxBuffer(pull-request-remote-ref-probes.ts:186, hosted-review-creation-git-state.ts:210), so nothing supplies a deadline. This is groundwork: if a future caller setstimeoutMs, it will now actually apply instead of being dropped.5. Inconclusive probes fail open, and one relay shape can never prove absence.
A probe that neither succeeds nor returns Git's exit-1 "no match" (dropped SSH transport, broken repo, output overflow) is classified
unknown, neverabsent:baseRefExistsOnRemotereturnstrue(preserves the candidate rather than blocking PR creation) and PR context setsprobeUnknownand falls back to the bare base name. This upholds the SSH-boundary rule that loss of contact is not evidence of absence. The deliberate corollary inisShowRefNoMatchError: only a numericcode === 1counts as absent, so a relay that reports a string"1"will always land inunknownand take the conservative branch.6. Ref probes run at most 8 at a time, and process count now scales with remote count.
EXACT_REF_PROBE_CONCURRENCY = 8bounds subprocess fan-out. The trade-off is shape, not just speed: onefor-each-refis replaced by oneshow-ref --verifyper candidate remote. A repo with ~30 configured remotes goes from 1 process to up to 4 sequential waves of 8 — noticeable on Windows and SSH where spawn is expensive. In the common 1-3 remote case it is a wash or faster, because the old command's cost scaled with total ref count rather than remote count.probeAnyExactRefstops scheduling on the first hit.7. Worktree scan sharing widens only where it is safe.
listWorktreeGraphnow routes through the shared in-flight cache instead of always spawning its owngit worktree list.listWorktreesStrictdeliberately does not — it stays unshared, and coalescing is opt-in vialistWorktreesSharedStrict. Sharing cannot serve stale data: entries are deleted on settle (no TTL), andnotifyPreparedWorktreeMutationfences the key so a post-mutation caller cannot join a pre-mutation scan. Strict/lenient/graph never share with each other, andAbortSignalcallers still get an isolated subprocess.8. Names Git itself would reject are now refused before reaching Git.
Branch/ref names containing
~ ^ : ? * [ \, control characters,..,@{, or a leading/trailing.are rejected up front in branch-conflict, PR context, and worktree base-ref probes. These are invalid Git ref names, so no legitimate branch is affected — the failure just surfaces one step later. One deliberate improvement: a malformed persisted base ref now returnsunknownrather thanabsent, so the "base branch may be stale" warning is preserved instead of silently suppressed.Validation
pnpm tc:node,pnpm tc:cli,pnpm tc:webpassed.Note on the original report
The reported 48 GB
sort -uwas an Orca/Codex diagnostic pipeline that enumerated every ref and rangit ls-tree -ronce per ref. Replacing the ref × tree shape removes the unbounded duplicate stream. No worktrees were deleted.AGENTS.mdgains a "Git Scan Safety" section so that pipeline shape is not reintroduced.No remote-wire gate is needed:
show-refwas already in the relay allowlist (src/relay/git-exec-validator.ts), and Git 2.25 support for exactshow-ref --verify --quiet --is covered by the real-binary compatibility test.Review fix
Review caught a regression in the first revision: re-exporting
listWorktreesSharedStrict as listWorktreesStrictsilently flipped seven production call sites from an isolated subprocess to the coalesced scan, none of which opted in. That matters becausegit worktree pruneinlocal-worktree-removal-recovery.tsruns raw and never bumps the scan generation, so the post-prune verification atlocal-worktree-removal-recovery.ts:61could join a pre-prune in-flight scan, still see the row, and surface "Git still reports the worktree registration after cleanup" for a removal that actually succeeded. The same gap defeated the post-archive-hook rechecks (remove-registered-local-worktree.ts:65,orca-runtime.ts:29740) that exist specifically to catch an external Git client locking the row — an external client never bumps the generation either.worktree-removal.ts:15had guarded exactly this hazard with an unshared import and a comment; the alias bypassed it.Fixed by restoring the unshared export and keeping coalescing opt-in through
listWorktreesSharedStrict(whichcreated-worktree-reconciliation.tsalready uses deliberately). Added a regression test that was mutation-verified: it fails with the alias restored, passes without it.Second review round
Four independent reviewers ran over the diff. Four real defects surfaced; all are fixed in
5dcc8ec, each with a mutation-verified regression test (the test was confirmed to fail with the fix reverted).baseRefExistsOnRemotereturned a false "exists." The replacedrefs/remotes/*/<base>cannot cross a slash, butshow-ref -- <base>matches a suffix at any depth. Reproduced on real Git 2.44: withrefs/remotes/origin/feature/mainpresent and noorigin/main,for-each-ref 'refs/remotes/*/main'is empty whileshow-ref -- mainmatches — so a review would be submitted against a base the provider rejects. Fixed by requiring the remote component to be exactly one segment.A WSL transport failure read as proven ref absence.
isShowRefNoMatchErroraccepted any numeric exit 1, butwsl.exeexits 1 for its own launch failures (dead distro, terminated instance). The replacedfor-each-refexited 0 on no-match, so any rejection was correctlyunknown. Worse, inbaseRefExistsOnRemoteevery probe and the suffix fallback read as no-match, so it returnedfalse— positively asserting absence from a transport failure, where the pre-PR code hitcatch { return true }. This is theunverifiable→exitedcollapsessh-execution-boundary.mdforbids. Fixed with an empty-stderr discriminator: a genuine miss under--quietprints nothing (verified: exit 1, 0 bytes), while a wrapper failure always explains itself. A runner that reports no stderr at all (the SSH provider) keeps its existing exit-code contract.A spawn regression on Windows/WSL, in a perf change.
show-refis inALWAYS_READ_SUBCOMMANDS, and the runner retried any numeric exit through the user's interactive login shell. The oldfor-each-refexited 0 on absence so never retried;show-ref --verify --quietexits 1, so every absent probe would have spawned a second login shell running the distro's rc files — on the branch-conflict check that runs on every worktree create. The same empty-stderr signal identifies this as Git control flow and skips the fallback.The real-binary compatibility contract had gone stale. It pinned
--exclude=refs/remotes/**/HEADwhile production emits*/HEADplus per-remote exact excludes. The*-does-not-cross-/claim is the entire correctness argument for theHEAD-exclusion change and nothing in CI exercised it. The test now asserts both that the symbolic slots are excluded and that a nested<remote>/feature/HEADbranch survives.Also: the concurrency tests asserted only
maxActive <= 8, so settingEXACT_REF_PROBE_CONCURRENCY = 1passed everything — the perf win could vanish silently. They now assert the pool actually saturates (mutation-verified: 4 tests fail at concurrency 1).