Skip to content

fix(persistence): sweep rows owned by deregistered repo ids at load - #17890

Closed
nwparker wants to merge 4 commits into
stablyai:mainfrom
nwparker:nwparker/bug-worktreemeta-session-orphans-never-swept-aft
Closed

nwparker wants to merge 4 commits into
stablyai:mainfrom
nwparker:nwparker/bug-worktreemeta-session-orphans-never-swept-aft

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

ELI5

If you remove a project from Orca, all the leftover bookkeeping for it — its worktrees, its tabs, its sleeping agents — stayed in the profile file forever, because every cleanup routine first asks "is this project still registered?" and the answer is no. On a paired client those leftovers showed up in the sidebar as ghost worktrees under an "Unknown" project, and there was no way to get rid of them short of hand-editing JSON. Now the store cleans them up the next time it loads.

What Changed

Store now reconciles its persisted rows against its own repo catalogue at load. Any repo id that owns rows but no longer appears in state.repos has those rows removed through the same path removeProject already uses.

  • New src/main/persistence/tracking-repos/deregistered-repo-residue.ts — collectDeregisteredRepoIds(state) walks worktreeMeta, worktreeIdentityAliases, both lineage maps, mobileClientTabSelectionsByDeviceId, and every session partition (workspaceSession plus each workspaceSessionsByHostId entry, including sleepingAgentSessionsByPaneKey and terminalSurfaceTombstonesByPaneKey records) and returns the repo ids that are absent from state.repos.
  • repo-lifecycle-operations.ts — sweepDeregisteredRepoResidue() runs pruneWorktreeStateForRepo + removeRepoFromWorkspaceSession + removeRepoFromHostWorkspaceSessions per orphan id, then clears orphaned ui residue (lastActiveRepoId, lastActiveWorktreeId, filterRepoIds, showDotfilesByWorktree).
  • store.ts — invoked in the constructor; schedules a save only when something was actually swept.
  • profile-project-worktree-identity.ts — extracted ownerKeyWorktreeId; ownerKeyBelongsToRepo now delegates to it. Behaviour-identical (the two branches are disjoint), it just makes "which worktree does this owner key name" reusable.

Two deliberate narrowings, both commented in the source:

  • Only a full <repoId>::<path> locator seeds the orphan set. A bare key can be a folder workspace id or a repo-keyed topology revision, and it cannot be told apart from a repo id — guessing wrong there deletes live session state.
  • sparsePresetsByRepo and retiredWorktreeNamesByRepo are left alone. Both are bounded, and dropping a retired-name row would let a re-added repo reissue a name onto a cwd that still holds a prior occupant's agent state.

Why

Every path that removes a repo's rows is gated on the repo still being registered:

  • pruneSessionlessMissingLocalWorktreeMetadataForRepo requires repoStillMatches (state.repos must contain the repo).
  • removeProject / removeProjectForHost / removeSourceRepo all take a repo id the local store currently owns.

So the cleanup is gated on the very condition whose absence created the garbage. Once an id leaves the catalogue, nothing can reach its rows again — and on a paired client the mirror of a remote host's session partition is keyed by ids that client never registers, so a removal on the owning host can never reach it either.

Reconciling against the catalogue at load removes that dependency. It is safe to ignore the session-ownership and local-execution-host gates the missing-directory sweeper needs, because an orphan has no owner that could object; that is also what lets it reach the remote-host partitions.

Scope — what this does not fix. The issue also reports that ~93–99% of worktreeMeta rows are dangling. Most of those belong to repos that are still registered, whose directories are gone. That is a different root cause: pruneMetadataMissingFromAuthoritativeLocalScan has exactly one caller, ipcMain.handle('worktrees:listAll'), so a headless runtime host (no renderer) never sweeps its own repos, and the prune is gated to LOCAL_EXECUTION_HOST_ID with !connectionId, so a client never sweeps remote rows. Fixing that needs a host-authoritative listing rather than a client-side stat (see docs/reference/ssh-execution-boundary.md) and is being sent as a follow-up PR stacked on this one.

Linked Issue

Refs #17776

Visual Proof

N/A — no UI code changes. The user-visible effect is the disappearance of sidebar rows that were only ever rendered from orphaned persisted state; there is no new or altered UI surface to show.

Testing

New src/main/persistence-deregistered-repo-residue.test.ts:

  • drops metadata, identity rows and session rows (tabs, lastVisitedAtByWorktreeId, activeTabTypeByWorktree, sleepingAgentSessionsByPaneKey) owned by an unregistered repo id
  • sweeps a runtime: host partition the owning host's removal can never reach
  • keeps rows for a registered repo on a non-local execution host — and asserts the sleeping-agent fixture survives, so the sweep assertions above cannot pass vacuously
  • leaves folder-workspace session keys alone
  • leaves a profile with no orphans byte-identical across two reloads, so the sweep cannot dirty every launch

12 existing test files had fixtures that wrote worktree rows without ever registering the repo — they were relying on orphans surviving a reload. Each now registers the repo it names. persistence-worktree-lineage-and-backups.test.ts ("prunes selections for a removed repo worktree") keeps its original intent by registering other-repo too, so it still asserts that removing r1 leaves another repo's selections untouched.

  • pnpm tc — clean
  • pnpm run check:code-quality:changed — 0 findings
  • pnpm test src/main/persistence + the touched files — 853 passed
  • Full pnpm test src/main — the only new failure was ssh-reattach-pane-cardinality.test.ts, a fixture of this same shape, now fixed. The remaining 7 failures reproduce on a stashed baseline (zsh live-shell, Electron dev-app rebuild, TUI transcript catchup, and two load-sensitive timeouts).

Platforms: logic is platform-independent (no path or shell handling). Verified on macOS. Remote/SSH covered by the runtime: and non-local-host tests above rather than a live host.

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

AI Disclosure

Claude Opus 4.5 (Claude Code).

Review

Agent skill upstream boundary

  • Not applicable.

Notes

  • Security — no new surface; strictly removes local persisted rows.
  • Cross-platform — no path, shell or keyboard handling; splitWorktreeId is the existing separator-based parse used everywhere else.
  • Remote SSH / runtime — this is the point of the change. It only ever consults state.repos, never the filesystem or a connection, so it makes no liveness claim about a remote host and does not touch the execution boundary. Loss of contact with a host cannot cause a sweep; only the repo leaving the client's own catalogue can.
  • Remote wire compatibility — no wire change. Nothing new is exchanged between client and host.
  • Mobile — orphaned mobileClientTabSelectionsByDeviceId rows are pruned via the existing pruneMobileClientTabSelections callback, same as project removal.
  • Backwards compatibility — on the first launch after upgrade a profile carrying orphans is rewritten once; a clean profile is left byte-identical (pinned by a test). Nothing is removed that any code path could still resolve, since resolution goes through state.repos.
  • Performance — one pass over the persisted collections at load, and it short-circuits before any mutation when no orphans exist. The removal loop is per orphan repo id, which is a small number in practice, and self-clearing after the first sweep.

Checklist

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

Deregistering a project stranded every row it owned. Each pruning path is
gated on the repo still being in `state.repos`, so once an id leaves the
catalogue its metadata, identity aliases, lineage and session rows became
unreachable forever -- and on a paired client they rendered as phantom
worktrees under an "Unknown" project.

Reconcile against the repo catalogue on load instead: any repo id that owns
rows but is absent from `state.repos` has its rows removed through the same
path `removeProject` uses. Host-independent and session-independent, because
an orphan has no owner that could object -- which is also why this reaches a
client's mirror of a remote host's session partition, something no local
removal can do.

Only a full `<repoId>::<path>` locator seeds the orphan set; bare keys can be
folder workspace ids or repo-keyed revisions, and guessing wrong there would
delete live state. `retiredWorktreeNamesByRepo` is deliberately untouched so a
re-added repo cannot reissue a name onto a cwd that still holds a prior
occupant's agent state.

Test fixtures that wrote worktree rows without registering their repo were
relying on orphans surviving a reload; they now register the repo they name.

Refs stablyai#17776
@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 106371e5-39d2-46f8-bc11-075100569597

📥 Commits

Reviewing files that changed from the base of the PR and between 0a6162d and 55b9d6f.

📒 Files selected for processing (1)
  • src/main/persistence-deregistered-repo-residue.test.ts

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


📝 Walkthrough

Walkthrough

The change adds shared owner-key worktree parsing and uses it for repository ownership checks. Store loading now detects deregistered repository IDs, removes their persisted worktree, session, lineage, alias, selection, filter, and dotfile state, and schedules a save when cleanup occurs. New tests cover local and remote residue cleanup, preservation of registered and folder-workspace state, and byte-stable reloads. Existing persistence fixtures now register the repositories referenced by their persisted rows.

Merge Risk: 🔵 Low · up to 55b9d

The change removes stale project data during profile loading, but a narrow terminal-state record may remain for some deregistered repositories, and one persistence test should verify that cleanup is written before reload. The PR is mergeable with explicit owner awareness and follow-up for these bounded cleanup-invariant gaps.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: sweeping persisted rows owned by deregistered repository IDs during load.
Description check ✅ Passed The description is complete and aligned with the template. It explains the change and rationale, links issue #17776, documents testing and platform coverage, addresses visual proof with N/A, and inclu…
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.
Full details: Description check

Explanation

The description is complete and aligned with the template. It explains the change and rationale, links issue #17776, documents testing and platform coverage, addresses visual proof with N/A, and includes the required checklist and review notes.

  • Fix all pre-merge checks with AI

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 95782b59-b7cd-4b38-a0ae-200050d627f2

📥 Commits

Reviewing files that changed from the base of the PR and between c475d23 and c19f6e9.

📒 Files selected for processing (16)
  • src/main/orca-profiles/profile-project-worktree-identity.ts
  • src/main/persistence-cohort-and-identity-migration.test.ts
  • src/main/persistence-cross-host-pane-identity.test.ts
  • src/main/persistence-deregistered-repo-residue.test.ts
  • src/main/persistence-host-partitioned-sessions.test.ts
  • src/main/persistence-initial-load.test.ts
  • src/main/persistence-native-chat-tab-view-mode.test.ts
  • src/main/persistence-repo-lifecycle.test.ts
  • src/main/persistence-settings-update.test.ts
  • src/main/persistence-ssh-targets-and-pane-keys.test.ts
  • src/main/persistence-worktree-lineage-and-backups.test.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts
  • src/main/persistence/loading-store/store.ts
  • src/main/persistence/tracking-repos/deregistered-repo-residue.ts
  • src/main/ssh-reattach-pane-cardinality.test.ts
  • src/main/worktree-identity-persistence.test.ts

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The sweep misses sleepingAgentSessionsByPaneKey when it is the only row left for a deregistered repo — the residue this PR is meant to clear survives, and the store re-dirties itself on every launch. Details inline.

Reviewed changes

  • Load-time orphan reconciliation — collectDeregisteredRepoIds walks every persisted collection against state.repos, and sweepDeregisteredRepoResidue routes orphan repo ids through the existing removeProject pruning paths plus new ui residue cleanup, scheduling a save only when something was swept.
  • Owner-key helper extraction — ownerKeyBelongsToRepo now delegates to a new ownerKeyWorktreeId (behavior-identical), exposing the worktree locator behind an owner key.
  • Fixture corrections — 12 existing test files now register the repos whose rows they persist, and a new persistence-deregistered-repo-residue.test.ts covers metadata, identity, session, remote-partition, folder-workspace, and byte-stability cases.

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

…ing orphans

Review found three holes in the load-time sweep.

`sleepingAgentSessionsByPaneKey` and `terminalSurfaceTombstonesByPaneKey` are
pruned by the worktreeId they name, not by their own key, but
`pruneWorktreeStateForRepo` only collected owner keys from `worktreeMeta` and
`lastVisitedAtByWorktreeId`. An orphan whose only residue was a sleeping agent
therefore survived the sweep and re-seeded it on the next load, so the store
never self-cleared and every launch scheduled another save. Collect owner keys
from those records too, which fixes `removeProject` for the same shape.

`ownerKeyBelongsToRepo` is restored to its original body. Reordering its two
readings was not behavior-preserving as claimed: for a repo named `folder` or
`worktree`, checking the workspace-key reading first flips the result. The
census now uses `ownerKeyWorktreeIds`, which returns both readings, and seeds
only when neither names a live repo -- seeding one reading of a key whose
other reading is live would hand the removal pass a live row to delete.

Seed from `activeWorktreeId`, `activeWorkspaceKey` and
`activeWorktreeIdsOnShutdown`, which are pruned by bespoke rules and so were
reachable by no owner-key loop, and record why
`terminalTopologyRevisionByRepoId` stays excluded.

Refs stablyai#17776
@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — three of the four findings were real bugs, and the sleeping-agent one was the serious one. Pushed 0a6162d.

@pullfrog: sleeping agents survive the sweep. Correct, and worse than "survives": collectDeregisteredRepoIds re-seeded the id every load, so the constructor scheduled a save on every launch forever. My own test missed it because its worktree also had a worktreeMeta row, so the owner key got collected for an unrelated reason.

Root cause is in pruneWorktreeStateForRepo: sleepingAgentSessionsByPaneKey and terminalSurfaceTombstonesByPaneKey are pruned by the worktreeId they name, but collectPrefixedKeys only read worktreeMeta and lastVisitedAtByWorktreeId. Those records now contribute owner keys, which fixes removeProject for the same shape. New test seeds a sleeping agent as the only residue and asserts a second load's sweep returns []; it fails without the fix.

@pullfrog: terminalTopologyRevisionByRepoId can never seed. Right, and intentional — but the note was on the wrong function. Moved it to the loop. Keeping the exclusion: its keys are bare, and addWorktreeId refuses bare keys precisely because a folder workspace id is indistinguishable from a repo id. Seeding from it broke persistence-split-pane-incarnation.test.ts, whose fixture uses a bare wt1 as a worktree id — degenerate, but it shows the failure mode is deleting live session state.

@coderabbitai: folder/worktree as a repo id. Correct, and it means my "behavior-identical" claim for the ownerKeyBelongsToRepo refactor was wrong: reordering the two readings flips the result for exactly those ids. Reverted it to its original body, so that predicate is now untouched by this PR. The census uses a new ownerKeyWorktreeIds, which returns both readings and seeds only when neither names a live repo — seeding one reading of a key whose other reading is live would hand the removal pass (which accepts either) a live row to delete.

@coderabbitai: census skips worktreeMetaByIdentity and the session scalars.

Half right, so half applied. Added activeWorktreeId, activeWorkspaceKey, and activeWorktreeIdsOnShutdown — those are pruned by bespoke rules, so no owner-key loop reached them, and an orphan whose only residue was one of them was never cleared.

Declining worktreeMetaByIdentity. Its keys are wt2:<host>:<instanceId> (canonicalWorktreeIdentity) and carry no repo id at all, so the proposed addOwnerKey would be a no-op — splitWorktreeId returns null on them. The locator lives on the alias (<host>|<repoId>::<path>), which the census already reads, and an identity row whose alias is gone is reclaimed by pruneUnreferencedWorktreeIdentityMeta. If you have a concrete state where an identity row is reachable but its alias is not, I'd like to see it — that would be a gap worth a separate fix.

pnpm tc, check:code-quality:changed, and the persistence + orca-profiles suites are green.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 171cd84a-e9bf-4dda-92f2-986a0d375f9e

📥 Commits

Reviewing files that changed from the base of the PR and between c19f6e9 and 0a6162d.

📒 Files selected for processing (4)
  • src/main/orca-profiles/profile-project-worktree-identity.ts
  • src/main/persistence-deregistered-repo-residue.test.ts
  • src/main/persistence/tracking-repos/deregistered-repo-residue.ts
  • src/main/persistence/tracking-repos/repo-worktree-pruning.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/persistence/tracking-repos/deregistered-repo-residue.ts

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

Comment on lines +65 to +76
const collectScannedRecordOwners = (session: WorkspaceSessionState | undefined): void => {
collectPrefixedKeys(Object.keys(session?.lastVisitedAtByWorktreeId ?? {}))
collectPrefixedKeys(
Object.values(session?.sleepingAgentSessionsByPaneKey ?? {}).map(
(record) => record.worktreeId
)
)
collectPrefixedKeys(
Object.values(session?.terminalSurfaceTombstonesByPaneKey ?? {}).map(
(tombstone) => tombstone.worktreeId
)
)

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 10 \
  'removeWorkspaceSessionOwners|activeWorktreeId|activeWorkspaceKey|activeWorktreeIdsOnShutdown' \
  src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -mindepth 2 -maxdepth 2 -type f -name '*.md' -print \
  -exec sh -c 'printf "\n### %s\n" "$1"; head -80 "$1"' _ {} \;

printf '%s\n' '--- target implementation files ---'
fd -i 'repo-worktree-pruning|session-owner-removal|workspace-session-state' src shared
printf '%s\n' '--- pruning source ---'
cat -n src/main/persistence/tracking-repos/repo-worktree-pruning.ts | sed -n '1,125p'
printf '%s\n' '--- owner-removal source ---'
cat -n src/main/persistence/restoring-sessions/session-owner-removal.ts | sed -n '1,240p'
printf '%s\n' '--- session type declarations ---'
rg -n -C 4 'activeWorktreeId|activeWorkspaceKey|activeWorktreeIdsOnShutdown' src/shared src/main/persistence/restoring-sessions

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- file sizes ---'
wc -l \
  src/main/persistence/tracking-repos/repo-worktree-pruning.ts \
  src/main/persistence/restoring-sessions/session-owner-removal.ts \
  src/shared/workspace-session-state-types.ts

printf '%s\n' '--- pruning implementation ---'
cat -n src/main/persistence/tracking-repos/repo-worktree-pruning.ts | sed -n '20,125p'

printf '%s\n' '--- owner-removal implementation ---'
cat -n src/main/persistence/restoring-sessions/session-owner-removal.ts

printf '%s\n' '--- session fields ---'
rg -n -C 8 \
  'activeWorktreeId|activeWorkspaceKey|activeWorktreeIdsOnShutdown|lastVisitedAtByWorktreeId|sleepingAgentSessionsByPaneKey|terminalSurfaceTombstonesByPaneKey' \
  src/shared/workspace-session-state-types.ts

Repository: stablyai/orca

Length of output: 14353


🏁 Script executed:

#!/bin/bash
set -euo pipefail

fd -i 'session-owner-fields' src/main/persistence/restoring-sessions
cat -n src/main/persistence/restoring-sessions/session-owner-fields.ts
printf '%s\n' '--- callers and tests for owner removal ---'
rg -n -C 6 \
  'deleteOwnerKeyedSessionFields|removeWorkspaceSessionOwner|removeWorkspaceSessionOwners|activeWorktreeIdsOnShutdown' \
  src/main/persistence/restoring-sessions src/main/persistence/tracking-repos \
  -g '*.ts'

Repository: stablyai/orca

Length of output: 41998


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- ownership census and workspace-key semantics ---'
cat -n src/main/persistence/restoring-sessions/session-worktree-ownership.ts | sed -n '1,180p'
printf '%s\n' '--- workspace-key helpers ---'
rg -n -C 8 \
  'export function (worktreeWorkspaceKey|folderWorkspaceKey|parseWorkspaceKey)|type WorkspaceKey|WorkspaceKey' \
  src/shared src/main/persistence/restoring-sessions \
  -g '*.ts' -g '!*.test.ts'
printf '%s\n' '--- pruning tests around orphan session fields ---'
cat -n src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts | sed -n '130,235p'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- ownership collector remainder ---'
cat -n src/main/persistence/restoring-sessions/session-worktree-ownership.ts | sed -n '154,280p'

printf '%s\n' '--- ownership collector tests ---'
cat -n src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts | sed -n '1,125p'

printf '%s\n' '--- pruning test setup and assertions ---'
cat -n src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts | sed -n '1,225p'

Repository: stablyai/orca

Length of output: 19921


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- remaining pruning assertions ---'
cat -n src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts | sed -n '225,360p'

printf '%s\n' '--- target function callers ---'
rg -n -C 8 \
  'pruneWorktreeStateForRepo\(' \
  src/main -g '*.ts' -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 15498


Include direct session owners in repository pruning.

When metadata and scanned records are absent, ownerKeysToPrune stays empty and removeWorkspaceSessionOwners returns the session unchanged. This leaves orphaned activeWorktreeId and activeWorktreeIdsOnShutdown. A canonical activeWorkspaceKey (worktree:<id>) also requires normalization before removal.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@nwparker Thanks for the detailed follow-up.

The sleeping-agent-only test covers the serious repeated-save case. The added session scalar collection closes the remaining ownership gap.

I withdraw the worktreeMetaByIdentity part of my finding. canonicalWorktreeIdentity does not encode a repository ID. The alias provides the repository-bearing locator, and pruneUnreferencedWorktreeIdentityMeta handles stale identity metadata. Excluding bare terminalTopologyRevisionByRepoId keys is also correct because folder-workspace IDs are ambiguous.

🐇 ✅


✏️ Learnings added
Learnt from: nwparker
URL: https://github.com/stablyai/orca/pull/17890

Timestamp: 2026-09-01T09:28:54.755Z
Learning: In the TypeScript persistence loader, `worktreeMetaByIdentity` is keyed by `canonicalWorktreeIdentity` (`wt2:<host>:<instanceId>`) and does not contain a repository ID. Repository ownership is available from the associated alias (`<host>|<repoId>::<path>`). `pruneUnreferencedWorktreeIdentityMeta` reclaims identity metadata whose alias is absent. Do not use bare topology or workspace keys to seed deregistered repository cleanup because a folder-workspace ID can equal a repository ID.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Sleeping-agent-only residue now swept — pruneWorktreeStateForRepo feeds sleeping-agent and tombstone worktreeIds into the owner-key scan, so an orphan whose only residue is a meta-less sleeping agent is pruned and the store self-clears on the next load.
  • Owner-key disambiguation — ownerKeyWorktreeIds returns both locator readings and collectDeregisteredRepoIds applies an all-or-nothing live-repo guard, so worktree:-prefixed keys no longer mis-seed orphans.
  • Wider residue seeding — the collector now also seeds from activeWorktreeId, activeWorkspaceKey, and activeWorktreeIdsOnShutdown.
  • Documented exclusion — the terminalTopologyRevisionByRepoId non-seeding rationale is now stated inline.
  • Regression coverage — a new test asserts a sleeping-agent-only orphan is dropped and that a second load finds nothing to sweep.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Sleeping-agent residue swept — pruneWorktreeStateForRepo now collects owner keys from sleepingAgentSessionsByPaneKey and terminalSurfaceTombstonesByPaneKey worktree ids, so an orphan whose only residue is a pane-keyed record is removed and the sweep self-clears.
  • Owner-key readings reconciled — ownerKeyBelongsToRepo is restored to its original body and the census uses the new ownerKeyWorktreeIds, which returns both locator readings and seeds an orphan only when neither names a live repo.
  • Bespoke-rule scalars seeded — activeWorktreeId, activeWorkspaceKey, and activeWorktreeIdsOnShutdown now contribute owner keys, with the terminalTopologyRevisionByRepoId exclusion documented inline.
  • Regression coverage — new test pins a sleeping agent as the only residue and asserts a second load's sweep returns [].

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

The self-clearing check loaded a second store, but that constructor runs the
sweep itself. If the first flush had not persisted the cleanup, the second load
would have redone it in memory and the assertion would have passed without
meaning anything. Read the profile back and assert the map is empty there first.

Refs stablyai#17776
@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai on persistence-deregistered-repo-residue.test.ts — good catch, applied in 3c59b4e.

You're right that the second createStore() runs the sweep in its own constructor, so if the first flush() had not persisted the cleanup, the reload would have silently redone it and sweepDeregisteredRepoResidue() would have returned [] regardless. The test now reads the profile back and asserts workspaceSession.sleepingAgentSessionsByPaneKey is empty on disk before the second load, so the self-clearing assertion is only reached once persistence is proven.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@nwparker Confirmed. The on-disk assertion verifies that flush() persisted removal of sleepingAgentSessionsByPaneKey. The second-load assertion now verifies that the sweep does not re-clean the same residue.

🐇 ✅


🧠 Learnings used
Learnt from: nwparker
URL: https://github.com/stablyai/orca/pull/17890

Timestamp: 2026-09-01T09:28:54.792Z
Learning: In the TypeScript persistence loader, `worktreeMetaByIdentity` is keyed by `canonicalWorktreeIdentity` (`wt2:<host>:<instanceId>`) and does not contain a repository ID. Repository ownership is available from the associated alias (`<host>|<repoId>::<path>`). `pruneUnreferencedWorktreeIdentityMeta` reclaims identity metadata whose alias is absent. Do not use bare topology or workspace keys to seed deregistered repository cleanup because a folder-workspace ID can equal a repository ID.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • On-disk sweep assertion — the sleeping-agent-only regression test now reads the persisted profile after flush() and asserts the pane-keyed rows are gone on disk, so a flush that silently fails to persist the cleanup fails the test instead of being masked by the subsequent reload.

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

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

This PR is fully contained in #17893 and #17901 — verified

Ancestry check: 17890 (3 commits) ⊂ 17893 (5) ⊂ 17901 (8). All three declare baseRefName: main and report MERGEABLE, but they are nested supersets with byte-identical shared hunks.

Do not squash-merge this one. If it is squash-merged, main receives a single commit whose patch is the sum of three, and none of the individual patch-ids match it — so git rebase main on #17893's branch will replay all three rather than auto-dropping them, producing identical-hunk conflicts across ~15 files. The correct resolution there is skip, and a mechanical "take ours/theirs" on the test files would look plausible while silently losing coverage.

Simplest safe path: land #17901 alone — it contains this PR and #17893 in full. Otherwise merge in stack order using merge commits, and do not rebase the upper branches afterwards.

Full analysis on #17901.

`activeWorktreeId`, `activeWorkspaceKey` and `activeWorktreeIdsOnShutdown` are
pruned by bespoke rules rather than by owner key, so no owner-key loop reaches
them and each has to be able to seed the sweep alone. The sweep already handles
all three -- the census seeds from them and `removeRepoFromWorkspaceSession`
clears them -- but nothing pinned it, and dropping that seeding turns all three
cases red.

The `activeWorkspaceKey` case uses the canonical `worktree:<id>` form, so it
also covers unwrapping the workspace key before the repo id is visible.

Refs stablyai#17776

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Parametrized scalar-residue regression test — a new it.each in persistence-deregistered-repo-residue.test.ts asserts that activeWorktreeId, activeWorkspaceKey (canonical worktree: form), and activeWorktreeIdsOnShutdown are each cleared when the scalar is a deregistered repo's only residue, and that a second load sweeps [].

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

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Landed via #17901, which contained this PR in full — closing as merged-by-proxy rather than as rejected.

allow_merge_commit is false on this repo, so the merge-commit path suggested in the stack analysis was not available. Squash-merging in stack order was the other option and is the one that goes wrong: each squash rewrites the patch-ids, so rebasing the upper branch afterwards replays commits that are already applied instead of dropping them, producing identical-hunk conflicts across ~15 files.

So #17901 was rebase-merged alone, which matches how multi-commit PRs land here (individual commits, no (#N) subject suffix). All eight commits are on main:

a2aea5d0b05 fix(persistence): sweep rows owned by deregistered repo ids at load
2f105b23d17 fix(persistence): sweep sleeping-agent-only residue and stop mis-seeding orphans
87f3e907ddd test(persistence): assert the sleeping-agent cleanup reached disk
1a11f82fcc2 test(persistence): cover each session scalar as an orphan's only residue
ff8b4d08ab9 fix(runtime): sweep missing local worktree metadata on the host that owns it
05a7d390588 test(runtime): make the off-host sweep case a real control
398aeccdfea fix(worktrees): retire runtime-host metadata a scan proved gone
f2fa4a7754e fix(worktrees): drop an unreachable runtime arm from the retirement gate

Every review finding from @coderabbitai and @pullfrog on this PR is addressed in those commits. The one exception is documented rather than fixed: the census does not seed from worktreeMetaByIdentity, because identity keys are wt2:<host>:<instanceId> and carry no repo id — the locator lives on the alias, which the census does read.

@nwparker nwparker closed this Sep 2, 2026
@pullfrog

pullfrog Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

No action needed — this is a closure note on an already-closed PR, and I verified its central claim.

PR #17890 is closed (closed_at 2026-09-02, merged: false), matching the "merged-by-proxy rather than rejected" framing in the note. The eight commits listed as landed via #17901 are all present on main, in the exact order given, with main's HEAD at f2fa4a77 (the last commit in the list):

  • a2aea5d0 → 2f105b23 → 87f3e907 → 1a11f82f → ff8b4d08 → 05a7d390 → 398aeccd → f2fa4a77

Nothing to implement, merge, or re-close; the note is informational and its factual basis checks out.

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

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@nwparker Confirmed. Landing #17901 by rebase merge was the safe path under the repository merge policy.

The eight listed commits contain the full #17890 change set and its follow-up fixes. The worktreeMetaByIdentity exclusion remains correct because canonicalWorktreeIdentity does not contain a repository ID. The alias supplies the repository locator.

🐇 ✅


🧠 Learnings used
Learnt from: nwparker
URL: https://github.com/stablyai/orca/pull/17890

Timestamp: 2026-09-01T09:28:54.792Z
Learning: In the TypeScript persistence loader, `worktreeMetaByIdentity` is keyed by `canonicalWorktreeIdentity` (`wt2:<host>:<instanceId>`) and does not contain a repository ID. Repository ownership is available from the associated alias (`<host>|<repoId>::<path>`). `pruneUnreferencedWorktreeIdentityMeta` reclaims identity metadata whose alias is absent. Do not use bare topology or workspace keys to seed deregistered repository cleanup because a folder-workspace ID can equal a repository ID.

You are interacting with an AI system.

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