Repository navigation
fix(worktree): complete a create Git can confirm but cannot list - #17388
Conversation
`worktree.create` verified against `listWorktrees`, which softens every git failure to `[]`. Any listing failure therefore failed a create whose worktree and branch `git worktree add` had already written, orphaning both, and reported only 'Worktree created but not found in listing' — the real cause reached the main-process console and never the user. Verify against the error-propagating listing instead, and when that fails or omits the row, rebuild the row by asking Git about the worktree itself. The direct read returns nothing unless Git resolves the path into this repo's object store with the expected branch checked out, so an unrelated or half-made checkout still fails the create. Fixes #16520
Greptile SummaryThe PR reconciles locally created worktrees through either a strict complete listing or a direct Git description when listing fails or omits the new row. It also introduces a separate recovered-root authorization layer so directly recovered worktrees survive cache rebuilding and conservative pruning.
Confidence Score: 4/5The PR is not yet safe to merge because a successfully recovered create remains unauthorized when its repository already has 64 live recovered roots. The new capacity handling preserves existing roots but silently refuses authorization for the next recovered worktree after Git has already created it, leaving filesystem and Git-status operations unable to use that workspace. Files Needing Attention: src/main/ipc/registered-worktree-roots-cache.ts, src/main/ipc/worktree-remote.ts
|
| Filename | Overview |
|---|---|
| src/main/git/worktree-listing.ts | Adds bounded direct reconstruction and repository-identity validation for a created worktree when listing cannot confirm it. |
| src/main/ipc/created-worktree-reconciliation.ts | Reconciles strict listing results with direct recovery while preserving listing completeness and useful errors. |
| src/main/ipc/registered-worktree-roots-cache.ts | Adds durable additive authorization and evidence-based pruning for recovered roots, but the fixed capacity still leaves the next recovered create unauthorized once 64 live entries accumulate. |
| src/main/ipc/worktree-remote.ts | Integrates complete-list registration and direct-recovery registration into the local worktree-create flow. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[git worktree add succeeds] --> B[Strict worktree listing]
B -->|Created row found| C[Use complete listing]
B -->|Fails or omits row| D[Describe created worktree directly]
D -->|Repo, branch, and HEAD confirmed| E[Use recovered row]
D -->|Confirmation fails| F[Surface listing or reconciliation error]
C --> G[Replace listed authorization roots]
E --> H[Add recovered authorization root]
H --> I[Future rebuild unions recovered roots]
Reviews (8): Last reviewed commit: "fix(worktree): retire a recovered root o..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
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 (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughAdds direct Git metadata recovery for newly created worktrees. Recovery validates branch, repository common directory, path, HEAD, and sparse-checkout state. Creation flows use shared reconciliation when Merge Risk: 🟡 Moderate · up to The change improves worktree creation recovery, but a recovered worktree can remain authorized after its repository is removed until a later cache rebuild, weakening the expected filesystem access-revocation boundary. Merge should wait for synchronous cleanup or explicit security-owner acceptance. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed, on-topic, and includes the linked issues, rationale, implementation details, testing, compatibility, and known gaps. Several template headings and checklist items are omitted, but the required technical information is mostly complete.
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e0b03951-5836-4f8b-9def-870ca3c63523
📒 Files selected for processing (14)
src/main/git/worktree-created-description-real-git.test.tssrc/main/git/worktree-list-reader.tssrc/main/git/worktree-listing.tssrc/main/git/worktree-sparse-state.tssrc/main/git/worktree.tssrc/main/ipc/created-worktree-reconciliation.test.tssrc/main/ipc/created-worktree-reconciliation.tssrc/main/ipc/worktree-remote.tssrc/main/ipc/worktrees-local-create-flow.test.tssrc/main/ipc/worktrees-test-harness.tssrc/main/ipc/worktrees-test-module-mocks.tssrc/main/ipc/worktrees-windows.test.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
There was a problem hiding this comment.
Important
The two new real-Git symlink tests call ln, which does not resolve on Windows execFile (no shell, and Git for Windows' usr/bin is not on the test PATH) — the Windows unit-test job will fail on them. See the inline comments for the two-line fix.
Reviewed changes
A focused fix for #16520: worktree-create verification no longer softens every listing failure to [], and instead re-lists strictly and rebuilds the created worktree's row directly from Git when the listing fails or omits it.
- Strict listing for create verification — both local create call sites now verify through
listWorktreesSharedStrict, which propagates errors instead of softening to[]while still coalescing with a concurrent refresh. describeCreatedWorktreedirect-read fallback — reconstructs the created row fromrev-parse --show-toplevel --git-common-dir,symbolic-ref --quiet HEAD, andrev-parse HEAD, gated on the worktree resolving into this repo's object store with the expected branch checked out.resolveCreatedWorktreereconciliation — one shared list-then-find-then-throw replacement at both call sites; it prefers the listing's own error, preserves thecreated but not found in listingclassifier substring, and reports whether the listing was authoritative.listingCompleteroot-set gate — worktree root registration only runs when the listing was complete, so a recovered create cannot revoke sibling worktrees' filesystem access.- Coverage — 9 real-Git-binary tests plus mocked-runner reconciliation and local-create-flow tests, including negative controls for the fallback, the
listingCompletegate, and canonicalization.
ℹ️ Nitpicks
- When
listWorktreesSharedStrictthrows butdescribeCreatedWorktreerecovers the row, the listing error is swallowed with no log (resolveCreatedWorktreedropslistingErroronce the fallback succeeds). For the exact failure mode this PR targets, aconsole.warnon the recovered path would keep the underlying cause observable instead of silently lost.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…HEAD Review follow-ups on the create-verification fallback: - register the recovered worktree's own root, additively, so the create the user just made is not rejected by filesystem/git-status IPC - treat an unreadable HEAD as no recovery instead of a blank OID - keep the direct read's failure when the listing merely omitted the row - skip the symlink cases on Windows and reset the new harness mock
|
Review follow-ups applied in 0557065. Recovered root remains unauthorized (P1) — real, and the more serious of the two behavioral findings: the gate skipped registration entirely, so the worktree the user had just successfully created was rejected by filesystem and Git-status IPC with Reject recovery when Git cannot read HEAD — real. Preserve the direct-read error after an incomplete listing — real. When the strict listing succeeded but omitted the row, the direct read's Git failure was the only diagnostic and was discarded. It is now appended to the Skip the symlink tests on Windows — correct; Reset Verified: |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The new commit hardens the recovered-create path and fixes the Windows break from the prior round.
- HEAD is now read up front —
describeCreatedWorktreereadsHEADin the same parallel batch and returnsundefinedwhen Git cannot resolve it, so an unborn-branch worktree is rejected instead of emitted with a blank OID. Covered by a new real-Git test that deletes the branch ref. - Windows break fixed — both
ln-based symlink tests are nowit.skipIf(process.platform === 'win32'), matchingworktree-separate-git-dir.test.ts. - Recovered create is authorized — new
registerCreatedWorktreeRootregisters only the newly created root (keeping siblings authorized and marking the cache dirty for a full rebuild), andworktree-remote.tscalls it on the recovered path. - Direct-read failure is surfaced —
resolveCreatedWorktreeappends the direct read's error only when the listing omitted the row, still preferring the listing's own error when it throws.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… case-sensitive Readiness-scan follow-ups: - deadline the filesystem common-dir read; a .git on a hung mount left the whole create IPC pending where it used to fail after the Git deadline - offer no disk candidate for a bare repo instead of a fabricated <repo>/.git - compare POSIX common dirs case-sensitively, so two WSL repos differing only in case are not accepted as one object store on a Windows desktop - move toGitOutputSpace to shared/wsl-paths as toWslExecutionSpace, next to the parseWslUncPath callers that already open-code it
|
Second review-fix pass, from the readiness scan ( Unbounded filesystem read on the recovery path. A fabricated POSIX common dirs were case-folded on a Windows host.
Also reported and deliberately not changed here:
Verification: |
…vered roots Three follow-ups from review of the create-recovery path: - The recovery no longer starts a fresh 30s deadline after the listing already burned one, so worst-case create verification stays at ~30s instead of ~60s. A 5s floor keeps the direct read a chance to answer when the listing spent the whole budget. - rebuildAuthorizedRootsCache now carries a repo's previously registered roots forward when its listing throws. A rebuild running while Git is still broken could otherwise un-authorize the worktree a create just recovered. - Corrected the scan-cache doc comment: it claimed strict and lenient listings coalesce, but the cache key includes the runner name precisely to keep them apart, so a strict joiner can never inherit a lenient scan's softened []. Each change has a negative control: reverting the hunk fails exactly its own test and nothing else.
Review-fix iteration 3 —
|
| # | Finding | Fix | Negative control |
|---|---|---|---|
| FC-04 | Create verification could spend two full 30 s budgets — one on the listing, then a fresh one on the direct read — doubling the wait before the user sees an error on a hung Git. | The recovery now gets the listing's remaining budget (WORKTREE_LIST_TIMEOUT_MS - elapsed), floored at 5 s so a listing that burned everything still leaves the direct read a chance to answer. A caller-supplied timeout still wins. |
Reverting to a fresh budget fails charges the recovery what the listing left of the budget, not a fresh one, nothing else. |
| — (residual risk) | rebuildAuthorizedRootsCache dropped a repo's roots when its listing threw. A rebuild running while Git is still broken would silently un-authorize the worktree a create had just recovered — the exact window this PR exists to cover. |
The catch branch now carries the repo's previously registered roots forward instead of returning an empty set for it. | Reverting the carry-forward fails keeps a repo's roots when its listing fails mid-rebuild, nothing else. |
| FC-03 | worktree-scan-cache.ts doc comment claimed the strict and lenient listings coalesce onto one in-flight scan, contradicting the cache key at :69, which includes the runner name precisely to keep them apart. |
Comment corrected to state the actual invariant: a strict joiner must never inherit a lenient scan's softened [], so the two scan separately by design. |
n/a (comment only) |
Both new tests were verified by reverting only their own hunk — each fails alone and takes nothing else with it.
Verification
$ pnpm tc clean
$ oxlint src/main/ipc src/main/git no findings
$ vitest run src/main/ipc/filesystem-auth.test.ts \
src/main/ipc/created-worktree-reconciliation.test.ts
Tests 35 passed (35)
$ vitest run src/main/git src/main/ipc
Tests 2 failed | 5449 passed | 15 skipped (5466)
The two failures are in repos-remote-client-events.test.ts, which passes in isolation (5 passed) and is untouched by this PR — a known load-dependent flake in this repo, seen in different files across repeat runs of the same sweep.
Deliberately not changed
The SSH/remote create site (worktree-remote.ts:1837-1844) still matches with branch?.endsWith(...) || path.endsWith(...) and the relay listing at git-handler-worktree-operations.ts:152 still softens failures to []. Both are pre-existing and outside this PR's local-create scope; they want their own change with their own remote-side tests rather than a drive-by here.
…ate-verification # Conflicts: # src/main/git/worktree-listing.ts
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 36756b62-8ee9-40cc-8ded-6ccfd2a1f370
📒 Files selected for processing (13)
src/main/git/worktree-common-dir-comparison.test.tssrc/main/git/worktree-created-description-real-git.test.tssrc/main/git/worktree-list-reader.tssrc/main/git/worktree-listing.tssrc/main/git/worktree-scan-cache.tssrc/main/ipc/created-worktree-reconciliation.test.tssrc/main/ipc/created-worktree-reconciliation.tssrc/main/ipc/filesystem-auth.test.tssrc/main/ipc/registered-worktree-roots-cache.tssrc/main/ipc/worktree-remote.tssrc/main/ipc/worktrees-local-create-flow.test.tssrc/main/ipc/worktrees-test-harness.tssrc/shared/wsl-paths.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The new commit hardens the recovered-create path: it stops the Windows host from folding case on WSL common-dir paths, and it bounds the filesystem common-dir read so a .git on a hung mount cannot leave the create IPC pending.
- Case-sensitive WSL common-dir comparison — new
isSameCommonDirPathcompares POSIX-absolute paths viaposix.resolve(case-sensitive, regardless of host) and refuses to compare a Linux path against a Windows one, while keepingareWorktreePathsEqualfor Windows-native pairs. This closes the false-accept where two WSL repos differing only by case were treated as the same object store. - Bounded disk read —
readRepoCommonDirFromDisknow wraps its.gitprobe andresolveGitDir → resolveGitCommonDirwalk in awithDeadlinehelper, and bails on bare repos (no.git) instead of lettingresolveGitDirfabricate a path. toWslExecutionSpacerelocation — the formertoGitOutputSpacemoved fromworktree-list-reader.tsintosrc/shared/wsl-paths.tswith identical behavior;readRepoLocationis now exported for the listing module.- Coverage — a four-case
isSameCommonDirPathunit suite plus a real-Gitmkfifotest provingdescribeCreatedWorktreesettles when the repo's.gitblocks forever.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…e rebuilds The previous approach registered a recovered create into the same per-repo set the rebuild recomputes from `git worktree list`. That set is derived from the very listing that failed, so a rebuild would re-deny the worktree — either by overlapping the registration, or by simply listing again and omitting the row. Carrying old roots forward on a thrown listing did not cover either case. Recovered roots now live in their own additive layer that rebuilds union in rather than replace. The layer is retired on evidence, not on a timer: - the listing can see the worktree again (Git recovered), or - the listing succeeded and the directory is gone (worktree removed). A repo whose listing threw is left untouched, because a dead mount fails both the listing and the stat, and treating that as "removed" would revoke the worktree in exactly the outage this layer exists for. The layer is capped so it cannot grow unbounded, and survives cache invalidation deliberately: repo mutations are frequent and would otherwise re-deny a recovered worktree. Three tests cover the healthy-rebuild-omits-the-row case, the in-flight rebuild race, and retirement once the listing sees it again. Removing the union fails exactly the two keep-tests and nothing else.
…swer disagrees The disk read is a second opinion on Git's reading of the common dir, but it ran unconditionally as part of the same Promise.all. A deadline bounds the IPC, not the syscall: Promise.race cannot cancel an in-flight fs operation, and a `.git` on a hung mount (dead NFS/SSHFS, stalled WSL 9p) pins a libuv threadpool thread that no timeout can reclaim. AbortSignal would not help either — fsPromises.stat takes no signal, and a blocked syscall is not interruptible from userland. So stop paying it on the happy path: read from disk only when Git's own reading did not already confirm the common dir. Same accept/reject outcome, but the threadpool exposure now requires both a failed listing and Git disagreeing about the repo, instead of every recovered create.
There was a problem hiding this comment.
Important
The rebuild-preservation fix targets the throw path, but local repos never throw on a broken listing — they soften to [], so the recovered root is still dropped.
Reviewed changes
Two follow-up commits landed since the last review: the author's cdcde584be and a merge of origin/main.
- Shared create-verification budget —
resolveCreatedWorktreenow charges the direct-read recovery the time the listing left of its 30s budget (5s floor), instead of starting a fresh deadline, and still honors a caller-suppliedtimeout. - Rebuild preserves old roots on listing throw —
rebuildAuthorizedRootsCachecarries a repo's previously registered roots forward when its listing throws, so a rebuild racing a broken Git doesn't revoke a just-recovered worktree. - Scan-cache doc correction — the coalescing comment now states the actual behavior: strict and lenient runners share a scan key that includes the runner name, so a strict joiner never inherits a softened
[]. - Merge of
origin/main— brings main's unrelated changes (updater-prerelease-feed, native-chat composer, relay PTY reaping) into the branch.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/runtime/orca-runtime.ts (1)
27241-27246: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRegister recovered worktrees in the runtime authorization cache
When
resolveCreatedWorktreeuses the direct-read fallback, it returnslistingComplete: falseand an emptyworktreeslist. This call keeps onlycreatedand only invalidates the authorization cache. If the next full scan cannot complete, Git IPC can reject the new path withAccess denied: unknown repository or worktree path. ConsumelistingCompleteand registercreated.pathwhen recovery succeeds without a complete listing, ascreateRemoteWorktreedoes.src/main/git/worktree-scan-cache.ts (1)
53-56: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winDocument the complete scan-sharing key.
The JSDoc omits
options.includeCreatePreparations, but the cache key includes it at Line 70. Add this dimension to the documented tuple so future changes do not incorrectly coalesce scans with different result shapes.Suggested documentation fix
- per (repo, distro, deadline, generation, runner) + per (repo, distro, deadline, includeCreatePreparations, generation, runner)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 98f7326d-c575-473d-9765-9653d45095e4
📒 Files selected for processing (9)
src/main/git/worktree-listing.tssrc/main/git/worktree-scan-cache.tssrc/main/git/worktree.tssrc/main/ipc/worktree-remote.tssrc/main/ipc/worktrees-local-create-flow.test.tssrc/main/runtime/orca-runtime.tssrc/main/updater-prerelease-feed-readiness.test.tssrc/main/updater-prerelease-feed.tssrc/renderer/src/components/native-chat/use-native-chat-composer-app-menu-selection.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
… space Exercising the fix on a real Windows host against WSL Ubuntu-24.04 found the filesystem second opinion is inert there. Node reads `.git` in the caller's space and answers `\\wsl.localhost\<Distro>\home\...\.git`, while Git-in-the- distro answers `/home/...`. isSameCommonDirPath refuses to compare a POSIX path against a Windows one, and canonicalizeLocalPath cannot bridge them because realpath on a Linux path from a Windows process is ENOENT. So the candidate could never match, and the one case that depends on this witness alone — a symlinked repo root on the Git 2.25 fallback — declined a worktree Git had already confirmed. Run the disk result through toWslExecutionSpace, the same translation readRepoLocation already uses. This is a false reject, not a false accept: it made recovery give up, never adopt the wrong repo. Verified on awin; the modern --path-format=absolute branch was unaffected because Git answers both sides itself there.
There was a problem hiding this comment.
Important
The prune's "gone from disk" test does an unbounded stat and treats any error as removal — on a hung mount it hangs the whole rebuild, and the listingFailed guard that was meant to skip pruning never fires for local repos.
Reviewed changes
The author's follow-ups landed after the merge: 9146c1fc (recovered-root survival) and d16305e (deferred disk read).
- Recovered roots live in their own layer —
registerCreatedWorktreeRootnow writes to a separatecreatedWorktreeRootsByRepomap that survives bothinvalidateAuthorizedRootsCacheandrebuildAuthorizedRootsCache, instead of being re-derived from the listing. It is pruned only on evidence (the listing can see the worktree again, or the path is gone from disk), capped at 64 roots per repo. - Deferred disk read —
describeCreatedWorktreeonly reads the repo's.gitfrom disk when Git's own--git-common-diranswer disagrees, so the happy path never pays the hung-mount disk read. - Tests — new
filesystem-authcases for softened-[]rebuilds, a rebuild already in flight, and retiring a root once the listing sees it again; plus a__resetCreatedWorktreeRootsForTestsreset wired into the harness.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta.
Reviewed changes
One commit landed since the last review: 614f6e59.
- Disk witness in Git's execution space —
readRepoCommonDirFromDisknow returnstoWslExecutionSpace(commonDir), so the Node-side UNC path is converted to Git's/home/...spelling before comparison. Under WSL the disk candidate could otherwise never equalcreated.commonDir, leaving the symlinked-root / Git-2.25 fallback witness inert. Correct and narrowly scoped.
The one open concern from the prior review — the unbounded stat in pathStillExists (and its dead listingFailed guard for local repos) — is unchanged by this commit.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 53485b61-deb6-4aa8-a55b-25a5b4609789
📒 Files selected for processing (4)
src/main/git/worktree-listing.tssrc/main/ipc/filesystem-auth.test.tssrc/main/ipc/registered-worktree-roots-cache.tssrc/main/ipc/worktrees-test-harness.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| // The recovered layer is deliberately not cleared: repo mutations are frequent, and dropping it here | ||
| // would re-deny a recovered worktree every time an unrelated repo is added or removed. | ||
| refreshRegisteredWorktreeRoots() |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
printf '%s\n' '--- relevant repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target file outline ---'
ast-grep outline src/main/ipc/registered-worktree-roots-cache.ts
printf '%s\n' '--- target implementation ---'
cat -n src/main/ipc/registered-worktree-roots-cache.ts
printf '%s\n' '--- direct references to resolver and invalidation ---'
rg -n -C 3 'resolveRegisteredWorktreePath|invalidateAuthorizedRootsCache|registerCreatedWorktreeRoot' src/main/ipcRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
printf '%s\n' '--- scoped convention ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-main-ipc.md
printf '%s\n' '--- resolver callers ---'
rg -l 'resolveRegisteredWorktreePath' src/main/ipc | sort
printf '%s\n' '--- resolver caller context ---'
rg -n -C 8 'resolveRegisteredWorktreePath' src/main/ipc --glob '!*.test.ts'
printf '%s\n' '--- repository removal handler ---'
cat -n src/main/ipc/repos/repo-catalog-handlers.ts | sed -n '65,102p'
printf '%s\n' '--- relevant filesystem handler registrations ---'
rg -n -C 5 "git:status|filesystem:|search|download|resolveRegisteredWorktreePath" src/main/ipc/filesystem.ts src/main/ipc/git-status-upstream-ref-watch-request.tsRepository: stablyai/orca
Length of output: 50370
Authorization Bypass (CWE-863): Incorrect Authorization
Reachability: External · Exploitability: Moderate
Revalidate recovered roots before the dirty-cache fast path.
After repos:remove invalidates the cache, resolveRegisteredWorktreePath() can still authorize a recovered worktree path before rebuilding. Rebuild before the fast path or filter recovered roots by current local repository IDs. Add a removal-and-invalidation regression test.
…led probe The prune ran an unbounded stat and read every failure as removal. Two consequences, both in the outage the recovered layer exists for: a hung mount stalled the rebuild that gates filesystem auth, and a transient EACCES/EIO revoked a live worktree. The listingFailed guard did not cover either, because listWorktrees softens Git failures to [] and never throws. Prune now retires on definitive ENOENT only, probes in parallel under a deadline, and treats a stall as inconclusive. The capacity bound refuses a new root instead of evicting an authorized one, so an over-cap create is merely unauthorized rather than a live worktree being revoked.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
One commit landed since the prior review, retiring the last open concern from the d16305e review.
- Prune on proof only —
isRootGoneFromDiskretires a recovered root only whenstatreturns a definitiveENOENT; a transientEACCES/EIO/EPERMor a hung probe keeps the root, since a dead mount fails the listing and the probe alike. - Bounded, parallel probes — the probe is wrapped in
withTimeout(1s, fallback "not gone") and runs in parallel, so a repo's up-to-64 recovered roots can no longer serialize into a rebuild stall. - Refuse rather than evict at capacity —
registerCreatedWorktreeRootnow declines a new root once the per-repo layer reaches 64, instead of silently evicting an already-authorized root. - Coverage — new
created-worktree-root-prune.test.tsasserts ENOENT-retires, transient-error-keeps, never-settles-probe-still-finishes, and capacity-refusal, all on the softened-[]listing path.
The prior open thread (pathStillExists unbounded stat + any-error-as-removal) is fully addressed: the probe is deadlined, treats only ENOENT as removal, and runs in parallel.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…blyai#17388) * fix(worktree): complete a create Git can confirm but cannot list `worktree.create` verified against `listWorktrees`, which softens every git failure to `[]`. Any listing failure therefore failed a create whose worktree and branch `git worktree add` had already written, orphaning both, and reported only 'Worktree created but not found in listing' — the real cause reached the main-process console and never the user. Verify against the error-propagating listing instead, and when that fails or omits the row, rebuild the row by asking Git about the worktree itself. The direct read returns nothing unless Git resolves the path into this repo's object store with the expected branch checked out, so an unrelated or half-made checkout still fails the create. Fixes stablyai#16520 * fix(worktree): authorize a recovered create and reject an unreadable HEAD Review follow-ups on the create-verification fallback: - register the recovered worktree's own root, additively, so the create the user just made is not rejected by filesystem/git-status IPC - treat an unreadable HEAD as no recovery instead of a blank OID - keep the direct read's failure when the listing merely omitted the row - skip the symlink cases on Windows and reset the new harness mock * fix(worktree): bound the create-recovery disk read and keep WSL paths case-sensitive Readiness-scan follow-ups: - deadline the filesystem common-dir read; a .git on a hung mount left the whole create IPC pending where it used to fail after the Git deadline - offer no disk candidate for a bare repo instead of a fabricated <repo>/.git - compare POSIX common dirs case-sensitively, so two WSL repos differing only in case are not accepted as one object store on a Windows desktop - move toGitOutputSpace to shared/wsl-paths as toWslExecutionSpace, next to the parseWslUncPath callers that already open-code it * fix(worktree): share one budget for create verification and keep recovered roots Three follow-ups from review of the create-recovery path: - The recovery no longer starts a fresh 30s deadline after the listing already burned one, so worst-case create verification stays at ~30s instead of ~60s. A 5s floor keeps the direct read a chance to answer when the listing spent the whole budget. - rebuildAuthorizedRootsCache now carries a repo's previously registered roots forward when its listing throws. A rebuild running while Git is still broken could otherwise un-authorize the worktree a create just recovered. - Corrected the scan-cache doc comment: it claimed strict and lenient listings coalesce, but the cache key includes the runner name precisely to keep them apart, so a strict joiner can never inherit a lenient scan's softened []. Each change has a negative control: reverting the hunk fails exactly its own test and nothing else. * fix(worktree): keep a recovered worktree authorized across roots-cache rebuilds The previous approach registered a recovered create into the same per-repo set the rebuild recomputes from `git worktree list`. That set is derived from the very listing that failed, so a rebuild would re-deny the worktree — either by overlapping the registration, or by simply listing again and omitting the row. Carrying old roots forward on a thrown listing did not cover either case. Recovered roots now live in their own additive layer that rebuilds union in rather than replace. The layer is retired on evidence, not on a timer: - the listing can see the worktree again (Git recovered), or - the listing succeeded and the directory is gone (worktree removed). A repo whose listing threw is left untouched, because a dead mount fails both the listing and the stat, and treating that as "removed" would revoke the worktree in exactly the outage this layer exists for. The layer is capped so it cannot grow unbounded, and survives cache invalidation deliberately: repo mutations are frequent and would otherwise re-deny a recovered worktree. Three tests cover the healthy-rebuild-omits-the-row case, the in-flight rebuild race, and retirement once the listing sees it again. Removing the union fails exactly the two keep-tests and nothing else. * perf(worktree): only read the repo's .git from disk when Git's own answer disagrees The disk read is a second opinion on Git's reading of the common dir, but it ran unconditionally as part of the same Promise.all. A deadline bounds the IPC, not the syscall: Promise.race cannot cancel an in-flight fs operation, and a `.git` on a hung mount (dead NFS/SSHFS, stalled WSL 9p) pins a libuv threadpool thread that no timeout can reclaim. AbortSignal would not help either — fsPromises.stat takes no signal, and a blocked syscall is not interruptible from userland. So stop paying it on the happy path: read from disk only when Git's own reading did not already confirm the common dir. Same accept/reject outcome, but the threadpool exposure now requires both a failed listing and Git disagreeing about the repo, instead of every recovered create. * fix(worktree): compare the disk common-dir witness in Git's execution space Exercising the fix on a real Windows host against WSL Ubuntu-24.04 found the filesystem second opinion is inert there. Node reads `.git` in the caller's space and answers `\\wsl.localhost\<Distro>\home\...\.git`, while Git-in-the- distro answers `/home/...`. isSameCommonDirPath refuses to compare a POSIX path against a Windows one, and canonicalizeLocalPath cannot bridge them because realpath on a Linux path from a Windows process is ENOENT. So the candidate could never match, and the one case that depends on this witness alone — a symlinked repo root on the Git 2.25 fallback — declined a worktree Git had already confirmed. Run the disk result through toWslExecutionSpace, the same translation readRepoLocation already uses. This is a false reject, not a false accept: it made recovery give up, never adopt the wrong repo. Verified on awin; the modern --path-format=absolute branch was unaffected because Git answers both sides itself there. * fix(worktree): retire a recovered root only on proof, never on a stalled probe The prune ran an unbounded stat and read every failure as removal. Two consequences, both in the outage the recovered layer exists for: a hung mount stalled the rebuild that gates filesystem auth, and a transient EACCES/EIO revoked a live worktree. The listingFailed guard did not cover either, because listWorktrees softens Git failures to [] and never throws. Prune now retires on definitive ENOENT only, probes in parallel under a deadline, and treats a stall as inconclusive. The capacity bound refuses a new root instead of evicting an authorized one, so an over-cap create is merely unauthorized rather than a live worktree being revoked.

Fixes #16520. Replaces #16700.
Why
worktree.createverified the new worktree againstlistWorktrees, which softens every Gitfailure to
[]:The comment says the opposite of what the code does. So any listing failure — exec error, timeout,
capability-fallback error, repo-state error — failed a create after
git worktree addhad alreadywritten the worktree and branch, leaving both orphaned. The user saw only
Worktree created but not found in listing; the real cause reached the main-process console andnothing else.
What changed
listWorktreesSharedStrictsurfaces the realGit error instead of an opaque message, while still coalescing with a concurrent refresh.
describeCreatedWorktree— when the listing fails or omits the row, rebuild that row byasking Git about the worktree itself (
rev-parse --show-toplevel --git-common-dir,symbolic-ref --quiet HEAD,rev-parse HEAD). It returns nothing unless Git resolves the pathinto this repo's object store with the expected branch checked out, so an unrelated or
half-made checkout still fails the create.
resolveCreatedWorktreereplaces the duplicated list-then-find-then-throw block at bothlocal call sites (desktop IPC and
orca worktree create). It throws only when both witnessesfail — preferring the listing's own error, else a message naming the path and branch.
The substring
created but not found in listingis preserved forclassifyWorkspaceCreateError.Two common-dir readings, not one
describeCreatedWorktreeaccepts the created worktree's common dir matching either Git'sreading or the filesystem's. That is not redundancy — an earlier single-source version of this fix
was inert exactly where it was needed, and each branch now has a test that fails without it:
--git-common-dir(no.gitfile to walk)Two authorization layers
registerWorktreeRootsForReporeplaces a repo's authorized-root set, so registering a createthat was recovered without a listing would revoke filesystem access to every worktree the listing
would have named. The resolution therefore reports whether its rows are the whole listing
(
listingComplete), and the IPC site takes that path only then.A recovered create instead goes through
registerCreatedWorktreeRootinto a second, additive layer.It needs to be separate because everything in the derived map is recomputed from
git worktree list— a rebuild during the outage would re-deny the worktree the create just recovered, whether the
listing threw or succeeded with the row missing. That layer survives rebuilds and retires a root
only on proof: the listing can see it again, or a probe returns a definitive
ENOENT. A probe thathangs or fails with
EACCES/EIOis inconclusive and keeps the root, because a dead mount producesexactly that while failing the listing too. The probe runs under a deadline so the rebuild — which
gates filesystem auth — cannot stall behind it, and the layer's capacity bound refuses a new root
rather than evicting an authorized one.
Pre-fix all of this was unreachable (the code threw instead); the fallback is what makes it
reachable, so it ships with the gate, a call-site test, and
created-worktree-root-prune.test.ts.Testing
src/main/git/worktree-created-description-real-git.test.ts— 9 tests against the real Gitbinary, including that the rebuilt row is deep-equal to the row
listWorktreesStrictreports forthe same worktree; plus bare repo, symlinked root, detached HEAD, foreign repo, non-worktree path,
and the Git 2.25 baseline (capability cache seeded unsupported to force the no-
--path-formatfallback against the real binary).
created-worktree-reconciliation.test.ts— listing hit / listing fails / listing omits the row /the listing's own error is surfaced / recovery failure does not mask it / exec options forwarding.
worktrees-local-create-flow.test.ts— a create the listing failed completes and leaves asibling worktree still authorized.
restore): the fallback, the
listingCompletegate, the Git-reading candidate, andcanonicalization.
src/main/ipc src/main/git src/main/runtime: 964 files, 10722 passed, 0 failed.pnpm tcclean. Changed-code quality gate clean.
Compatibility
readRepoCommonDirFromGituses--git-common-diralone (adding
--show-toplevelmakes rev-parse fail outright on a bare repo) and resolves therelative
.gitthat pre-2.31 Git prints against Git's own output space. Covered by the baselinetest above. An earlier revision of this body claimed that made the recovery "not inert on WSL";
hardware testing refuted that for one case — see Known gaps.
translateWorktreePath/parseWslUncPathhelpers; no new path assumptions.worktree-remote.ts:1841) still verifies offprovider.listWorktreesand throws the same opaque message. Left alone deliberately: fixing itmeans deciding what the execution host owes the client, which belongs in its own change under the
SSH execution-boundary rules.
Known gaps
Windows-native: the rebuilt row is deep-equal to the row
listWorktreesStrictreports for the sameworktree — lowercase drive letter and forward slashes included — and the common-dir guard refuses a
foreign repo in both directions on both platforms. No false accept was found anywhere. The
reporter's own
D:volume is still not reproducible on that box.the repo's
.git/HEADinside Ubuntu-24.04 (Git 2.43) maderesolveCreatedWorktreerethrowfatal: not a git repositoryand orphan the worktree ond16305e5f6d; on614f6e59ab5the sameinduced fault returns
{created, worktrees: [], listingComplete: false}and the create completes.The cause was the disk witness being expressed in Windows space, unusable against Git's Linux-space
answer.
the only witness in that case, and it cannot be built there —
resolveGitDirreturns<worktree>/.gitverbatim without canonicalizing, andrealpathon the UNC spelling of a Linuxsymlink is
ENOENT, because the plan9 share does not expose it as a resolvable reparse point.614f6e59ab5translates the disk candidate into the distro's execution space, which fixes the spacebut not the spelling: Git says
.../repo/.gitwhile both witnesses say.../repo-link/.git.Measured on the distro, the symlinked case is unchanged (
false→false). Closing it needscanonicalization inside the distro, not a spelling translation. The consequence is that such a
create fails exactly as it does on
maintoday: an improvement this cut does not finish, not aregression, and a false reject rather than a false accept. It also needs three conditions at once —
a symlinked WSL repo root, Git < 2.31 in the distro, and a listing failure at create time.
This fix is written so it does not need to be: it surfaces the real error and stops the create
from failing when Git can still confirm the worktree.
Note on #17351
Part of this work —
worktree-scan-cache.ts,worktree-listing.ts, andworktree-list-reader.tsscaffolding — landed on
maininside #17351 by mistake. Uncommitted changes rode along a branchcheckout and were committed under that PR's title, so no reviewer evaluated them as worktree work.
mainis green and the accompanying tests came along, but the diff there was not reviewed on itsmerits. Flagging it explicitly so this PR is read as the review of that code too — it is included in
the coverage and negative controls above.
Relationship to #16700
Same first step (strict listing), and I've adopted its
resetRuntimeTestMocksapproach of making thestrict mock delegate to
listWorktrees. Two differences worth recording:main. fix(worktree): verify creates with a fresh listing #16700 attributes the bug to verification joininga stale in-flight scan.
addWorktreeretires every overlapping scan generation in itsfinally,and the generation is part of the shared-scan key, so I could not construct that join;
worktree-scan-cache-sharing.test.ts:188already guards it. The real cause is thereturn []softening.
fails the create after
git worktree addsucceeded, so the reported impact — every create leavingan orphaned but valid worktree and branch — is unchanged. The direct-read fallback is what fixes it.