Skip to content

fix(routing): resolve unstamped local worktrees to the local host (STA-5683) - #16841

Merged
brennanb2025 merged 3 commits into
mainfrom
brennan/sta-5683-bug-local-git-worktrees-fail-closed-with-terminal-creation
Aug 27, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennan/sta-5683-bug-local-git-worktrees-fail-closed-with-terminal-creation

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​211 $\color{#cf222e}{\Huge{\mathbf{−}}}$​13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​198
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​10 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​5

ELI5

What this looked like before

You had a perfectly normal local worktree that worked fine. Then you saved a remote server in Settings → Remote Orca Servers — maybe to try it once, maybe for a different project entirely. You didn't select it. You didn't use it.

That workspace stopped working. Specifically:

  • Clicking + → New Terminal did nothing at all. No terminal, no error, no toast — the click just went nowhere.
  • The File Explorer showed Could not load files for this workspace: Couldn't determine which host owns this workspace.
  • Resuming an agent session from Agent Session History or the AI Vault failed with "Terminal creation is unavailable because the worktree owner could not be resolved."
  • The workspace otherwise looked completely normal in the sidebar, so there was no hint about what was wrong.

And the obvious fix didn't work. Deleting the saved server did not bring the workspace back — Orca remembered that a server had once existed, and that memory kept the workspace shut. Restarting didn't help either. In practice the only way out was to never save a remote server at all, which means giving up remote runtimes entirely.

On one real setup this hit 181 of 569 worktrees the moment a single server was saved.

What this looks like after

  • + → New Terminal opens a terminal, like it always should have.
  • File Explorer lists your files.
  • Agent sessions resume.
  • Saving, using, and deleting remote servers has no effect on your local worktrees — they're unrelated, and now Orca treats them that way.
  • If you delete a server, nothing stays broken behind you.

You no longer have to choose between using remote servers and using your local worktrees.

What was actually going wrong

Every workspace lives on some machine — your laptop, an SSH box, or a remote server. Before opening a terminal, Orca has to answer: which machine does this belong to? If it can't answer, it refuses, because guessing could run your commands on the wrong computer. That refusal is the right instinct; it was just firing on the wrong input.

Older workspace records don't have the machine written on them. To decide whether a blank record meant "your laptop", Orca looked at something unrelated: how many remote servers you had saved. None saved meant "must be local, go ahead". One or more meant "I can't tell" — even though that server had nothing to do with the folder in question. The count of servers in your Settings says nothing about where one particular folder lives, and that was the bug.

While fixing it we found the blank records weren't only old leftovers — Orca was still creating them. When it asked a remote server for its list of worktrees, it addressed the request to the remote server but filed the answers as if they'd come from your laptop, leaving the machine blank. So genuinely-remote workspaces were being recorded with no owner. A naive fix would have then confidently called those "local", which is the dangerous direction — that's how a delete lands on the wrong machine.

What changed

  1. Records get labelled correctly when they arrive. If Orca asks a remote server for worktrees, it now writes that server down as the owner instead of leaving it blank.
  2. Saying "local" now requires real evidence — the workspace actually turning up in a scan of your machine — rather than being assumed because nothing said otherwise. And the number of servers you've saved is no longer treated as evidence of anything.

The safety behaviour people rely on is unchanged: a workspace on an SSH box still routes to that box, a workspace on a remote runtime still routes to that runtime, a workspace that genuinely could be on two machines still refuses rather than guessing, and an unknown workspace still fails closed.

Summary

  • Stamp ownerless worktree results from a remote runtime with the captured execution host before repo hydration, including modern detected-list, legacy worktree.list, remote create, and lineage responses.
  • Tighten legacy ownerless routing so saved-runtime configurations require current detected presence while preserving the hydrated empty-catalog local fallback during the create-before-scan window.
  • Keep explicit SSH/runtime ownership, duplicate-host ambiguity, unknown identities, and ownerless stale remote publications fail-closed.

Reachability and root cause

YES: the fully ownerless remote shape was reachable before this fix. When an active runtime worktree refresh ran before its repo row hydrated, the RPC used the focused runtime settings, but repoHostId fell back to local; withRepoHostOwnership intentionally does not stamp a local host, so an older remote host that omitted ownership fields placed fully ownerless remote rows in both worktreesByRepo and detectedWorktreesByRepo. The same gap covered the legacy worktree.list fallback.

Persistence does not directly seed either worktree map: they initialize empty, and persisted session rehydration only synthesizes runtime placeholders with explicit repo/worktree host IDs or SSH placeholders beneath repos with a connectionId. Runtime repo RPC rows are client-stamped, and push-style worktree notifications trigger a host-qualified refresh instead of carrying raw rows.

The ingest fix makes repoHostId fall back to the focused execution host, matching the host that receives the RPC and stamping remote results with hostId and runtimeOwnerEnvironmentId before indexing. The resolver fix then permits an ownerless row only when the runtime catalog is unavailable, when the catalog is hydrated and empty, or when the row has current detected presence.

Detected catalog safety invariant

detectedWorktreesByRepo is host-aggregated, not local-only. Both visible and detected-only refreshes call mergeDetectedWorktreesForHost for whichever local, runtime, or SSH host was fetched.

The safety property is the conjunction of ownerless identity and current detected presence, under the writer invariant that every remote origin stamps ownership before indexing, with explicit owner routing evaluated first. A detected row is therefore not local evidence by itself: stamped remote rows resolve through their explicit owner and never reach the legacy local fallback. With a hydrated empty saved-runtime catalog, no runtime can originate a remote ownerless row, and SSH ingest is always explicitly host-qualified; preserving the empty-catalog fallback restores the pre-PR local behavior without reopening the reachable remote path.

Tests and safety guards

  • Added modern and old-host ingestion regressions proving pre-repo remote results are stamped in both worktree maps.
  • Restored the paired-client ownerless stale-publication fail-closed regression.
  • Added and mutation-tested the zero-saved-runtime create-before-detected-scan regression.
  • Kept one-runtime and several-runtime unstamped-local reproductions green with current detected evidence, including the removed-runtime tombstone case.
  • Updated remote create, refresh, and lineage tests to require client-side runtime ownership projection.
  • Existing unknown-id, unhydrated-catalog, focused-runtime, explicit-owner, SSH, folder-workspace, generation-fence, terminal-route, and ambiguity guards remain green.

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Worktree routing now uses detected-worktree evidence when runtime catalogs are hydrated and supports local resolution for unstamped local worktrees. Remote worktree fetch, lineage updates, and creation tests now require runtime host and owner environment metadata. Repository host resolution falls back to the settings-focused execution host when no valid host ID is supplied.

Merge Risk: 🟡 Moderate · up to fe75f

The routing change can still direct stale ownerless remote worktrees to the local host in an empty hydrated catalog, potentially causing operations to target the wrong worktree. This bounded correctness risk requires a fix or explicit owner acceptance before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the primary change: routing unstamped local worktrees to the local host.
Description check ✅ Passed The description is detailed, on-topic, and explains the problem, root cause, implementation, safety behavior, tests, and QA results. It does not reproduce every template heading and does not include a…
Full details: Description check

Explanation

The description is detailed, on-topic, and explains the problem, root cause, implementation, safety behavior, tests, and QA results. It does not reproduce every template heading and does not include an issue link or visual-proof entry, but the main required information is present.

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

@brennanb2025
brennanb2025 force-pushed the brennan/sta-5683-bug-local-git-worktrees-fail-closed-with-terminal-creation branch from 32dddd7 to a2046a9 Compare August 27, 2026 19:53
@brennanb2025

Copy link
Copy Markdown
Contributor Author

STA-5683 Electron QA (FIXED build)

Isolated Electron of this worktree (devWorktreeName: sta-5683-bug-local-git-worktrees-fail-closed-wit, CDP 9334). Did not attach to Brennan's running Orca. Constructed the reported unstamped local git worktree by adding a fixture repo, then clearing host stamps on repos + worktreesByRepo + detectedWorktreesByRepo. Saved environments were dummy catalog injects (activeRuntimeEnvironmentId stayed null). Tab-bar + → New Terminal ⌘T was clicked through the real UI.

# Scenario Result
1 Unstamped, zero saved envs → + creates a terminal PASS Terminal 1→2
2 Unstamped, one saved env, not selected → + creates a terminal; File Explorer loads files PASS Terminal 2→3; explorer listed README.md (no owner error)
3 Several saved envs (count is irrelevant) PASS Terminal 3→4
4 Save then delete env (tombstones present) → + still works PASS Terminal 4→5
5 Stamped ssh: / runtime: rows must not become local PASS (CDP eval below)
6 Unknown/stale worktree id still fails closed PASS (CDP eval below)

Headline routing for scenario 2 (pre-fix this was {kind:'missing'} / null):

op: {"kind":"resolved","route":{"executionHostId":"local","runtimeEnvironmentId":null}}
term: {"runtimeEnvironmentId":null}

Scenario 5 / 6 raw resolutions

ssh stamped:     {"kind":"resolved","route":{"executionHostId":"ssh:fake-target","runtimeEnvironmentId":null}}
runtime stamped: {"kind":"resolved","route":{"executionHostId":"runtime:some-env-id","runtimeEnvironmentId":"some-env-id"}}
stale unknown:   {"kind":"missing"}  terminal=null

Screenshots

1 — unstamped, zero envs, before +. Terminal 1, File Explorer lists README.md, status bar not stuck.

01-unstamped-zero-envs-before-plus.png

1 — after + / New Terminal. Terminal 2 created.

02-unstamped-zero-envs-plus-created-terminal.png

2 — unstamped + one unselected saved env, before + (headline bug shape). Explorer still lists README.md. Dummy injected server shows its own Remote-host Connecting… chip; that is not the workspace-owner fail-closed (which previously also hid files behind Couldn't determine which host owns this workspace).

03-unstamped-one-env-before-plus.png

2 — after + / New Terminal. Terminal 3 created. This is the path that previously no-op'd.

04-unstamped-one-env-plus-created-terminal.png

3 — three saved envs, before +.

05-unstamped-several-envs-before-plus.png

3 — after + / New Terminal. Terminal 4 created.

06-unstamped-several-envs-plus-created-terminal.png

4 — catalog emptied, four removedRuntimeEnvironmentIds tombstones, before +. Connecting chip gone. Explorer still lists README.md.

07-unstamped-deleted-env-tombstone-before-plus.png

4 — after + / New Terminal. Terminal 5 created. Pre-fix, tombstones kept this fail-closed.

08-unstamped-deleted-env-tombstone-plus-created-terminal.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop status — ready for human review, not yet merged

Eight orchestrated lanes across macOS, Linux, and Windows. Head fe75f169ae.

Reproduction — confirmed on 3 platforms

Platform Agent Result
macOS grok REPRODUCED (unit + isolated Electron)
Linux grok REPRODUCED against a real Docker SSH target; remote SSH worktree still routed to ssh:<target> (must-not-regress baseline)
Windows codex Mutation both ways: 48 pass with the fix, 6 fail without it

The reproduction lanes refuted three claims in the issue, and the PR reflects what is actually true rather than what was reported:

  1. The create path is not the source of unstamped rows — repos.add stamps executionHostId/hostId as local on current main. The affected population is legacy rows.
  2. Deleting the environment does not restore the worktree — removedRuntimeEnvironmentIds tombstones kept the gate shut, so there was no recovery path at all.
  3. Clicking + shows no toast — it silently no-ops. The quoted toast is the IPC path (terminal-request-ipc-bridge.ts). What users actually see is a dead +, plus Couldn't determine which host owns this workspace in File Explorer.

The fix got bigger after review, for a real reason

The first cut resolved any ownerless identity to local on hydration alone. Closing readiness returned FAIL / keep-P1: that deleted the deliberate #9994 paired-client fence.

Settling the disputed question found a live defect, not a legacy ghost: fetchWorktrees derived its request host via repoHostId, which returned local before the repo row hydrated, while settingsForRepoOwner still sent the RPC to the focused runtime. withRepoHostOwnership(…, 'local') then preserved an absent hostId, so worktrees fetched from a remote host were recorded fully ownerless. The same gap covered the legacy worktree.list fallback.

So the PR now fixes ingest and tightens the resolver, and the #9994 fence is restored verbatim.

Correcting one thing stated earlier in this PR

detectedWorktreesByRepo is host-aggregated, not local-only — both refresh paths call mergeDetectedWorktreesForHost for whichever host was fetched. Detected presence alone is not local evidence. The safety property is the conjunction of ownerless identity plus current detected presence, under the invariant that every remote writer stamps ownership before indexing, with explicit owner routing evaluated first.

Verification

  • Every new test mutation-tested: reverting each production change fails the matching tests, restoring passes. Independently re-run by the coordinator, not taken on report.
  • All required GitHub checks green, including cross-version wire compatibility and package (windows).
  • Electron QA on the fixed build: 6/6 scenarios PASS (screenshots in the comment above), including stamped ssh:/runtime: rows staying non-local and unknown ids still failing closed.
  • Two independent four-seat findings-severity counsels with blind peer rating. Round 2: F1 dropped 4×, no P0/P1, no revert authorized.

Known and tracked

  • A Remote host connection status: Connecting… chip appears in the QA fixtures. That is the injected dummy environment, not this bug — overallStatus() never consults the owner resolver.
  • Remaining scan-window gap with saved runtimes present (pane parks as terminalOwnerUnresolved and misses the remount path) is pre-existing and narrowed by this PR, tracked as STA-5749. The zero-saved-runtime half was a regression this PR introduced and is fixed in fe75f169ae.

Reviewer attention

Two judgement calls change deliberate prior behaviour and deserve human sign-off:

  1. Removing the removedRuntimeEnvironmentIds tombstone gate. Traced through stale-runtime-host-rows.ts → purge-stale-runtime-host-state.ts → host-catalog-fencing.ts: a row genuinely left by a removed runtime is either stamped or purged, so an unrelated tombstone is never attribution. Keeping it left users with no recovery path.
  2. The repoHostId ingest fallback now routes through the focused execution host. This is the root-cause fix, but it is the widest-blast-radius line in the diff.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f27c1b9-2a53-4d95-84db-9efdc2a42298

📥 Commits

Reviewing files that changed from the base of the PR and between b75133b and fe75f16.

📒 Files selected for processing (2)
  • 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.test.ts

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

Comment on lines +223 to +227
// Why: no saved runtime can publish a remote ownerless row; otherwise current detected presence affirms identity under the stamped-writer invariant.
const mayBeLegacyLocal =
(savedRuntimeIds === undefined ||
(state.runtimeEnvironmentCatalogHydrated === true && savedRuntimeIds.length === 0)) &&
(state.removedRuntimeEnvironmentIds?.size ?? 0) === 0
savedRuntimeIds === undefined ||
(state.runtimeEnvironmentCatalogHydrated === true &&
(savedRuntimeIds.length === 0 || hasDetectedWorktree))

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Require detected-worktree evidence after catalog hydration.

When runtimeEnvironmentCatalogHydrated is true and savedRuntimeIds is empty, this branch resolves stale ownerless remote rows to the local host without checking hasDetectedWorktree. Require current detected-worktree evidence for every hydrated-catalog fallback.

Proposed fix
-      (savedRuntimeIds.length === 0 || hasDetectedWorktree))
+      hasDetectedWorktree)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Why: no saved runtime can publish a remote ownerless row; otherwise current detected presence affirms identity under the stamped-writer invariant.
const mayBeLegacyLocal =
(savedRuntimeIds === undefined ||
(state.runtimeEnvironmentCatalogHydrated === true && savedRuntimeIds.length === 0)) &&
(state.removedRuntimeEnvironmentIds?.size ?? 0) === 0
savedRuntimeIds === undefined ||
(state.runtimeEnvironmentCatalogHydrated === true &&
(savedRuntimeIds.length === 0 || hasDetectedWorktree))
// Why: no saved runtime can publish a remote ownerless row; otherwise current detected presence affirms identity under the stamped-writer invariant.
const mayBeLegacyLocal =
savedRuntimeIds === undefined ||
(state.runtimeEnvironmentCatalogHydrated === true &&
hasDetectedWorktree)

@brennanb2025
brennanb2025 merged commit d347595 into main Aug 27, 2026
48 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…A-5683) (stablyai#16841)

* fix(routing): resolve unstamped local worktrees

* fix(routing): preserve remote worktree ownership

* fix(routing): restore empty-catalog local fallback

(cherry picked from commit d347595)
svc-orca Bot pushed a commit to LesleyMurfin/orca that referenced this pull request Sep 7, 2026
…-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.
nwparker pushed a commit that referenced this pull request Sep 15, 2026
#16841 still fails closed (#16829)

* test(worktrees): cover local worktree owner routing with saved runtimes (#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 (#16733)

Two cases in src/renderer/src/lib/worktree-operation-route.test.ts assert the
behaviour #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 #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 #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 (#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 #10251/#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 (#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 #16841's fail-closed rule (#16733)

Upstream #16841 (merged d347595) landed its own fix for #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 #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
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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…A-5683) (stablyai#16841)

* fix(routing): resolve unstamped local worktrees

* fix(routing): preserve remote worktree ownership

* fix(routing): restore empty-catalog local fallback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant