Skip to content

perf(git): bound ref and worktree scans - #17655

Merged
nwparker merged 4 commits into
stablyai:mainfrom
nwparker:nwparker/slow-worktree-create-dizzy-eyes
Aug 31, 2026
Merged

nwparker merged 4 commits into
stablyai:mainfrom
nwparker:nwparker/slow-worktree-create-dizzy-eyes

Conversation

@nwparker

@nwparker nwparker commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Replace broad remote-ref enumeration in branch-conflict, hosted-review eligibility, and PR-context paths with exact bounded git show-ref --verify probes.
  • Coalesce generation-fenced worktree graph/lenient/strict scans and cap probe concurrency.
  • Keep a bounded stale-ref fallback, preserve valid nested branch names and remote punctuation, and prevent option-leading remote names from becoming fetch arguments.
  • Carry the same behavior through local, WSL, SSH, Windows, folder-workspace, relay, and Git 2.25-compatible paths.

ELI5

Orca used to answer small yes/no questions by reading the repository's entire phone book.

To find out "does the branch main already exist on a remote?", it ran git 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 runs git 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 used run.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:

  • Bounded memory. No path retains a full refs/remotes listing 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").
  • Correct scan sharing in packaged builds. The run.name cache 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. listWorktreeGraph now shares scans too, which removes duplicate git worktree list processes (expensive on Windows).
  • Legitimate branches named .../HEAD are no longer hidden. The old exclude was --exclude=refs/remotes/**/HEAD, where ** crosses / — so a real branch origin/feature/HEAD was filtered out of branch search along with the symbolic origin/HEAD slot. Now only the direct <remote>/HEAD slot is excluded, and the display name is de-DWIM'd so origin/feature/HEAD no longer renders as origin/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 truncated gets looser.
searchBaseRefs / searchBaseRefDetails previously passed the caller's limit straight to --count. It is now clamped by REPO_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.ts sets truncated: limit > effectiveLimit || refDetails.length > effectiveLimit, so a request for 5,000 in a repo with 3 refs reports truncated: true. A consumer reading truncated as "more data exists" will be misled.

2. Branches literally named <something>/HEAD now appear in the picker.
The old --exclude=refs/remotes/**/HEAD plus a /^refs\/remotes\/.+\/HEAD$/ post-filter hid a real branch origin/feature/HEAD; isRemoteHeadRef now excludes only the direct <remote>/HEAD symbolic slot. Their display name is also corrected — Git's refname:short DWIM was rendering origin/feature/HEAD as origin/feature. This is a fix, but it does change what the picker lists.

3. The PR-context suffix fallback is skipped when origin/upstream is configured.
shouldSearchSuffixRemoteRefs (pull-request-remote-ref-probes.ts:157-172) skips the bounded show-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 on state.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. baseRefExistsOnRemote runs 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.ts and filesystem.ts previously spread ...options into gitExecFileAsync, so a timeoutMs key was passed as an unrecognized option and silently ignored; the SSH path dropped options entirely. Both now normalize timeoutMs/timeout → timeout and forward maxBuffer. No live behavior change today — every probe site passes only maxBuffer (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 sets timeoutMs, 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, never absent: baseRefExistsOnRemote returns true (preserves the candidate rather than blocking PR creation) and PR context sets probeUnknown and 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 in isShowRefNoMatchError: only a numeric code === 1 counts as absent, so a relay that reports a string "1" will always land in unknown and 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 = 8 bounds subprocess fan-out. The trade-off is shape, not just speed: one for-each-ref is replaced by one show-ref --verify per 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. probeAnyExactRef stops scheduling on the first hit.

7. Worktree scan sharing widens only where it is safe.
listWorktreeGraph now routes through the shared in-flight cache instead of always spawning its own git worktree list. listWorktreesStrict deliberately does not — it stays unshared, and coalescing is opt-in via listWorktreesSharedStrict. Sharing cannot serve stale data: entries are deleted on settle (no TTL), and notifyPreparedWorktreeMutation fences the key so a post-mutation caller cannot join a pre-mutation scan. Strict/lenient/graph never share with each other, and AbortSignal callers 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 returns unknown rather than absent, so the "base branch may be stale" warning is preserved instead of silently suppressed.

Validation

  • Changed-area suite: 1,577 passed, 11 skipped.
  • Focused exact-ref/remote/worktree suites: 74 tests plus independent 155-test review suite passed.
  • pnpm tc:node, pnpm tc:cli, pnpm tc:web passed.
  • Changed-code quality, React Doctor, reliability gates, and formatting passed.
  • Benchmark: 56 exact probes at concurrency 8 took about 392 ms; prior broad scans took about 6–38 s on the affected repository.

Note on the original report

The reported 48 GB sort -u was an Orca/Codex diagnostic pipeline that enumerated every ref and ran git ls-tree -r once per ref. Replacing the ref × tree shape removes the unbounded duplicate stream. No worktrees were deleted. AGENTS.md gains a "Git Scan Safety" section so that pipeline shape is not reintroduced.

No remote-wire gate is needed: show-ref was already in the relay allowlist (src/relay/git-exec-validator.ts), and Git 2.25 support for exact show-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 listWorktreesStrict silently flipped seven production call sites from an isolated subprocess to the coalesced scan, none of which opted in. That matters because git worktree prune in local-worktree-removal-recovery.ts runs raw and never bumps the scan generation, so the post-prune verification at local-worktree-removal-recovery.ts:61 could 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:15 had 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 (which created-worktree-reconciliation.ts already 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).

  1. baseRefExistsOnRemote returned a false "exists." The replaced refs/remotes/*/<base> cannot cross a slash, but show-ref -- <base> matches a suffix at any depth. Reproduced on real Git 2.44: with refs/remotes/origin/feature/main present and no origin/main, for-each-ref 'refs/remotes/*/main' is empty while show-ref -- main matches — so a review would be submitted against a base the provider rejects. Fixed by requiring the remote component to be exactly one segment.

  2. A WSL transport failure read as proven ref absence. isShowRefNoMatchError accepted any numeric exit 1, but wsl.exe exits 1 for its own launch failures (dead distro, terminated instance). The replaced for-each-ref exited 0 on no-match, so any rejection was correctly unknown. Worse, in baseRefExistsOnRemote every probe and the suffix fallback read as no-match, so it returned false — positively asserting absence from a transport failure, where the pre-PR code hit catch { return true }. This is the unverifiable→exited collapse ssh-execution-boundary.md forbids. Fixed with an empty-stderr discriminator: a genuine miss under --quiet prints 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.

  3. A spawn regression on Windows/WSL, in a perf change. show-ref is in ALWAYS_READ_SUBCOMMANDS, and the runner retried any numeric exit through the user's interactive login shell. The old for-each-ref exited 0 on absence so never retried; show-ref --verify --quiet exits 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.

  4. The real-binary compatibility contract had gone stale. It pinned --exclude=refs/remotes/**/HEAD while production emits */HEAD plus per-remote exact excludes. The *-does-not-cross-/ claim is the entire correctness argument for the HEAD-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/HEAD branch survives.

Also: the concurrency tests asserted only maxActive <= 8, so setting EXACT_REF_PROBE_CONCURRENCY = 1 passed everything — the perf win could vanish silently. They now assert the pool actually saturates (mutation-verified: 4 tests fail at concurrency 1).

@greptile-apps

greptile-apps Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR replaces broad remote-ref enumeration with bounded exact probes and introduces generation-aware sharing for compatible worktree scans.

  • Caps repository ref-search results and subprocess concurrency.
  • Preserves nested branch names and validates ref and remote inputs before invoking Git.
  • Keeps strict post-mutation worktree verification unshared while allowing explicitly compatible scans to coalesce.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

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
Loading

Reviews (4): Last reviewed commit: "fix(git): separate a proven absent ref f..." | Re-trigger Greptile

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • 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 with show-ref --verify lookups.
  • Bounded search excludes — repo-base-ref-search.ts swaps --exclude=refs/remotes/**/HEAD for --exclude=refs/remotes/*/HEAD plus exact slash-remote excludes, and parseAndFilterSearchRefDetails preserves nested feature/HEAD branch names via isRemoteHeadRef.
  • Worktree probes/caching — worktree-base-ref-probe.ts moves to an exact show-ref --verify probe; worktree-scan-cache.ts keys the in-flight map by an explicit kind (bundler-safe) and shares listWorktreeGraph.
  • Adapter plumbing — filesystem.ts, worktree-remote.ts, and runtime-git-generation-commands.ts thread maxBuffer/timeoutMs/timeout through the local and SSH exec adapters.
  • Docs — AGENTS.md gains 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.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Shared ref-search limit constants — new src/shared/repo-search-limits.ts defines REPO_SEARCH_REFS_DEFAULT_LIMIT (25), REPO_SEARCH_REFS_MAX_LIMIT (1000), and REPO_SEARCH_REFS_MAX_SCAN_LIMIT (1001), with is… guards plus clamp… / getRepoSearchRefsProbeLimit helpers.
  • Bounded for-each-ref --count — buildSearchBaseRefsArgv clamps the scan limit before computing the candidate count, so an oversized request stops at --count=4004 instead 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 [] / throw invalid_limit for malformed ones), reporting oversized runtime requests as truncated.
  • Truncation sentinel preserved — getRepoSearchRefsProbeLimit keeps the +1 probe row (capped at MAX_SCAN_LIMIT) so the runtime truncated flag still fires without overflowing at MAX_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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Restored unshared listWorktreesStrict — removed the listWorktreesSharedStrict as listWorktreesStrict re-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 listWorktreesStrict calls 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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — the 5dcc8ec commit separates a proven-absent ref from a failed probe and narrows the hosted-review suffix fallback:

  • Empty-stderr absence discriminator — isShowRefNoMatchError now requires empty (or missing) stderr alongside a numeric exit 1, so a wsl.exe launch failure reads as unknown instead of a proven miss, while a genuine show-ref --verify --quiet miss (exit 1, 0 bytes on stderr) still resolves as absent.
  • WSL retry suppression — new isQuietGitControlFlowExit skips the interactive-login-shell fallback for quiet exit-1 control flow, removing the per-absent-probe spawn regression on the always-read show-ref path.
  • Single-segment suffix match — parseSuffixRemoteRefs requires the remote component to be exactly one segment, so a nested origin/feature/main no longer answers a bare main base 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`)?

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

@nwparker
nwparker merged commit 8ac1c6e into stablyai:main Aug 31, 2026
33 checks passed
nwparker added a commit to nwparker/orca that referenced this pull request Sep 1, 2026
…-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.
nwparker added a commit that referenced this pull request Sep 2, 2026
…d it (#18050)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Mirror-Of: a7db6c3
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…d it (stablyai#18050)

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

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

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

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

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

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

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

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

Not in this change:
- The badge listing itself. It still probes, still annotates, and still keys on
  the distro exactly as stablyai#17932 left it.
- The remaining `listRepoWorktrees` callers. They read `isSparse`, or feed rows
  to something that does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant