Skip to content

fix(ssh): never claim authority over host tabs this client could not place - #16956

Merged
nwparker merged 13 commits into
mainfrom
nwparker/sta3593-unplaced-host-tabs
Aug 28, 2026
Merged

nwparker merged 13 commits into
mainfrom
nwparker/sta3593-unplaced-host-tabs

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

A host tab row this client cannot place is unverifiable, not absent

Fixes STA-3593 — a fresh client connects to a direct-SSH host that has 3 terminal tabs open and adopts 0 of them, permanently.

It also closes a data-loss path that is live on main today: the same client goes on to upload its empty picture, deleting the host's tabs.

ELI5

You come back to your remote machine. It still has your three terminals running. Orca asks it "what have you got?", gets the right answer, and throws all three away — because at that moment it hadn't finished loading its own list of which folders live on that machine. Not knowing where a tab belongs isn't the same as the tab not existing, but the code treated it as the same thing.

It then wrote down "synced, all done". And because "all done" is what gives Orca permission to push its copy back, it later pushed that empty copy to the machine and deleted the three real terminals.

This PR makes Orca notice it couldn't place the tabs, and refuse to call that an answer — so it neither hides them nor overwrites them.

Root cause

exactTargetWorktreeIds (remote-workspace-snapshot-apply.ts:41) derives the target's worktree scope from state.worktreesByRepo / detectedWorktreesByRepo. On an initial connect the host workspace snapshot is applied before that scope contains the host's repo path — worktreesByRepo is populated by the scheduler's repo-refresh leases, a different path from the lineage merge. So the scope is empty when the snapshot lands.

From there the failure is silent and total:

Step File What happens
1 remote-workspace-snapshot-apply.ts:41 exactTargetWorktreeIds → empty set
2 remote-workspace-session-merge.ts uniqueWorktreeIdByPath(∅) returns null for every host path
3 remote-workspace-session-projection.ts the tabsByWorktreePath loop hits if (!worktreeId) continue → every tab row dropped, silently
4 remote-workspace-snapshot-apply.ts:138 markRemoteWorkspaceHydrated + 'synced' — the empty result is declared authoritative

Step 3 is the category error this codebase already names. An unplaceable path means our catalog has not landed; it is never evidence the row is not ours. Per docs/reference/ssh-execution-boundary.md that is unverifiable, and unverifiable must not collapse into a neighbour.

Correction. Earlier revisions of this description attributed the empty scope to a 'degraded' return from readLineage (direct-ssh-reconnect-preparation.ts:181). That is wrong, and testing disproved it: an agent planted 200 real worktrees on a remote host specifically to blow DIRECT_SSH_HOST_READ_TIMEOUT_MS, and worktreesByRepo never emptied — Orca filters external worktrees, so the deadline never fired. mergeExactHostLineage merges worktreeLineageById / workspaceLineageByChildKey, not worktreesByRepo, so that route could not produce this state. The ordinary initial connect does, with no provocation at all.

Step 4 is worse than it looks: it deletes the host's tabs

Hydration is not just a display flag. It is the upload permission:

  • use-app-session-persistence.ts:92 filters uploads to remoteWorkspaceHydratedTargetIds;
  • an upload is workspace.patch with kind: 'replace-session' — remote-workspace-relay-sync.ts:66;
  • replace-session wholesale replaces the host snapshot — relay/workspace-session-handler.ts:146-152.

So on main today, a degraded lineage plus any later local session mutation is sufficient for the client to overwrite the host's tab list with its own empty projection. A suppressed upload is deferred and recoverable. A wiped host snapshot is not.

It also flips the seeding gate: workspace-terminal-host-authority.ts:45 reads "not hydrated" as unverifiable and refuses to seed, so marking hydrated authorises a fresh default tab beside the host's orphaned ones.

Fix

Two files, one rule: report what you could not place, and never claim authority over a picture you could not assemble.

  1. src/shared/remote-workspace-session-projection.ts — new optional ImportOptions.onUnplacedTerminalTabs, fired per path carrying > 0 tabs that resolveWorktreeId could not place. The silent continue becomes observable. No return-type change; every existing caller is untouched.
  2. src/renderer/src/hooks/remote-workspace-snapshot-apply.ts — the apply returns 'placed' | 'unplaced' | 'not-applied'. markRemoteWorkspaceHydrated + 'synced' happen only on 'placed'. On 'unplaced' it instead revokes hydration and sets phase 'conflict'.

Both halves of that are load-bearing, and neither is obvious:

  • Revoke, don't just withhold. The hydrated set is add-only (ssh.ts), so withholding protects only a target that never synced. One that synced cleanly and later hit a degraded lineage keeps its flag — and keeps uploading the incomplete picture. clearRemoteWorkspaceHydrated closes that.
  • 'conflict', not 'error'. workspace-terminal-host-authority.ts treats offline/error on an un-hydrated target as its bounded floor and resolves them to 'none' — which authorises seeding and sleeping-agent resume, the double---resume this gate exists to prevent. 'conflict' sits outside that set, so authority stays 'unverifiable', and it is independently excluded from uploads by use-app-session-persistence.ts:93.

Recovery needs no new machinery: syncAfterConnect and applyUnsolicitedSnapshot already re-pull on the next connect or host push.

What was removed, and why that is the interesting part

Earlier revisions of this PR carried a bounded re-pull chain that retried the degraded lineage in-session. It is gone. Across review it produced twelve defects — unbounded retry, dead retry, a cancelled final attempt, a wedged chain, repeated exhaustion, overlapping chains, stale-callback cleanup corrupting a newer chain, and a dropped report — every one of them in code that passed the full suite at the time it was written.

It bought only faster recovery within a single connection. Dropping it costs a retry, never the data. The surviving rule is the one that was correct in the first commit.

Two further P1s were then found in the simplified code — the add-only hydration set and the 'error' phase above. Both are fixed. Worth recording that the pre-existing tests passed with both fixes reverted; the two new tests each fail when their own fix is reverted individually. Every one of the twelve defects was ultimately a check passing on a proxy rather than on the thing it claimed.

One reversal is worth recording, because it was mine and the evidence overturned it: the chain originally marked the target hydrated on exhaustion, reasoning that a permanently un-hydrated target never uploads again. That is backwards — not uploading is the safe failure. Hydrating on a known-incomplete picture is what destroys host state.

Backward compatibility

  • No wire change. onUnplacedTerminalTabs is client-local and optional; the host publishes nothing new.
  • No schema or persistence change, so no rollback hazard.
  • The happy path is unchanged: a snapshot whose rows all place still marks hydrated and 'synced' with the same fields. Pinned by an explicit test.

Fix evidence

Fail-without-fix verified by forcing placement to 'placed' and re-running — both oracles go red:

 FAIL  remote-workspace-unplaced-upload-suppression.test.tsx
       > issues no upload for a target whose host tabs it could not place
 FAIL  remote-workspace-snapshot-unplaced-tab-adoption.test.ts
       > does not call the empty result authoritative when the local catalog never landed
 Tests  2 failed | 3 passed (5)

Restored, then:

$ pnpm test src/renderer/src/hooks/ src/shared/ src/renderer/src/app-shell/ src/renderer/src/lib/
 Test Files  1179 passed | 4 skipped (1183)
      Tests  11526 passed | 67 skipped (11593)
$ pnpm tc          exit 0
$ npx oxlint       clean

The upload-suppression test asserts the upload itself never names an unplaced target, through the real persistence gate — not the hydrated flag. That matters: every one of the ten defects above was a check passing on a proxy instead of the thing it claimed.

Residual risk

exactTargetWorktreeIds returns only gitWorktreeIds, while the export side filters on the repo's connectionId. A reviewer confirmed folder-workspace rows cannot currently reach tabsByWorktreePath (folder:<id> keys fail splitWorktreeId), so the asymmetry is not reachable today — but the two sides are not derived from one definition, and nothing enforces that they stay aligned. Worth a separate issue.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Remote workspace session import now reports terminal tabs that cannot be mapped to local worktrees. Direct SSH snapshot application returns placement status. Fully placed snapshots become hydrated and synced. Unplaced snapshots clear hydration and enter the conflict phase with pull metadata. Target synchronization no longer schedules re-pulls for unplaced snapshots. Tests cover placement, hydration, authority, synchronization phases, and upload suppression.

Merge Risk: 🟠 High · up to b58ec

The PR correctly prevents incomplete host-tab snapshots from becoming authoritative, but two merge-readiness risks remain: an upload already queued before authority is revoked may still replace the host snapshot, and a later offline/error transition may allow terminal or agent activity without an authoritative snapshot. These can cause host-state loss or conflicting terminal actions, so the PR is not ready to merge without fixes or explicit acceptance.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 36 functions across 12 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 describes the primary SSH fix: preventing authority claims over host tabs that the client could not place.
Description check ✅ Passed The description is detailed and directly covers the problem, root cause, fix, rationale, linked issue, testing evidence, compatibility, and residual risk. It does not include every template heading, s…
Full details: Description check

Explanation

The description is detailed and directly covers the problem, root cause, fix, rationale, linked issue, testing evidence, compatibility, and residual risk. It does not include every template heading, such as an explicit Visual Proof section or checklist, but the core 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-apply.ts (1)

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

Reduce the duplicated incident narrative. Keep the invariant concise and retain the detailed failure analysis in the issue or SSH-boundary documentation.

  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L77-L84: reduce the type comment to the placement invariant and recovery action.
  • src/renderer/src/hooks/remote-workspace-snapshot-unplaced-tab-adoption.test.ts#L1-L20: reduce the test preamble to the scenario and expected result.
    As per coding guidelines, “DO NOT: be verbose, explain the obvious, walk through the code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 00e8bd9f-9037-4d4c-a361-2e03854dfbc4

📥 Commits

Reviewing files that changed from the base of the PR and between 6f3c5cc and 5a09190.

📒 Files selected for processing (7)
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-unplaced-tab-adoption.test.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.ts
  • src/renderer/src/hooks/remote-workspace-unplaced-snapshot-repull.test.ts
  • src/renderer/src/hooks/remote-workspace-unplaced-snapshot-repull.ts
  • src/shared/remote-workspace-session-projection.test.ts
  • src/shared/remote-workspace-session-projection.ts

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

Comment on lines 121 to +126
const worktreeIds = exactTargetWorktreeIds(state, authority)
const unplacedTabWorktreePaths: string[] = []
const remoteSession = importRemoteWorkspaceSession(snapshot.session, {
resolveWorktreeId: uniqueWorktreeIdByPath(worktreeIds),
executionHostId: toSshExecutionHostId(authority.targetId)
executionHostId: toSshExecutionHostId(authority.targetId),
onUnplacedTerminalTabs: (worktreePath) => unplacedTabWorktreePaths.push(worktreePath)

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 | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- applicable repository convention files ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print

printf '%s\n' '--- target file outline ---'
ast-grep outline src/renderer/src/hooks/remote-workspace-snapshot-apply.ts

printf '%s\n' '--- target implementation ---'
sed -n '1,190p' src/renderer/src/hooks/remote-workspace-snapshot-apply.ts

printf '%s\n' '--- directly bound definitions and related contracts ---'
rg -n -C 5 'exactTargetWorktreeIds|resolveDirectSshTargetScope|uniqueWorktreeIdByPath|importRemoteWorkspaceSession|onUnplacedTerminalTabs|gitWorktreeIds|folderWorkspace' src docs

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- convention scopes ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print | sort | head -80

printf '%s\n' '--- convention headers and learnings headers ---'
for f in /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/*/*.md; do
  [ -f "$f" ] || continue
  printf '\n### %s\n' "$f"
  head -5 "$f"
done

printf '%s\n' '--- exact target symbols ---'
rg -n -C 8 \
  'exactTargetWorktreeIds|resolveDirectSshTargetScope|uniqueWorktreeIdByPath|importRemoteWorkspaceSession|onUnplacedTerminalTabs|DirectSshSnapshotPlacement' \
  src/renderer/src/hooks/remote-workspace-snapshot-apply.ts \
  src/renderer/src src/shared \
  --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- applicable conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-renderer.md

printf '%s\n' '--- snapshot target-scope caller ---'
sed -n '35,76p' src/renderer/src/hooks/remote-workspace-snapshot-apply.ts

printf '%s\n' '--- target-scope return contract ---'
sed -n '1,80p' src/renderer/src/lib/direct-ssh-target-scope.ts
sed -n '232,330p' src/renderer/src/lib/direct-ssh-target-scope.ts

printf '%s\n' '--- path resolver implementation ---'
sed -n '330,375p' src/renderer/src/hooks/remote-workspace-session-merge.ts

printf '%s\n' '--- remote session import path ---'
sed -n '1,35p' src/shared/remote-workspace-session-projection.ts
sed -n '145,195p' src/shared/remote-workspace-session-projection.ts

printf '%s\n' '--- folder workspace identity construction ---'
rg -n -C 6 'folderWorkspaceToWorktree|folderWorkspaceKey|splitWorktreeId|getWorktreeHostIdentity' \
  src/shared src/renderer/src/lib src/renderer/src/hooks \
  --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- workspace-key parsing ---'
cat -n src/shared/workspace-scope.ts
rg -n -C 5 'function splitWorktreeId|export function splitWorktreeId|splitWorktreeId' src/shared/worktree src/shared --glob '*.ts' | head -120

printf '%s\n' '--- scope types ---'
cat -n src/renderer/src/lib/direct-ssh-target-scope-types.ts

printf '%s\n' '--- merge contract and affected key flow ---'
rg -n -C 8 'function mergeDirectSshRemoteWorkspaceSession|export function mergeDirectSshRemoteWorkspaceSession|replaceWorkspaceKeys|worktreeIds' \
  src/renderer/src/hooks/remote-workspace-session-merge.ts \
  src/renderer/src/store \
  --glob '*.ts' --glob '*.tsx' | head -260

printf '%s\n' '--- direct SSH scope tests for folder workspaces ---'
rg -n -C 10 'folder|terminalWorkspaceKeys|gitWorktreeIds|lineageWorkspaceKeys' \
  src/renderer/src/lib/*direct-ssh*test*.ts \
  src/renderer/src/hooks/*snapshot*test*.ts \
  --glob '*.ts' | head -300

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- folder workspace projection ---'
cat -n src/shared/folder-workspace-worktree.ts

printf '%s\n' '--- merge implementation ---'
sed -n '1,180p' src/renderer/src/hooks/remote-workspace-session-merge.ts

printf '%s\n' '--- hydration validity and replacement ---'
sed -n '1,95p' src/renderer/src/store/terminals/workspace-terminal-row-plan.ts
rg -n -C 8 'hydrateWorkspaceSession|buildWorkspaceTerminalRowPlan|replaceWorkspaceKeys|validWorktreeIds' \
  src/renderer/src/store --glob '*.ts' --glob '*.tsx' | head -240

printf '%s\n' '--- snapshot apply tests and repull caller ---'
rg -n -C 12 'applyDirectSshRemoteWorkspaceSnapshot|unplaced|placement|createUnplacedSnapshotRepull' \
  src/renderer/src/hooks --glob '*snapshot*test*.ts' --glob '*repull*.ts' | head -320

Repository: stablyai/orca

Length of output: 50369


Include folder workspace paths in direct-SSH snapshot placement. resolveDirectSshTargetScope stores folder workspaces in terminalWorkspaceKeys, but exactTargetWorktreeIds returns only gitWorktreeIds. uniqueWorktreeIdByPath also cannot derive a path from folder:<id>. Map each applicable folder folderPath to its folderWorkspaceKey and use those keys for placement and hydration. Otherwise, folder terminal tabs can remain unplaced until the repull chain exhausts. Add a test that a direct-SSH folder snapshot returns placed and adopts all terminal tabs.

Source: Coding guidelines

@nwparker nwparker changed the title fix(ssh): a host tab row this client cannot place is unverifiable, not absent fix(ssh): never claim authority over host tabs this client could not place Aug 28, 2026

@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: f3a91c66-1658-48e5-97c9-474d5109ebce

📥 Commits

Reviewing files that changed from the base of the PR and between 5a09190 and b3c048d516d0dbbfaf62cf3d7f7f5fb3d7456608.

📒 Files selected for processing (5)
  • src/renderer/src/hooks/remote-workspace-target-sync.ts
  • src/renderer/src/hooks/remote-workspace-unplaced-snapshot-repull-wiring.test.ts
  • src/renderer/src/hooks/remote-workspace-unplaced-snapshot-repull.test.ts
  • src/renderer/src/hooks/remote-workspace-unplaced-snapshot-repull.ts
  • src/renderer/src/hooks/zzprobe-hydrateonexhaust.ts

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

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

🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-apply.ts (1)

163-170: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the new comments. Keep one short statement for each non-obvious invariant.

  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L163-L170: Reduce this to the invariant that unplaced snapshots remain unhydrated to prevent incomplete uploads.
  • src/renderer/src/app-shell/remote-workspace-unplaced-upload-suppression.test.tsx#L3-L13: Reduce this to the upload-suppression behavior under test.

As per coding guidelines: “DO NOT: be verbose … BE CONCISE. 1 LINE if possible.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c278152c-70dd-4ff0-bc6b-2fe2289a0712

📥 Commits

Reviewing files that changed from the base of the PR and between b3c048d516d0dbbfaf62cf3d7f7f5fb3d7456608 and e09ec61568ce98bb7405c6d8fc3a650ba143524d.

📒 Files selected for processing (3)
  • src/renderer/src/app-shell/remote-workspace-unplaced-upload-suppression.test.tsx
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.ts

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

@nwparker
nwparker force-pushed the nwparker/sta3593-unplaced-host-tabs branch from c5a5f79 to deccb54 Compare August 28, 2026 04:21

@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: 647b912e-67cd-4755-98fc-aa01a6721717

📥 Commits

Reviewing files that changed from the base of the PR and between c5a5f79111d5bc2201f325351008a6736137e049 and b58ec5c34108512352802571de5ca68586b7c47e.

📒 Files selected for processing (2)
  • src/renderer/src/hooks/remote-workspace-target-sync.ts
  • src/renderer/src/lib/workspace-terminal-host-authority.ts

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

…t absent

A degraded listLineage leaves worktreesByRepo empty, so exactTargetWorktreeIds
returns nothing, every host path fails to resolve, and importRemoteWorkspaceSession
silently dropped every tab row. The apply then marked the target hydrated and
'synced', freezing that emptiness in permanently — nothing re-pulls a hydrated
target (STA-3593).

The importer now reports unplaceable rows, the apply claims authority only when
every row landed, and a bounded chain re-pulls the missing input (catalog +
lineage). On exhaustion it settles back to the pre-fix behaviour so a genuinely
unplaceable path is never left worse off than today.
…once

Five defects in the first cut of the chain, all found before merge:

1. the caller owned the attempt counter, so an unsolicited host push re-armed
   it at 0 and the chain never exhausted - an unbounded workspace.get loop;
2. exhaustion never cleared the counter, so after one bad connection every
   later reconnect re-exhausted instantly and the retry was silently dead;
3. the exhaustion check preceded the armed-timer guard, letting a concurrent
   report cancel the still-pending final retry;
4. a rejected host read left no timer armed and nothing rescheduled, stranding
   the target on 'pulling' and un-hydrated forever - and an un-hydrated target
   never uploads again, the exact permanent degradation this design avoids;
5. exhaustion re-announced on every later report, re-marking hydrated and
   rewriting status on each host push.

The module now owns the counter, resetTarget gives each connection a fresh
chain, the armed guard precedes exhaustion, the timer body always reschedules
so any failure walks to exhaustion, and exhaustion is announced once.
Reversal of this branch's own exhaustion fallback, on evidence.

Hydration authorises uploads (use-app-session-persistence.ts), and an upload is
a workspace.patch of kind 'replace-session' (remote-workspace-relay-sync.ts:66)
which wholesale replaces the host snapshot (relay/workspace-session-handler.ts).
So marking a target hydrated on a picture we know is missing rows does not
'settle back to the old behaviour' - it uploads an empty projection that DELETES
the host tabs we failed to adopt. Suppressed uploads are recoverable; a wiped
host snapshot is not. That data loss is reachable on main today, because today
the apply marks hydrated immediately.

Exhaustion therefore reports 'error' and leaves the target un-hydrated, so
terminal authority stays 'unverifiable' and no upload can be built from it.

Also closes two chain-lifecycle gaps found in review:
- the callback dropped its timer guard before awaiting the host, leaving a gap
  in which a concurrent report armed a second overlapping chain and could trip
  exhaustion before the pending apply resolved; an in-flight guard now spans it;
- resetTarget could not cancel a callback already past its await, so a stale one
  rescheduled on top of the new connection's chain; chains are now generation
  stamped and a stale callback exits.
Two races found in review of the previous commit:

- schedule(target,'placed') cleared timer/count/exhaustion but did not
  invalidate an apply already in flight. When that apply later resolved
  'unplaced' its generation still matched, so it started a fresh chain from
  attempt 0; a host repeating placed pushes during each in-flight retry could
  reset the budget indefinitely. Retirement now bumps the generation too.

- the in-flight marker was a bare Set, so a superseded callback's finally
  deleted whichever marker was present - including one a newer generation had
  since taken. A later report could then arm an overlapping timer while that
  newer apply was still running. Ownership is now a target -> generation map and
  a callback releases only the marker it still owns.

resetTarget deliberately no longer drops the marker: its owner is the only party
that may release it, and clearing it there would let a new chain arm while the
superseded apply is still running.
…apply

Regression from the previous commit. Keeping the stale in-flight marker across
resetTarget stops overlap, but it also swallows the new connection's result: the
new apply reports 'unplaced', hits the guard because the superseded apply still
owns the marker, and the superseded callback then exits on its stale generation
without scheduling. Nothing replayed the dropped report, so no chain started -
the retry silently never ran for that connection.

A blocked unplaced report is now recorded, and the marker's owner replays it on
release. Only the stale path reaches the finally still owning the marker, so the
normal path - which released early and scheduled its own outcome - cannot replay
twice.
The chain produced ten defects across review - unbounded retry, dead retry,
cancelled final attempt, wedged chain, repeated exhaustion, overlapping chains,
stale-callback cleanup, a lost report - every one in code that passed the full
suite at the time. It bought only faster recovery *within* one connection:
syncAfterConnect and applyUnsolicitedSnapshot already re-pull on the next
connect or host push, so dropping it costs a retry, never the data.

What remains is the part that was correct from the first commit: the importer
reports rows it could not place, and an apply that could not place them neither
marks the target hydrated nor sets 'synced'. Because hydration is what
authorises uploads, and an upload wholesale replaces the host snapshot, that
single rule is what stops a client from deleting the host tabs it failed to
adopt.

Status is now 'error' rather than 'pulling': with no chain pending, 'pulling'
claimed a request that was not in flight.
… unplaced

Two holes in the previous commit, both found in review.

The hydrated set is add-only (ssh.ts), so withholding hydration only protects a
target that never synced. A target that synced cleanly and then reconnected with
a degraded lineage kept its flag, and hydration is what authorises uploads - so
it would still send a replace-session patch built from the incomplete picture
and delete the host tabs it had just failed to place. Hydration is now revoked,
not merely withheld.

The status phase was 'error'. workspace-terminal-host-authority.ts treats
'offline'/'error' on an un-hydrated target as its bounded floor and resolves
them to 'none' - which authorises seeding AND sleeping-agent resume, the exact
double-resume this gate exists to prevent. 'conflict' is the phase that actually
describes the situation, is excluded from uploads by use-app-session-persistence,
and is deliberately outside that floor set, so authority stays 'unverifiable'.

Both invariants are pinned by tests verified to fail when either fix is reverted
individually; the pre-existing tests passed with both reverted.
The phase drives the user-visible label ('Workspace sync conflict'); carrying an
'unavailable' message alongside it only risked contradicting that wherever the
message is surfaced.
…d wrapper

Two findings from the post-merge correctness sweep.

The bounded floor in workspace-terminal-host-authority.ts justified itself on
'remoteWorkspaceHydratedTargetIds is add-only, clearRemoteWorkspaceHydrated has
no production caller'. This branch adds that caller, so the premise is now false
and a future reader would have been misled by it. The comment records the real
consequence: a target that later lands on offline/error reaches the floor having
demonstrably answered, so seeding is authorised over live host terminals. Not a
regression - before revocation existed the same target was marked hydrated and
synced, reaching 'none' sooner - but the floor should learn to tell a revoked
target from one that never answered. Flagged for the SSH-v3 consolidation, where
one authoritative liveness source replaces this pair.

applyUnsolicitedSnapshot had become a pass-through to applyPreparedSnapshot,
carrying a docstring about a re-pull chain that no longer exists. The two
collapse back into one function.
Consolidation pass finding. The union was exported and threaded through two
modules, but no production consumer ever read it: remote-workspace-ipc-bridge.ts
discards the promise's value and syncAfterConnect ignored it. 'not-applied' was
not a placement at all, only 'this apply did not happen'.

That is a parallel verdict concept with no consumer - precisely what the SSH-v3
consolidation would have had to unpick. It collapses to a local
hasUnplacedTerminalTabs boolean and a void return.

The one test that asserted the return value now asserts adoption instead, which
is the observable outcome rather than a proxy for it. All five unplaced oracles
still fail when the placement decision is forced, verified individually.
Elegance pass. Kept the two non-obvious claims - absence cannot distinguish
'never told' from 'user closed', and uuid tab ids make a tombstoned id safe to
drop - and cut the incident narrative around them. The twice-reverted history in
remote-workspace-session-merge.ts is deliberately left alone: that one is
institutional memory about regressions, not restatement of the code.
The spec was a characterization test whose own title said 'because hydration is
marked even when adoption wrote nothing', and whose comment described exactly
the defect this branch fixes: markRemoteWorkspaceHydrated ran unconditionally
after the hydrate calls, so in the same tick adoption yielded zero, authority
flipped unverifiable -> none, and Terminal.tsx seeded a phantom tab. It polled
for hydrated === true, so the fix turned it red.

It now asserts hydrated === false, phase === 'conflict', and zero tabs - the
count measured before asserting rather than assumed, confirming the phantom seed
is gone. The phase is re-read after the tabs settle and asserted a second time,
because a conflict verdict a later apply flipped back would silently re-authorise
seeding and a single poll would miss it.

The fixme stays a fixme: this branch stops the client claiming false authority
and overwriting the host, but adoption is still the open gap. Declining to seed
is a safe wait, not the destination.

Three-legged A/B against fork point c72afda, spec byte-identical across the
first two legs:
  branch   + updated spec  -> PASS
  baseline + updated spec  -> FAIL 'never reported the unplaced snapshot as a conflict'
  baseline + original spec -> PASS (baseline actively exhibits the old behaviour)
@nwparker
nwparker force-pushed the nwparker/sta3593-unplaced-host-tabs branch from 0e2fd67 to 80e497b Compare August 28, 2026 04:56
@nwparker
nwparker merged commit b1fe907 into main Aug 28, 2026
27 of 28 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…place (stablyai#16956)

* fix(ssh): a host tab row this client cannot place is unverifiable, not absent

A degraded listLineage leaves worktreesByRepo empty, so exactTargetWorktreeIds
returns nothing, every host path fails to resolve, and importRemoteWorkspaceSession
silently dropped every tab row. The apply then marked the target hydrated and
'synced', freezing that emptiness in permanently — nothing re-pulls a hydrated
target (STA-3593).

The importer now reports unplaceable rows, the apply claims authority only when
every row landed, and a bounded chain re-pulls the missing input (catalog +
lineage). On exhaustion it settles back to the pre-fix behaviour so a genuinely
unplaceable path is never left worse off than today.

* fix(ssh): keep the re-pull chain bounded, unwedgeable, and announced once

Five defects in the first cut of the chain, all found before merge:

1. the caller owned the attempt counter, so an unsolicited host push re-armed
   it at 0 and the chain never exhausted - an unbounded workspace.get loop;
2. exhaustion never cleared the counter, so after one bad connection every
   later reconnect re-exhausted instantly and the retry was silently dead;
3. the exhaustion check preceded the armed-timer guard, letting a concurrent
   report cancel the still-pending final retry;
4. a rejected host read left no timer armed and nothing rescheduled, stranding
   the target on 'pulling' and un-hydrated forever - and an un-hydrated target
   never uploads again, the exact permanent degradation this design avoids;
5. exhaustion re-announced on every later report, re-marking hydrated and
   rewriting status on each host push.

The module now owns the counter, resetTarget gives each connection a fresh
chain, the armed guard precedes exhaustion, the timer body always reschedules
so any failure walks to exhaustion, and exhaustion is announced once.

* fix(ssh): never authorise uploads from a picture known to be incomplete

Reversal of this branch's own exhaustion fallback, on evidence.

Hydration authorises uploads (use-app-session-persistence.ts), and an upload is
a workspace.patch of kind 'replace-session' (remote-workspace-relay-sync.ts:66)
which wholesale replaces the host snapshot (relay/workspace-session-handler.ts).
So marking a target hydrated on a picture we know is missing rows does not
'settle back to the old behaviour' - it uploads an empty projection that DELETES
the host tabs we failed to adopt. Suppressed uploads are recoverable; a wiped
host snapshot is not. That data loss is reachable on main today, because today
the apply marks hydrated immediately.

Exhaustion therefore reports 'error' and leaves the target un-hydrated, so
terminal authority stays 'unverifiable' and no upload can be built from it.

Also closes two chain-lifecycle gaps found in review:
- the callback dropped its timer guard before awaiting the host, leaving a gap
  in which a concurrent report armed a second overlapping chain and could trip
  exhaustion before the pending apply resolved; an in-flight guard now spans it;
- resetTarget could not cancel a callback already past its await, so a stale one
  rescheduled on top of the new connection's chain; chains are now generation
  stamped and a stale callback exits.

* fix(ssh): scope re-pull in-flight ownership to a generation

Two races found in review of the previous commit:

- schedule(target,'placed') cleared timer/count/exhaustion but did not
  invalidate an apply already in flight. When that apply later resolved
  'unplaced' its generation still matched, so it started a fresh chain from
  attempt 0; a host repeating placed pushes during each in-flight retry could
  reset the budget indefinitely. Retirement now bumps the generation too.

- the in-flight marker was a bare Set, so a superseded callback's finally
  deleted whichever marker was present - including one a newer generation had
  since taken. A later report could then arm an overlapping timer while that
  newer apply was still running. Ownership is now a target -> generation map and
  a callback releases only the marker it still owns.

resetTarget deliberately no longer drops the marker: its owner is the only party
that may release it, and clearing it there would let a new chain arm while the
superseded apply is still running.

* fix(ssh): replay an unplaced report that was blocked by a superseded apply

Regression from the previous commit. Keeping the stale in-flight marker across
resetTarget stops overlap, but it also swallows the new connection's result: the
new apply reports 'unplaced', hits the guard because the superseded apply still
owns the marker, and the superseded callback then exits on its stale generation
without scheduling. Nothing replayed the dropped report, so no chain started -
the retry silently never ran for that connection.

A blocked unplaced report is now recorded, and the marker's owner replays it on
release. Only the stale path reaches the finally still owning the marker, so the
normal path - which released early and scheduled its own outcome - cannot replay
twice.

* refactor(ssh): drop the re-pull retry chain, keep the fix

The chain produced ten defects across review - unbounded retry, dead retry,
cancelled final attempt, wedged chain, repeated exhaustion, overlapping chains,
stale-callback cleanup, a lost report - every one in code that passed the full
suite at the time. It bought only faster recovery *within* one connection:
syncAfterConnect and applyUnsolicitedSnapshot already re-pull on the next
connect or host push, so dropping it costs a retry, never the data.

What remains is the part that was correct from the first commit: the importer
reports rows it could not place, and an apply that could not place them neither
marks the target hydrated nor sets 'synced'. Because hydration is what
authorises uploads, and an upload wholesale replaces the host snapshot, that
single rule is what stops a client from deleting the host tabs it failed to
adopt.

Status is now 'error' rather than 'pulling': with no chain pending, 'pulling'
claimed a request that was not in flight.

* test(ssh): name the upload-suppression case for the chainless design

* fix(ssh): revoke stale hydration and keep authority unverifiable when unplaced

Two holes in the previous commit, both found in review.

The hydrated set is add-only (ssh.ts), so withholding hydration only protects a
target that never synced. A target that synced cleanly and then reconnected with
a degraded lineage kept its flag, and hydration is what authorises uploads - so
it would still send a replace-session patch built from the incomplete picture
and delete the host tabs it had just failed to place. Hydration is now revoked,
not merely withheld.

The status phase was 'error'. workspace-terminal-host-authority.ts treats
'offline'/'error' on an un-hydrated target as its bounded floor and resolves
them to 'none' - which authorises seeding AND sleeping-agent resume, the exact
double-resume this gate exists to prevent. 'conflict' is the phase that actually
describes the situation, is excluded from uploads by use-app-session-persistence,
and is deliberately outside that floor set, so authority stays 'unverifiable'.

Both invariants are pinned by tests verified to fail when either fix is reverted
individually; the pre-existing tests passed with both reverted.

* fix(ssh): drop the mismatched message on the unplaced conflict status

The phase drives the user-visible label ('Workspace sync conflict'); carrying an
'unavailable' message alongside it only risked contradicting that wherever the
message is surfaced.

* docs+refactor(ssh): correct the authority floor's premise, drop a dead wrapper

Two findings from the post-merge correctness sweep.

The bounded floor in workspace-terminal-host-authority.ts justified itself on
'remoteWorkspaceHydratedTargetIds is add-only, clearRemoteWorkspaceHydrated has
no production caller'. This branch adds that caller, so the premise is now false
and a future reader would have been misled by it. The comment records the real
consequence: a target that later lands on offline/error reaches the floor having
demonstrably answered, so seeding is authorised over live host terminals. Not a
regression - before revocation existed the same target was marked hydrated and
synced, reaching 'none' sooner - but the floor should learn to tell a revoked
target from one that never answered. Flagged for the SSH-v3 consolidation, where
one authoritative liveness source replaces this pair.

applyUnsolicitedSnapshot had become a pass-through to applyPreparedSnapshot,
carrying a docstring about a re-pull chain that no longer exists. The two
collapse back into one function.

* refactor(ssh): delete the DirectSshSnapshotPlacement union

Consolidation pass finding. The union was exported and threaded through two
modules, but no production consumer ever read it: remote-workspace-ipc-bridge.ts
discards the promise's value and syncAfterConnect ignored it. 'not-applied' was
not a placement at all, only 'this apply did not happen'.

That is a parallel verdict concept with no consumer - precisely what the SSH-v3
consolidation would have had to unpick. It collapses to a local
hasUnplacedTerminalTabs boolean and a void return.

The one test that asserted the return value now asserts adoption instead, which
is the observable outcome rather than a proxy for it. All five unplaced oracles
still fail when the placement decision is forced, verified individually.

* docs(ssh): compress the tombstone rationale to its load-bearing WHY

Elegance pass. Kept the two non-obvious claims - absence cannot distinguish
'never told' from 'user closed', and uuid tab ids make a tombstoned id safe to
drop - and cut the incident narrative around them. The twice-reverted history in
remote-workspace-session-merge.ts is deliberately left alone: that one is
institutional memory about regressions, not restatement of the code.

* test(ssh): pin the fixed behaviour instead of the defect it replaced

The spec was a characterization test whose own title said 'because hydration is
marked even when adoption wrote nothing', and whose comment described exactly
the defect this branch fixes: markRemoteWorkspaceHydrated ran unconditionally
after the hydrate calls, so in the same tick adoption yielded zero, authority
flipped unverifiable -> none, and Terminal.tsx seeded a phantom tab. It polled
for hydrated === true, so the fix turned it red.

It now asserts hydrated === false, phase === 'conflict', and zero tabs - the
count measured before asserting rather than assumed, confirming the phantom seed
is gone. The phase is re-read after the tabs settle and asserted a second time,
because a conflict verdict a later apply flipped back would silently re-authorise
seeding and a single poll would miss it.

The fixme stays a fixme: this branch stops the client claiming false authority
and overwriting the host, but adoption is still the open gap. Declining to seed
is a safe wait, not the destination.

Three-legged A/B against fork point c72afda, spec byte-identical across the
first two legs:
  branch   + updated spec  -> PASS
  baseline + updated spec  -> FAIL 'never reported the unplaced snapshot as a conflict'
  baseline + original spec -> PASS (baseline actively exhibits the old behaviour)

(cherry picked from commit b1fe907)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…place (stablyai#16956)

* fix(ssh): a host tab row this client cannot place is unverifiable, not absent

A degraded listLineage leaves worktreesByRepo empty, so exactTargetWorktreeIds
returns nothing, every host path fails to resolve, and importRemoteWorkspaceSession
silently dropped every tab row. The apply then marked the target hydrated and
'synced', freezing that emptiness in permanently — nothing re-pulls a hydrated
target (STA-3593).

The importer now reports unplaceable rows, the apply claims authority only when
every row landed, and a bounded chain re-pulls the missing input (catalog +
lineage). On exhaustion it settles back to the pre-fix behaviour so a genuinely
unplaceable path is never left worse off than today.

* fix(ssh): keep the re-pull chain bounded, unwedgeable, and announced once

Five defects in the first cut of the chain, all found before merge:

1. the caller owned the attempt counter, so an unsolicited host push re-armed
   it at 0 and the chain never exhausted - an unbounded workspace.get loop;
2. exhaustion never cleared the counter, so after one bad connection every
   later reconnect re-exhausted instantly and the retry was silently dead;
3. the exhaustion check preceded the armed-timer guard, letting a concurrent
   report cancel the still-pending final retry;
4. a rejected host read left no timer armed and nothing rescheduled, stranding
   the target on 'pulling' and un-hydrated forever - and an un-hydrated target
   never uploads again, the exact permanent degradation this design avoids;
5. exhaustion re-announced on every later report, re-marking hydrated and
   rewriting status on each host push.

The module now owns the counter, resetTarget gives each connection a fresh
chain, the armed guard precedes exhaustion, the timer body always reschedules
so any failure walks to exhaustion, and exhaustion is announced once.

* fix(ssh): never authorise uploads from a picture known to be incomplete

Reversal of this branch's own exhaustion fallback, on evidence.

Hydration authorises uploads (use-app-session-persistence.ts), and an upload is
a workspace.patch of kind 'replace-session' (remote-workspace-relay-sync.ts:66)
which wholesale replaces the host snapshot (relay/workspace-session-handler.ts).
So marking a target hydrated on a picture we know is missing rows does not
'settle back to the old behaviour' - it uploads an empty projection that DELETES
the host tabs we failed to adopt. Suppressed uploads are recoverable; a wiped
host snapshot is not. That data loss is reachable on main today, because today
the apply marks hydrated immediately.

Exhaustion therefore reports 'error' and leaves the target un-hydrated, so
terminal authority stays 'unverifiable' and no upload can be built from it.

Also closes two chain-lifecycle gaps found in review:
- the callback dropped its timer guard before awaiting the host, leaving a gap
  in which a concurrent report armed a second overlapping chain and could trip
  exhaustion before the pending apply resolved; an in-flight guard now spans it;
- resetTarget could not cancel a callback already past its await, so a stale one
  rescheduled on top of the new connection's chain; chains are now generation
  stamped and a stale callback exits.

* fix(ssh): scope re-pull in-flight ownership to a generation

Two races found in review of the previous commit:

- schedule(target,'placed') cleared timer/count/exhaustion but did not
  invalidate an apply already in flight. When that apply later resolved
  'unplaced' its generation still matched, so it started a fresh chain from
  attempt 0; a host repeating placed pushes during each in-flight retry could
  reset the budget indefinitely. Retirement now bumps the generation too.

- the in-flight marker was a bare Set, so a superseded callback's finally
  deleted whichever marker was present - including one a newer generation had
  since taken. A later report could then arm an overlapping timer while that
  newer apply was still running. Ownership is now a target -> generation map and
  a callback releases only the marker it still owns.

resetTarget deliberately no longer drops the marker: its owner is the only party
that may release it, and clearing it there would let a new chain arm while the
superseded apply is still running.

* fix(ssh): replay an unplaced report that was blocked by a superseded apply

Regression from the previous commit. Keeping the stale in-flight marker across
resetTarget stops overlap, but it also swallows the new connection's result: the
new apply reports 'unplaced', hits the guard because the superseded apply still
owns the marker, and the superseded callback then exits on its stale generation
without scheduling. Nothing replayed the dropped report, so no chain started -
the retry silently never ran for that connection.

A blocked unplaced report is now recorded, and the marker's owner replays it on
release. Only the stale path reaches the finally still owning the marker, so the
normal path - which released early and scheduled its own outcome - cannot replay
twice.

* refactor(ssh): drop the re-pull retry chain, keep the fix

The chain produced ten defects across review - unbounded retry, dead retry,
cancelled final attempt, wedged chain, repeated exhaustion, overlapping chains,
stale-callback cleanup, a lost report - every one in code that passed the full
suite at the time. It bought only faster recovery *within* one connection:
syncAfterConnect and applyUnsolicitedSnapshot already re-pull on the next
connect or host push, so dropping it costs a retry, never the data.

What remains is the part that was correct from the first commit: the importer
reports rows it could not place, and an apply that could not place them neither
marks the target hydrated nor sets 'synced'. Because hydration is what
authorises uploads, and an upload wholesale replaces the host snapshot, that
single rule is what stops a client from deleting the host tabs it failed to
adopt.

Status is now 'error' rather than 'pulling': with no chain pending, 'pulling'
claimed a request that was not in flight.

* test(ssh): name the upload-suppression case for the chainless design

* fix(ssh): revoke stale hydration and keep authority unverifiable when unplaced

Two holes in the previous commit, both found in review.

The hydrated set is add-only (ssh.ts), so withholding hydration only protects a
target that never synced. A target that synced cleanly and then reconnected with
a degraded lineage kept its flag, and hydration is what authorises uploads - so
it would still send a replace-session patch built from the incomplete picture
and delete the host tabs it had just failed to place. Hydration is now revoked,
not merely withheld.

The status phase was 'error'. workspace-terminal-host-authority.ts treats
'offline'/'error' on an un-hydrated target as its bounded floor and resolves
them to 'none' - which authorises seeding AND sleeping-agent resume, the exact
double-resume this gate exists to prevent. 'conflict' is the phase that actually
describes the situation, is excluded from uploads by use-app-session-persistence,
and is deliberately outside that floor set, so authority stays 'unverifiable'.

Both invariants are pinned by tests verified to fail when either fix is reverted
individually; the pre-existing tests passed with both reverted.

* fix(ssh): drop the mismatched message on the unplaced conflict status

The phase drives the user-visible label ('Workspace sync conflict'); carrying an
'unavailable' message alongside it only risked contradicting that wherever the
message is surfaced.

* docs+refactor(ssh): correct the authority floor's premise, drop a dead wrapper

Two findings from the post-merge correctness sweep.

The bounded floor in workspace-terminal-host-authority.ts justified itself on
'remoteWorkspaceHydratedTargetIds is add-only, clearRemoteWorkspaceHydrated has
no production caller'. This branch adds that caller, so the premise is now false
and a future reader would have been misled by it. The comment records the real
consequence: a target that later lands on offline/error reaches the floor having
demonstrably answered, so seeding is authorised over live host terminals. Not a
regression - before revocation existed the same target was marked hydrated and
synced, reaching 'none' sooner - but the floor should learn to tell a revoked
target from one that never answered. Flagged for the SSH-v3 consolidation, where
one authoritative liveness source replaces this pair.

applyUnsolicitedSnapshot had become a pass-through to applyPreparedSnapshot,
carrying a docstring about a re-pull chain that no longer exists. The two
collapse back into one function.

* refactor(ssh): delete the DirectSshSnapshotPlacement union

Consolidation pass finding. The union was exported and threaded through two
modules, but no production consumer ever read it: remote-workspace-ipc-bridge.ts
discards the promise's value and syncAfterConnect ignored it. 'not-applied' was
not a placement at all, only 'this apply did not happen'.

That is a parallel verdict concept with no consumer - precisely what the SSH-v3
consolidation would have had to unpick. It collapses to a local
hasUnplacedTerminalTabs boolean and a void return.

The one test that asserted the return value now asserts adoption instead, which
is the observable outcome rather than a proxy for it. All five unplaced oracles
still fail when the placement decision is forced, verified individually.

* docs(ssh): compress the tombstone rationale to its load-bearing WHY

Elegance pass. Kept the two non-obvious claims - absence cannot distinguish
'never told' from 'user closed', and uuid tab ids make a tombstoned id safe to
drop - and cut the incident narrative around them. The twice-reverted history in
remote-workspace-session-merge.ts is deliberately left alone: that one is
institutional memory about regressions, not restatement of the code.

* test(ssh): pin the fixed behaviour instead of the defect it replaced

The spec was a characterization test whose own title said 'because hydration is
marked even when adoption wrote nothing', and whose comment described exactly
the defect this branch fixes: markRemoteWorkspaceHydrated ran unconditionally
after the hydrate calls, so in the same tick adoption yielded zero, authority
flipped unverifiable -> none, and Terminal.tsx seeded a phantom tab. It polled
for hydrated === true, so the fix turned it red.

It now asserts hydrated === false, phase === 'conflict', and zero tabs - the
count measured before asserting rather than assumed, confirming the phantom seed
is gone. The phase is re-read after the tabs settle and asserted a second time,
because a conflict verdict a later apply flipped back would silently re-authorise
seeding and a single poll would miss it.

The fixme stays a fixme: this branch stops the client claiming false authority
and overwriting the host, but adoption is still the open gap. Declining to seed
is a safe wait, not the destination.

Three-legged A/B against fork point 6c03236, spec byte-identical across the
first two legs:
  branch   + updated spec  -> PASS
  baseline + updated spec  -> FAIL 'never reported the unplaced snapshot as a conflict'
  baseline + original spec -> PASS (baseline actively exhibits the old behaviour)
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