Repository navigation
perf(worktree): prepare checkouts while the composer is open - #17290
Conversation
|
Readiness follow-up (2026-08-30):
|
7468047 to
e3b25ba
Compare
|
Rebased onto Readiness / race hardening:
Validation:
Residual risk is the small external-actor window between unlocking the preparation and moving it; Git does not provide a portable lock-preserving move primitive across the Git 2.25 baseline. Any finalization failure is cleaned and falls back to ordinary creation. |
|
Follow-up hardening on : stale branch-attached recovery unlocks now use the same cancellation-independent 30s cleanup timeout as discard. Focused prep/real-Git tests remain 8/8 green; typecheck remains green. |
|
Follow-up hardening in commit 0f0c631: stale branch-attached recovery unlocks now use the same cancellation-independent 30s cleanup timeout as discard. Focused preparation and real-Git tests remain 8/8 green; typecheck remains green. |
|
Additional race reduction in commit fd09e29: Git 2.25+ supports worktree move -f -f, which moves the locked preparation while preserving its lock reason. Finalization now uses this lock-preserving move, removing the unlock-to-move crash window; cleanup still unlocks/removes or preserves branch-attached stale paths as appropriate. Focused tests, typecheck, and changed-code quality are green. |
|
Correction to the earlier readiness note: after fd09e29/3e8ba2799f7, the residual unlock-to-move window no longer applies. The finalization path uses lock-preserving move -f -f (verified against Git 2.25 compatibility and real Git 2.43/2.44/2.55). Remaining risk is limited to normal external destination/path conflicts, which still fall back to ordinary creation. |
3e8ba27 to
e70824f
Compare
|
Readiness check (final, 2026-08-30; tested SHA
The PR remains draft intentionally. It is ready for maintainer review/merge once the normal product owner approval is given. |
|
Correction: #17290 is now marked Ready for review (not draft) after the final verify gate passed. No merge was performed. |
|
Warning Review limit reachedNext included review available in 36 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThis change adds a prepared worktree creation flow. It introduces preparation-state helpers, Git APIs to prepare, discard, unlock, and finalize prepared worktrees, and a cache with TTL, deduplication, limits, and stale cleanup. Worktree base prefetch now returns the resolved base branch and can trigger preparation. Normal worktree creation paths can consume a prepared worktree before they fall back to the existing add flow. Worktree listing now hides preparation worktrees by default. The change also adds Windows host-path handling, tests, real-Git coverage, and a benchmark script. Merge Risk: 🟡 Moderate · up to This change moves worktree materialization earlier to speed submission, but an interruption during finalization can leave a hidden, locked detached checkout that is not automatically recovered, affecting local repository availability. Merge also carries bounded follow-up risk because the benchmark does not match the production finalization sequence and lock preservation depends on Git behavior across versions. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and covers the implementation, rationale, measured impact, compatibility, safety, and verification. It does not follow the repository template fully: it lacks explicit ELI5, What Changed, Why, Linked Issue, Visual Proof, Review, Notes, and completed Checklist sections, and it references Full details: Docstring CoverageExplanation Docstring coverage is 7.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 53 functions across 19 files. (1 skipped: 1 too large.) ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThis PR moves worktree checkout materialization into a hidden speculative preparation performed while the composer is open, then claims, retargets, moves, and attaches that checkout during submission. It also adds preparation expiry and stale-process cleanup, scan filtering and invalidation, runtime-aware routing, Windows long-path handling, and lifecycle/compatibility coverage.
Confidence Score: 4/5The PR is not safe to merge until stale cleanup can prove preparation ownership without relying solely on caller-controlled path and lock metadata. A legitimate detached worktree with matching UUID-shaped path and preparation-prefixed lock metadata still reaches forced removal, so the previously reported destructive-cleanup defect remains reachable despite the narrower classifier. Files Needing Attention: src/shared/worktree/create-preparation.ts, src/main/worktree-create-preparation.ts, src/main/git/worktree-create-preparation.ts
|
| Filename | Overview |
|---|---|
| src/shared/worktree/create-preparation.ts | Defines preparation identity parsing, but still treats user-controlled lock metadata as ownership and combines it with a forgeable UUID-shaped path during cleanup. |
| src/main/worktree-create-preparation.ts | Implements preparation lifecycle and claiming; stale cleanup can forcibly remove a legitimate detached worktree whose caller-selected path and lock reason contain matching dead PIDs. |
| src/main/git/worktree-create-preparation.ts | Implements low-level prepare, move, finalize, and forced-discard Git operations; its destructive primitive is reached by insufficient ownership proof upstream. |
| src/main/git/worktree-listing.ts | Filters preparation rows from ordinary scans while allowing explicit internal inclusion; path-only worktrees are no longer hidden. |
| src/main/runtime/orca-runtime.ts | Integrates speculative preparation and consumption into runtime-managed creation while retaining sparse, existing-branch, and ordinary-add fallbacks. |
| src/main/ipc/worktree-remote.ts | Integrates prepared checkout consumption into local worktree creation with fallback to existing creation paths. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[Composer base prefetch] --> B[Create detached no-checkout worktree]
B --> C[Materialize and lock preparation]
C --> D{Submit inputs match?}
D -->|No| E[Ordinary worktree creation]
D -->|Yes| F[Retarget prepared HEAD]
F --> G[Move to final path]
G --> H[Attach final branch and metadata]
H --> I[Unlock and publish worktree]
C --> J{Expired or owner process dead?}
J -->|Yes| K[Stale cleanup]
Reviews (7): Last reviewed commit: "test: mirror locked preparation finaliza..." | Re-trigger Greptile
| return options.includeCreatePreparations | ||
| ? worktrees | ||
| : worktrees.filter((worktree) => !isWorktreeCreatePreparation(worktree)) |
There was a problem hiding this comment.
Path filter hides real worktrees
When a legitimate worktree resides beneath a user-created .orca-preparing directory, this filter removes it from ordinary listings based on its path alone. A parent-worktree removal then operates on an incomplete graph and can bypass the nested-worktree guard, causing git worktree remove --force to delete the child checkout's files while leaving its registration prunable.
Knowledge Base Used:
There was a problem hiding this comment.
Important
The paired-runtime prefetch path now awaits a fallible hidden checkout without the best-effort guard its IPC twin has — see the inline comment on orca-runtime.ts. Everything else looks solid; the fallback design, WSL/SSH scoping, and real-Git + compatibility coverage are well done.
Reviewed changes
- Speculative checkout preparation — after the composer-open base prefetch, a hidden, locked
--detach --no-checkout+reset --hardworktree is materialized under.orca-preparing; submit claims it by exact repo/base/runtime/workspace-root match, retargets an advanced base, moves it lock-preservingly (worktree move -f -f), attaches the branch, and unlocks. Any mismatch or failure falls back to ordinaryaddWorktree. - Preparation registry — in-memory dedupe with a 5-minute TTL, a cap of three, and stale-cleanup that unlocks branch-attached final paths but discards detached/hidden leftovers left by dead Orca processes.
- Listing filtering — a new
includeCreatePreparationsoption hides preparation worktrees fromlistWorktreeGraph/listWorktrees/listWorktreesStrict, and the shared-scan cache key now includes it. - Refactor —
resolveWorktreeAddBaseContext,persistWorktreeCreationBase, andconfigurePushAutoSetupRemotewere extracted fromworktree-add.tsso finalization can reuse the identical base-resolution and config side effects. - Verification — a reproducible cross-platform benchmark plus real-Git lifecycle tests and a Git 2.25 compatibility test covering the prepare/move/finalize command sequence.
ℹ️ Crash between move and unlock can temporarily hide a real worktree
finalizePreparedWorktree moves the still-locked preparation to the final path and only unlocks it after the branch is attached. If the process dies in that window, the final-path worktree is left locked with the orca-create-preparation:v1: reason, and isWorktreeCreatePreparation keeps it filtered out of every listing until the next prepare for that repo runs stale cleanup (which correctly unlocks rather than discards it). That is a small, self-healing window, but worth being aware of: a user-facing worktree can be invisible until the composer is reopened for that repo.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
|
||
| /** | ||
| * `listWorktreesStrict` through the same in-flight map, so callers that must see a Git failure | ||
| * `listWorktreeGraph` through the same in-flight map, so callers that must see a Git failure |
There was a problem hiding this comment.
JSDoc drift: this says listWorktreeGraph but listWorktreesSharedStrict wraps listWorktreesStrict (see the shareWorktreeScan(..., listWorktreesStrict) call below). Revert the word to listWorktreesStrict.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/main/git/worktree-add.ts (1)
95-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCarry the deleted Git-semantics rationale into the extracted function.
The logic moved unchanged, but two "Why" comments were dropped in the move. They explained two non-obvious choices that a future reader is likely to change here:
--getinstead of--local --get, so a value at any scope counts as an explicit user choice and is not overwritten.git config --getexits 1 only when the key is unset at every scope, so any other exit code is a real read failure and must rethrow instead of overwriting the user value.Restore both comments at the new call sites.
♻️ Proposed comment restoration
export async function configurePushAutoSetupRemote( worktreePath: string, options: GitWorktreeExecOptions ): Promise<void> { try { + // Why: `--get` (not `--local --get`) so a value at any scope counts as "user already chose" and isn't overwritten. let alreadySet = false try { await gitExecFileAsync(['config', '--get', 'push.autoSetupRemote'], { ...gitExecOptions(worktreePath, options) }) alreadySet = true } catch (readError) { + // Why: `git config --get` exits 1 only when unset at every scope; any other code is a real read failure — rethrow rather than overwrite the user's value. const code = (readError as { code?: unknown })?.code if (code !== 1) { throw readError } }Also applies to: 100-101
src/main/git/worktree-create-preparation.ts (2)
16-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the shared
gitExecOptionsinstead of redeclaring it.This local helper is identical to the exported
gitExecOptionsinsrc/main/git/worktree-operation-options.ts(Lines 80-90). Both build the same{ cwd, wslDistro?, signal?, timeout? }pass-through shape.Two copies must stay in sync. If a later change adds a field that the Git runner must receive, one copy will be updated and the other missed. Export
gitExecOptionsfrom./worktreeand import it here. KeepgitCleanupOptionslocal, because it adds the signal-stripping behavior.
212-225: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd an explicit lock-preservation assertion. Git 2.25 supports
worktree move -f -ffor locked worktrees and preserves the lock reason. The compatibility test should assert thelockedentry and reason after the move, before unlocking; its current checkout/unlock sequence would also pass if the lock were dropped. Move the explanatory comment directly above theworktree movecall.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6cf461c8-4bbd-4544-8053-c066145ffa08
📒 Files selected for processing (19)
src/main/git/worktree-add.tssrc/main/git/worktree-create-preparation-real-git.test.tssrc/main/git/worktree-create-preparation.tssrc/main/git/worktree-listing.tssrc/main/git/worktree-operation-options.tssrc/main/git/worktree-scan-cache.tssrc/main/git/worktree.tssrc/main/host-tree-removal.tssrc/main/ipc/worktree-remote.tssrc/main/ipc/worktrees/create/register-worktree-prefetch-handler.tssrc/main/local-worktree-filesystem.test.tssrc/main/local-worktree-filesystem.tssrc/main/runtime/orca-runtime.tssrc/main/worktree-create-base-prefetch.tssrc/main/worktree-create-preparation.test.tssrc/main/worktree-create-preparation.tssrc/shared/git-binary-compatibility.test.tssrc/shared/worktree/create-preparation.tstests/tools/benchmarks/worktree-create-speculation-bench.mjs
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
Follow-up hardening (f8f154d)
Focused verification after the hardening: 43 tests passed across preparation, filesystem, Git long-path, sparse-add, and real-Git suites. The latest GitHub run is blocked during dependency installation by the repository minimum-release-age policy for the unrelated |
|
Additional race/data-loss hardening ( Focused classifier/preparation/real-Git suites: 13 passed; direct typecheck, oxlint, formatting, and diff checks pass. |
|
One more classifier tightening ( Regression/preparation/real-Git tests: 14 passed; direct typecheck, oxlint, formatting, and diff checks pass. |
|
Final ownership hardening ( Classifier/preparation/real-Git tests remain green (14 focused tests), with direct typecheck, oxlint, formatting, and diff checks passing. |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 13d587c7-7562-4836-bc6d-0326a4962636
📒 Files selected for processing (3)
src/main/worktree-create-preparation.test.tssrc/shared/worktree/create-preparation.test.tssrc/shared/worktree/create-preparation.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| // The Git lock reason is the durable ownership proof. A path can be chosen | ||
| // by a user (including for an uncommitted detached worktree), so path shape | ||
| // alone must never hide or force-remove it. A crash before locking may leave | ||
| // an unlocked detached entry for manual cleanup, but cannot delete user data. | ||
| return worktree.lockReason?.startsWith(WORKTREE_CREATE_PREPARATION_LOCK_PREFIX) ?? false |
There was a problem hiding this comment.
Lock prefix authorizes destructive cleanup
When a legitimate detached worktree is locked with a reason beginning orca-create-preparation:v1:<dead-pid>:, isWorktreeCreatePreparation treats that caller-controlled Git metadata as Orca ownership. The next composer prefetch classifies the checkout as stale, unlocks it, and runs git worktree remove --force, deleting its uncommitted files.
Knowledge Base Used: Workspace and worktree lifecycle
There was a problem hiding this comment.
Important
The new toHostFilesystemPath namespacing also rewrites WSL UNC workspace roots (see the inline comment on host-tree-removal.ts), while the established windowsLongPathGitArgs deliberately opts those out of long-path treatment — please verify on a WSL host or exclude WSL UNC paths.
Reviewed changes
- Windows preparation path namespacing — added
toHostFilesystemPathand wrapped the two preparationmkdircalls so native Windows paths use the\\?\namespace, and routedtoHostRemovalPaththrough it so POSIX WSL paths are no longer rewritten. - Test coverage — added cases for native-Windows namespacing, POSIX WSL passthrough, and a platform-aware workspace-root mock.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| export function toHostFilesystemPath(targetPath: string): string { | ||
| // POSIX paths are used by WSL callers even while the Electron process runs | ||
| // on Windows; do not reinterpret those as drive-relative Win32 paths. | ||
| return process.platform === 'win32' && isWindowsAbsolutePathLike(targetPath) |
There was a problem hiding this comment.
WSL UNC paths also satisfy isWindowsAbsolutePathLike (they start with \\), so this rewrites \\wsl.localhost\Distro\...\.orca-preparing into \\?\UNC\wsl.localhost\... before fs.mkdir. windowsLongPathGitArgs deliberately opts out of long-path treatment for WSL UNC paths (parseWslUncPath(cwd) returns []), so preparation mkdir is now inconsistent with it. Verify \\?\UNC\wsl.localhost\... resolves through the 9P provider on a WSL host, or exclude isWslUncPath(targetPath) here.
Technical details
# Exclude WSL UNC paths from host-filesystem namespacing
## Affected sites
- src/main/host-tree-removal.ts:19 — `toHostFilesystemPath` guard accepts WSL UNC paths
- src/main/worktree-create-preparation.ts:199,252 — preparation and final-parent `mkdir` calls route through it
## Required outcome
- `\\wsl.localhost\...` / `\\wsl$\...` paths must stay in their original UNC form (or be proven safe to namespace on a WSL host); otherwise WSL preparation `mkdir` may fail and silently disable the optimization for WSL repos.
## Suggested approach (optional)
- Mirror `windowsLongPathGitArgs`: skip namespacing when `parseWslUncPath(targetPath)` matches.|
Readiness update (2026-08-30, head
No merge performed. |
|
Run failed. View the logs →
|
| } else if (pathOwnerPid === lockOwnerPid) { | ||
| await discardPreparedWorktree(repoPath, worktree.path, options).catch(() => {}) |
There was a problem hiding this comment.
Spoofed ownership deletes worktree
When a legitimate detached worktree uses .orca-preparing/<dead-pid>-<UUID> and a lock reason beginning orca-create-preparation:v1:<same-dead-pid>:, stale cleanup treats those two user-controlled values as ownership proof and runs git worktree remove --force, deleting the checkout and any uncommitted files.
Knowledge Base Used: Workspace and worktree lifecycle
Squashed merge of PR stablyai#17290.

Summary
This explores the speculative-creation idea raised as a follow-up to #13704.
Measured impact
Five-iteration medians using the production-equivalent sequence (
--no-checkout, materialize, lock, target-head probes, unlock, move, and branch attach):openclaw, Linux, Git 2.43awin, Windows, Git 2.55Preparation medians were 6695.1 ms on macOS, 1011.6 ms on Linux, and 8172.7 ms on Windows. Retargeting an already-prepared checkout to another commit took 263.5 ms, 646.4 ms, and 631.6 ms respectively.
The rendered Electron flow completed in 7.0 seconds in the benchmark repository because that checkout currently discovers roughly 430 worktrees and post-create reconciliation dominates. This change measurably removes the Git materialization cost from submit; pathological listing/reconciliation remains separate work.
Run the benchmark with:
Compatibility and safety
git worktree add --no-checkoutplusreset --hardmaterializes files without firing post-checkout hooks before submit; final branch attachment fires the normal checkout hook from the final pathpush.autoSetupRemotebehavior are preservedVerification
pnpm tcpnpm run check:code-quality:changed: zero findingsgit diff --check