Skip to content

perf(worktree): prepare checkouts while the composer is open - #17290

Merged
nwparker merged 20 commits into
mainfrom
nwparker/faster-worktree-create-2-arrow-double-up
Aug 30, 2026
Merged

nwparker merged 20 commits into
mainfrom
nwparker/faster-worktree-create-2-arrow-double-up

Conversation

@nwparker

@nwparker nwparker commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​605 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​605
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​779 $\color{#cf222e}{\Huge{\mathbf{−}}}$​63 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​716

Summary

  • prepare a hidden detached checkout after the existing composer base prefetch, moving the expensive materialization off the submit path
  • claim only an exact repository, base, runtime, and workspace-root match; retarget the checkout if the selected base advanced, then move it and attach the final branch
  • hide and lock preparations, expire them after five minutes, cap them at three, and clean up preparations left by dead Orca processes
  • fall back to ordinary worktree creation for sparse checkouts, existing branches, changed inputs, unsupported moves such as submodule worktrees, or any preparation/finalization failure
  • add a reproducible cross-platform benchmark and real-Git lifecycle coverage

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):

Host Tracked files Ordinary submit Prepared submit Reduction
Local macOS, Git 2.44 20,019 6908.8 ms 413.1 ms 94%
openclaw, Linux, Git 2.43 20,012 1026.0 ms 327.5 ms 68%
awin, Windows, Git 2.55 16,622 8315.3 ms 747.7 ms 91%

Preparation 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:

node tests/tools/benchmarks/worktree-create-speculation-bench.mjs --repo /path/to/repo --iterations 5

Compatibility and safety

  • git worktree add --no-checkout plus reset --hard materializes files without firing post-checkout hooks before submit; final branch attachment fires the normal checkout hook from the final path
  • native, WSL, and paired-runtime work remain owned by their existing execution host and routing
  • direct SSH remains fetch-prefetch-only; this does not add a relay mutation RPC
  • there is no remote wire change, and mixed client/server versions retain ordinary creation as the fallback
  • folder workspaces are unaffected
  • the exact prepare/move/finalize command sequence is covered by the Git 2.25 compatibility contract
  • creation-base metadata, local-base refresh suggestions, and push.autoSetupRemote behavior are preserved

Verification

  • pnpm tc
  • focused worktree, WSL-routing, SSH-prefetch, listing-cache, real-Git, and compatibility tests: 53 passed, 11 environment-gated tests skipped locally
  • pnpm run check:code-quality:changed: zero findings
  • git diff --check
  • Electron/CDP validation: preparation remained absent from the sidebar/store, nested workspace movement used the prepared fast path, and the final branch rendered normally

@nwparker

Copy link
Copy Markdown
Contributor Author

Readiness follow-up (2026-08-30):

  • stale-preparation cleanup now uses graph-only listing and a bounded four-worker pool
  • finalization/cleanup Git commands have bounded timeouts and Windows long-path arguments
  • on a 954-worktree repo, strict listing measured ~10.7 s cold vs graph-only ~311 ms
  • audit found no proven P0/P1/P2 findings; local, WSL, paired-runtime, direct-SSH fallback, folder-workspace, Git 2.25, and mobile-facing wire surfaces were reviewed
  • checks: pnpm tc; 53 focused tests (11 environment-gated skips); 159 broader worktree tests; changed-code quality; git diff --check

@nwparker
nwparker force-pushed the nwparker/faster-worktree-create-2-arrow-double-up branch from 7468047 to e3b25ba Compare August 30, 2026 07:58
@nwparker

Copy link
Copy Markdown
Contributor Author

Rebased onto origin/main (85de42cdce7) and force-updated this draft PR to e3b25ba499c.

Readiness / race hardening:

  • Preparation is still local-only and opt-in from the existing prefetch hook; folder workspaces, sparse creates, existing-branch creates, SSH/relay mutation paths, and mismatched bases use the ordinary path.
  • Cleanup is cancellation-independent and bounded; stale discovery uses graph-only listing and four cleanup workers.
  • Finalization now carries the preparation lock reason through move, re-locks the final path until checkout + metadata/config complete, and unlocks only after the protected section succeeds.
  • A stale branch-attached moved checkout is unlocked/preserved on restart rather than deleted; detached/hidden stale preparations remain removable.
  • Windows test fixtures normalize CRLF and path separators.

Validation:

  • macOS (Git 2.44): focused preparation/create/list suites 56 passed, 11 environment-gated skipped; 25-cycle move/re-lock stress passed.
  • Ubuntu/openclaw (Git 2.43, Node 24): focused suites 53 passed, 11 skipped; 25-cycle stress passed.
  • awin/Windows (Git 2.55): registry suite 5/5 and 25 lifecycle cycles passed, including retarget, lock/move, metadata, and push configuration. Native pnpm postinstall remains blocked by the host's pre-existing MSBuild/node-pty toolchain issue, so direct Vitest was used there.
  • Local pnpm tc, changed-code quality, formatting, diff-check, and 127 focused tests pass.
  • Tiny-repo benchmark (macOS, 5 iterations): ordinary full add median 21.0 ms; speculative preparation 20.4 ms and submit 30.5 ms. The empty-repo result is intentionally not presented as a speedup claim; the expected win is that checkout/reset work overlaps the open dialog and the submit path stays independent of repository materialization cost.

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

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.

@nwparker
nwparker force-pushed the nwparker/faster-worktree-create-2-arrow-double-up branch from 3e8ba27 to e70824f Compare August 30, 2026 08:27
@nwparker

Copy link
Copy Markdown
Contributor Author

Readiness check (final, 2026-08-30; tested SHA e70824fc1b3)

  • Required PR checks are green: typecheck, static analysis, all 8 Node 24 test shards, Git compatibility, Linux/Windows packaging, and verify.
  • Cross-platform lifecycle stress passed on macOS (Git 2.44), Ubuntu/openclaw (Git 2.43), and Windows/awin (Git 2.55): 25 prepare → retarget → lock-preserving move → checkout → unlock/remove cycles per host.
  • Windows confirmed git worktree move -f -f preserves the preparation lock reason. Native awin postinstall remains blocked only by the host's pre-existing MSBuild/node-pty toolchain issue; focused Vitest and compatibility tests pass.
  • Race hardening: preparation locks stay held through finalization; -f -f removes the unlock→move crash window; cleanup is cancellation-independent, timeout-bounded, and preserves branch-attached final paths after a crash.
  • No proven P0/P1/P2 findings in the readiness audit. No mobile/remote wire changes; SSH remains prefetch-only; folder/sparse/existing-branch paths retain ordinary creation fallback.
  • Benchmark evidence is in the PR description: submit-time Git materialization reduction was 94% macOS, 68% Ubuntu, and 91% Windows on the representative repo.

The PR remains draft intentionally. It is ready for maintainer review/merge once the normal product owner approval is given.

@nwparker
nwparker marked this pull request as ready for review August 30, 2026 08:41
@nwparker

Copy link
Copy Markdown
Contributor Author

Correction: #17290 is now marked Ready for review (not draft) after the final verify gate passed. No merge was performed.

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

Next included review available in 36 minutes.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dc370575-c887-4daa-b070-97821a70910e

📥 Commits

Reviewing files that changed from the base of the PR and between a1fbae8 and a29d2b2.

📒 Files selected for processing (2)
  • src/main/git/worktree-scan-cache.ts
  • tests/tools/benchmarks/worktree-create-speculation-bench.mjs

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 98c9238d-34b1-4869-8d8e-52813b22c348

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7edc8 and a1fbae8.

📒 Files selected for processing (9)
  • src/main/git/worktree-add.ts
  • src/main/git/worktree-create-preparation-real-git.test.ts
  • src/main/host-tree-removal.ts
  • src/main/local-worktree-filesystem.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/worktree-create-preparation.test.ts
  • src/main/worktree-create-preparation.ts
  • src/shared/worktree/create-preparation.test.ts
  • src/shared/worktree/create-preparation.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/local-worktree-filesystem.test.ts
  • src/main/git/worktree-add.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

This 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 a1fba

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: preparing worktree checkouts while the composer is open to improve submit performance.
Description check ✅ Passed 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…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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 #13704 without providing the required issue link format.

Full details: Docstring Coverage

Explanation

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 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This 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.

  • Prefetches detached worktree preparations for matching local repository, base, runtime, and workspace-root inputs.
  • Finalizes matching preparations while retaining ordinary creation as the fallback.
  • Hides active preparations, limits and expires them, and cleans up preparations attributed to dead processes.
  • Adds real-Git, routing, cache, compatibility, and benchmark coverage.

Confidence Score: 4/5

The 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

Important Files Changed

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]
Loading

Reviews (7): Last reviewed commit: "test: mirror locked preparation finaliza..." | Re-trigger Greptile

Comment on lines +18 to +20
return options.includeCreatePreparations
? worktrees
: worktrees.filter((worktree) => !isWorktreeCreatePreparation(worktree))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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:

@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.

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 --hard worktree 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 ordinary addWorktree.
  • 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 includeCreatePreparations option hides preparation worktrees from listWorktreeGraph/listWorktrees/listWorktreesStrict, and the shared-scan cache key now includes it.
  • Refactor — resolveWorktreeAddBaseContext, persistWorktreeCreationBase, and configurePushAutoSetupRemote were extracted from worktree-add.ts so 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/git/worktree-scan-cache.ts Outdated

/**
* `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

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.

JSDoc drift: this says listWorktreeGraph but listWorktreesSharedStrict wraps listWorktreesStrict (see the shareWorktreeScan(..., listWorktreesStrict) call below). Revert the word to listWorktreesStrict.

Comment thread src/main/worktree-create-preparation.ts Resolved

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/main/git/worktree-add.ts (1)

95-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Carry 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:

  • --get instead of --local --get, so a value at any scope counts as an explicit user choice and is not overwritten.
  • git config --get exits 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 win

Reuse the shared gitExecOptions instead of redeclaring it.

This local helper is identical to the exported gitExecOptions in src/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 gitExecOptions from ./worktree and import it here. Keep gitCleanupOptions local, because it adds the signal-stripping behavior.


212-225: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add an explicit lock-preservation assertion. Git 2.25 supports worktree move -f -f for locked worktrees and preserves the lock reason. The compatibility test should assert the locked entry 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 the worktree move call.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6cf461c8-4bbd-4544-8053-c066145ffa08

📥 Commits

Reviewing files that changed from the base of the PR and between d9cb020 and f8f154d.

📒 Files selected for processing (19)
  • src/main/git/worktree-add.ts
  • src/main/git/worktree-create-preparation-real-git.test.ts
  • src/main/git/worktree-create-preparation.ts
  • src/main/git/worktree-listing.ts
  • src/main/git/worktree-operation-options.ts
  • src/main/git/worktree-scan-cache.ts
  • src/main/git/worktree.ts
  • src/main/host-tree-removal.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees/create/register-worktree-prefetch-handler.ts
  • src/main/local-worktree-filesystem.test.ts
  • src/main/local-worktree-filesystem.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/worktree-create-base-prefetch.ts
  • src/main/worktree-create-preparation.test.ts
  • src/main/worktree-create-preparation.ts
  • src/shared/git-binary-compatibility.test.ts
  • src/shared/worktree/create-preparation.ts
  • tests/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.

@nwparker

Copy link
Copy Markdown
Contributor Author

Follow-up hardening (f8f154d)

  • Native Windows preparation-root and final-parent mkdir calls now use the Win32 \\?\\ namespace, matching the existing core.longpaths=true Git argv handling.
  • POSIX paths used by WSL remain unchanged even when the Electron process runs on Windows; coverage now exercises both cases.
  • This cannot override a disabled Windows long-path policy or an MSYS/host configuration that rejects deep paths. On awin, the normal lifecycle passes, while an artificial >260-character path still reports Filename too long, which is host policy rather than an Orca cleanup/move race.

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 [email protected] lockfile entry; jobs do not reach compile/test steps.

@nwparker

Copy link
Copy Markdown
Contributor Author

Additional race/data-loss hardening (5c38897d286): stale preparation classification now refuses to treat any branch-attached worktree as a path-only preparation. A user-owned worktree under a directory named .orca-preparing/<pid>-... remains visible and cannot be force-removed by cleanup; only detached path markers or Orca's explicit lock prefix are eligible. Added unit coverage for explicit locks, detached markers, and branch-attached user paths.

Focused classifier/preparation/real-Git suites: 13 passed; direct typecheck, oxlint, formatting, and diff checks pass.

@nwparker

Copy link
Copy Markdown
Contributor Author

One more classifier tightening (7b7edc80b26): unlocked path-only leftovers now require the generated <pid>-... segment, in addition to being detached. An arbitrary detached or branch-attached directory named .orca-preparing is neither hidden nor eligible for cleanup. This keeps pre-lock crash recovery while removing the broad directory-name collision case.

Regression/preparation/real-Git tests: 14 passed; direct typecheck, oxlint, formatting, and diff checks pass.

@nwparker

Copy link
Copy Markdown
Contributor Author

Final ownership hardening (1242b4508fb): path-only preparation detection is removed. The durable Git lock reason is now the sole authority for hiding and stale cleanup. This prevents Orca from force-removing any user-owned worktree—branch-attached or detached—whose path happens to resemble .orca-preparing/<pid>-.... The explicit trade-off is that a crash before the lock command can leave an unlocked detached worktree visible for manual cleanup; it is never auto-deleted from ambiguous path evidence.

Classifier/preparation/real-Git tests remain green (14 focused tests), with direct typecheck, oxlint, formatting, and diff checks passing.

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8f154d and 7b7edc8.

📒 Files selected for processing (3)
  • src/main/worktree-create-preparation.test.ts
  • src/shared/worktree/create-preparation.test.ts
  • src/shared/worktree/create-preparation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +31 to +35
// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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

@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.

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 toHostFilesystemPath and wrapped the two preparation mkdir calls so native Windows paths use the \\?\ namespace, and routed toHostRemovalPath through 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/host-tree-removal.ts Outdated
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)

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.

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

Readiness update (2026-08-30, head 3474d5ff336):

  • Paired-runtime speculative preparation now remains best-effort; preparation failures cannot reject worktree.prefetchCreateBase.
  • Windows test fixtures now distinguish native drive paths from POSIX/WSL paths.
  • Fresh CI run 33306176061 is fully green, including Greptile, typecheck, static analysis, Linux/Windows packaging, all 8 Node 24 shards, compatibility, changed E2E specs, and verify.
  • Focused real-Git + compatibility validation passed on macOS/Git 2.44, Ubuntu/openclaw/Git 2.43, and Windows/awin/Git 2.55.
  • The >260-character Windows probe still fails when host long-path policy is disabled; that is a Windows/Git policy limitation, not an Orca lifecycle failure. Native filesystem namespace handling is in place when policy permits.

No merge performed.

@pullfrog

pullfrog Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment on lines +139 to +140
} else if (pathOwnerPid === lockOwnerPid) {
await discardPreparedWorktree(repoPath, worktree.path, options).catch(() => {})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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

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