Skip to content

fix(worktrees): keep retirement tombstones across project and SSH target re-add - #14917

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/fix-4449-4491
Aug 17, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/fix-4449-4491

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​619 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​618
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​393 $\color{#cf222e}{\Huge{\mathbf{−}}}$​46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​347

Merge order — read this first

#14917  (STA-4449 P0 + STA-4491 P1)  → main      ← THIS PR is the base
  └── #14919  (STA-4471 P0)          → #14917
        └── #14924  (STA-4472 P0 + STA-4473 P1) → #14919
#14926  (STA-4479/4480 P2)           → main      — independent, mobile-only

Merge strictly bottom-up. This PR stands alone: it typechecks and passes its suites with nothing
above it, and it is the one to merge if the stack has to be broken up.

#14919 is deliberately not folded into this one. It reverses a considered #14350 product decision —
a deliberately typed pool name such as nautilus is now redirected to nautilus-2 when that cwd is
retired, and typed pool-shaped names are now recorded as spent. That judgement has to stay
rejectable without losing the two P0/P1 tombstone fixes here, which change no user-visible
behaviour.

One sequencing caveat: #14919 widens the set of creates that reach the deadline-less retirement
backfill scan, and only #14924 bounds it. Do not ship a build between those two. #14924's description
has the detail.

Fixes STA-4449 (P0) and STA-4491 (P1) — both regressions from #14350.

What breaks today

Generated workspace names are retired so a name is never reissued onto a cwd that still holds another workspace's Claude/Codex history. Two re-add paths lose that record.

STA-4449 (local, P0). Retirement is stored only under repo.id. Removing a project deletes that row; re-adding the same path mints a new id, so the new repo starts with an empty registry. The on-disk backfill normally re-seeds local repos, which is why this is narrower than it first looks — the hole is the intersection with the deliberate Codex non-scan. A name spent under Codex whose workspace directory is gone has no evidence the backfill will read, because Codex rollout JSONL files are deliberately not scanned. That name comes back, and the new workspace inherits the old cwd's Codex history.

STA-4491 (SSH, P1). The second, path-derived copy embeds the SSH target row id. Row ids are minted fresh on every re-add, so ssh:ssh-old:… becomes ssh:ssh-new:…, and reassignSshTargetId migrates other carrier state but not retiredWorktreeNamesByNamespace.

Why not just key storage on the namespace

That option is explicitly rejected in #14350's own body, and it is still the wrong call. The namespace derives from workspaceDir, nestWorkspaces, worktreeBasePath and repo.path — so keying storage on it orphans every retirement the moment a user toggles any one of those, which is far more common than remove/re-add.

So repo.id stays primary storage and the path-derived namespace stays a mirror. The two fail on different events and reads union both:

Event repo.id row namespace mirror
workspace-path setting toggled survives lost
project removed and re-added lost survives

The change

  • Mirror local repos into the namespace too, not only remote ones. This is the STA-4449 fix; folder repos stay excluded.
  • Key the namespace's host half on the SSH endpoint (host|port|username) rather than the target row id. The endpoint is what actually decides which machine, account, and therefore which filesystem a path lands on; two rows sharing it share every absolute path. This is the STA-4491 fix.
    • Reads also accept the pre-identity key, so an upgrade keeps tombstones it already wrote.
    • reassignSshTargetId re-keys the rest, covering both the pre-identity row-id key and — via the removal tombstone — an endpoint that genuinely moved while its ssh-config alias stayed put.
    • Targets that cannot be resolved to a row share one bucket. Retirement prefers spending one name out of a 552-name pool over reissuing a cwd whose agent history is still on disk.
  • Cap the namespace map. It outlives the repos that wrote it by design — that is what makes a re-add recover — so nothing prunes it per repo. Insertion order is the LRU list, which JSON round-trips, so no timestamp has to be persisted.
  • Endpoint identity is extracted from ssh-target-readoption.ts, which already compared these exact fields for the same reason. Re-adoption and retirement now cannot drift apart.

Defect found in this PR's own cap, and fixed

Writing the first direct unit test for the cap turned it RED, and the cap was wrong:

for (const stale of keys.slice(0, keys.length - MAX_RETIREMENT_NAMESPACES)) delete namespaces[stale]

A negative end makes slice count back from the tail, so instead of yielding nothing on an under-full map it yields nearly all of it. Measured on the previous revision: filling the map to its nominal 256 left 128 entries, and every write past that dropped another old namespace. The mirror that exists to survive a remove/re-add was silently discarding itself for anyone with more than ~128 workspace namespaces.

Fixed by clamping the overflow to Math.max(0, …). This is why the new worktree-retirement-namespace.test.ts exists: without it the bug ships behind a comment that claims a 256-entry cap.

Rebased onto current main

main moved 29 commits since this branch was cut and split the 8k-line persistence.ts into modules, so both persistence hunks were re-homed, not merged:

Hunk Was Now
namespace write goes through the cap persistence.ts persistence/loading-store/store.ts
SSH rotation re-keys namespaces private Store method persistence/leasing-ssh-ptys/ssh-target-reassignment.ts

A pre-split branch can merge cleanly into code that no longer runs, so each re-homed hunk was proven live by reverting only that file to origin/main:

Reverted file (alone) Tests that go RED
persistence/leasing-ssh-ptys/ssh-target-reassignment.ts 2 — both "reassigning a target id carries retirements …"
persistence/loading-store/store.ts 1 — "bounds the namespace map instead of growing it …"

The reassignment hunk moved out of Store entirely: it now reads state.sshTargets and state.removedSshTargetTombstones directly, so the private-method indirection is gone.

Proof the tests are non-vacuous

Reverting the production files to origin/main and keeping the tests turns 5 behavioural tests in this suite RED, with the material diff the reproduction predicted:

AssertionError: expected { exhaustedTiers: +0, names: [] } to deeply equal { exhaustedTiers: +0, …(1) }
  {
    "exhaustedTiers": 0,
-   "names": [ "nautilus" ],
+   "names": [],
  }

× preserves a Codex-only local retirement across remove and re-add
× preserves a remote retirement when an SSH target id rotates before re-add
× reassigning a target id carries retirements written before endpoint identity
× reassigning a target id carries retirements when the endpoint itself moved
× shares one retirement bucket across SSH repos whose target row is gone

That diff is the point: it proves the tests reach the registry read after the remove/re-add transition and fail because the name was lost, not because setup threw.

A whole-file revert is a weak proof on its own, so each test was also pinned by a targeted mutation — every test has at least one mutation that kills it and only it:

Mutation Test it kills
local repos stop mirroring into the namespace Codex-only local retirement
host identity keys on the target row id SSH target id rotates before re-add
reassignSshTargetId stops migrating namespaces retirements written before endpoint identity
migration drops the legacy row-id arm retirements written before endpoint identity
migration drops the tombstone (old-endpoint) arm endpoint itself moved
unresolvable targets stop sharing a bucket shares one retirement bucket
retirementNamespaceKeysToRead drops the legacy key profile transfer folds the pre-identity key
every SSH repo collapses into the unknown bucket does not leak to a different endpoint
the LRU cap reverts to the unclamped slice evicts the least recently recorded namespace

The last two matter in the other direction. "Does not leak to a different endpoint" is the guard that this fix does not over-share retirements between distinct hosts — stub the SSH target lookup out and it fails, which is also what proves the SSH tests resolve real SshTarget rows instead of passing through the unknown-identity fallback.

One honest limit: preserves a remote retirement when an SSH target id rotates before re-add still passes with the lookup stubbed, because the unknown-identity fallback lands both repos in the same bucket and produces the same answer. It is the paired negative test that discriminates. Read the two together, not alone.

An earlier mutation pass also found a real defect in the tests themselves — the "endpoint itself moved" case originally passed via the surviving repo.id row rather than the migration under test. It now drops the repo row first.

Gates

Gate Result
vitest — the 9 affected suites 1250 passed, 1 skipped
this commit alone (base of the stack) — typecheck:node + its 6 suites exit 0; 70 passed
tsc --noEmit × node/cli/web exit 0
oxlint --config config/oxlint-code-quality-native-plugins.json … --deny-warnings exit 0
oxlint --type-aware --config config/oxlint-code-quality-type-aware.json … --deny-warnings exit 0
check:max-lines-ratchet OK, no new bypasses
oxfmt clean

oxlint prints nothing when clean, so the gate was verified live by injecting a no-fallthrough violation into worktree-retirement-namespace.ts and confirming it was reported, then reverting.

What is test-proven vs. reasoned

Test-proven: the local Codex-only retirement survives remove/re-add; the SSH retirement survives a target-id rotation; retirements do not leak between distinct endpoints; the pre-identity key is still read and is folded on profile transfer; unresolvable targets share one bucket; the namespace map is bounded and refreshes on rewrite; Windows path halves are case- and separator-insensitive and cannot collide with a POSIX path.

Reasoned, not test-proven: that host|port|username is the right equivalence class for "same filesystem" — it is the same tuple ssh-target-readoption.ts already trusted for re-adoption, and this PR extracts rather than invents it; that 256 is the right cap; that sharing one bucket for unresolvable targets is the better error (it over-retires rather than reissuing a live cwd). None of these are observed against a real SSH host in CI.

Notes for review

  • No wire-format change. retiredWorktreeNamesByNamespace is local persisted state; nothing a paired client and host exchange is touched.
  • Cross-platform: path halves go through the existing worktreePathComparisonKey, which lowercases and normalizes Windows separators and namespaces the two flavours (windows: / posix:) so they cannot collide. Directly tested.
  • Folder workspaces are unaffected (isFolderRepo still returns early).
  • The host-identity prefix match in the migration is separator-anchored, so …|dev cannot swallow …|dev2. Directly tested.
  • Still open from fix(worktree): never reissue a generated workspace name #14350 and NOT covered here: STA-4472 (WSL backfill never scans <wslHome>/.claude/projects; this PR does not touch backfill discovery), STA-4473 (backfill scan has no deadline and its Promise is cached forever), STA-4479 / STA-4480 (mobile-side suggestion cache). STA-4471 lands as fix(worktrees): retire a created pool name whatever the client claims (STA-4471) #14919 on top of this.

Stacked: this is the base. #14919 sits on top and can be dropped without losing these two fixes.

@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 9 seconds

Limit details: You’ve used all 10 included reviews currently available under your plan.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8bfdd17d-467d-4c0c-9e9d-b5e582480baf

📥 Commits

Reviewing files that changed from the base of the PR and between 1131dcb and 2e1e6ca.

📒 Files selected for processing (2)
  • src/main/worktree-retirement-namespace.test.ts
  • src/main/worktree-retirement-namespace.ts
📝 Walkthrough

Walkthrough

The change adds shared SSH endpoint identity helpers and canonical retirement namespace utilities. Retirement registries read canonical and legacy keys, merge matching entries, use capped storage, and persist for non-folder repositories. SSH target reassignment and endpoint updates migrate namespaces. Transfer handling uses canonical endpoint keys. Tests cover migration, endpoint isolation, local and remote persistence, unavailable targets, runtime targets, eviction, and transfer behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.72% which is insufficient. The required threshold is 80.00%. 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 identifies the fix: preserving retirement tombstones across project and SSH target re-addition.
Description check ✅ Passed The description thoroughly explains the regressions, implementation, linked issues, compatibility scope, tests, and validation results.
✨ Finishing Touches
📝 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: 1

🧹 Nitpick comments (1)
src/main/ssh/ssh-target-identity.ts (1)

3-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the new block comments.

Keep the identity invariant in the source. Move detailed rationale to adjacent documentation if needed.

  • src/main/ssh/ssh-target-identity.ts#L3-L8: reduce the comment to the target re-add identity invariant.
  • src/main/worktree-retirement-namespace.ts#L10-L18: reduce the comment to the repo-ID and namespace-copy retention contract.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: afdc086f-1cc9-4cfc-80bb-f9f022c51fa4

📥 Commits

Reviewing files that changed from the base of the PR and between 516a269 and 46294c6.

📒 Files selected for processing (8)
  • src/main/orca-profiles/profile-project-retired-name-transfer.ts
  • src/main/orca-profiles/profile-project-transfer.test.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • src/main/persistence.ts
  • src/main/ssh/ssh-target-identity.ts
  • src/main/ssh/ssh-target-readoption.ts
  • src/main/worktree-name-retirement.ts
  • src/main/worktree-retirement-namespace.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.

Comment on lines +66 to +76
export function retirementNamespaceKeysToRead(
repo: RepoHostFields,
namespaceKey: string,
lookup?: SshTargetLookup
): string[] {
const legacyKey = swapRetirementNamespaceHost(
namespaceKey,
retirementHostIdentity(repo, lookup),
getRepoExecutionHostId(repo)
)
return legacyKey ? [namespaceKey, legacyKey] : [namespaceKey]

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

Read the unknown SSH namespace after target recovery.

If getSshTarget is unavailable during retirement, the registry is stored under ssh:?. After the target becomes available, this function reads only the endpoint key and target-ID legacy key. It then misses the prior ssh:? registry, and the same workspace name can be reissued.

For known SSH targets, also read the equivalent ssh:? namespace as a read-only fallback. Add a regression test that retires a name while the target is unavailable, restores the target, and verifies that the name remains retired.

Proposed fix
 export function retirementNamespaceKeysToRead(
   repo: RepoHostFields,
   namespaceKey: string,
   lookup?: SshTargetLookup
 ): string[] {
+  const hostIdentity = retirementHostIdentity(repo, lookup)
   const legacyKey = swapRetirementNamespaceHost(
     namespaceKey,
-    retirementHostIdentity(repo, lookup),
+    hostIdentity,
     getRepoExecutionHostId(repo)
   )
-  return legacyKey ? [namespaceKey, legacyKey] : [namespaceKey]
+  const unknownKey =
+    parseExecutionHostId(getRepoExecutionHostId(repo))?.kind === 'ssh' &&
+    hostIdentity !== UNKNOWN_SSH_HOST_IDENTITY
+      ? swapRetirementNamespaceHost(
+          namespaceKey,
+          hostIdentity,
+          UNKNOWN_SSH_HOST_IDENTITY
+        )
+      : null
+  return [namespaceKey, legacyKey, unknownKey].filter(
+    (key): key is string => key !== null
+  )
 }
📝 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
export function retirementNamespaceKeysToRead(
repo: RepoHostFields,
namespaceKey: string,
lookup?: SshTargetLookup
): string[] {
const legacyKey = swapRetirementNamespaceHost(
namespaceKey,
retirementHostIdentity(repo, lookup),
getRepoExecutionHostId(repo)
)
return legacyKey ? [namespaceKey, legacyKey] : [namespaceKey]
export function retirementNamespaceKeysToRead(
repo: RepoHostFields,
namespaceKey: string,
lookup?: SshTargetLookup
): string[] {
const hostIdentity = retirementHostIdentity(repo, lookup)
const legacyKey = swapRetirementNamespaceHost(
namespaceKey,
hostIdentity,
getRepoExecutionHostId(repo)
)
const unknownKey =
parseExecutionHostId(getRepoExecutionHostId(repo))?.kind === 'ssh' &&
hostIdentity !== UNKNOWN_SSH_HOST_IDENTITY
? swapRetirementNamespaceHost(
namespaceKey,
hostIdentity,
UNKNOWN_SSH_HOST_IDENTITY
)
: null
return [namespaceKey, legacyKey, unknownKey].filter(
(key): key is string => key !== null
)
}

…get re-add

Generated workspace names are retired so a name is never reissued onto a cwd
that still holds another workspace's Claude/Codex history. Two re-add paths
lost that record.

STA-4449 (local): retirement was stored only under `repo.id`. Removing a
project deletes that row and re-adding the same path mints a new id, so the
new repo starts with an empty registry. The on-disk backfill normally
re-seeds local repos, but it cannot recover a name whose only surviving
evidence is a Codex rollout JSONL — those are deliberately not scanned — so a
name spent under Codex with its workspace directory gone came back.

STA-4491 (SSH): the second, path-derived copy embedded the SSH target row id.
Row ids are minted fresh on every re-add, so `ssh:ssh-old:...` became
`ssh:ssh-new:...` and `reassignSshTargetId` migrated other carrier state but
not the retirement namespaces.

Keying the store on the namespace instead of `repo.id` was rejected in
`nestWorkspaces`, `worktreeBasePath` and `repo.path`, so a settings toggle
would orphan every retirement at once. `repo.id` therefore stays primary and
the path-derived namespace stays a mirror — a settings toggle loses the
mirror but keeps the repo row, a re-add loses the repo row but keeps the
mirror, and reads union both.

- Mirror local repos into the namespace too, not just remote ones.
- Key the namespace's host half on the SSH endpoint (host+port+username), the
  thing that actually decides which filesystem a path lands on, instead of the
  target row id. Reads also accept the pre-identity key so an upgrade keeps
  tombstones it already wrote, and `reassignSshTargetId` re-keys the rest.
- Cap the namespace map, which by design outlives the repos that wrote it and
  so has nothing to prune it per repo.

Endpoint identity is extracted from ssh-target-readoption.ts, which already
compared these fields for exactly the same reason, so re-adoption and
retirement cannot drift apart.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-4449-4491 branch from 46294c6 to 910e39c Compare August 16, 2026 18:31
@coderabbitai

coderabbitai Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Note

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validation: real SSH host + running app, with before/after

Ran the review loop plus field validation on this PR. Both tickets were exercised against real state, not only the unit suite.

STA-4491 — real Linux SSH host

Throwaway Ubuntu 22.04 container, real sshd, key auth, real git repo at /work/demo-project (git 2.34.1, node v20.20.2). Orca connected through the real relay path — remote platform detection, node probe, relay install (including the node-pty toolchain gate), launch and socket reconnect all ran against that host from this build.

The sequence: create a real git worktree over SSH → delete it → retire the generated name → rotate the SSH target row id (remove + re-add the same endpoint, exercising reassignSshTargetId) → also remove and re-add the project, which mints a fresh repo.id and makes the path-derived mirror the only surviving copy of the tombstone.

namespace key produced tombstone after rotation + project re-add
merge-base 516a2693 ssh:ssh-field-old:posix:/work/demo-project-orca-retirement-probe lost — expected [] to include 'nautilus'
this PR ssh:127.0.0.1|2242|root:posix:/work/demo-project-orca-retirement-probe survives

The host half is the endpoint, not the row id, so the rotation no longer strands the key. Reverting only the production files (keeping the new modules so imports still resolve) flips this red, so the check is not vacuous.

STA-4449 — running app, local project

Driven through the app's own IPC on an isolated dev profile, fresh profile per run:

repo.id after re-add worktrees:listRetiredNames
merge-base 516a2693 changed [] — name reissuable
this PR changed ["nautilus"]

repo.id changes in both runs, so the re-add is genuine; only the mirror explains the difference.

qa-AFTER-01-workspace.png

Workspace nautilus in the sidebar before deletion. After the project is removed and re-added the sidebar looks the same in both builds:

before (merge-base) after (this PR)
before after

On rendered surface, stated plainly: this fix has no deterministic pixel-level difference. What changes is persisted retirement state, and the user-visible symptom — a reissued name landing on a cwd that still holds another workspace's Codex history — depends on a random draw from a 552-name pool. The screenshots show the scenario running in the real app; the table above is the actual evidence.

Other checks

  • Non-vacuity: reverting the five modified production files (new modules kept) turns 7 tests red, all behavioural, zero load failures. Deleting the two new modules as well gives 2 files that cannot load — compile failures, reported separately rather than counted as behavioural evidence.
  • Prior-art pass, re-derived: endpoint-derived identity for remote state matches established editor precedent, which hashes the full remote URI (authority included) rather than any session-minted connection id, and deliberately keeps that identity stable for a given URI. The capped recency map with trim-oldest matches standard LRU/MRU cache precedent. Dual-read of canonical + legacy key during a key-format change is the conventional migration shape. One deviation worth naming: precedent usually stores recency as an explicit list, whereas this uses object key insertion order — spec-correct here because namespace keys always contain : and so are never integer-like, but it is implicit.
  • Every call site of the namespace-key helpers passes the SSH lookup, so nothing silently falls back to the ssh:? bucket; and for local repos the backfill's scanKey is byte-identical to retirementNamespaceKey(...), so backfill and write agree.

Test scaffolding lived outside the tree and is not part of the diff; the container and temp workspaces were torn down.

…g them

An endpoint identity is not owned by the target row that rotates: nothing
dedupes SSH targets by host|port|username, so a second live target can still
resolve to the same host. Moving the bucket stripped that target's tombstones
and reissued a path whose agent history is still on disk.

Row-id identities stay a move — reassignment leaves nothing pointing at them.
…edits

Config sync rewrites host/port/username on the existing target row and a
runtime-owned target takes a fresh address from every provision, both keeping
the row id. No re-adoption runs, so nothing carried the endpoint-keyed mirror
across and it stranded — strictly worse than the pre-change key, which was the
row id and was invariant under these edits.

Also bound the map after a migration: a retained source bucket grows it, so the
cap has to be applied there too, and compare registries by membership rather
than size so an uncompacted destination cannot trade a folded name for a new
one and read as unchanged.
An on-demand VM is discarded between provisions, so its fresh address reaches an
empty filesystem and a reissued name collides with nothing. Migrating there
would spend names against history that no longer exists, and because each
provision mints another address it would add a namespace bucket per run,
evicting the real tombstones of local and ordinary SSH repos.
… wrote

Two defects with one root cause. Assigning to an existing key leaves it in its
original insertion slot, so a merged destination kept the oldest position and the
trim deleted the bucket it had just enriched. Retained source buckets are older
than the destinations a copy appends, so at the cap the trim removed exactly the
sources the copy existed to keep — silently turning it back into a move. The trim
now exempts the keys the migration wrote or deliberately kept.

Also stop on-demand runtime workspaces writing namespace mirrors at all: each
provision reaches a discarded filesystem under a fresh address, so the entry can
never be read back and only spends a capped slot that a local or SSH project
needs. The repo-id row still records the name for the live session.
Resolves an import-union conflict in worktree-name-retirement.ts. Main's #15023
gates the backfill on the execution host id rather than connectionId; this branch
adds a runtime-owned guard on the namespace write. Both apply.
…a migration

Exempting keys from the trim protected them for that one call and no other. A
merged destination keeps its original insertion slot, so it sat at the front of
the eviction queue and the next unrelated retirement write dropped it — losing
both the migrated name and the name the destination already held, on a host that
had just been re-added.

Re-insert what the migration writes instead, the same discipline the ordinary
writer already follows, so insertion order reflects use. That also removes the
exemption, which could otherwise leave the map stuck at twice the cap until one
later write evicted the whole excess at once.

Corrects the runtime-gate comment as well: the mirror is unreadable after the
next provision, not immediately, so a remove/re-add inside one provision is a
real if narrow loss.
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Note

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts (1)

58-66: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the endpoint-migration comment.

Lines 58-66 explain implementation details across nine lines. Keep only the non-obvious decisions: retain the old namespace for sibling targets, and exclude runtime-owned targets because their filesystems are ephemeral.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dca5b2ea-f242-4e21-9053-5b223fb196eb

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae6aed and 1131dcb.

📒 Files selected for processing (11)
  • src/main/orca-profiles/profile-project-retired-name-transfer.ts
  • src/main/orca-profiles/profile-project-transfer.test.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts
  • src/main/persistence/loading-store/store.ts
  • src/main/ssh/ssh-target-identity.ts
  • src/main/ssh/ssh-target-readoption.ts
  • src/main/worktree-name-retirement.ts
  • src/main/worktree-retirement-namespace.test.ts
  • src/main/worktree-retirement-namespace.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/main/orca-profiles/profile-project-transfer.test.ts
  • src/main/persistence/loading-store/store.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts
  • src/main/orca-profiles/profile-project-retired-name-transfer.ts
  • src/main/ssh/ssh-target-identity.ts
  • src/main/worktree-retirement-namespace.test.ts
  • src/main/ssh/ssh-target-readoption.ts
  • src/main/worktree-retirement-namespace.ts
  • src/main/worktree-name-retirement.ts

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

…ge adds nothing

Replacing the trim exemption with re-insertion narrowed the protection: the
exemption covered every retained source, the re-insertion only covered sources
whose merge actually wrote. A copy whose destination already held the same names
was then neither re-inserted nor exempt, so the migration's own trim evicted the
shared source bucket ahead of hundreds of untouched ones — losing the tombstones
of a live sibling target still on that endpoint, which is what copying exists to
prevent.

A move's destination gets the same treatment: deleting the source makes it the
only remaining copy, so it has been used. Both are order-only and deliberately do
not set the changed flag, keeping an import that moved nothing from scheduling a
save.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-4449-4491 branch from d453d5c to 2e1e6ca Compare August 17, 2026 11:12
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent review rounds — 5 defects found and fixed

The original commit (910e39c43c) had only been self-reviewed: both independent reviewers on the earlier
attempt were killed by machine resource exhaustion before returning anything. This run re-ran the loop to a
stopping condition. Every round below found a real defect in the previous round's fix, and every one of
them was passing CI when it was found.

Round Defect Fix
1 migrateRetirementNamespaceHostIdentity moved namespaces keyed by SSH endpoint identity. An endpoint is not owned by the row that rotates — nothing dedupes targets by host|port|username, and re-adoption calls reassignSshTargetId unprompted on every SSH add/import — so rotating one target stripped a live sibling target's tombstones. Split moveFrom (row-id, safe to delete) from copyFrom (endpoint, source retained). 6e3c97694e
2 Config-derived targets are refreshed in place, keeping the row id (ssh-connection-store.ts:211), so no re-adoption ran and the endpoint-keyed mirror stranded on any ~/.ssh/config edit. Pre-change the key was the row id, which was invariant under these edits — so the mirror was strictly worse than before. Migrate the mirror at the updateSshTarget chokepoint. c4bf600559
2b That migration then fired for on-demand runtime targets, which take a fresh address every provision — churning the capped map with a bucket per run. Skip runtime-owned targets. 22874ed934
3 The round-2 trim evicted the bucket it had just enriched (assigning to an existing key keeps its original slot), and at the cap it removed exactly the sources a copy was retaining — silently collapsing copyFrom back into a move. The 256 cap (new here; the map was previously uncapped) also landed on unbounded key producers. Trim exempts migrated keys; runtime workspaces write no mirror at all. 45507b4691
4 The exemption was call-scoped: a merged destination kept its original slot, so the next unrelated retirement write evicted it — losing both the migrated name and the name the destination already held. Re-insert what the migration writes, the same discipline the ordinary writer follows. 1131dcb4cc
5 Swapping the exemption for re-insertion silently narrowed it: the exemption covered every retained source, the re-insertion only covered sources whose merge wrote. A copy whose destination already held the same names fell through both, so the trim evicted the shared source ahead of hundreds of untouched buckets. Caught by diffing behaviour against the parent commit — the parent evicted a stale bystander, this one evicted the source. Re-insert a retained source unconditionally, and refresh a move's destination once it becomes the only copy. Both order-only, so a no-op import still schedules no save. 2e1e6ca561

Evidence

  • Both re-homed hunks are live, proven by reverting each ported file alone and observing behavioural RED
    (2 RED for ssh-target-reassignment.ts, 1 RED for the store.ts hunk, driven through the real Store).
    This repo has a repeated history of module splits merging a fix into dead code; a clean rebase is not
    evidence.
  • Non-vacuity: reverting the 5 modified production files (keeping tests and the new modules) gives exactly
    7 RED, all AssertionError, zero load/compile failures.
  • Every test added in this review was proven load-bearing by disabling its production line and confirming
    that test — and only that test — goes RED. One first-draft test was not load-bearing (it placed the
    bystanders oldest so the guard was never exercised) and was rewritten.
  • Sweep: 2048 passed / 0 failed across 163 SSH, persistence and profile suites; tsc --noEmit exit 0;
    oxlint and oxfmt clean.

Prior-art alignment

Deriving workspace identity from the durable endpoint (including host/authority) rather than a session-minted
row id matches established practice, as does a capped trim-oldest LRU with an explicit size > limit guard —
the same defensive shape as the Math.max(0, …) clamp here. One deliberate divergence: the common pattern
refreshes LRU position on read, while this map refreshes only when a name is actually added, because
touching on read would dirty the store and schedule a save on every composer open.

Rendered surface

This change has no deterministic rendered surface — it is main-process persistence and SSH target identity.
The screenshots already attached to this PR remain the applicable visual evidence; the commits added during
this review are logic-only and change nothing on screen.

Residual risk (recorded, not blocking)

  1. Write-recency eviction. The 256-entry LRU refreshes position only when a name is added, so a namespace
    read constantly but written once can still be evicted. Reaching 256 needs a lot of distinct projects.
  2. Rollback loses the mirror only. The repo.id row is untouched, so no name is reissued from a downgrade
    alone.
  3. ssh:? buckets are not migrated forward. Names retired while a repo's SSH target row is absent are
    unreachable once the row returns. The write appears unreachable in practice — every retirement call site is
    inside a create path that needs a live provider.
  4. On-demand runtime remove/re-add within one provision loses that namespace's tombstones, since runtime
    workspaces no longer write a mirror. Deliberate: the address changes per provision, so the entry would be
    unreadable afterwards while still consuming a capped slot. A follow-up worth considering is keying runtime
    repos on the stable runtime-ssh-<id> target id instead of the volatile endpoint, which would restore the
    mirror without churn.
  5. Order-only refreshes on the reassignment path may not be persisted immediately. The config-edit path
    saves unconditionally, so it is durable there; a reassignment that re-points nothing could leave memory
    and disk ordering briefly divergent, self-healing at the next ordinary write. Order only decides which
    entry gives way at the cap, so there is no correctness impact. Measured alongside: an over-cap migration
    keeps half the sources and half the destinations rather than wiping either side, and a no-op-only
    migration reports no change and does not trim.
  6. Profile transfer does not carry the mirror for local projects.
    extractRetiredNameRegistriesByNamespace still returns {} when a repo has no connectionId, while this
    branch newly makes local repos write mirrors. Not data loss today — a transfer preserves repo.id, so the
    primary row still holds every name; the mirror only matters if the project is then removed and re-added
    inside the target profile.
  7. mergeRetiredNameRegistryMaps writes the namespace map without the capped writer, so a transferred key
    that already exists keeps its original slot despite being freshly written. Bounded at one key per transfer.

Final round

The loop ran to a clean stop: the last round found nothing merge-blocking and changed nothing. Every
earlier round found a defect in the round before it, including two in work added during this review — so the
stopping condition was the point, not a formality.
6. Profile transfer writes the namespace map without the capped writer, so a transfer can leave it one
entry over the cap until the next ordinary write reclaims it.

@brennanb2025
brennanb2025 merged commit a7f1653 into main Aug 17, 2026
45 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…get re-add (stablyai#14917)

* fix(worktrees): keep retirement tombstones across project and SSH target re-add

Generated workspace names are retired so a name is never reissued onto a cwd
that still holds another workspace's Claude/Codex history. Two re-add paths
lost that record.

STA-4449 (local): retirement was stored only under `repo.id`. Removing a
project deletes that row and re-adding the same path mints a new id, so the
new repo starts with an empty registry. The on-disk backfill normally
re-seeds local repos, but it cannot recover a name whose only surviving
evidence is a Codex rollout JSONL — those are deliberately not scanned — so a
name spent under Codex with its workspace directory gone came back.

STA-4491 (SSH): the second, path-derived copy embedded the SSH target row id.
Row ids are minted fresh on every re-add, so `ssh:ssh-old:...` became
`ssh:ssh-new:...` and `reassignSshTargetId` migrated other carrier state but
not the retirement namespaces.

Keying the store on the namespace instead of `repo.id` was rejected in
`nestWorkspaces`, `worktreeBasePath` and `repo.path`, so a settings toggle
would orphan every retirement at once. `repo.id` therefore stays primary and
the path-derived namespace stays a mirror — a settings toggle loses the
mirror but keeps the repo row, a re-add loses the repo row but keeps the
mirror, and reads union both.

- Mirror local repos into the namespace too, not just remote ones.
- Key the namespace's host half on the SSH endpoint (host+port+username), the
  thing that actually decides which filesystem a path lands on, instead of the
  target row id. Reads also accept the pre-identity key so an upgrade keeps
  tombstones it already wrote, and `reassignSshTargetId` re-keys the rest.
- Cap the namespace map, which by design outlives the repos that wrote it and
  so has nothing to prune it per repo.

Endpoint identity is extracted from ssh-target-readoption.ts, which already
compared these fields for exactly the same reason, so re-adoption and
retirement cannot drift apart.

* fix(worktrees): copy shared SSH endpoint retirements instead of moving them

An endpoint identity is not owned by the target row that rotates: nothing
dedupes SSH targets by host|port|username, so a second live target can still
resolve to the same host. Moving the bucket stripped that target's tombstones
and reissued a path whose agent history is still on disk.

Row-id identities stay a move — reassignment leaves nothing pointing at them.

* fix(worktrees): carry retirement mirror across in-place SSH endpoint edits

Config sync rewrites host/port/username on the existing target row and a
runtime-owned target takes a fresh address from every provision, both keeping
the row id. No re-adoption runs, so nothing carried the endpoint-keyed mirror
across and it stranded — strictly worse than the pre-change key, which was the
row id and was invariant under these edits.

Also bound the map after a migration: a retained source bucket grows it, so the
cap has to be applied there too, and compare registries by membership rather
than size so an uncompacted destination cannot trade a folded name for a new
one and read as unchanged.

* fix(worktrees): skip retirement migration for on-demand runtime targets

An on-demand VM is discarded between provisions, so its fresh address reaches an
empty filesystem and a reissued name collides with nothing. Migrating there
would spend names against history that no longer exists, and because each
provision mints another address it would add a namespace bucket per run,
evicting the real tombstones of local and ordinary SSH repos.

* fix(worktrees): stop the namespace cap evicting what a migration just wrote

Two defects with one root cause. Assigning to an existing key leaves it in its
original insertion slot, so a merged destination kept the oldest position and the
trim deleted the bucket it had just enriched. Retained source buckets are older
than the destinations a copy appends, so at the cap the trim removed exactly the
sources the copy existed to keep — silently turning it back into a move. The trim
now exempts the keys the migration wrote or deliberately kept.

Also stop on-demand runtime workspaces writing namespace mirrors at all: each
provision reaches a discarded filesystem under a fresh address, so the entry can
never be read back and only spends a capped slot that a local or SSH project
needs. The repo-id row still records the name for the live session.

* fix(worktrees): re-insert migrated namespaces so the cap cannot undo a migration

Exempting keys from the trim protected them for that one call and no other. A
merged destination keeps its original insertion slot, so it sat at the front of
the eviction queue and the next unrelated retirement write dropped it — losing
both the migrated name and the name the destination already held, on a host that
had just been re-added.

Re-insert what the migration writes instead, the same discipline the ordinary
writer already follows, so insertion order reflects use. That also removes the
exemption, which could otherwise leave the map stuck at twice the cap until one
later write evicted the whole excess at once.

Corrects the runtime-gate comment as well: the mirror is unreadable after the
next provision, not immediately, so a remove/re-add inside one provision is a
real if narrow loss.

* fix(worktrees): refresh a retained namespace source even when its merge adds nothing

Replacing the trim exemption with re-insertion narrowed the protection: the
exemption covered every retained source, the re-insertion only covered sources
whose merge actually wrote. A copy whose destination already held the same names
was then neither re-inserted nor exempt, so the migration's own trim evicted the
shared source bucket ahead of hundreds of untouched ones — losing the tombstones
of a live sibling target still on that endpoint, which is what copying exists to
prevent.

A move's destination gets the same treatment: deleting the source makes it the
only remaining copy, so it has been used. Both are order-only and deliberately do
not set the changed flag, keeping an import that moved nothing from scheduling a
save.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…get re-add (stablyai#14917)

* fix(worktrees): keep retirement tombstones across project and SSH target re-add

Generated workspace names are retired so a name is never reissued onto a cwd
that still holds another workspace's Claude/Codex history. Two re-add paths
lost that record.

STA-4449 (local): retirement was stored only under `repo.id`. Removing a
project deletes that row and re-adding the same path mints a new id, so the
new repo starts with an empty registry. The on-disk backfill normally
re-seeds local repos, but it cannot recover a name whose only surviving
evidence is a Codex rollout JSONL — those are deliberately not scanned — so a
name spent under Codex with its workspace directory gone came back.

STA-4491 (SSH): the second, path-derived copy embedded the SSH target row id.
Row ids are minted fresh on every re-add, so `ssh:ssh-old:...` became
`ssh:ssh-new:...` and `reassignSshTargetId` migrated other carrier state but
not the retirement namespaces.

Keying the store on the namespace instead of `repo.id` was rejected in
`nestWorkspaces`, `worktreeBasePath` and `repo.path`, so a settings toggle
would orphan every retirement at once. `repo.id` therefore stays primary and
the path-derived namespace stays a mirror — a settings toggle loses the
mirror but keeps the repo row, a re-add loses the repo row but keeps the
mirror, and reads union both.

- Mirror local repos into the namespace too, not just remote ones.
- Key the namespace's host half on the SSH endpoint (host+port+username), the
  thing that actually decides which filesystem a path lands on, instead of the
  target row id. Reads also accept the pre-identity key so an upgrade keeps
  tombstones it already wrote, and `reassignSshTargetId` re-keys the rest.
- Cap the namespace map, which by design outlives the repos that wrote it and
  so has nothing to prune it per repo.

Endpoint identity is extracted from ssh-target-readoption.ts, which already
compared these fields for exactly the same reason, so re-adoption and
retirement cannot drift apart.

* fix(worktrees): copy shared SSH endpoint retirements instead of moving them

An endpoint identity is not owned by the target row that rotates: nothing
dedupes SSH targets by host|port|username, so a second live target can still
resolve to the same host. Moving the bucket stripped that target's tombstones
and reissued a path whose agent history is still on disk.

Row-id identities stay a move — reassignment leaves nothing pointing at them.

* fix(worktrees): carry retirement mirror across in-place SSH endpoint edits

Config sync rewrites host/port/username on the existing target row and a
runtime-owned target takes a fresh address from every provision, both keeping
the row id. No re-adoption runs, so nothing carried the endpoint-keyed mirror
across and it stranded — strictly worse than the pre-change key, which was the
row id and was invariant under these edits.

Also bound the map after a migration: a retained source bucket grows it, so the
cap has to be applied there too, and compare registries by membership rather
than size so an uncompacted destination cannot trade a folded name for a new
one and read as unchanged.

* fix(worktrees): skip retirement migration for on-demand runtime targets

An on-demand VM is discarded between provisions, so its fresh address reaches an
empty filesystem and a reissued name collides with nothing. Migrating there
would spend names against history that no longer exists, and because each
provision mints another address it would add a namespace bucket per run,
evicting the real tombstones of local and ordinary SSH repos.

* fix(worktrees): stop the namespace cap evicting what a migration just wrote

Two defects with one root cause. Assigning to an existing key leaves it in its
original insertion slot, so a merged destination kept the oldest position and the
trim deleted the bucket it had just enriched. Retained source buckets are older
than the destinations a copy appends, so at the cap the trim removed exactly the
sources the copy existed to keep — silently turning it back into a move. The trim
now exempts the keys the migration wrote or deliberately kept.

Also stop on-demand runtime workspaces writing namespace mirrors at all: each
provision reaches a discarded filesystem under a fresh address, so the entry can
never be read back and only spends a capped slot that a local or SSH project
needs. The repo-id row still records the name for the live session.

* fix(worktrees): re-insert migrated namespaces so the cap cannot undo a migration

Exempting keys from the trim protected them for that one call and no other. A
merged destination keeps its original insertion slot, so it sat at the front of
the eviction queue and the next unrelated retirement write dropped it — losing
both the migrated name and the name the destination already held, on a host that
had just been re-added.

Re-insert what the migration writes instead, the same discipline the ordinary
writer already follows, so insertion order reflects use. That also removes the
exemption, which could otherwise leave the map stuck at twice the cap until one
later write evicted the whole excess at once.

Corrects the runtime-gate comment as well: the mirror is unreadable after the
next provision, not immediately, so a remove/re-add inside one provision is a
real if narrow loss.

* fix(worktrees): refresh a retained namespace source even when its merge adds nothing

Replacing the trim exemption with re-insertion narrowed the protection: the
exemption covered every retained source, the re-insertion only covered sources
whose merge actually wrote. A copy whose destination already held the same names
was then neither re-inserted nor exempt, so the migration's own trim evicted the
shared source bucket ahead of hundreds of untouched ones — losing the tombstones
of a live sibling target still on that endpoint, which is what copying exists to
prevent.

A move's destination gets the same treatment: deleting the source makes it the
only remaining copy, so it has been used. Both are order-only and deliberately do
not set the changed flag, keeping an import that moved nothing from scheduling a
save.
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