Skip to content

fix(worktree): complete a create Git can confirm but cannot list - #17388

Merged
nwparker merged 9 commits into
mainfrom
nwparker/worktree-create-verification
Aug 30, 2026
Merged

nwparker merged 9 commits into
mainfrom
nwparker/worktree-create-verification

Conversation

@nwparker

@nwparker nwparker commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​591 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​568
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​523 $\color{#cf222e}{\Huge{\mathbf{−}}}$​48 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​475

Fixes #16520. Replaces #16700.

Why

worktree.create verified the new worktree against listWorktrees, which softens every Git
failure to []:

// Why: don't swallow git-compat/repo-state failures — else they resurface as opaque
// "created but not found in listing" errors.
console.warn(`[git/worktree] listWorktrees failed for ${repoPath}:`, err)
return []

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 add had already
written 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 and
nothing else.

What changed

  1. Verify against the error-propagating listing. listWorktreesSharedStrict surfaces the real
    Git error instead of an opaque message, while still coalescing with a concurrent refresh.
  2. New describeCreatedWorktree — when the listing fails or omits the row, rebuild that row by
    asking 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 path
    into this repo's object store with the expected branch checked out, so an unrelated or
    half-made checkout still fails the create.
  3. New resolveCreatedWorktree replaces the duplicated list-then-find-then-throw block at both
    local call sites (desktop IPC and orca worktree create). It throws only when both witnesses
    fail — preferring the listing's own error, else a message naming the path and branch.
    The substring created but not found in listing is preserved for classifyWorkspaceCreateError.

Two common-dir readings, not one

describeCreatedWorktree accepts the created worktree's common dir matching either Git's
reading 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:

Case Only witness
Bare repo Git's --git-common-dir (no .git file to walk)
Symlinked root on the Git 2.25 fallback filesystem, after canonicalization

Two authorization layers

registerWorktreeRootsForRepo replaces a repo's authorized-root set, so registering a create
that 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 registerCreatedWorktreeRoot into 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 that
hangs or fails with EACCES/EIO is inconclusive and keeps the root, because a dead mount produces
exactly 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 Git
    binary
    , including that the rebuilt row is deep-equal to the row listWorktreesStrict reports for
    the 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-format
    fallback 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 a
    sibling worktree still authorized.
  • Negative controls run for every non-obvious branch (revert the code, confirm the test fails,
    restore): the fallback, the listingComplete gate, the Git-reading candidate, and
    canonicalization.
  • src/main/ipc src/main/git src/main/runtime: 964 files, 10722 passed, 0 failed. pnpm tc
    clean. Changed-code quality gate clean.

Compatibility

  • Git 2.25 baseline — no new subcommand. readRepoCommonDirFromGit uses --git-common-dir
    alone (adding --show-toplevel makes rev-parse fail outright on a bare repo) and resolves the
    relative .git that pre-2.31 Git prints against Git's own output space. Covered by the baseline
    test 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.
  • Windows / WSL — paths translate through the existing translateWorktreePath /
    parseWslUncPath helpers; no new path assumptions.
  • SSH / remote — untouched. The remote create path (worktree-remote.ts:1841) still verifies off
    provider.listWorktrees and throws the same opaque message. Left alone deliberately: fixing it
    means deciding what the execution host owes the client, which belongs in its own change under the
    SSH execution-boundary rules.
  • Wire — no RPC params, stream frames, or published content change.
  • Folder workspaces — unaffected; this is on the git-worktree create path only.

Known gaps

  • Exercised on a real Windows 11 host (Git 2.55 native, Git 2.43 in WSL), not only on macOS.
    Windows-native: the rebuilt row is deep-equal to the row listWorktreesStrict reports for the same
    worktree — 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.
  • WSL: the induced-listing-failure case was exercised on the real distro and is fixed. Breaking
    the repo's .git/HEAD inside Ubuntu-24.04 (Git 2.43) made resolveCreatedWorktree rethrow
    fatal: not a git repository and orphan the worktree on d16305e5f6d; on 614f6e59ab5 the same
    induced 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.
  • WSL, symlinked worktree root on the Git 2.25 fallback: still a false reject. The filesystem is
    the only witness in that case, and it cannot be built there — resolveGitDir returns
    <worktree>/.git verbatim without canonicalizing, and realpath on the UNC spelling of a Linux
    symlink is ENOENT, because the plan9 share does not expose it as a resolvable reparse point.
    614f6e59ab5 translates the disk candidate into the distro's execution space, which fixes the space
    but not the spelling: Git says .../repo/.git while both witnesses say .../repo-link/.git.
    Measured on the distro, the symlinked case is unchanged (false → false). Closing it needs
    canonicalization inside the distro, not a spelling translation. The consequence is that such a
    create fails exactly as it does on main today: an improvement this cut does not finish, not a
    regression, 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.
  • The specific Git failure that fires deterministically on the reporter's setup is still unidentified.
    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, and worktree-list-reader.ts
scaffolding — landed on main inside #17351 by mistake. Uncommitted changes rode along a branch
checkout and were committed under that PR's title, so no reviewer evaluated them as worktree work.
main is green and the accompanying tests came along, but the diff there was not reviewed on its
merits. 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 resetRuntimeTestMocks approach of making the
strict mock delegate to listWorktrees. Two differences worth recording:

  • Its stated cause is not reachable on main. fix(worktree): verify creates with a fresh listing #16700 attributes the bug to verification joining
    a stale in-flight scan. addWorktree retires every overlapping scan generation in its finally,
    and the generation is part of the shared-scan key, so I could not construct that join;
    worktree-scan-cache-sharing.test.ts:188 already guards it. The real cause is the return []
    softening.
  • It changes the message, not the outcome. With the strict listing alone, a failing listing still
    fails the create after git worktree add succeeded, so the reported impact — every create leaving
    an orphaned but valid worktree and branch — is unchanged. The direct-read fallback is what fixes it.

`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-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

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

  • Adds direct worktree reconstruction with repository, branch, HEAD, path-space, and common-directory validation.
  • Shares strict worktree scans separately from lenient scans and propagates useful listing failures.
  • Registers directly recovered roots additively, preserving them across rebuilds and pruning them only when relisted or definitively absent.
  • Updates desktop and CLI create flows and adds real-Git, WSL, authorization, reconciliation, and lifecycle tests.

Confidence Score: 4/5

The 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

Important Files Changed

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

Reviews (8): Last reviewed commit: "fix(worktree): retire a recovered root o..." | Re-trigger Greptile

Comment thread src/main/ipc/worktree-remote.ts Resolved
@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 5a70c5bd-d6ee-46b5-9560-529232b7e60a

📥 Commits

Reviewing files that changed from the base of the PR and between 614f6e5 and 19c9dfe.

📒 Files selected for processing (2)
  • src/main/ipc/created-worktree-root-prune.test.ts
  • src/main/ipc/registered-worktree-roots-cache.ts

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


📝 Walkthrough

Walkthrough

Adds 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 git worktree list fails or omits the new row. Root registration preserves existing roots during incomplete listings. Tests cover mocked flows and real Git cases, including bare repositories, symlinked paths, detached HEAD, cross-repository paths, blocking filesystem access, and older Git versions.

Merge Risk: 🟡 Moderate · up to 19c9d

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 21 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ⚠️ Warning The pull request includes unrelated formatting-only changes in the updater and renderer files. These changes do not support the worktree creation fix and weaken the stated scope. Remove the unrelated formatting-only changes, or explain why they are required for this pull request.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed 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 omit…
Linked Issues check ✅ Passed The description links this work to issue #16520 and identifies #16700 as the replaced pull request.
Title check ✅ Passed The title clearly summarizes the main fix: completing worktree creation when Git confirms creation but cannot list the worktree.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ 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.

@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: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e0b03951-5836-4f8b-9def-870ca3c63523

📥 Commits

Reviewing files that changed from the base of the PR and between 3d0bd6a and 9f4fd27.

📒 Files selected for processing (14)
  • src/main/git/worktree-created-description-real-git.test.ts
  • src/main/git/worktree-list-reader.ts
  • src/main/git/worktree-listing.ts
  • src/main/git/worktree-sparse-state.ts
  • src/main/git/worktree.ts
  • src/main/ipc/created-worktree-reconciliation.test.ts
  • src/main/ipc/created-worktree-reconciliation.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-local-create-flow.test.ts
  • src/main/ipc/worktrees-test-harness.ts
  • src/main/ipc/worktrees-test-module-mocks.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

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

Comment thread src/main/git/worktree-list-reader.ts Resolved
Comment thread src/main/ipc/worktrees-test-harness.ts Resolved

@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 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.
  • describeCreatedWorktree direct-read fallback — reconstructs the created row from rev-parse --show-toplevel --git-common-dir, symbolic-ref --quiet HEAD, and rev-parse HEAD, gated on the worktree resolving into this repo's object store with the expected branch checked out.
  • resolveCreatedWorktree reconciliation — one shared list-then-find-then-throw replacement at both call sites; it prefers the listing's own error, preserves the created but not found in listing classifier substring, and reports whether the listing was authoritative.
  • listingComplete root-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 listingComplete gate, and canonicalization.

ℹ️ Nitpicks

  • When listWorktreesSharedStrict throws but describeCreatedWorktree recovers the row, the listing error is swallowed with no log (resolveCreatedWorktree drops listingError once the fallback succeeds). For the exact failure mode this PR targets, a console.warn on the recovered path would keep the underlying cause observable instead of silently lost.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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
@nwparker

Copy link
Copy Markdown
Contributor Author

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 Access denied: unknown repository or worktree path. Fixed with a new additive registerCreatedWorktreeRoot in registered-worktree-roots-cache.ts, which adds the single root to the repo's existing set and deliberately leaves the cache dirty so the next ensureAuthorizedRootsCache still performs a full rebuild. Reverting only that call makes completes a create the listing failed and keeps sibling worktrees authorized fail on Access denied: unknown repository or worktree path and nothing else.

Reject recovery when Git cannot read HEAD — real. readWorktreeHeadOid returns '' on failure, and the row was built anyway. describeCreatedWorktree now reads HEAD alongside the other probes and returns undefined when it is empty. New real-binary test rejects a worktree whose HEAD Git cannot resolve deletes the branch ref so HEAD stays symbolic but unborn — symbolic-ref still answers refs/heads/feature while rev-parse HEAD fails, which is exactly the state the guard has to catch. It fails without the guard.

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 created but not found in listing message, which stays intact for classifyWorkspaceCreateError.

Skip the symlink tests on Windows — correct; ln is not on the Windows test PATH. Both are now guarded with it.skipIf(process.platform === 'win32').

Reset describeCreatedWorktreeMock between tests — correct; added to the mockReset() loop, with the default assignment still applied after it.

Verified: src/main/ipc src/main/git src/main/runtime — 1024 files, 11,339 passed. Three files fail (automation-change-publication, orca-runtime-skill-recovery, quarter-circle-title-send-authorization); they fail identically with this branch stashed, so they are pre-existing on main, not from this change. pnpm tc clean, oxlint clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

The new commit hardens the recovered-create path and fixes the Windows break from the prior round.

  • HEAD is now read up front — describeCreatedWorktree reads HEAD in the same parallel batch and returns undefined when 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 now it.skipIf(process.platform === 'win32'), matching worktree-separate-git-dir.test.ts.
  • Recovered create is authorized — new registerCreatedWorktreeRoot registers only the newly created root (keeping siblings authorized and marking the cache dirty for a full rebuild), and worktree-remote.ts calls it on the recovered path.
  • Direct-read failure is surfaced — resolveCreatedWorktree appends the direct read's error only when the listing omitted the row, still preferring the listing's own error when it throws.

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

Copy link
Copy Markdown
Contributor Author

Second review-fix pass, from the readiness scan (f8cae8f89e3). Four candidate findings, all P2, all addressed; none release-blocking.

Unbounded filesystem read on the recovery path. readRepoCommonDirFromDisk sat inside the same Promise.all as the three deadlined Git reads but took neither a timeout nor a signal, so a .git on a hung mount (dead NFS/SSHFS, stalled WSL 9p) would leave the create IPC pending forever — strictly worse than the pre-PR behavior, where the create rejected after the Git deadline. It is now deadlined against the same budget. New real-binary test still settles when the repo's .git blocks forever stands a mkfifo in for the hung mount and asserts the call resolves; it releases the pending read in finally so no threadpool thread stays pinned.

A fabricated .git candidate for bare repos. resolveGitDir returns <repoPath>/.git unconditionally, so a bare repo got a candidate that does not exist. It now stats .git first and offers no disk candidate when there is none — the caveat in the old doc comment is gone rather than documented. The existing bare-repo test still passes, which is the point: that case is carried by Git's own reading.

POSIX common dirs were case-folded on a Windows host. areWorktreePathsEqual (the git/ copy) lowercases every path once process.platform === 'win32', including POSIX ones. Since this PR makes that comparison decide whether a create is confirmed, two WSL repos differing only in case could be accepted as the same object store — a false accept in a trust check, where the pre-PR code threw. isSameCommonDirPath now refuses to compare across path flavors and compares POSIX pairs case-sensitively. New unit test worktree-common-dir-comparison.test.ts; reverting the guard fails keeps WSL paths case-sensitive on a Windows host and nothing else. The broader divergence between the git/ and ipc/ comparators is pre-existing and left alone deliberately — converging them would change worktree dedupe repo-wide.

toGitOutputSpace was unreachable from its other callers. parseWslUncPath(x)?.linuxPath ?? x is open-coded verbatim in three other modules. Moved to src/shared/wsl-paths.ts as toWslExecutionSpace, beside parseWslUncPath.

Also reported and deliberately not changed here:

  • The SSH create site still hand-rolls its match (worktree-remote.ts, gw.branch?.endsWith(branchName) || gw.path.endsWith(...)), so branch feature suffix-matches an existing refs/heads/my-feature row. Pre-existing, not a regression from this PR, and consolidating it would mean changing remote create semantics in a PR about the local path. Worth a follow-up.
  • The pinned-Git-2.25 CI lane runs only git-binary-compatibility.test.ts, so this PR's new --path-format=absolute call site exercises its fallback by seeding the capability cache rather than against a binary that actually echoes. I verified the echo shape by hand (git rev-parse --path-format-bogus=absolute --git-common-dir → the flag echoed first, then .git, exit 0) and the bare-repo justification for omitting --show-toplevel (fatal: this operation must be run in a work tree, exit 128).
  • WSL repos on a Windows drive with distro Git < 2.31: toWslExecutionSpace bridges UNC→Linux but not drive→/mnt/<letter>, so both common-dir candidates mismatch and the recovery is inert. It fails closed to pre-PR behavior, needs all three conditions at once, and the same limitation already affects normalizeMainWorktreePath — an unfinished pre-existing gap rather than a regression.

Verification: pnpm tc clean; src/main/git src/main/ipc — 518 files, 5448 tests passed; oxlint clean. Flaky failures observed across repeat runs in repos-remote-client-events, automation-change-publication, orca-runtime-skill-recovery and quarter-circle-title-send-authorization are pre-existing: they fail identically with this branch stashed.

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

Copy link
Copy Markdown
Contributor Author

Review-fix iteration 3 — cdcde584be3

Third pass over the readiness-checklist scan (section 05 functional, plus one residual-risk item). No P0/P1 in any of the four scanner sections; these are the three P2s worth acting on.

# 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

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 36756b62-8ee9-40cc-8ded-6ccfd2a1f370

📥 Commits

Reviewing files that changed from the base of the PR and between 9f4fd27 and cdcde58.

📒 Files selected for processing (13)
  • src/main/git/worktree-common-dir-comparison.test.ts
  • src/main/git/worktree-created-description-real-git.test.ts
  • src/main/git/worktree-list-reader.ts
  • src/main/git/worktree-listing.ts
  • src/main/git/worktree-scan-cache.ts
  • src/main/ipc/created-worktree-reconciliation.test.ts
  • src/main/ipc/created-worktree-reconciliation.ts
  • src/main/ipc/filesystem-auth.test.ts
  • src/main/ipc/registered-worktree-roots-cache.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-local-create-flow.test.ts
  • src/main/ipc/worktrees-test-harness.ts
  • src/shared/wsl-paths.ts

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

Comment thread src/main/git/worktree-listing.ts Resolved
Comment thread src/shared/wsl-paths.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

The 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 isSameCommonDirPath compares POSIX-absolute paths via posix.resolve (case-sensitive, regardless of host) and refuses to compare a Linux path against a Windows one, while keeping areWorktreePathsEqual for 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 — readRepoCommonDirFromDisk now wraps its .git probe and resolveGitDir → resolveGitCommonDir walk in a withDeadline helper, and bails on bare repos (no .git) instead of letting resolveGitDir fabricate a path.
  • toWslExecutionSpace relocation — the former toGitOutputSpace moved from worktree-list-reader.ts into src/shared/wsl-paths.ts with identical behavior; readRepoLocation is now exported for the listing module.
  • Coverage — a four-case isSameCommonDirPath unit suite plus a real-Git mkfifo test proving describeCreatedWorktree settles when the repo's .git blocks forever.

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

@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 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 — resolveCreatedWorktree now 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-supplied timeout.
  • Rebuild preserves old roots on listing throw — rebuildAuthorizedRootsCache carries 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.

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

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

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 win

Register recovered worktrees in the runtime authorization cache

When resolveCreatedWorktree uses the direct-read fallback, it returns listingComplete: false and an empty worktrees list. This call keeps only created and only invalidates the authorization cache. If the next full scan cannot complete, Git IPC can reject the new path with Access denied: unknown repository or worktree path. Consume listingComplete and register created.path when recovery succeeds without a complete listing, as createRemoteWorktree does.

src/main/git/worktree-scan-cache.ts (1)

53-56: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document 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

📥 Commits

Reviewing files that changed from the base of the PR and between cdcde58 and b7c8839.

📒 Files selected for processing (9)
  • src/main/git/worktree-listing.ts
  • src/main/git/worktree-scan-cache.ts
  • src/main/git/worktree.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-local-create-flow.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/updater-prerelease-feed-readiness.test.ts
  • src/main/updater-prerelease-feed.ts
  • src/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.

@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 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 — registerCreatedWorktreeRoot now writes to a separate createdWorktreeRootsByRepo map that survives both invalidateAuthorizedRootsCache and rebuildAuthorizedRootsCache, 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 — describeCreatedWorktree only reads the repo's .git from disk when Git's own --git-common-dir answer disagrees, so the happy path never pays the hung-mount disk read.
  • Tests — new filesystem-auth cases for softened-[] rebuilds, a rebuild already in flight, and retiring a root once the listing sees it again; plus a __resetCreatedWorktreeRootsForTests reset wired into the harness.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta.

Reviewed changes

One commit landed since the last review: 614f6e59.

  • Disk witness in Git's execution space — readRepoCommonDirFromDisk now returns toWslExecutionSpace(commonDir), so the Node-side UNC path is converted to Git's /home/... spelling before comparison. Under WSL the disk candidate could otherwise never equal created.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.

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

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 53485b61-deb6-4aa8-a55b-25a5b4609789

📥 Commits

Reviewing files that changed from the base of the PR and between b7c8839 and 614f6e5.

📒 Files selected for processing (4)
  • src/main/git/worktree-listing.ts
  • src/main/ipc/filesystem-auth.test.ts
  • src/main/ipc/registered-worktree-roots-cache.ts
  • src/main/ipc/worktrees-test-harness.ts

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

Comment on lines +34 to +36
// 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()

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.

🔒 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/ipc

Repository: 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.ts

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

One commit landed since the prior review, retiring the last open concern from the d16305e review.

  • Prune on proof only — isRootGoneFromDisk retires a recovered root only when stat returns a definitive ENOENT; a transient EACCES/EIO/EPERM or 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 — registerCreatedWorktreeRoot now 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.ts asserts 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.

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

@nwparker
nwparker merged commit 1268fb5 into main Aug 30, 2026
32 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

[Bug]: worktree.create fails with "Worktree created but not found in listing" although the worktree is actually created

1 participant