Repository navigation
Conversation
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
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is complete and aligned with the template. It explains the change and rationale, links issue
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 95782b59-b7cd-4b38-a0ae-200050d627f2
📒 Files selected for processing (16)
src/main/orca-profiles/profile-project-worktree-identity.tssrc/main/persistence-cohort-and-identity-migration.test.tssrc/main/persistence-cross-host-pane-identity.test.tssrc/main/persistence-deregistered-repo-residue.test.tssrc/main/persistence-host-partitioned-sessions.test.tssrc/main/persistence-initial-load.test.tssrc/main/persistence-native-chat-tab-view-mode.test.tssrc/main/persistence-repo-lifecycle.test.tssrc/main/persistence-settings-update.test.tssrc/main/persistence-ssh-targets-and-pane-keys.test.tssrc/main/persistence-worktree-lineage-and-backups.test.tssrc/main/persistence/loading-store/repo-lifecycle-operations.tssrc/main/persistence/loading-store/store.tssrc/main/persistence/tracking-repos/deregistered-repo-residue.tssrc/main/ssh-reattach-pane-cardinality.test.tssrc/main/worktree-identity-persistence.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
There was a problem hiding this comment.
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 —
collectDeregisteredRepoIdswalks every persisted collection againststate.repos, andsweepDeregisteredRepoResidueroutes orphan repo ids through the existingremoveProjectpruning paths plus newuiresidue cleanup, scheduling a save only when something was swept. - Owner-key helper extraction —
ownerKeyBelongsToReponow delegates to a newownerKeyWorktreeId(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.tscovers metadata, identity, session, remote-partition, folder-workspace, and byte-stability cases.
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
|
Thanks — three of the four findings were real bugs, and the sleeping-agent one was the serious one. Pushed @pullfrog: sleeping agents survive the sweep. Correct, and worse than "survives": Root cause is in @pullfrog: @coderabbitai: @coderabbitai: census skips Half right, so half applied. Added Declining
|
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 171cd84a-e9bf-4dda-92f2-986a0d375f9e
📒 Files selected for processing (4)
src/main/orca-profiles/profile-project-worktree-identity.tssrc/main/persistence-deregistered-repo-residue.test.tssrc/main/persistence/tracking-repos/deregistered-repo-residue.tssrc/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.
| 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 | ||
| ) | ||
| ) |
There was a problem hiding this comment.
🗄️ 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/mainRepository: 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-sessionsRepository: 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.tsRepository: 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.
|
Tip For best results, initiate chat on the files or code changes.
The sleeping-agent-only test covers the serious repeated-save case. The added session scalar collection closes the remaining ownership gap. I withdraw the 🐇 ✅ ✏️ Learnings added
You are interacting with an AI system. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Sleeping-agent-only residue now swept —
pruneWorktreeStateForRepofeeds sleeping-agent and tombstoneworktreeIds 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 —
ownerKeyWorktreeIdsreturns both locator readings andcollectDeregisteredRepoIdsapplies an all-or-nothing live-repo guard, soworktree:-prefixed keys no longer mis-seed orphans. - Wider residue seeding — the collector now also seeds from
activeWorktreeId,activeWorkspaceKey, andactiveWorktreeIdsOnShutdown. - Documented exclusion — the
terminalTopologyRevisionByRepoIdnon-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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Sleeping-agent residue swept —
pruneWorktreeStateForReponow collects owner keys fromsleepingAgentSessionsByPaneKeyandterminalSurfaceTombstonesByPaneKeyworktree ids, so an orphan whose only residue is a pane-keyed record is removed and the sweep self-clears. - Owner-key readings reconciled —
ownerKeyBelongsToRepois restored to its original body and the census uses the newownerKeyWorktreeIds, which returns both locator readings and seeds an orphan only when neither names a live repo. - Bespoke-rule scalars seeded —
activeWorktreeId,activeWorkspaceKey, andactiveWorktreeIdsOnShutdownnow contribute owner keys, with theterminalTopologyRevisionByRepoIdexclusion documented inline. - Regression coverage — new test pins a sleeping agent as the only residue and asserts a second load's sweep returns
[].
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
|
@coderabbitai on You're right that the second |
|
Tip For best results, initiate chat on the files or code changes.
🐇 ✅ 🧠 Learnings usedIf 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. |
There was a problem hiding this comment.
✅ 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
This PR is fully contained in #17893 and #17901 — verifiedAncestry check: Do not squash-merge this one. If it is squash-merged, 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
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Parametrized scalar-residue regression test — a new
it.eachinpersistence-deregistered-repo-residue.test.tsasserts thatactiveWorktreeId,activeWorkspaceKey(canonicalworktree:form), andactiveWorktreeIdsOnShutdownare each cleared when the scalar is a deregistered repo's only residue, and that a second load sweeps[].
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Landed via #17901, which contained this PR in full — closing as merged-by-proxy rather than as rejected.
So #17901 was rebase-merged alone, which matches how multi-commit PRs land here (individual commits, no 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 |
|
No action needed — this is a closure note on an already-closed PR, and I verified its central claim. PR #17890 is closed (
Nothing to implement, merge, or re-close; the note is informational and its factual basis checks out.
|
|
Tip For best results, initiate chat on the files or code changes.
The eight listed commits contain the full 🐇 ✅ 🧠 Learnings usedYou are interacting with an AI system. |

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
Storenow reconciles its persisted rows against its own repo catalogue at load. Any repo id that owns rows but no longer appears instate.reposhas those rows removed through the same pathremoveProjectalready uses.src/main/persistence/tracking-repos/deregistered-repo-residue.ts—collectDeregisteredRepoIds(state)walksworktreeMeta,worktreeIdentityAliases, both lineage maps,mobileClientTabSelectionsByDeviceId, and every session partition (workspaceSessionplus eachworkspaceSessionsByHostIdentry, includingsleepingAgentSessionsByPaneKeyandterminalSurfaceTombstonesByPaneKeyrecords) and returns the repo ids that are absent fromstate.repos.repo-lifecycle-operations.ts—sweepDeregisteredRepoResidue()runspruneWorktreeStateForRepo+removeRepoFromWorkspaceSession+removeRepoFromHostWorkspaceSessionsper orphan id, then clears orphaneduiresidue (lastActiveRepoId,lastActiveWorktreeId,filterRepoIds,showDotfilesByWorktree).store.ts— invoked in the constructor; schedules a save only when something was actually swept.profile-project-worktree-identity.ts— extractedownerKeyWorktreeId;ownerKeyBelongsToReponow 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:
<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.sparsePresetsByRepoandretiredWorktreeNamesByRepoare 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:
pruneSessionlessMissingLocalWorktreeMetadataForReporequiresrepoStillMatches(state.reposmust contain the repo).removeProject/removeProjectForHost/removeSourceRepoall 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
worktreeMetarows are dangling. Most of those belong to repos that are still registered, whose directories are gone. That is a different root cause:pruneMetadataMissingFromAuthoritativeLocalScanhas exactly one caller,ipcMain.handle('worktrees:listAll'), so a headless runtime host (no renderer) never sweeps its own repos, and the prune is gated toLOCAL_EXECUTION_HOST_IDwith!connectionId, so a client never sweeps remote rows. Fixing that needs a host-authoritative listing rather than a client-sidestat(seedocs/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:lastVisitedAtByWorktreeId,activeTabTypeByWorktree,sleepingAgentSessionsByPaneKey) owned by an unregistered repo idruntime:host partition the owning host's removal can never reach12 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 registeringother-repotoo, so it still asserts that removingr1leaves another repo's selections untouched.pnpm tc— cleanpnpm run check:code-quality:changed— 0 findingspnpm test src/main/persistence+ the touched files — 853 passedpnpm test src/main— the only new failure wasssh-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.AI Disclosure
Claude Opus 4.5 (Claude Code).
Review
Agent skill upstream boundary
Notes
splitWorktreeIdis the existing separator-based parse used everywhere else.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.mobileClientTabSelectionsByDeviceIdrows are pruned via the existingpruneMobileClientTabSelectionscallback, same as project removal.state.repos.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm testpass locally (pnpm buildleft to CI)