Skip to content

fix(worktrees): route unstamped local worktrees local in the two states #16841 still fails closed - #16829

Merged
nwparker merged 6 commits into
stablyai:mainfrom
LesleyMurfin:ai/16733-local-worktree-owner-fallback
Sep 15, 2026
Merged

nwparker merged 6 commits into
stablyai:mainfrom
LesleyMurfin:ai/16733-local-worktree-owner-fallback

Conversation

@LesleyMurfin

@LesleyMurfin LesleyMurfin commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Status — scope reduced, and the headline fix is no longer mine

#16733 is already closed. It was fixed by #16841 ("fix(routing): resolve unstamped local
worktrees to the local host (STA-5683)"
), merged 2026-08-27, and the issue closed with it. This
branch predates that merge and originally claimed the whole fix. It no longer does, and nothing
here asks to close #16733
— that credit is #16841's.

This branch was rebased onto upstream/main at 1d1b73c408 (which contains #16841) and
reconciled with it. Correcting that reference: this branch's true merge-base with main is
6a47d2831f ("fix(native-chat): scope composer file drops to the pane that received them
(#19328)"
), which is a descendant of 1d1b73c408 and therefore also contains #16841; main has
advanced since and its tip is now 12f2c6b991.

What survives is the part #16841 does not cover: two states that still
fail a genuinely local git worktree closed.
Both fixes now coexist inside
resolveWorktreeOperationRouteResult — #16841's stricter identity rule is kept intact, and this
branch narrows itself to fit inside it rather than around it.

Measured against the rebase base (#16841 alone), 6 of the 66 targeted tests still fail; with
this branch, 66/66 pass. Those 6 are the two families below.

The two residual fail-closed states

The relevant base tail is hydrated && (no saved runtimes || hasDetectedWorktree). It is false in
exactly two shapes that are nonetheless local:

  1. Listed-but-unstamped worktree with no detected row yet — runtimes saved, catalog hydrated.
    The worktree is present in worktreesByRepo but absent from detectedWorktreesByRepo, so the
    tail is false and the row fails closed.
    • worktree-operation-route.test.ts › keeps a local worktree local when an unrelated runtime is saved
  2. Saved runtime with hydration still in progress — runtimeEnvironmentCatalogHydrated: false,
    so the tail is false regardless of how unambiguous the rows are.
    • worktree-operation-route.test.ts › keeps a local worktree local while the saved-runtime catalog is still hydrating

Checked directly, not assumed: with the source file reverted to the base and the tests left as they
are on this branch, both cases return { kind: 'missing' }
(AssertionError: expected { kind: 'missing' } to deeply equal { kind: 'resolved', … }). With the
branch's source, both return the local route.

Conceded to #16841 on purpose — please do not read this as reopening it

The original branch also routed repo-row-only identity (a known repo, no worktree row at all)
to local. #16841 deliberately fails that closed — a repo row is repo identity, not worktree
identity — and its test
fails a paired-client ownerless stale publication closed instead of routing it locally asserts
exactly that. That case is given up, not re-argued. The new branch is gated behind
hasKnownWorktree, and #16841's test passes here unmodified.

ELI5

Saving a remote environment should not stop an ordinary local workspace from opening a terminal. This follow-up fixes two remaining cases: Orca knows the local worktree but has not detected it on this scan, or the saved environment list is still loading. Known SSH and remote owners keep their routes, and unknown worktrees still fail closed.

What Changed

One new branch in resolveWorktreeOperationRouteResult
(src/renderer/src/lib/worktree-operation-route.ts), plus the small helper it delegates to.
+73 / -2 in the source file.

                       resolveWorktreeOperationRouteResult
                                    │
        ┌───────────────────────────┼───────────────────────────┐
        │                           │                           │
   active workspace          folder workspace            explicit catalog
   host selected             (#10251 carve-out)          (stamped rows)
        │                           │                           │
     resolved                   resolved                    resolved
                                                                │ missing
                                                                ▼
                                                   positive identity check
                                                   (known repo OR worktree)
                                                                │
                                          ┌─────────────────────┴──────────┐
                                       unknown                          known
                                          │                                │
                                       missing                    active runtime?
                                                                           │
                                                      ┌────────────────────┴────────┐
                                                     yes                           no
                                                      │                             │
                                            runtime: / missing        ►► NEW: known WORKTREE row
                                                                         (listed or detected)?
                                                                              │        │
                                                                             no       yes
                                                                              │        │
                                                             #16841's tail    │   every repo row
                                                             (unchanged)      │   for this id
                                                                              │   unstamped/local?
                                                                              │        │    │
                                                                              │      yes    no
                                                                              │        │    │
                                                                              │    local   #16841's
                                                                              │            tail
  • hasKnownWorktree gate — the branch is only reachable when a worktree row is known, listed
    or currently detected
    . This is the reconciliation with fix(routing): resolve unstamped local worktrees to the local host (STA-5683) #16841: a repo row alone is repo identity,
    not worktree identity, so it no longer routes anything local.
  • resolveUnstampedLocalWorktreeRoute(state, repoId) — returns a local route only when a repo
    row for the id exists and every matching row resolves to LOCAL_EXECUTION_HOST_ID via
    getRepoExecutionHostId. No repo row → null. Any row disagreeing → null, so contradictions
    stay a refusal rather than becoming a default.
  • The pre-existing mayBeLegacyLocal tail — the code fix(routing): resolve unstamped local worktrees to the local host (STA-5683) #16841 amended — is left intact and still
    handles everything that reaches it.
  • 'local' is the existing LOCAL_EXECUTION_HOST_ID sentinel — no new vocabulary.

One pre-existing test was re-aimed, and I want that called out rather than buried, because it
asserted one of the states above. (The original version of this PR re-aimed two; the second is the
repo-row-only case now conceded to #16841, so that test is back to untouched.)

Was Now
fails ownerless rows closed until the saved-runtime catalog is hydrated — runtimeEnvironments: [], unhydrated fails ownerless rows closed mid-hydration while a saved runtime could own them — no repo row or active runtime, two saved runtimes, a detected worktree row, unhydrated

It arrived with #9994 (41751dd90d), whose goal — fail closed for missing or stale owners — is
kept, and #16841 did not touch it. Its fixture did not describe a missing owner though: it carried a
present-but-unstamped repos: [{ id: 'repo-1' }] with no saved runtime at all, a state three
places in this codebase already read as locally owned (getRepoExecutionHostId,
resolveRepoOwnershipEvidence in main/ipc/worktrees/listing/worktree-host-ownership.ts, and
Repo.executionHostId's documented contract in shared/repo-types.ts). It is re-pointed at the
state it was actually defending — mid-hydration where a saved runtime genuinely could own the row
— so fail-closed coverage is not reduced, and the state it vacates is re-asserted with its corrected
expected result in the #16733 block. Reviewer's call if you would rather I keep it verbatim and
gate differently; I think the re-aim is the honest reading, but it is the one judgement call left in
here.

Why

savedRuntimeIds.length === 0 was the original defect, and #16841 already removed most of its
sting. What remains is the same category error in two narrower places: the count of saved
environments, and the hydration status of that list, say nothing about who owns this worktree.
An unrelated runtime existing in settings is not evidence of ambiguity, and neither is a list that
has not finished loading — yet either one still flips a recognised worktree to { kind: 'missing' }.

The approach is not new reasoning — it is the reasoning already written into
resolveFolderWorkspaceOperationRoute in the same file, whose comment describes this bug for the
other workspace kind:

// Why: a found folder record is positive identity evidence, so keep terminal-owner parity;
// the worktree legacy hydration gates would fail local folders closed whenever unrelated
// runtimes exist — the exact #10251 symptom.

Why this is safe rather than a loosening. Every row that carries host provenance routes above
the new branch and never reaches it:

  • a stamped repo row routes through resolveIndexedRepoOperationRoute, which only skips rows
    where both executionHostId and connectionId are empty (worktree-operation-catalog-route.ts:94);
  • a stamped worktree row routes through resolveIndexedWorktreeOwner / exactRoutes, so it
    still outranks its unstamped repo;
  • an active runtime keeps its existing precedence, ambiguity refusal included;
  • and after reconciliation, a row with no worktree identity at all no longer reaches it either.

So the branch is reachable only for rows that carry no host evidence and have a known worktree —
precisely the legacy pre-owner-projection shape, local by construction.

Scale. Not a corner case in an aged store: on the reporting deployment, 181 of 569 worktree rows
under live repos carry no host stamp and every repo row lacks both fields. An earlier stamping pass
fixed the rows that existed then; the create path does not write the stamp, so everything created
since is unstamped again. Hand-stamping rows is therefore a treadmill, not a fix.

Deliberate behavioural note: the new branch resolves local even when
removedRuntimeEnvironmentIds is non-empty. That is intentional and symmetric with the folder
carve-out — an unstamped row is not evidence of having belonged to a deleted runtime either.
Covered by keeps a local worktree local after an unrelated runtime has been removed. Flag it if
you disagree; it is easy to gate.

Linked Issue

Relates to #16733 — already closed by #16841 (merged 2026-08-27). Intentionally not
Fixes #16733: this PR must not close an issue it did not fix. It is the residual follow-up
described at the top.

Visual Proof

Independent review at c8bf96b exercised New tab → New Terminal in a hidden macOS Electron renderer using a real disposable Git repo and a synthetic legacy catalog (unstamped repo/worktree, no detected rows, no selected host, one unrelated saved environment).

Before: the baseline routing source returns missing and clicking New Terminal creates no tab.

Before: New Terminal produces no tab

After: the exact PR head opens a real local terminal; printf ORCA_LOCAL_PR16829_OK executes successfully.

After: local shell executes successfully

This proves the local renderer/PTY flow. It is not a reproduction of the original Windows-desktop-paired-to-headless-Linux deployment.

Independent validation — 2026-09-07

  • Exact PR head changed suites: 66/66 on Windows awin, Linux openclaw (via Orca SSH terminal), and macOS.
  • macOS broader routing, generation, editor/explorer and destructive owner-boundary checks: 125 tests passed total.
  • Baseline routing source with PR tests: six failures / 60 passes; restored exact head passes all 66.
  • pnpm tc:web, targeted oxlint and oxfmt checks pass.
  • No proven code findings from the readiness review. SSH/runtime ownership precedence and folder parity remain covered.

Contributor testing (original report)

Gates on this branch, rebased onto upstream/main @ 1d1b73c408 (contains #16841), on Node
24.19.0 (the version engines pins — worth stating, because a stale Node 22 on PATH produces
widespread unrelated reds):

Gate Result
pnpm run typecheck (all projects) pass
pnpm run lint (full chain incl. reliability/ratchet/localization gates) pass
targeted suites (the 2 changed test files) 66 passed (66)
same 2 files, source reverted to base (#16841 only) 6 failed, 60 passed of 66 — the residual states
pnpm vitest run src/renderer/src/lib (scoped) 5182 passed, 1 skipped
pnpm run test (full) not green here — and not green on main either; see below

The 6 that fail on the base and pass here, i.e. exactly what this PR still buys:

× keeps a local worktree local when an unrelated runtime is saved
× keeps a local worktree local when several unrelated runtimes are saved
× keeps a local worktree local while the saved-runtime catalog is still hydrating
× keeps a local worktree local after an unrelated runtime has been removed
× routes a folder workspace and a git worktree alike in one local state (#16733)
× keeps a terminal routable on a local worktree while an unrelated runtime is saved

Reproduce the comparison:

pnpm vitest run --config config/vitest.config.ts \
  src/renderer/src/lib/worktree-operation-route.test.ts \
  src/renderer/src/lib/terminal-worktree-route.test.ts
#  Tests  66 passed (66)

git checkout upstream/main -- src/renderer/src/lib/worktree-operation-route.ts
pnpm vitest run --config config/vitest.config.ts \
  src/renderer/src/lib/worktree-operation-route.test.ts \
  src/renderer/src/lib/terminal-worktree-route.test.ts
#  Tests  6 failed | 60 passed (66)   <- the states #16841 still fails closed
git checkout HEAD -- src/renderer/src/lib/worktree-operation-route.ts

Coverage — the negative cases are the point, not the happy path:

  • resolves local: unrelated runtime saved; several unrelated runtimes; catalog still hydrating;
    unrelated runtime removed; no runtime saved; adapters with no runtime catalog at all.
  • still refuses: connection-owned repo never routes local; runtime-stamped repo never routes
    local; a host-stamped worktree row stays authoritative over its unstamped repo; a second
    connection-owned repo row for the id refuses; contradictory repo rows report ambiguous, not
    local; unknown id with neither repo nor worktree row still missing; ambiguous active runtime
    still fails closed; unambiguous active runtime stays authoritative over the local fallback; and
    fix(routing): resolve unstamped local worktrees to the local host (STA-5683) #16841's repo-row-only refusal, unmodified.
  • parity: a folder workspace and a git worktree in one identical local store route alike.

Platforms actually run: Linux (this is renderer-side pure routing logic with no platform branch;
I have not run the desktop client on Windows or macOS). The reported environment is Windows-desktop
paired to a headless Linux orca serve, which I could not reproduce end-to-end — noted plainly
rather than implied.

Being straight about the full suite. I will not tick pnpm test as clean, because it is not. On
the pre-rebase run I diffed the failing-file lists against a pristine upstream/main worktree in the
identical environment: 69 failing files on baseline, 74 on the branch, none only-in-baseline, and
each of the 5 differing files accounted for — 3 terminal-pane remote-runtime transport tests that
pass in isolation (30s-timeout tests under parallel load) and 2 src/main/runtime/orchestration-*
files that are skipped unless out/ build artifacts exist and fail identically on baseline once
built. The load-bearing point: none of the files this change touches or reads
(worktree-operation-route, terminal-worktree-route, worktree-owner-route,
worktree-operation-catalog-route) appears in any failing list, in any run.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Deliberately left unticked: I did not run the desktop client by hand. I do not have the
reporter's Windows-desktop-paired-to-headless-Linux-orca serve rig, and ticking a manual-test box
on the strength of unit tests would be exactly the kind of claim this template is trying to stop.
What I verified is stated above, no more than that.

AI Disclosure

AI-assisted. Claude (Anthropic, Opus-class) driving an agent harness on my machine, under my
direction: it did the code reading, wrote the tests and the fix, ran the gates, and performed the
rebase and reconciliation against #16841; I set the approach, reviewed every diff and commit
message, and I'm the one accountable for what's here. Flagging it because the template asks and
because you should weigh the diff knowing it — not as a disclaimer on its correctness.

One meta note in the spirit of the same honesty: issue #16733 itself was filed by my
svc-orca[bot] account
, which is an automation account of mine, not a third-party reporter. The
deployment numbers in it are from my own store. Same person, both ends — no independent
corroboration is being implied.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Not applicable — nothing here touches skill-installer source, tests, fixtures, registry entries,
path tables, or docs.

Notes

  • Destructive paths — the one thing I most want a reviewer to check.
    resolveWorktreeOperationRoute also feeds worktree removal, so missing → local means an
    unqualified removal on an unstamped row now proceeds locally where it previously refused with
    a toast. I believe that is correct and is the same bug in another costume — the row carries no
    remote evidence, so there is no remote thing that could be destroyed, and refusing to delete a
    local worktree is not a safety property, just the same fail-closed defect. Two guards that are
    safety properties are untouched and I verified both by reading, not assuming:

    • the STA-4343 host-qualified path is unaffected — a caller that confirmed a host routes through
      resolveWorktreeOperationRouteResultForHost → resolveSelectedHostRoute, neither of which
      calls the modified function at all;
    • the multi-host ambiguity refusal still uses getWorktreeOperationOwnerHostIds, also unmodified.

    host-qualified-removal-refusal.test.ts passes unchanged. Still — this is the judgement worth a
    second pair of eyes, more than the terminal case in the title.

  • Security: grants nothing new. The branch can only return the local sentinel, and only when
    no row carries host provenance. It cannot synthesise a runtime: or ssh: route, so it cannot
    cause an operation to be sent to a remote host that would not already have received it.

  • Cross-platform: pure renderer routing logic, no platform branch, no path handling.

  • Remote SSH: connection-owned and runtime-stamped rows route above the new branch and are
    covered by explicit negative tests; ssh:/HUB precedence from fix: route server project adds to selected runtime #11346 and fix(runtime): route HUB-owned SSH worktrees through owning runtime #9994 is untouched.

  • Mobile: not on this path.

  • Backwards compatibility: additive. The only behaviour that changes is missing → local for
    rows that have a known worktree and carry no host evidence; fix(routing): resolve unstamped local worktrees to the local host (STA-5683) #16841's tail is preserved for
    everything that reaches it, including the repo-row-only refusal.

  • Performance: one Array.prototype.filter over state.repos, on the fall-through path only —
    reached after the cached catalog index has already missed, and now only when a worktree row is
    already known. No new allocation on the hot resolved paths.

  • Not fixed here, on purpose: the create path still does not write a host stamp, which is why
    unstamped rows keep appearing. This PR makes the router correct for rows in that state rather than
    chasing both; say the word if you would rather see the stamp-on-create in the same change.

  • If you would rather not carry this at all: that is a legitimate call now that fix(routing): resolve unstamped local worktrees to the local host (STA-5683) #16841 has
    shipped the main fix. The two residual states are real and reproducible, but they are narrower
    than what this PR originally proposed, and I would rather it be closed knowingly than merged on
    the strength of a stale description.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

lint and typecheck pass locally on the rebased branch. pnpm test does not fully pass — nor
does it on main in the same environment
— so I have left that unticked rather than tick it on a
technicality. The measured diff, the isolation results, and the reason each differing file differs
are all in Testing; none of them touch this change's files.

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3d3b4f89-7454-40e9-bca0-5b7bd4b271b3

📥 Commits

Reviewing files that changed from the base of the PR and between d00e599 and 693dc85.

📒 Files selected for processing (1)
  • src/renderer/src/lib/worktree-operation-route.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/worktree-operation-route.ts

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


📝 Walkthrough

Walkthrough

The change routes known unstamped local worktrees locally when repository identity exists, even when unrelated runtime environments are saved. It uses LOCAL_EXECUTION_HOST_ID consistently and preserves fail-closed behavior for unknown worktrees. Tests cover hydration states, repository evidence without worktree identity, folder workspaces, terminal routability, and unknown worktree identifiers.

Priority: ⚪ Not assessed

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 693dc

The change adds local routing for known unstamped worktrees while retaining fail-closed behavior for unknown or conflicting ownership states. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address the residual requirements from #16733 by routing known unstamped local worktrees locally when unrelated runtimes exist or catalog hydration is incomplete. The changes retain fail-c…
Out of Scope Changes check ✅ Passed The source changes and tests are directly related to worktree operation routing and the linked issue. The added comments and regression coverage support the routing behavior. No unrelated code changes…
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 3 files.
Title check ✅ Passed The title clearly identifies the main change: routing unstamped local worktrees locally in the remaining fail-closed states. It is specific and related to the implementation, although the trailing #16…
Description check ✅ Passed The description is comprehensive and follows the repository template. It includes the ELI5 summary, change details, rationale, issue reference, visual proof, testing results, AI disclosure, boundary d…

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 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: aafebe0e-457e-4ee8-843c-688002030969

📥 Commits

Reviewing files that changed from the base of the PR and between 1d1b73c and b14857c66b52d7eceb8c9ebca900173c2a11f083.

📒 Files selected for processing (3)
  • src/renderer/src/lib/terminal-worktree-route.test.ts
  • src/renderer/src/lib/worktree-operation-route.test.ts
  • src/renderer/src/lib/worktree-operation-route.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/worktree-operation-route.ts

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

@svc-orca
svc-orca Bot force-pushed the ai/16733-local-worktree-owner-fallback branch 4 times, most recently from dbe57f9 to 80934b9 Compare September 7, 2026 20:28
@LesleyMurfin LesleyMurfin changed the title fix(worktrees): keep unstamped local git worktrees routable when a runtime is saved fix(worktrees): route unstamped local worktrees local in the two states #16841 still fails closed Sep 7, 2026
…es (stablyai#16733)

A local git worktree whose rows carry no host stamp fails every owner-routed
operation closed as soon as any runtime environment is saved, however unrelated.
resolveWorktreeOperationRouteResult establishes positive identity from the
worktree/repo catalogs, then discards it: with no runtime active the only exit is
the legacy-local gate, which demands an empty saved-runtime list. One saved
environment makes that false and the call returns { kind: 'missing' }.

These tests state the contract before the fix, so the claim that the fix is
purely additive can be checked rather than asserted. Committed red on purpose.

Observed at 5631aa0 (vitest run, both files):

  Tests  7 failed | 52 passed (59)

The 7 failing are exactly the states that must become local, plus their two
consumers:

  - an unrelated runtime is saved (the reported bug)
  - several unrelated runtimes are saved
  - the repo is known before its worktree row is listed
  - the saved-runtime catalog has not hydrated
  - an unrelated runtime was removed
  - resolveTerminalWorktreeRoute on such a worktree (the gate in front of the
    "Terminal creation is unavailable" reply)
  - the folder/worktree parity state: identical store, folder local, worktree
    missing

The other 52 pass now and must keep passing: connection-owned and
runtime-stamped repos never route local, a stamped worktree row still outranks
its repo, contradictory repo rows stay ambiguous, an ambiguous or hydrating
runtime focus still fails closed, and a genuinely unknown id still fails closed.
That set is the additive-only guarantee.
…ners (stablyai#16733)

Two cases in src/renderer/src/lib/worktree-operation-route.test.ts assert the
behaviour stablyai#16733 reports as the bug, so they have to move:

  - :158 'fails a paired-client ownerless stale publication closed instead of
    routing it locally'
  - :171 'fails ownerless rows closed until the saved-runtime catalog is hydrated'

Both arrived with stablyai#9994 (41751dd, route HUB-owned SSH worktrees through their
owning runtime), whose stated goal was to fail closed for missing or stale
owners. That goal is right and is kept. The premise being rebutted is narrower:
neither fixture describes a missing or stale owner. Each carries a present repo
row that is merely unstamped -- repos: [{ id: 'repo-1' }] -- and three places in
this codebase already read exactly that row as locally owned:

  - shared/execution-host.ts getRepoExecutionHostId returns LOCAL_EXECUTION_HOST_ID
  - main/ipc/worktrees/listing/worktree-host-ownership.ts resolveRepoOwnershipEvidence
    falls back to LOCAL_EXECUTION_HOST_ID, and the listing and removal paths trust it
  - shared/repo-types.ts documents executionHostId as the field runtime-host repos
    need precisely because they otherwise look identical to local repos

attribute. It swept in the legacy-local case because at the time nothing in this
resolver consulted the repo index for an unstamped row.

So each case is re-aimed at the state it was actually defending, and neither is
deleted -- the fail-closed coverage is not reduced, it is pointed at a real
missing owner:

  - the first becomes 'fails a paired-client publication closed when no repo row
    can own it': same runtime state, repos: []. A worktree row alone is not host
    evidence, so this still returns missing, before and after the fix.
  - the second becomes 'fails ownerless rows closed mid-hydration while a saved
    runtime could own them': an active runtime with an ambiguous saved catalog
    during hydration. This returns missing from the active-runtime branch and is
    untouched by the fix. It is worded to stay distinct from the neighbouring
    case at :185, which already covers focus-is-not-ownership with an empty
    catalog, rather than duplicating it.

The states these two cases vacate are re-asserted with their corrected expected
result in the stablyai#16733 block added by the previous commit. Suite unchanged at
7 failed | 52 passed (59): the rewrites pass, the 7 reds are still the 7 states
the fix must convert.
… are saved (stablyai#16733)

resolveWorktreeOperationRouteResult establishes positive identity from the
worktree and repo catalogs, then discards it. With no runtime active the only
exit is the legacy-local gate, which requires an empty saved-runtime list, so one
saved runtime environment -- connected or not, related or not -- made it false
and the call returned { kind: 'missing' }. Every owner-routed operation on a
genuinely local git worktree then failed closed, and because
resolveTerminalWorktreeRoute is the sole gate in front of
terminal-request-ipc-bridge.ts, the user saw "Terminal creation is unavailable
because the worktree owner could not be resolved".

Folder workspaces hit the same gate and were carved out in stablyai#10251/stablyai#10269, whose
comment in this file states the principle and names this exact failure mode: a
found record is positive identity evidence, and the worktree legacy hydration
gates "would fail local folders closed whenever unrelated runtimes exist". Git
worktrees never got the equivalent. This adds it, in the same shape and the same
function.

The rule is not new. An unstamped repo row is read as locally owned by
getRepoExecutionHostId, by main's resolveRepoOwnershipEvidence, and by
Repo.executionHostId's own documentation; and the repo write path
(repoWithFetchedOwner) stamps runtime: and ssh: owners at fetch time, so an
unstamped row is a legacy row that predates owner projection -- local by
construction. The router now consults that evidence instead of contradicting it.
The sidebar already rendered these worktrees as Local; this removes the
disagreement rather than adding a heuristic.

Four properties this change holds to:

1. The branch sits after the active-runtime block, so an unambiguous active
   runtime still wins (routes runtime:<id>, not local) and an ambiguous or
   mid-hydration focus still returns missing. That ordering is structural, not
   incidental.
2. mayBeLegacyLocal is left byte-identical (verified: both 7-line hunks hash to
   f0ed1b4287c646cb). The new branch does take over the two states where a local
   repo row exists and no runtime is saved, but returns the identical local
   route, so no input changes its answer -- only which branch produced it.
3. The helper returns null on anything but unanimous local, so the branch can
   only ever convert missing into local. It never returns ambiguous: a
   contradiction between repo rows is already decided upstream by
   resolveExplicitWorktreeOperationRouteResult, and answering it here would be a
   second, divergent authority.
4. It reads neither runtimeEnvironmentCatalogHydrated nor
   removedRuntimeEnvironmentIds. That is sound rather than merely convenient,
   because it consults host evidence rather than runtime-environment inference: a
   runtime-owned repo row is stamped runtime:<id> at fetch time, so neither an
   unhydrated runtime catalog nor a removed environment can turn an unstamped row
   into a remote one.

Control only reaches this point after the explicit catalog resolver returned
missing, which means every worktree row and every repo row for this id is
unstamped -- any stamped row routes ssh: or runtime: earlier, and two disagreeing
rows return ambiguous earlier. There is no remote-owned state left here to leak.

Out of scope, deliberately: who wins when a runtime is focused (stablyai#11512), and
back-filling Worktree.hostId at creation time, which is a persistence migration
over worktreeMeta and does nothing for the users already carrying unstamped rows.

The 7 cases red in the two preceding commits now pass; the 52 that guard the
fail-closed contract are unchanged.

  Test Files  2 passed (2)
       Tests  59 passed (59)
…-closed rule (stablyai#16733)

Upstream stablyai#16841 (merged d347595) landed its own fix for stablyai#16733 and drew the
positive-identity line one notch tighter than this branch did: its
'does not treat a repo row alone as positive local identity' case asserts that a
worktree id no row has ever listed stays `missing`, even when the repo row for
its repoId is local.

This branch's 'routes a known local repo before its worktree row has been listed'
asserted the opposite result for that identical state, so the two cannot both
hold. Main's rule is the safer reading — a repo row is repo identity, not
worktree identity — so the reconciled code gates
resolveUnstampedLocalWorktreeRoute on hasKnownWorktree and this case is dropped
rather than re-pinned. Every state that actually reproduces stablyai#16733 keeps a
worktree row (listed or detected), so the reported bug and both extra
fail-closed edge cases this branch fixes are unaffected.
@svc-orca
svc-orca Bot force-pushed the ai/16733-local-worktree-owner-fallback branch from 80934b9 to c8bf96b Compare September 7, 2026 21:14
@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed and review finished.

…eUnstampedLocalWorktreeRoute

resolveWorktreeOperationRouteResult only calls resolveUnstampedLocalWorktreeRoute after
resolveExplicitWorktreeOperationRouteResult has already returned 'missing' for this repoId.
That function (worktree-operation-catalog-route.ts) indexes every repo row carrying a
non-empty executionHostId or connectionId and resolves/ambiguous-es on any of them, so by
construction every row resolveUnstampedLocalWorktreeRoute ever sees is unstamped -- and
getRepoExecutionHostId's own fallback (shared/execution-host.ts) always resolves an unstamped
row to local. The per-row disagreement check could never actually return null; it was dead
defensive code describing a state the caller's short-circuit already rules out. Reduced to
an existence check with identical behavior (verified: same 66/66 tests, same mutation-proof
property -- reverting only this file still fails exactly the same 6 tests it did before).
Also harmonized a same-function 'local' string literal to the LOCAL_EXECUTION_HOST_ID constant
already in use one branch above it, and dropped a dangling getWorktreeExecutionHostId doc
reference the shipped code never actually calls.

@LesleyMurfin LesleyMurfin left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verdict: SAFE TO MERGE.

Reviewed at head d00e599e47ac against base d0506bf5de0d (main). Verified independently — not taken from the PR description: live gh pr view metadata, full diff read, source read of resolveWorktreeOperationRouteResult / resolveUnstampedLocalWorktreeRoute and the upstream functions they compose with, and direct test execution including a red/green mutation proof (source reverted to the merge-base with the branch's own tests → 6/66 fail exactly as claimed; restored → 66/66; git diff HEAD empty both times). Typecheck (tsc --noEmit, all three pnpm tc projects) and lint (oxlint, all four configured passes plus the changed-code-quality gate) both pass clean on the 3 changed files, each confirmed genuine via a negative control. No CI ever reported on this branch (statusCheckRollup empty) — the above is a from-scratch reproduction, not a rubber stamp of a badge.

What's good

src/renderer/src/lib/worktree-operation-route.ts:180-183,232-239 — both new comment blocks name the exact invariant and cite the three call sites that already treat an unstamped repo row as local (getRepoExecutionHostId, resolveRepoOwnershipEvidence, repo-types.ts). I re-derived the same argument independently from worktree-operation-catalog-route.ts before reading the comment, and it holds: resolveIndexedRepoOperationRoute skips any row where both executionHostId and connectionId are blank, so a stamped row — including one that disagrees with an unstamped sibling — is always caught upstream and returns resolved/ambiguous before resolveUnstampedLocalWorktreeRoute is reached. Reaching it therefore guarantees every row for the id is unstamped, and getRepoExecutionHostId's own fallback resolves an unstamped row to local unconditionally — so the plain .some() existence check is behaviorally equivalent to a per-row check, just enforced by control flow. Confirmed against this repo's own docs/reference/ssh-execution-boundary.md Rule 1 (no silent substitution): the guard tests for connection-owned and runtime-stamped rows pass, so no SSH-owned repo is ever routed local by this change.

Commit 7306a818d9's message is a good model of "teach the why": it names the exact invariant, cites the same three call sites, and states the suite's pass count before and after the rename.

Findings (informational, non-blocking)

PR body: diff-size claim is off. “+52 / -1 in the source file” vs. actual +49 / -2 (gh api, git apply --stat). Cosmetic.

PR body: rebase-base SHA is stale. 1d1b73c408 is a real ancestor of HEAD and does contain #16841, but the true merge-base with current upstream/main is the newer 6a47d2831f. Worth a rebase before merge given mergeStateStatus: UNSTABLE.

Docstring coverage: 75% vs. the configured 80% threshold (CodeRabbit pre-merge check, 4 functions across 3 files). Everything else in that automated check passed.

Checked and cleared

  • Test-rename accounting — exactly one test was renamed on this branch (fails ownerless rows closed until the saved-runtime catalog is hydrated → fails ownerless rows closed mid-hydration while a saved runtime could own them), matching the PR body's disclosure. A second suspected rename (fails a paired-client ownerless stale publication closed instead of routing it locally) traced to a no-op: upstream #16841 already made the equivalent fixture edit before this branch rebased onto it: the test is byte-identical between base and HEAD.
  • Review threads — the one CodeRabbit thread on this PR is resolved and outdated (anchored to a pre-rebase commit); the later pass against the current head reported zero actionable comments.
  • Scope — exactly 3 files touched (source + 2 test files), no drive-by changes.
  • Issue/PR references — #16733 closed, #16841 merged, both as claimed.

No code-correctness objection. This is a written verdict only — no approval, merge, or push taken beyond posting this review.

@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

Heads-up rather than a request: this PR is ready from my side — the change is verified locally and the description has been corrected.

CI hasn't run yet. Both required workflow runs on 693dc85 are sitting at action_required, which is the fork-PR approval gate — they need a maintainer to hit Approve and run workflows on the Checks tab. Flagging it only because the checks read as stalled rather than pending.

Happy to rebase or adjust anything if it would help.

@nwparker

Copy link
Copy Markdown
Contributor

Fresh behavioral verification (2026-09-11), exact head 693dc8555dc:

Hidden Windows Electron desktop paired with an isolated real Linux server:

  • UI New Terminal opened an unstamped local Windows worktree, printed PR16829_WINDOWS_PAIRED_LOCAL_OK in Git Bash on awin.
  • The same app opened a remote terminal, printed PR16829_LINUX_REMOTE_OK, Linux, and /tmp/pr16829-remote-fixture on the Linux host.
  • Local non-Git folder terminal printed PR16829_FOLDER_OK.
  • All three screenshots downloaded and visually inspected. Catalog ownership fields were deliberately removed to model the legacy unstamped state; the unrelated Linux runtime remained saved/paired.

Wrong-host negative: production beginHostQualifiedRemoval called in the renderer with same-ID local/remote competing rows refused with “Workspace identity is ambiguous across hosts. Refresh projects and try again.” This was a production-guard fixture, not an actual UI/filesystem delete. Unknown missing identities and remote routes remained protected. Current routing tests 66/66 and destructive guards 29/29 pass.

Merge risk LOW for the tested change; no proven negative user regression. Native WSL and destructive filesystem operations were not exercised in this loop. Five owned test tabs closed and owned app/server/display shut down. No merge performed.

@nwparker
nwparker merged commit 946dacc into stablyai:main Sep 15, 2026
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
stablyai#16841 still fails closed (stablyai#16829)

* test(worktrees): cover local worktree owner routing with saved runtimes (stablyai#16733)

A local git worktree whose rows carry no host stamp fails every owner-routed
operation closed as soon as any runtime environment is saved, however unrelated.
resolveWorktreeOperationRouteResult establishes positive identity from the
worktree/repo catalogs, then discards it: with no runtime active the only exit is
the legacy-local gate, which demands an empty saved-runtime list. One saved
environment makes that false and the call returns { kind: 'missing' }.

These tests state the contract before the fix, so the claim that the fix is
purely additive can be checked rather than asserted. Committed red on purpose.

Observed at 5631aa0 (vitest run, both files):

  Tests  7 failed | 52 passed (59)

The 7 failing are exactly the states that must become local, plus their two
consumers:

  - an unrelated runtime is saved (the reported bug)
  - several unrelated runtimes are saved
  - the repo is known before its worktree row is listed
  - the saved-runtime catalog has not hydrated
  - an unrelated runtime was removed
  - resolveTerminalWorktreeRoute on such a worktree (the gate in front of the
    "Terminal creation is unavailable" reply)
  - the folder/worktree parity state: identical store, folder local, worktree
    missing

The other 52 pass now and must keep passing: connection-owned and
runtime-stamped repos never route local, a stamped worktree row still outranks
its repo, contradictory repo rows stay ambiguous, an ambiguous or hydrating
runtime focus still fails closed, and a genuinely unknown id still fails closed.
That set is the additive-only guarantee.

* test(worktrees): re-aim two fail-closed cases at genuinely missing owners (stablyai#16733)

Two cases in src/renderer/src/lib/worktree-operation-route.test.ts assert the
behaviour stablyai#16733 reports as the bug, so they have to move:

  - :158 'fails a paired-client ownerless stale publication closed instead of
    routing it locally'
  - :171 'fails ownerless rows closed until the saved-runtime catalog is hydrated'

Both arrived with stablyai#9994 (41751dd, route HUB-owned SSH worktrees through their
owning runtime), whose stated goal was to fail closed for missing or stale
owners. That goal is right and is kept. The premise being rebutted is narrower:
neither fixture describes a missing or stale owner. Each carries a present repo
row that is merely unstamped -- repos: [{ id: 'repo-1' }] -- and three places in
this codebase already read exactly that row as locally owned:

  - shared/execution-host.ts getRepoExecutionHostId returns LOCAL_EXECUTION_HOST_ID
  - main/ipc/worktrees/listing/worktree-host-ownership.ts resolveRepoOwnershipEvidence
    falls back to LOCAL_EXECUTION_HOST_ID, and the listing and removal paths trust it
  - shared/repo-types.ts documents executionHostId as the field runtime-host repos
    need precisely because they otherwise look identical to local repos

attribute. It swept in the legacy-local case because at the time nothing in this
resolver consulted the repo index for an unstamped row.

So each case is re-aimed at the state it was actually defending, and neither is
deleted -- the fail-closed coverage is not reduced, it is pointed at a real
missing owner:

  - the first becomes 'fails a paired-client publication closed when no repo row
    can own it': same runtime state, repos: []. A worktree row alone is not host
    evidence, so this still returns missing, before and after the fix.
  - the second becomes 'fails ownerless rows closed mid-hydration while a saved
    runtime could own them': an active runtime with an ambiguous saved catalog
    during hydration. This returns missing from the active-runtime branch and is
    untouched by the fix. It is worded to stay distinct from the neighbouring
    case at :185, which already covers focus-is-not-ownership with an empty
    catalog, rather than duplicating it.

The states these two cases vacate are re-asserted with their corrected expected
result in the stablyai#16733 block added by the previous commit. Suite unchanged at
7 failed | 52 passed (59): the rewrites pass, the 7 reds are still the 7 states
the fix must convert.

* fix(worktrees): keep unstamped local worktrees routable when runtimes are saved (stablyai#16733)

resolveWorktreeOperationRouteResult establishes positive identity from the
worktree and repo catalogs, then discards it. With no runtime active the only
exit is the legacy-local gate, which requires an empty saved-runtime list, so one
saved runtime environment -- connected or not, related or not -- made it false
and the call returned { kind: 'missing' }. Every owner-routed operation on a
genuinely local git worktree then failed closed, and because
resolveTerminalWorktreeRoute is the sole gate in front of
terminal-request-ipc-bridge.ts, the user saw "Terminal creation is unavailable
because the worktree owner could not be resolved".

Folder workspaces hit the same gate and were carved out in stablyai#10251/stablyai#10269, whose
comment in this file states the principle and names this exact failure mode: a
found record is positive identity evidence, and the worktree legacy hydration
gates "would fail local folders closed whenever unrelated runtimes exist". Git
worktrees never got the equivalent. This adds it, in the same shape and the same
function.

The rule is not new. An unstamped repo row is read as locally owned by
getRepoExecutionHostId, by main's resolveRepoOwnershipEvidence, and by
Repo.executionHostId's own documentation; and the repo write path
(repoWithFetchedOwner) stamps runtime: and ssh: owners at fetch time, so an
unstamped row is a legacy row that predates owner projection -- local by
construction. The router now consults that evidence instead of contradicting it.
The sidebar already rendered these worktrees as Local; this removes the
disagreement rather than adding a heuristic.

Four properties this change holds to:

1. The branch sits after the active-runtime block, so an unambiguous active
   runtime still wins (routes runtime:<id>, not local) and an ambiguous or
   mid-hydration focus still returns missing. That ordering is structural, not
   incidental.
2. mayBeLegacyLocal is left byte-identical (verified: both 7-line hunks hash to
   f0ed1b4287c646cb). The new branch does take over the two states where a local
   repo row exists and no runtime is saved, but returns the identical local
   route, so no input changes its answer -- only which branch produced it.
3. The helper returns null on anything but unanimous local, so the branch can
   only ever convert missing into local. It never returns ambiguous: a
   contradiction between repo rows is already decided upstream by
   resolveExplicitWorktreeOperationRouteResult, and answering it here would be a
   second, divergent authority.
4. It reads neither runtimeEnvironmentCatalogHydrated nor
   removedRuntimeEnvironmentIds. That is sound rather than merely convenient,
   because it consults host evidence rather than runtime-environment inference: a
   runtime-owned repo row is stamped runtime:<id> at fetch time, so neither an
   unhydrated runtime catalog nor a removed environment can turn an unstamped row
   into a remote one.

Control only reaches this point after the explicit catalog resolver returned
missing, which means every worktree row and every repo row for this id is
unstamped -- any stamped row routes ssh: or runtime: earlier, and two disagreeing
rows return ambiguous earlier. There is no remote-owned state left here to leak.

Out of scope, deliberately: who wins when a runtime is focused (stablyai#11512), and
back-filling Worktree.hostId at creation time, which is a persistence migration
over worktreeMeta and does nothing for the users already carrying unstamped rows.

The 7 cases red in the two preceding commits now pass; the 52 that guard the
fail-closed contract are unchanged.

  Test Files  2 passed (2)
       Tests  59 passed (59)

* test(worktrees): defer repo-row-only routing to stablyai#16841's fail-closed rule (stablyai#16733)

Upstream stablyai#16841 (merged d347595) landed its own fix for stablyai#16733 and drew the
positive-identity line one notch tighter than this branch did: its
'does not treat a repo row alone as positive local identity' case asserts that a
worktree id no row has ever listed stays `missing`, even when the repo row for
its repoId is local.

This branch's 'routes a known local repo before its worktree row has been listed'
asserted the opposite result for that identical state, so the two cannot both
hold. Main's rule is the safer reading — a repo row is repo identity, not
worktree identity — so the reconciled code gates
resolveUnstampedLocalWorktreeRoute on hasKnownWorktree and this case is dropped
rather than re-pinned. Every state that actually reproduces stablyai#16733 keeps a
worktree row (listed or detected), so the reported bug and both extra
fail-closed edge cases this branch fixes are unaffected.

* refactor(worktrees): drop the unreachable disagreement loop in resolveUnstampedLocalWorktreeRoute

resolveWorktreeOperationRouteResult only calls resolveUnstampedLocalWorktreeRoute after
resolveExplicitWorktreeOperationRouteResult has already returned 'missing' for this repoId.
That function (worktree-operation-catalog-route.ts) indexes every repo row carrying a
non-empty executionHostId or connectionId and resolves/ambiguous-es on any of them, so by
construction every row resolveUnstampedLocalWorktreeRoute ever sees is unstamped -- and
getRepoExecutionHostId's own fallback (shared/execution-host.ts) always resolves an unstamped
row to local. The per-row disagreement check could never actually return null; it was dead
defensive code describing a state the caller's short-circuit already rules out. Reduced to
an existence check with identical behavior (verified: same 66/66 tests, same mutation-proof
property -- reverting only this file still fails exactly the same 6 tests it did before).
Also harmonized a same-function 'local' string literal to the LOCAL_EXECUTION_HOST_ID constant
already in use one branch above it, and dropped a dangling getWorktreeExecutionHostId doc
reference the shipped code never actually calls.

* docs(routing): document the undocumented worktree operation route helpers
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]: Local git worktrees fail closed with "Terminal creation is unavailable" when any runtime environment is saved

2 participants