Introducing a new way to review your PRs.

Read the announcement

stablyai / orca

Orca lets you run a fleet of bots with your own subscription (e.g. Claude Code, Grok, Agy, Codex). Available on desktop, mobile and remote runtime.

View on GitHub

34 documents · Updated Nov 20, 2026

docs / git-operations-and-status

Git operations and status

The Git operation layer gives source-control features one consistent way to inspect and change a repository on the local machine or on a remote host. It reports worktree state, shows safe comparisons, applies guarded changes, synchronizes branches, manages linked worktrees, and keeps local and relay execution aligned across native, WSL, and SSH runtimes. For the wider source-control model, see Source control and reviews. See also Source control AI workflows.

System boundary

The Git layer sits between source-control surfaces and the repository. Callers use runtime-aware clients and shared operation contracts instead of choosing a process, host, or transport themselves.

Runtime routing

The runtime Git client chooses where Git runs from the active runtime and worktree context. Local work reaches the main-process runner through the preload boundary. A remote runtime uses runtime RPC. An SSH-backed worktree sends the same provider operation to a relay on the host that owns the worktree. Diff reads also use the explicit worktree owner, so a twin does not inherit the focused runtime by accident.

This routing keeps the meaning of an operation stable. A status read or branch diff has the same product purpose whether Git runs in the desktop process, in WSL, or on an SSH host. On Windows, a local project follows its configured runtime unless the caller explicitly requires host Git. Read-only WSL work can use a direct Git process after a bounded environment probe. Network work and calls with custom Git environment policy use the shell route. Network Git also derives an SSH policy from explicit environment or a bounded Git-config probe, while keeping shell startup text out of the result. A stopped or missing WSL distro is handled before a child starts, and a host launch failure remains distinct from a Git failure.

This diagram shows how a source-control request reaches the repository that owns the worktree.

flowchart LR
    Caller[Source-control caller] --> Client[Runtime Git client]
    Client -->|local| Preload[Preload Git API]
    Client -->|remote runtime| RuntimeRPC[Runtime RPC]
    Preload --> LocalProvider[Local Git provider]
    RuntimeRPC --> RemoteProvider[Remote runtime provider]
    LocalProvider --> Runner[Platform-aware Git runner]
    RemoteProvider --> SshProvider[SSH Git provider]
    SshProvider --> Relay[Git relay]
    Runner --> Git[Repository]
    Relay --> Git

References: src/…/runtime-git-client.ts• L66-82 src/…/runtime-git-client.ts• L124-177 src/…/runtime-git-client-context.ts• L60-88 src/…/diff-runtime-owner.ts• L4-15 src/…/ssh-git-provider.ts• L89-122 src/…/local-git-runtime-route.ts• L1-52 src/…/wsl-command-resolution.ts• L87-120 src/…/git-ssh-policy-env.ts• L19-77

Operation contract

The shared provider contract is the capability boundary for local and SSH execution. It covers repository reads, worktree changes, branch and remote sync, comparisons, and worktree management. Common result types let the renderer use one source-control model for both execution modes.

The relay exposes the same boundary as named git.* requests. The relay groups requests by product action rather than exposing unrestricted remote process access. Shared status, worktree, conflict, and push-target rules keep local and relay results aligned.

References: src/…/git-provider-contract.ts• L21-105 src/…/git-handler-operation-set.ts• L1-34 src/…/git-handler-registration.ts• L10-79 src/…/git-operation-api.ts• L8-125 src/…/git-porcelain-local-parity.test.ts• L1-7

IPC action routing

The main-process boundary registers Git status, commit, diff, index, remote, URL, and review-generation actions as separate groups. Shared handler context gives requests sender-scoped cancellation, so a closed renderer does not leave an unowned Git operation running.

The boundary selects Git options for the worktree that owns a path. This keeps WSL worktrees and their .git metadata on the correct runtime. Remote paths use the SSH provider instead of local filesystem access.

References: src/…/filesystem.ts• L1-48 src/…/filesystem-conflict-operation-routing.test.ts• L56-84 src/…/filesystem-pull-request-field-generation.test.ts• L180-227

Repository inspection

Inspection turns repository state into structured data for source-control views. The layer reports the current worktree, committed history, branch relationships, conflicts, and file content without making a partial or unavailable read look complete.

Status model

Git status is exposed as entries grouped by staging area: staged, unstaged, or untracked. An entry can describe a file change, rename or copy, conflict kind, submodule state, and line counts. The result also carries branch and commit data, upstream state, conflict-operation state, optional ignored paths, branch line totals, and an explicit partial-result marker.

Status uses an incremental stream. A row limit can stop the scan after enough changes, and the result then reports that it is partial. Line statistics run only when needed. Branch line totals require a complete status scan and a verified base. A failed read returns a bounded error instead of looking like a clean tree. Cancellation remains cancellation rather than an empty result.

Status reads share one in-flight lease for identical worktree and option sets. Mutations invalidate the lease and related caches, so a read started before a stage, discard, commit, fetch, or worktree change cannot become the current result after that change. A missing configured upstream is distinct from a real synchronized upstream. A same-name remote probe can supply useful effective-upstream state without changing Git configuration. Ambiguous upstream names are resolved against known remotes so a local branch name does not make the status view follow the wrong remote branch.

Shared-link filtering is narrow. The status path removes a row only when the exact configured path is a symlink. An unreadable probe keeps the row visible. Submodules remain separate worktrees: the parent reports a moved submodule pointer, while an explicit expansion reads the submodule's own state or committed range.

References: src/…/status.ts• L1-47 src/…/status-read.ts• L40-67 src/…/status-read.ts• L114-289 src/…/effective-upstream-status-probe.ts• L31-153 src/…/status-upstream-ambiguous-ref-real-git.test.ts• L18-50 src/…/submodule-restore-recurse.ts• L7-37 src/…/git-status-types.ts• L1-105 src/…/git-path-decoration.ts• L15-124

Diff views

Diff operations compare the file states selected by the caller. A staged diff compares HEAD with the index. An unstaged diff compares the index with the working tree, or compares HEAD with the working tree when that view is requested. Rename diffs keep the old path for the left side. Submodule paths use the submodule repository and can show either a pointer change or an inner commit-range change.

The result distinguishes text, binary content, large content, and a proven deletion. A failed read does not become an empty-file deletion. Large content returns a safe marker rather than a large payload. Diff reads coalesce while they are in flight and reuse settled data only when a fresh stamp proves that the relevant repository inputs did not change.

References: src/…/file-diff.ts• L31-81 src/…/file-diff.ts• L87-215 src/…/git-blob-read.ts• L16-31 src/…/git-diff-compare-types.ts• L6-75 src/…/submodule-gitlink-oid.ts• L6-57

Branch and ref comparison

Branch comparison measures the current branch against an explicit base. It resolves both commit IDs and their merge base before loading changed files, then reports changed-file count and ahead or behind counts. Commit comparison measures one commit against its first parent. A root commit uses an empty tree as its base. Each comparison keeps summary state separate from file entries so callers can explain why Git cannot prove a comparison.

Branch and remote-ref helpers use exact ref checks. They reject unsafe names, detect case-folded local aliases, handle remote names that contain slashes, and keep an undecided probe separate from proof that a ref is absent. Base-ref search is bounded and removes direct remote HEAD aliases without hiding nested branch names. Local slash-named branches are qualified as local refs even when no remote is configured. Search filtering removes unsupported or duplicate candidates before applying the page limit, so valid later candidates are not displaced by malformed names.

The search accepts plain text and slash-separated tokens. It uses a bounded candidate scan and a compatible Git form when an older Git does not support ref exclusions. A ref snapshot can serve several searches while preserving a generation boundary, so a result from before a ref change does not replace newer data.

Older clients can receive Git-short selectors, while newer clients can use fully qualified refs. This compatibility layer preserves the identity of a local branch when its name also exists as a tag or remote ref. A ref snapshot also fences old results when a mutation fails or when a repository is replaced at the same path.

References: src/…/branch-compare.ts• L17-121 src/…/branch-diff.ts• L9-67 src/…/commit-compare.ts• L9-63 src/…/commit-diff.ts• L9-69 src/…/repo-ref-search-command.ts• L18-147 src/…/repo-legacy-ref-search.ts• L19-167 src/…/branch-ref-snapshot-data.ts• L7-146 src/…/branch-ref-snapshot-store.test.ts• L77-110 src/…/legacy-ref-selectors.ts• L1-71 src/…/repo-branch-conflict.ts• L151-247 src/…/branch-ref-snapshot-real-git.test.ts• L84-205 src/…/exact-ref-probe.performance.test.ts• L65-89 src/…/ref-search-tokens.ts• L1-3

Repository identity and refs

Repository helpers answer whether a path is a Git repository, find its root, identify a linked worktree's main repository, count or list remotes, resolve a default base, and measure remote drift. Git remains the main authority. A failed probe stays indeterminate instead of becoming proof that a repository is absent.

Repositories that share linked worktrees use common Git metadata as their shared identity. Worktree operations still keep the execution host and path context so the same path-like value on two hosts cannot route a destructive action to the wrong checkout. Local branch listing and checkout use exact branch refs, so a tag with the same name does not change which branch is selected.

Remote name and URL probes are bounded and coalesced. A config-signed local listing can prove that a remote is absent. A failed, unsigned, remote-host, or timed-out probe cannot. The layer can use a stand-in remote when origin is absent, but it does not guess a provider from an unreadable remote state. Fork fetch can remove only refspecs that Git proves are stale.

Remote file and commit links use a validated hosted remote target. GitHub, GitLab, and Bitbucket links encode the repository, branch, file path, line range, or commit; unsupported hosts produce no guessed URL. Before a branch rename, the operation probes the effective upstream. This includes a configured target and a usable same-name remote target, so a probe failure stays retryable instead of being treated as proof that the branch has no upstream.

Remote probes are coalesced, but a stale probe can be replaced without its cleanup removing the newer probe. This prevents old remote identity or branch data from becoming the current answer after the repository changes.

References: src/…/repo-detection.ts• L14-59 src/…/repo-detection.ts• L92-152 src/…/repo.ts• L47-107 src/…/remote-name-listing.ts• L71-177 src/…/remote-url-probe.ts• L24-83 src/…/origin-stand-in-remote.ts• L6-40 src/…/remote-git-probe-timeout.ts• L1-2 src/…/repo-branch-conflict.ts• L31-49 src/…/coalesced-probe.test.ts• L18-52 src/…/remote-url-probe.performance.test.ts• L84-141 src/…/current-branch-identity-real-git.test.ts• L20-67 src/…/fork-remote-stale-branch-refspec.test.ts• L14-79 src/…/git-effective-upstream.ts• L112-238

Line attribution

Blame reads explain which committed change owns each line of a file. The result combines the committed file text with commit metadata and line ranges, so a caller can map unsaved editor content against the committed baseline without treating working-tree edits as committed history.

The read is anchored to the file's own repository and current commit. Shallow state forms part of the baseline identity because unshallowing can change attribution. Results can be reused for the same commit and file, while unavailable, untracked, binary, and too-large cases remain explicit states.

References: src/…/git-blame-read.ts• L24-60 src/…/git-blame-read.ts• L63-169 src/…/git-blame-incremental-parser.ts• L7-54 src/…/git-blame-types.ts• L1-25 src/…/git-blame-result-cache.ts• L1-41

Repository changes

Mutation operations change files, the index, refs, or remote history through named actions. They validate the target worktree, serialize shared Git state where needed, and clear related reads before and after the operation. This makes later status and diff results reflect the new repository state.

Staging, conflict resolution, and discard

Staging moves selected paths into the index. Unstaging removes them from the index without removing working-tree content. Discard restores tracked paths from HEAD and removes selected untracked paths through Git's path-aware cleanup. Conflict resolution re-reads the exact live conflict before it stages a file or records a deletion, so a stale source-control row cannot overwrite another client's resolution.

The layer supports worktree-wide staging when a capped status list cannot name every change. The all scope stages tracked and untracked changes. The tracked scope stages tracked changes only. Scoped actions stay inside a nested folder workspace, leave unresolved conflicts unstaged, and exclude shared worktree links only after a positive symlink check. Scoped path lists preserve literal names and use stdin when the list is large. A worktree-wide action returns a receipt so an older or incomplete host cannot report success for a narrower action.

References: src/…/staging.ts• L26-191 src/…/discard-changes.ts• L17-135 src/…/git-pathspec.ts• L18-91 src/…/git-tracked-pathspecs.test.ts• L1-13 src/…/git-stage-worktree-scope.ts• L3-95

Commit and conflict recovery

Commit actions return a product result that preserves hook, signing, and nothing-to-commit messages. Completing a merge first proves that a merge is active, then lets Git use its prepared merge message while removing conflict comments. Merge, rebase, and cherry-pick state remains visible to status consumers, and abort actions return the worktree toward its prior state.

References: src/…/commit-changes.ts• L7-55 src/…/git-conflict-operation.ts• L10-64 src/…/git-status-conflict-entries.ts• L8-103

Branch synchronization

Fetch, pull, fast-forward, rebase, and push connect local branch state to a remote target. Push uses an explicit target when one is supplied. Otherwise it uses the branch's effective configured target and falls back to origin with HEAD for first publication. Force push uses lease protection rather than unconditional replacement.

Pull respects the user's configured strategy. If no strategy is configured and Git reports divergent branches, the layer retries once as a merge. Fast-forward refuses divergence. A base rebase fetches into a temporary private ref, rebases from that ref, and removes it even when the operation fails. A standalone fetch can retry a narrowly identified remote-ref compare-and-swap race. Remote errors are normalized before they reach the caller, and credentials are removed from surfaced messages.

Fetch and pull pause background ref maintenance while shared metadata is in use. On Windows, cancellation can settle the caller before the writer ends, but the operation lane remains held until the child is actually terminated.

References: src/…/remote.ts• L28-176 src/…/remote-rebase.ts• L15-105 src/…/git-fetch-ref-race.ts• L48-95 src/…/local-repo-ref-maintenance.ts• L79-106 src/…/remote.test.ts• L55-103 src/…/current-branch-identity-real-git.test.ts• L42-67 src/…/git-remote-error.ts• L1-240

Branch switching

Branch switching converts a requested local, remote, or new branch target into a guarded checkout. The operation checks live worktree status and any agent blocker before it changes HEAD, then records the branch and landed commit only after the target is known.

Remote targets resolve explicitly, including remote names and branch names that contain slashes. An existing local tracker can be reused without creating a duplicate branch, while a new branch starts from the current HEAD without inheriting an exact remote's tracking configuration by accident. Dirty changes can move to a new branch but block switching to an existing branch. A refusal leaves no branch or tracking configuration behind.

Checkout errors are checked against the repository after Git returns. If checkout landed but a hook or later step reports an error, the result preserves the landed branch and head as a warning rather than claiming that the switch did not happen. Live branch and worktree occupancy are read during target resolution, so stale discovery data does not authorize a conflicting switch.

References: src/…/branch-switch.ts• L1-245 src/…/branch-switch-target.ts• L23-161 src/…/checkout.ts• L6-58 src/…/branch-switch-target-real-git.test.ts• L66-242

Worktree operations

Worktree operations manage checkouts that share one repository. Listing reports paths, branches, heads, main or bare state, sparse state, lock state, and prunable state. Older Git forms can be used when the preferred porcelain form is unavailable, and missing linked paths are checked before they are marked prunable.

Creation can start a new branch from a base or check out an existing branch. A same-name remote base may become the new branch's upstream; a different new branch does not inherit upstream state by accident. Creation records base lineage and can report a local-base refresh, an update suggestion, an upstream warning, and checkout progress. A path or branch held by pending background removal is refused before Git runs. Config writes retry lock contention without replacing an explicit user setting.

Sparse setup rolls back a partial checkout when it cannot finish. Preparation creates a detached, locked worktree, materializes the selected base, and later moves it into the target before creating the final branch and tracking state. The preparation owner checks its lock before each stage and preserves a replacement if ownership is lost. Cleanup can restore a missing .git link only when the linked admin directory is verified.

Removal rechecks authority before deletion. It blocks dirty or locked checkouts and names populated submodules because force removal can destroy commits held only inside a submodule. Normal branch cleanup deletes a branch only when Git can prove its commits are safe to remove. Otherwise the checkout is removed and the branch is returned as preserved state. Host-qualified worktree identity ensures a destructive action uses the confirmed row's host rather than the active workspace host.

Worktree paths use the path syntax that Git reports. Windows paths fold case, while POSIX and WSL filesystem tails stay case-sensitive, so distinct checkouts do not merge into one row. Worktree metadata has a direct read path for per-worktree Git files such as HEAD, index, and FETCH_HEAD. It uses this only when the .git link is valid and the requested file belongs to the per-worktree set. Common repository data stays with real Git, and stale links fall back to Git instead of being recreated. Worktree changes invalidate cached WSL route decisions because they can rewrite .git markers.

This diagram shows the safe relationship between worktree preparation, finalization, and cleanup.

flowchart LR
    Base[Resolve and check base] --> Prepare[Prepare locked checkout]
    Prepare --> Finalize[Finalize branch and worktree]
    Finalize --> Register[Publish metadata]
    Prepare -->|failure or expiry| Cleanup[Verify ownership and remove]
    Finalize -->|failure| Cleanup

References: src/…/worktree-scan-cache.ts• L16-93 src/…/worktree-path-comparison.ts• L7-141 src/…/worktree-list-porcelain.test.ts• L65-101 src/…/worktree-list-paths.test.ts• L84-110 src/…/worktree-add.ts• L191-329 src/…/worktree-add-pending-removal.test.ts• L59-83 src/…/worktree-config-write.ts• L1-15 src/…/worktree-sparse-add.ts• L16-85 src/…/worktree-preparation-discard.ts• L131-245 src/…/worktree-preparation-lock-real-git.test.ts• L68-204 src/…/worktree-preparation-gitlink.ts• L10-30 src/…/worktree-removal-real-git.test.ts• L73-204 src/…/worktree-remove-branch-deletion.test.ts• L49-66 src/…/worktree-git-path.ts• L12-76 src/…/git-metadata-path.ts• L18-65

Transport behavior

The same Git operation can run through a local process, WSL, runtime RPC, or an SSH relay. The runner and relay preserve operation meaning while controlling process load, output size, path form, cancellation, and compatibility.

Platform-aware execution

The runner selects native Git or WSL Git from the worktree path and runtime settings. It translates path arguments when crossing into WSL and keeps the caller's worktree context. Fixed command execution uses argument arrays rather than shell fragments. Buffered login-shell reads fence profile output so startup text does not become Git data. Streamed records avoid that fence because control markers could become part of the first record.

Read-only WSL operations can use a direct Git process after a bounded login-environment probe. Network reads, custom Git environment policy, and unsupported direct reads stay on the login-shell route. A direct read may retry through the shell only before it produces output. A partial stream is not silently replayed. Every WSL route checks the internal distro allowlist before spawn and records that the distro was launched. Drive-backed and linked worktrees settle their ownership, mount, and line-ending evidence before commands that depend on their path or file mode run.

Commands use stable English output for parsers, bounded output, deadlines, and non-interactive credential behavior. Cancellation and deadline cleanup cover the spawned command tree. WSL operations can install a guest process-group barrier so a timeout or abort does not leave descendants running. A stopped distro is not booted by background Git or by cleanup that could otherwise wake it only to kill a process.

Temporary Git writes can use a local object quarantine when the repository and WSL object-store namespaces can be mapped safely. If that mapping is uncertain, the operation stays unquarantined rather than writing to a guessed object store.

References: src/…/git-exec-file.ts• L40-203 src/…/git-runtime-options.ts• L3-36 src/…/git-ssh-policy-env.ts• L19-77 src/…/wsl-command-resolution.ts• L86-236 src/…/wsl-aware-spawn.ts• L10-51 src/…/wsl-path-translation.ts• L12-51 src/…/wsl-drive-checkout-git-routing.ts• L11-39 src/…/wsl-windows-checkout-git-probe.ts• L122-189 src/…/runner-wsl-direct-read.test.ts• L102-168 src/…/local-git-object-quarantine.ts• L20-93

Admission control

Git admission control limits concurrent child processes before they start. It separates general work from network work and applies route limits for a WSL distro or host route. Interactive, status, and background work use different scheduling priority.

The same admission grant covers buffered execution, spawned execution, and streamed status output. A request waits for repository-wide fetch serialization before it consumes a child-process grant. Its execution timeout starts after admission. Caller cancellation can still end a request that remains queued. A child keeps its slot until it really closes, even when a timeout or kill settles the caller first.

Mutation writers keep ownership independent of a canceled caller. This is important on Windows, where process creation and tree cleanup can finish after the request has returned. Read-only work may release capacity when its worker is lost. A writer keeps its mutation fence until the child or its process tree is proven to have ended.

References: src/…/git-exec-file.ts• L74-124 src/…/git-exec-admission-lifetime.test.ts• L86-203 src/…/git-owned-lifetime.test.ts• L39-159 src/…/git-writer-lifetime.ts• L1-24 src/…/git-subprocess-admission.ts• L1-24 src/…/git-admission-scheduler.ts• L38-239

Streaming output

Status output streams from Git to an incremental parser. The parser keeps incomplete records across chunks and can stop Git after the status limit. This keeps memory bounded while preserving the explicit partial-result signal. The stream decodes split UTF-8 characters and bounds both standard output and error output.

Large diff and generic-exec responses use an opt-in relay stream. The relay sends ordered chunks on a bulk lane. The client acknowledges chunks within a credit window, reassembles the payload, and cancels the stream when it stalls, exceeds protocol limits, or loses its consumer. Older relays return the normal single-frame result. Worktree creation uses the same stream discipline for checkout progress, and a failing progress observer does not fail the checkout.

Native streamed Git owns a POSIX process group when it can. Windows may start Git or its cleanup worker away from the main loop. A worker loss ends a read when no mutation fence depends on proof, but cleanup still ends the abandoned process tree when needed. Output overflow, parser failure, timeout, and abort all stop the child and retain the correct lifetime state.

References: src/…/git-stream-stdout.ts• L41-295 src/…/git-stream-child-spawn.ts• L13-60 src/…/exec-file-capture.ts• L46-315 src/…/exec-file-capture-to-termination.ts• L13-116 src/…/process-spec-worker-launch.ts• L19-90 src/…/spawned-command-tree-kill.ts• L37-239 src/…/worker-exec-file.ts• L44-164 src/…/exec-file-result-shape.ts• L1-17 src/…/worktree-checkout-progress.ts• L18-47 src/…/git-response-stream.ts• L108-221 src/…/ssh-git-response-stream-reader.ts• L7-120

Capability checks

Git features vary by installed version and execution host. The capability layer probes optional command forms and falls back to older forms when Git rejects a known option. Results are kept per native host, per WSL distro, or per SSH provider lifetime. A reconnect creates a new remote capability state, and a later retry can notice an in-place Git upgrade.

Worktree, ref, fetch, merge-tree, branch-cleanup, and default-base readers use these checks so an older Git version returns a usable result instead of a false empty state. Exact-ref batches keep missing refs as data while treating an incomplete or failed probe as unknown. Ref search also keeps its candidate scan bounded when an optional for-each-ref form is unavailable.

References: src/…/git-capability-cache.ts• L1-19 src/…/git-capability-state.ts• L15-75 src/…/repo-ref-search-command.ts• L107-147 src/…/worktree-graph-listing.test.ts• L35-65 src/…/legacy-ref-selectors.ts• L15-50 src/…/remote-rebase.ts• L64-80 src/…/exact-ref-probe.ts• L153-194

Forge command execution

GitHub and GitLab command helpers use the same runtime-aware process rules as Git. They route CLI calls through WSL when needed and qualify repository hosts so a self-hosted service is not sent to a different host.

Hosted CLI calls apply configured proxy settings and preserve a ported GitLab host through the WSL environment. They classify API traffic by rate-limit bucket and scope blocks by service host and execution runtime. A primary limit blocks only the affected bucket. A reset probe can refine the block. Local token reads and the rate-limit probe remain available while an API bucket is blocked.

When a selected hosted account is bound to a request, the runner checks the target host before it starts the child and injects the token only into that child. Missing host CLIs can fall back between the host and the default WSL distro. A batch records only proved native executable absence for peer calls in the same search scope; API failures, missing working directories, and WSL absence do not become global absence. Background fallback refuses a stopped or unverifiable distro, while a user action may start it. Transient retries are limited to idempotent calls, and a host or runtime fallback checks its rate-limit scope again before retrying.

References: src/…/gh-exec-file.ts• L40-304 src/…/gh-executable-absence-batch.ts• L14-123 src/…/gh-executable-absence-batch.test.ts• L7-25 src/…/runner-wsl-gh-fallback.test.ts• L132-259 src/…/glab-exec-file.ts• L18-115 src/…/glab-exec-file.test.ts• L19-44 src/…/gh-rate-limit-breaker.ts• L3-217

Safety and failure handling

Git commands can change files, refs, and remote history. The operation layers reduce that risk by separating narrow actions from general execution, validating inputs at the boundary, serializing shared Git state, and returning expected conditions as states that callers can act on.

Command boundaries

The relay's generic git.exec path allows read commands and a small set of exact setup shapes. It rejects repository-redirection flags and unsafe write forms. Destructive actions use named requests such as stage, discard, push, branch rename, and worktree removal, where the handler can apply the right checks.

Reference names, remote names, push targets, and file paths are checked before they reach Git. Literal path handling and worktree-boundary checks protect against option injection, traversal, and accidental operations on the worktree root. Bulk pathspecs are chunked for the actual transport command line, including WSL shell overhead.

References: src/…/git-exec-validator.ts• L13-229 src/…/git-handler-exec-operations.ts• L8-54 src/…/git-push-target-validation.ts• L13-53 src/…/git-pathspec.ts• L18-91 src/…/staging.ts• L119-189 src/…/discard-changes.ts• L23-58

Operation serialization

Some Git actions change shared metadata even when they start from one worktree. A keyed operation lock serializes those actions and lets a waiting caller abort without breaking the predecessor. Fetch and pull protect shared fetch metadata. Worktree operations use a repository or worktree key so aliases for one checkout do not run concurrently.

This serialization works with cache invalidation rather than replacing it. The lock prevents conflicting writes from overlapping. Invalidation prevents reads that started before a write from being published afterward. Worktree scan generations add the same protection to catalog reads that overlap creation, removal, prune, or an external Git client. Background ref maintenance waits for WSL access when a repository lives in a stopped or unverifiable distro. A standalone fetch can retry only the narrow remote-ref race that is safe to replay.

References: src/…/git-operation-lock.ts• L1-68 src/…/git-fetch-head-lock.ts• L55-175 src/…/git-fetch-ref-race.ts• L48-95 src/…/git-worktree-operation-lock.ts• L1-14 src/…/git-read-cache-invalidation.ts• L12-39 src/…/worktree-scan-cache.ts• L16-93

Error contracts

Expected repository conditions become useful states. A missing upstream becomes hasUpstream: false. An unborn head, invalid base, or missing merge base becomes a comparison status. A status limit becomes an explicit partial result. A proven missing blob stays different from a read that timed out or failed.

Git process errors are read from explicit stderr and stdout fields before fallback text. Availability returns false only when the command is proven absent and the working directory exists. A missing working directory or a failed host probe remains an error or unknown result. Cancellation rejects as cancellation rather than resolving as an empty read.

Fetch, pull, push, upstream, and relay errors are normalized before they reach the renderer. A missing relay method produces a reconnect hint for features that need a newer relay. Temporary transport failures remain distinct from missing refs and authentication failures. Worktree removal preserves a branch when Git cannot prove that it is safe to delete, and prepared-checkout cleanup preserves a path when lock ownership or physical settlement is uncertain.

Process capture also preserves raw output when callers need bytes, rejects clipped structured output, and checks cancellation again after executable lookup. A deadline or abort settles the caller before a late child can start, while termination reporting keeps admission and mutation state until the child tree has closed. Windows tree cleanup does not kill an exited root whose process ID may already be reused.

References: src/…/exec-file-capture.ts• L87-315 src/…/exec-file-capture-to-termination.ts• L31-115 src/…/exec-file-capture-resolution.test.ts• L18-141 src/…/spawned-command-tree-kill.ts• L37-169 src/…/status-read.ts• L164-289 src/…/git-remote-error.ts• L1-240 src/…/removal.ts• L120-172

Change checklist

When these files or sections are changed, remember to consider these:

  • Update the shared provider contract, preload API, runtime routing, SSH provider, and relay registration together when an operation or result field changes.
  • Keep local and relay operation groups aligned when a change affects read invalidation, target resolution, locks, cancellation, or cleanup.
  • Keep status and worktree cache keys aligned with every option that changes result shape or execution context, including limits, ignored paths, line-stat reuse, upstream probes, WSL distro, and shared-link paths.
  • Preserve the difference between no upstream, zero ahead/behind values, and a real synchronized upstream. Keep unknown probe results separate from proof of absence.
  • Keep shared-link filtering and staging exclusion positive-only. A failed symlink probe must not hide or skip a user's file.
  • When changing scoped staging, keep the all and tracked scopes, nested-folder boundary, conflict exclusion, shared-link exclusion, literal path spelling, and scope receipt aligned across local and relay hosts.
  • When changing a stream, update its marker, chunk sequence, byte limits, ACK window, inactivity guard, cancellation, child lifetime, and old-relay fallback together.
  • When adding an optional Git form, update its unsupported detector, per-host capability cache, and fallback path together.
  • When changing fetch, pull, rebase, commit, or worktree operations, check the shared metadata lock, writer lifetime, and cache invalidation before and after the operation.
  • When changing repository or worktree identity, preserve execution-host scope, common-directory resolution, path-folding rules, per-worktree Git metadata handling, and destructive-removal host claims.
  • When changing branch or ref search, keep exact ref qualification, short-selector compatibility, case-folded collision checks, remote names with slashes, snapshot generations, bounded candidate scans, filtering, de-duplication, and page-limit ordering aligned.
  • When changing paths or refs, check native, WSL, linked-worktree, SSH, spaces, Unicode names, newline names, slash-containing remotes, and flag-like values separately.
  • Keep admission grants, process timeout, termination barriers, worker-loss handling, and cancellation behavior consistent between local and relay execution. A queued request must not spawn after its caller has canceled, and a settled request must not release its grant before the child closes.
  • When changing WSL routing, keep distro allowlisting, runtime selection, direct-read eligibility, network and custom-environment exclusions, shell fallback, output fencing, object-store variables, host diagnostics, stopped-distro gates, and partial-stream retry rules aligned.
  • When changing hosted CLI calls, keep host qualification, proxy and account scope, rate-limit buckets, runtime/host scopes, executable-absence batching, idempotent retry rules, child lifetime, and host/WSL fallback aligned.
  • When changing worktree preparation, keep lock ownership, preparation expiry, maintenance pauses, writer settlement, finalization transfer, cleanup retries, replacement protection, gitlink restoration, and cache or WSL-route invalidation aligned.
  • When changing worktree creation or cleanup, keep base-ref presence, remote tracking, ownership checks, progress completion, timeout bounds, listing recovery, path equality, Windows removal safety, branch preservation, submodule refusal, pending-removal checks, and relay parity aligned.
  • When changing branch rename or effective-upstream resolution, keep configured upstreams, same-name remote fallbacks, remote names with slashes, ambiguous local names, no-upstream detection, collision checks, and credential-safe probe errors aligned.
  • When changing guarded branch switching, preserve exact local-versus-remote target identity, live occupancy checks, dirty-worktree rules, new-branch tracking behavior, blocker checks, post-checkout landed-state reporting, and cleanup after refusal.
  • Keep native executable resolution and process spawning aligned. Pass the resolved executable through the shared process host so launch timing and subprocess diagnostics remain intact without a second lookup.

Important failure modes

TriggerConsequenceGuard
A repository emits more status rows than the configured limitThe view has only a prefix of the changesIncremental parsing stops Git and returns an explicit partial result
A status or diff read overlaps a repository mutationA stale result can appear currentMutation paths invalidate in-flight reads and settled result caches before and after the change
A status command fails because the index is unreadableThe view can falsely show a clean treeThe result carries a bounded readError, and recovery requires a later successful read
A failed blob or working-tree read looks like an empty fileThe view can report a false deletionOnly a proven missing path becomes a deletion; failed reads are not reusable
A local branch or tag makes Git print an ambiguous upstream nameStatus or sync can follow the wrong remote branchEffective-upstream resolution uses full refs and known remote names before accepting the target
A direct WSL read fails after producing outputRetrying can duplicate or corrupt the parsed streamDirect streams retry only when no stdout was delivered
A WSL request targets a distro outside the allowlistAn unapproved guest command could startResolution refuses the request before any child process starts
A WSL checkout needs path or line-ending context that was not settledGit can read or write the checkout with the wrong host assumptionsDrive and linked-worktree probes run before the dependent command and retain unknown state when probes fail
A hosted CLI receives a ported self-hosted GitLab host as a flagThe CLI can reject the call or target gitlab.comThe host moves to GITLAB_HOST and crosses WSL through the environment
A hosted CLI is absent in one peer checkoutA whole batch can be marked unavailable even when another checkout has a local binaryAbsence is shared only for a proven native search scope and an existing working directory
A command is canceled or expires while its executable is resolvingThe command can start after the caller no longer needs itCapture checks eligibility again at the spawn call and reports termination without launching
A command times out while descendants still runThe request releases capacity while the host remains loadedTermination barriers retain admission until child termination is observed
A worker dies while a Git writer still runsA later mutation can overlap the abandoned writerRead capacity may return, but mutation fences wait for tree termination proof
An optional Git form is rejected by an older Git versionThe feature fails or looks like an empty resultCapability checks select a compatible form and preserve the result meaning
A remote or branch probe cannot prove ref absenceA new branch or link can be based on a false availability claimUnknown probe results stay unknown and do not authorize destructive or naming decisions
A slash-named local branch is treated as a remote candidateA base search or switch can select the wrong refSelector logic qualifies exact local refs before remote interpretation and preserves full ref identity
A branch name differs only by case or Unicode normalizationTwo branches can collide on a ref filesystemConflict checks fold names and namespaces before creation
A worktree preparation lock is replaced or its path reappearsCleanup can delete a new checkout or user dataOwnership markers, linked-admin pointers, and physical path checks must agree before removal
A prepared checkout loses its .git link during cleanupGit refuses removal or cleanup touches the wrong metadataCleanup restores a link only from a verified admin directory and host namespace
A sparse checkout fails after a worktree is createdA partial checkout or new branch can remain behindRollback removes the worktree and only the newly created branch; cleanup failure is reported
A worktree path is compared with the wrong filesystem's case rulesTwo real checkouts can merge into one row or the wrong checkout can be removedPath syntax selects comparison rules; POSIX and WSL tails stay case-sensitive
A branch or path is held by pending background removalA new worktree can race with destructive cleanupCreation checks pending removal by both path and branch before running Git
A remote branch switch lands but a hook reports failureThe caller can claim that checkout failed although HEAD changedPost-checkout state is read and returned as a landed warning with the resolved branch and head
A dirty worktree is switched to an existing branchUncommitted work can be overwritten or mixed with another branchGuarded switching blocks existing targets while allowing a new branch to carry the changes
A remote URL is unsupported or contains an unsafe organization valueA source link or credential target can point to the wrong hostProvider ownership and host-specific input checks return no guessed link or reject the target

Key files

FileWhy to read it
src/…/runtime-git-client.tsShows the caller-facing route for local and remote Git work.
src/…/runtime-git-client-context.tsDefines worktree-owner routing context for runtime Git features.
src/…/git-provider-contract.tsDefines the shared operation and result boundary.
src/…/git-handler.tsCoordinates relay execution, invalidation, capabilities, and large responses.
src/…/status.tsKeeps the main-process source-control surface stable for status, diffs, staging, commit, conflict, and discard.
src/…/status-read.tsShows status assembly, limits, upstream context, line stats, submodules, and cancellation.
src/…/file-diff.tsShows selected diff inputs, rename handling, submodule routing, and safe read reuse.
src/…/git-diff-compare-types.tsDefines comparison summaries and the distinction between deletion, binary, and large content.
src/…/staging.tsShows selected, conflict, and worktree-wide staging actions.
src/…/discard-changes.tsShows worktree-bound discard and tracked/untracked cleanup.
src/…/remote.tsShows remote sync, effective push targets, locks, and error normalization.
src/…/remote-name-listing.tsShows bounded remote discovery and the difference between absent and unknown remotes.
src/…/remote-url-probe.tsShows shared remote reads and transient-probe handling.
src/…/repo-detection.tsShows authoritative repository detection and linked-worktree identity.
src/…/repo-ref-search-command.tsShows bounded exact ref search and older-Git fallback.
src/…/branch-ref-snapshot-data.tsShows branch/ref identity and search projection.
src/…/repo-branch-conflict.tsShows exact branch collision checks and unknown-result handling.
src/…/legacy-ref-selectors.tsShows compatibility between fully qualified and older short ref selectors.
src/…/branch-ref-snapshot-real-git.test.tsDemonstrates ref identity, linked checkout scope, and stale-result fencing.
src/…/worktree-scan-cache.tsShows worktree catalog reads, generations, and invalidation.
src/…/worktree-path-comparison.tsDefines cross-platform worktree path identity.
src/…/worktree-add.tsShows base resolution, lineage, tracking, progress, and creation cleanup.
src/…/worktree-preparation-operation.tsDefines preparation lifetime, writer settlement, maintenance pauses, and disposal.
src/…/worktree-preparation-discard.tsShows ownership-aware cleanup and path reconciliation.
src/…/worktree-preparation-lock-real-git.test.tsDemonstrates replacement-safe preparation ownership.
src/…/worktree-removal-real-git.test.tsDemonstrates branch preservation, submodule refusal, and stale-registration cleanup.
src/…/branch-switch-target.tsShows exact local, remote, and new-branch target resolution.
src/…/runner.tsDefines the stable entry point for Git, forge CLI, WSL, and stream execution.
src/…/git-exec-file.tsShows routing, admission, timeout, cache-safe child lifetime, and buffered execution.
src/…/git-stream-stdout.tsShows bounded streaming, early stop, UTF-8 handling, and retry rules.
src/…/exec-file-capture.tsShows executable selection, bounded capture, cancellation, and child termination.
src/…/spawned-command-tree-kill.tsShows safe process-tree cleanup and worker-loss handling.
src/…/wsl-command-resolution.tsDefines WSL path, distro, environment, shell, and direct-read routing.
src/…/git-ssh-policy-env.tsDefines network SSH policy discovery and shell-output fencing.
src/…/gh-exec-file.tsDefines GitHub CLI host, account, fallback, rate-limit, and retry behavior.
src/…/gh-executable-absence-batch.tsDefines safe sharing of proven executable absence.
src/…/git-response-stream.tsDefines relay-side large-response flow control.
src/…/git-operation-lock.tsDefines abortable serialization for shared Git state.
src/…/git-fetch-head-lock.tsDefines repository-wide fetch metadata locking.
src/…/git-fetch-ref-race.tsDefines the narrow safe retry for concurrent remote-ref updates.
src/…/git-capability-cache.tsDefines optional Git feature probing and retry timing.