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
📝 WalkthroughWalkthroughThe change adds centralized owner-key worktree ID extraction and load-time cleanup for residue linked to deregistered repositories. Cleanup covers worktree metadata, identity mappings, workspace sessions, host-partitioned sessions, and related UI state. The store saves changes caused by the cleanup. Runtime worktree listing now prunes missing local metadata only after authoritative scans. Persistence and runtime tests add repository fixtures and validate cleanup, preservation, and reload behavior. Merge Risk: 🟡 Moderate · up to The PR adds host-side cleanup for stale worktree records, but a current cleanup path can still leave canonical orphaned metadata persisted, and one test does not verify that cleared state was actually saved to disk. Merge should wait for these issues to be fixed or explicitly accepted; the remaining runtime capability concern is bounded. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description follows the repository template. It includes ELI5, changes, rationale, linked issue, visual proof, testing, AI disclosure, boundary notes, and a completed checklist. It also documents the stacked-commit scope and remaining CI build validation.
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 02c8d637-ff53-4bf1-b40c-aa528952c83c
📥 Commits
Reviewing files that changed from the base of the PR and between c475d23 and c505388b861d071059e399579733c7d9fe4ed321.
📒 Files selected for processing (19)
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/runtime/runtime-managed-worktree-metadata-sweep.test.tssrc/main/runtime/runtime-managed-worktree-queries.tssrc/main/runtime/runtime-store-contract.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; 0 remain after this review.
| for (const worktreeId of Object.keys(state.worktreeMeta)) { | ||
| addWorktreeId(worktreeId) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Include canonical metadata identities in the residue census.
Line 34 scans only worktreeMeta. It skips worktreeMetaByIdentity, which can be the only persisted row for an orphaned worktree. In that state, collectDeregisteredRepoIds returns no repo ID, so the load-time sweep does not remove the canonical metadata.
Add each worktreeMetaByIdentity key through addOwnerKey.
Proposed fix
for (const worktreeId of Object.keys(state.worktreeMeta)) {
addWorktreeId(worktreeId)
}
+ for (const ownerKey of Object.keys(state.worktreeMetaByIdentity ?? {})) {
+ addOwnerKey(ownerKey)
+ }📝 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.
| for (const worktreeId of Object.keys(state.worktreeMeta)) { | |
| addWorktreeId(worktreeId) | |
| for (const worktreeId of Object.keys(state.worktreeMeta)) { | |
| addWorktreeId(worktreeId) | |
| } | |
| for (const ownerKey of Object.keys(state.worktreeMetaByIdentity ?? {})) { | |
| addOwnerKey(ownerKey) | |
| } |
There was a problem hiding this comment.
ℹ️ No critical issues — one test doesn't pin what its comment claims, so it would still pass with the bug present.
Reviewed changes
Reviewed the second commit of this stacked branch (fix(runtime): sweep missing local worktree metadata on the host that owns it), which reuses the existing authoritative metadata prune on the runtime's listDetected path.
- Runtime sweep wiring —
RuntimeManagedWorktreeQueries.listDetectednow captures the scan generation and a native-local prune expectation beforescanRepo, then runspruneMetadataMissingFromAuthoritativeLocalScanonscan.ok, beside the lineage prune it already ran there. - Capability-gated expectation capture — the new
captureLocalMetadataPruneExpectationhelper bails when the store lacks the capture method, when the repo is WSL-routed, or when runtime resolution throws (repair-required), so no destructive expectation is carried for those repos. - Typed store contract —
RuntimeStoregains three optional members so the capability check is typed rather than a bare cast. - Test coverage — a new test drives a real
Storeagainst temp directories for the drop / keep / non-authoritative / off-host 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
c505388 to
5ec6e63
Compare
|
Good catch — the off-host test was vacuous. Pushed @pullfrog: the off-host case passes vacuously. Confirmed. The row was stamped Took your suggestion ( So the test is now a paired control instead: identical fixture to @coderabbitai: census skips
|
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
identity_file=$(fd -a '^profile-project-worktree-identity\.ts$' src | head -n 1)
residue_file=$(fd -a '^deregistered-repo-residue\.ts$' src | head -n 1)
printf '%s\n' '--- identity module outline ---'
ast-grep outline "$identity_file" --items all --view expanded
printf '%s\n' '--- identity module relevant symbols ---'
rg -n -C 8 'ownerKeyWorktreeIds|ownerKeyBelongsToRepo|wt2:' "$identity_file"
printf '%s\n' '--- residue module outline ---'
ast-grep outline "$residue_file" --items all --view expanded
printf '%s\n' '--- census and identity-map references ---'
rg -n -C 10 'worktreeMetaByIdentity|addOwnerKey|ownerKeyWorktreeIds|alias' "$residue_file"Length of output: 9509
The census does not need to scan ✏️ Learnings added
You are interacting with an AI system. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior review — one commit (5ec6e63) that reworks the off-host sweep test into a paired control.
- Off-host test is now a real control — the row is stamped
localsocaptureNativeLocalWorktreeMetadataScanExpectationactually candidates it, and the fixture is otherwise byte-for-byte the drop case apart fromconnectionId. The pairing is the proof: the same fixture without a connection loses the row, so the connection is demonstrably the only reason this one keeps it.
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
5ec6e63 to
c492182
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review: the off-host sweep test was reworked into a real control, and the branch picked up a persistence fix for sleeping-agent-only residue plus the orphan-census hardening that comes with it.
- Off-host test is now a real control — the row is stamped
localsocaptureNativeLocalWorktreeMetadataScanExpectationcandidates it, and only therepo.connectionId/ execution-host gate keeps it alive; the row would now be deleted if that gate regressed. - Two-reading owner-key identity restored —
ownerKeyBelongsToRepoagain checks the raw<repoId>::<path>reading before theworktree:workspace-key reading, andownerKeyWorktreeIdbecameownerKeyWorktreeIds, which returns both readings so callers agree with the predicate. - Orphan census is all-or-nothing —
addOwnerKeynow seeds a repo id only when no reading of the key names a live repo, and the census additionally seeds fromactiveWorktreeId,activeWorkspaceKey, andactiveWorktreeIdsOnShutdown. - Pane-keyed residue is collected —
pruneWorktreeStateForRepocollects owner keys fromsleepingAgentSessionsByPaneKeyandterminalSurfaceTombstonesByPaneKeyworktreeIds, so an orphan whose only residue is a sleeping agent is dropped and the store self-clears. - Regression coverage — a new test drives a real
Storethrough "drops a sleeping agent that is the orphan repo's only residue, and self-clears," and a reload assertssweepDeregisteredRepoResidue()finds nothing.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review: the branch was rebased and gained one test-only commit.
- On-disk persistence assertion — the sleeping-agent self-clearing test now reads the flushed profile and asserts
sleepingAgentSessionsByPaneKeyis empty on disk before the reload, so the subsequent "nothing to sweep on next load" assertion cannot pass vacuously when the cleanup was only applied in memory.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
`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
…owns it
`pruneMetadataMissingFromAuthoritativeLocalScan` had exactly one caller:
`ipcMain.handle('worktrees:listAll')`. A headless runtime host has no
renderer, so it never ran, and that host's `worktreeMeta` grew without bound
even for its own local repos -- 129 of 139 rows dangling on the profile in
stablyai#17776.
Run it from the runtime's own detected listing instead. That is the same
trigger on the same evidence: `listDetected` already prunes lineage on an
authoritative scan, and a paired client refreshing a remote repo calls
`worktree.detectedList`, so the host now sweeps exactly when the desktop
would have.
The expectation is captured before the scan, because listing can mutate
metadata synchronously before its first await. WSL-routed repos are excluded
for the reason the desktop listing excludes them: the listing runs in the
distro and reports Linux paths while metadata can hold UNC ones, and v1
cannot prove those aliases equivalent. A runtime needing repair throws rather
than resolving routing, which is likewise no basis for deleting rows.
The prune's own gates still apply, so an SSH- or otherwise off-host repo is
never swept from a local stat -- the execution host owns that verdict.
Refs stablyai#17776
The row was stamped `ssh:build-box`, which `captureNativeLocalWorktreeMetadataScanExpectation` filters out before the prune runs -- so it survived whether or not any host gate existed and pinned nothing. Stamp it `local` so it is a genuine prune candidate whose directory really is missing, and make the fixture identical to the first case apart from `connectionId`. That pairing is what proves the behavior: the same fixture without a connection loses the row. Deleting any single gate would not show it, since four independent checks derive from `connectionId` on this path. Refs stablyai#17776
c492182 to
c4b7ccb
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: f2addeec-94de-40c5-9f9c-4029e58ac6d2
📥 Commits
Reviewing files that changed from the base of the PR and between 5ec6e635a9731fadea405d430d7f9e713609ae2c and c4b7ccb.
📒 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; 1 remains after this review.
| const reloaded = await createStore() | ||
| expect(reloaded.sweepDeregisteredRepoResidue()).toEqual([]) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Assert scalar cleanup on disk before reloading.
The later empty sweep does not prove that store.flush() persisted the cleared fields. createStore() performs load-time cleanup, so a stale scalar can be removed again during reload and still make the sweep return [].
Read readDataFile() after the flush and assert the RUNTIME_HOST partition before creating reloaded.
Proposed test adjustment
const partition = store.getWorkspaceSession(RUNTIME_HOST)
expect(partition.activeWorktreeId ?? null).toBeNull()
expect(partition.activeWorkspaceKey ?? null).toBeNull()
expect(partition.activeWorktreeIdsOnShutdown ?? []).toEqual([])
+ const persisted = readDataFile() as PersistedState
+ const persistedPartition = persisted.workspaceSessionsByHostId?.[RUNTIME_HOST] ?? {}
+ expect(persistedPartition.activeWorktreeId ?? null).toBeNull()
+ expect(persistedPartition.activeWorkspaceKey ?? null).toBeNull()
+ expect(persistedPartition.activeWorktreeIdsOnShutdown ?? []).toEqual([])
const reloaded = await createStore()
expect(reloaded.sweepDeregisteredRepoResidue()).toEqual([])📝 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.
| const reloaded = await createStore() | |
| expect(reloaded.sweepDeregisteredRepoResidue()).toEqual([]) | |
| const partition = store.getWorkspaceSession(RUNTIME_HOST) | |
| expect(partition.activeWorktreeId ?? null).toBeNull() | |
| expect(partition.activeWorkspaceKey ?? null).toBeNull() | |
| expect(partition.activeWorktreeIdsOnShutdown ?? []).toEqual([]) | |
| const persisted = readDataFile() as PersistedState | |
| const persistedPartition = persisted.workspaceSessionsByHostId?.[RUNTIME_HOST] ?? {} | |
| expect(persistedPartition.activeWorktreeId ?? null).toBeNull() | |
| expect(persistedPartition.activeWorkspaceKey ?? null).toBeNull() | |
| expect(persistedPartition.activeWorktreeIdsOnShutdown ?? []).toEqual([]) | |
| const reloaded = await createStore() | |
| expect(reloaded.sweepDeregisteredRepoResidue()).toEqual([]) |
|
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. The comment's intent — close #17893 as merged-by-proxy rather than rejected — is already the state on the PR: it is
|
|
Tip For best results, initiate chat on the files or code changes.
The rebase merge preserved the eight commits on The prior merge-commit option was not available because 🐇 ✏️ Learnings added
🧠 Learnings usedYou are interacting with an AI system. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review: the two runtime commits were rebased unchanged, and a test-only commit added parametrized coverage for each session scalar held as an orphan repo's only residue.
- Session-scalar orphan coverage —
persistence-deregistered-repo-residue.test.tsgained anit.eachoveractiveWorktreeId,activeWorkspaceKey(canonicalworktree:<id>form), andactiveWorktreeIdsOnShutdown, each seeded as the orphan's only residue. Each case asserts the scalar is cleared and that a reload finds nothing left to sweep (self-clearing). Verified meaningful and passing (9 tests green against a realStore).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

ELI5
Orca already knows how to notice "this worktree's folder is gone, drop its leftover bookkeeping." But that cleanup only ever ran when the desktop window asked for a worktree list. A remote Orca host has no window, so it never cleaned up its own — one profile in the issue had 129 of 139 rows pointing at folders that no longer existed. Now the host runs the same cleanup when a client asks it for its worktrees.
What Changed
RuntimeManagedWorktreeQueries.listDetectednow runs the existing authoritative metadata prune, alongside the lineage prune it already ran on the samescan.okcondition.runtime-managed-worktree-queries.ts— capturesgetLocalWorktreeScanGeneration(repo.id)and the scan expectation beforescanRepo, then callspruneMetadataMissingFromAuthoritativeLocalScanwhen the scan came back authoritative. NewcaptureLocalMetadataPruneExpectationhelper decides whether this repo may carry a destructive expectation at all.runtime-store-contract.ts— three optional members so the capability check is typed rather than a bare cast:captureNativeLocalWorktreeMetadataScanExpectation,pruneSessionlessMissingLocalWorktreeMetadataForRepo,getProfileStorageDirectory.No new pruning logic. The prune, its fences, and its host gates are all reused as-is.
Why
pruneMetadataMissingFromAuthoritativeLocalScanhad exactly one caller —ipcMain.handle('worktrees:listAll'). That is a renderer IPC, so on a headless runtime host it never fires and nothing else ever removes aworktreeMetarow whose directory is gone. #17776 measures the result directly: 129 of 139 rows dangling on the Linux host, for its own local repos.listDetectedis the right hook rather than a new sweep:pruneLineageForMissingRepoWorktrees) on exactly the samescan.okcondition.worktree.detectedList, which lands here — so the host now sweeps on the same trigger the desktop always used, with no new polling or subprocess.Ordering. The expectation is captured before
scanRepobecause listing can mutate metadata synchronously before its first await; the prune revalidates against the rows as they stood when the scan was issued.A cached scan cannot cause a wrong deletion. The runtime's scan has a TTL and a Git-admin fingerprint fast path, so
scan.worktreesmay be slightly stale. That is safe in both directions: the listing only narrows the candidate set (livePathKeys), and removal is decided by a freshstatof each candidate. A stale listing that omits a new worktree still finds its directory present and keeps the row; a stale listing that still names a removed worktree simply skips it that round.WSL is excluded, matching the desktop listing: the listing runs in the distro and reports Linux paths while metadata can hold UNC ones, and v1 cannot prove those aliases equivalent.
getLocalProjectWorktreeGitOptionsthrows for a runtime that needs repair, which is likewise no basis for deleting rows, so that path yields no expectation either.Linked Issue
Refs #17776
Visual Proof
N/A— no UI code changes. The effect is the disappearance of persisted rows that only ever backed stale sidebar entries; there is no new or altered UI surface.Testing
New
src/main/runtime/runtime-managed-worktree-metadata-sweep.test.tsdrives a realStoreagainst real temp directories:statmiss cannot condemn an SSH checkoutI confirmed the first test fails without the production change (stubbing the call out flips exactly that one to red), so it is not passing vacuously.
pnpm tc— cleanpnpm run check:code-quality:changed— 0 findingspnpm test src/main/runtime src/main/ipc/worktrees— 6347 passed, 0 failedPlatforms: verified on macOS. The WSL and SSH branches are covered by unit tests rather than live hosts; both are exclusion paths, so the failure mode of a wrong exclusion is "keeps doing what it does today."
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
Notes
!repo.connectionIdandgetRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID, so a host only ever condemns checkouts it can itself stat. Loss of contact with another host still removes nothing. Covered by the off-host test.win32UNC guards.listDetectedreturns before this code on theisFolderRepobranch, so folder workspaces are untouched.statper metadata row that the scan did not list, and only on an authoritative scan. That set is exactly the rows being leaked today, so it shrinks to zero after the first sweep.worktrees:listAllcan prune. That is idempotent and generation-fenced, the same property the co-located lineage prune already relies on.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm testpass locally (pnpm buildleft to CI)