Skip to content

fix(runtime): sweep missing local worktree metadata on the host that owns it - #17893

Closed
nwparker wants to merge 6 commits into
stablyai:mainfrom
nwparker:nwparker/17776-runtime-host-worktree-metadata-sweep
Closed

nwparker wants to merge 6 commits into
stablyai:mainfrom
nwparker:nwparker/17776-runtime-host-worktree-metadata-sweep

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Stacked on #17890. Review that first — this branch contains its commit. The diff to read here is the second commit, fix(runtime): sweep missing local worktree metadata on the host that owns it.

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.listDetected now runs the existing authoritative metadata prune, alongside the lineage prune it already ran on the same scan.ok condition.

  • runtime-managed-worktree-queries.ts — captures getLocalWorktreeScanGeneration(repo.id) and the scan expectation before scanRepo, then calls pruneMetadataMissingFromAuthoritativeLocalScan when the scan came back authoritative. New captureLocalMetadataPruneExpectation helper 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

pruneMetadataMissingFromAuthoritativeLocalScan had 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 a worktreeMeta row whose directory is gone. #17776 measures the result directly: 129 of 139 rows dangling on the Linux host, for its own local repos.

listDetected is the right hook rather than a new sweep:

  • It is the runtime's counterpart of the desktop listing, and already performs the sibling side effect (pruneLineageForMissingRepoWorktrees) on exactly the same scan.ok condition.
  • A paired client refreshing a remote repo calls 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 scanRepo because 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.worktrees may be slightly stale. That is safe in both directions: the listing only narrows the candidate set (livePathKeys), and removal is decided by a fresh stat of 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. getLocalProjectWorktreeGitOptions throws 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.ts drives a real Store against real temp directories:

  • drops a row whose directory is gone and which the authoritative scan does not list
  • keeps a row whose directory still exists
  • keeps every row when the scan is not authoritative (a failed listing is no evidence a checkout is gone)
  • never sweeps a repo whose Git runs off-host, so a local stat miss cannot condemn an SSH checkout

I 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 — clean

  • pnpm run check:code-quality:changed — 0 findings

  • pnpm test src/main/runtime src/main/ipc/worktrees — 6347 passed, 0 failed

  • Platforms: 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

  • Not applicable.

Notes

  • SSH / execution boundary — this is the sensitive part, and the invariant is preserved: the prune's own gates already require !repo.connectionId and getRepoExecutionHostId(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.
  • Remote wire compatibility — no wire change. No RPC params, stream frames, or published content differ; only a host-local side effect of an existing method.
  • Cross-platform — no new path handling. WSL/UNC shapes are excluded up front, and the prune keeps its existing win32 UNC guards.
  • Folder workspaces — listDetected returns before this code on the isFolderRepo branch, so folder workspaces are untouched.
  • Performance — no new subprocess: the prune reuses the scan the listing already ran. It adds a stat per 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.
  • Backwards compatibility — rows are only removed when the host's own Git listing is authoritative and the directory is confirmed missing, which is the same standard the desktop has applied since this prune was introduced.
  • Desktop double-run — on desktop both this and worktrees:listAll can prune. That is idempotent and generation-fenced, the same property the co-located lineage prune already relies on.

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

📝 Walkthrough

Walkthrough

The 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 c4b7c

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 20 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 identifies the primary change: runtime worktree listing now sweeps missing local worktree metadata on the owning host.
Description check ✅ Passed 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 …
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 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.

  • 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: 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.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/runtime/runtime-managed-worktree-metadata-sweep.test.ts
  • src/main/runtime/runtime-managed-worktree-queries.ts
  • src/main/runtime/runtime-store-contract.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; 0 remain after this review.

Comment on lines +34 to +35
for (const worktreeId of Object.keys(state.worktreeMeta)) {
addWorktreeId(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

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.

Suggested change
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)
}

@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 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.listDetected now captures the scan generation and a native-local prune expectation before scanRepo, then runs pruneMetadataMissingFromAuthoritativeLocalScan on scan.ok, beside the lineage prune it already ran there.
  • Capability-gated expectation capture — the new captureLocalMetadataPruneExpectation helper 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 — RuntimeStore gains three optional members so the capability check is typed rather than a bare cast.
  • Test coverage — a new test drives a real Store against temp directories for the drop / keep / non-authoritative / off-host 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 force-pushed the nwparker/17776-runtime-host-worktree-metadata-sweep branch from c505388 to 5ec6e63 Compare September 1, 2026 09:24
@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Good catch — the off-host test was vacuous. Pushed 5ec6e63 (branch rebased on the updated #17890).

@pullfrog: the off-host case passes vacuously. Confirmed. The row was stamped ssh:build-box, and captureNativeLocalWorktreeMetadataScanExpectation only candidates rows with no hostId or hostId === 'local', so it was filtered out before the prune ever ran. It would have survived with every host gate deleted.

Took your suggestion (setWorktreeMetaForHost(missingId, 'local', …), assert via getWorktreeMeta), but the follow-up mattered: I removed repo.connectionId from pruneMetadataMissingFromAuthoritativeLocalScan to check the test now bites, and it still passed. Three more gates derive from the same field on this path — repoStillMatches requires !current.connectionId, and both layers separately require getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID, which resolves to ssh:build-box for a connection-backed repo. Deleting all four to make one test red would be testing the scaffolding, not the behavior.

So the test is now a paired control instead: identical fixture to drops a metadata row whose directory is gone, differing only by connectionId. The first loses the row, this one keeps it, so the connection is demonstrably the only reason. Both comments say so.

@coderabbitai: census skips worktreeMetaByIdentity. That points at #17890's file; answered on that PR. Short version: identity keys are wt2:<host>:<instanceId> and carry no repo id, so the suggested addOwnerKey is a no-op; the locator is on the alias, which the census already reads.

pnpm tc and check:code-quality:changed clean; the runtime sweep tests pass and the dropped-row case still fails with the production change stubbed out.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

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


@nwparker, verification confirms your explanation.

worktreeMetaByIdentity keys are host-qualified identity keys. They do not contain a repository locator. collectDeregisteredRepoIds reads worktreeIdentityAliases and converts each alias with getWorktreeIdFromHostIdentity, which supplies the required worktree locator.

The census does not need to scan worktreeMetaByIdentity directly. I withdraw the finding.


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

Timestamp: 2026-09-01T09:32:38.612Z
Learning: In `src/main/persistence/tracking-repos/deregistered-repo-residue.ts`, `collectDeregisteredRepoIds` must derive repository ownership for host-qualified worktree identity rows from `state.worktreeIdentityAliases`. Keys in `state.worktreeMetaByIdentity` are host-qualified identity keys and do not contain a repository locator.

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

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 local so captureNativeLocalWorktreeMetadataScanExpectation actually candidates it, and the fixture is otherwise byte-for-byte the drop case apart from connectionId. 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.

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 force-pushed the nwparker/17776-runtime-host-worktree-metadata-sweep branch from 5ec6e63 to c492182 Compare September 1, 2026 09:49

@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

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 local so captureNativeLocalWorktreeMetadataScanExpectation candidates it, and only the repo.connectionId / execution-host gate keeps it alive; the row would now be deleted if that gate regressed.
  • Two-reading owner-key identity restored — ownerKeyBelongsToRepo again checks the raw <repoId>::<path> reading before the worktree: workspace-key reading, and ownerKeyWorktreeId became ownerKeyWorktreeIds, which returns both readings so callers agree with the predicate.
  • Orphan census is all-or-nothing — addOwnerKey now seeds a repo id only when no reading of the key names a live repo, and the census additionally seeds from activeWorktreeId, activeWorkspaceKey, and activeWorktreeIdsOnShutdown.
  • Pane-keyed residue is collected — pruneWorktreeStateForRepo collects owner keys from sleepingAgentSessionsByPaneKey and terminalSurfaceTombstonesByPaneKey worktreeIds, 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 Store through "drops a sleeping agent that is the orphan repo's only residue, and self-clears," and a reload asserts sweepDeregisteredRepoResidue() finds nothing.

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

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 sleepingAgentSessionsByPaneKey is 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.

Pullfrog  | View workflow run | Using 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
@nwparker
nwparker force-pushed the nwparker/17776-runtime-host-worktree-metadata-sweep branch from c492182 to c4b7ccb Compare September 2, 2026 00:05

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: 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.

Comment on lines +219 to +220
const reloaded = await createStore()
expect(reloaded.sweepDeregisteredRepoResidue()).toEqual([])

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

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.

Suggested change
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([])

@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. The comment's intent — close #17893 as merged-by-proxy rather than rejected — is already the state on the PR: it is CLOSED with stateReason: COMPLETED (not NOT_PLANNED), closed by nwparker at 2026-09-02T00:20:47Z, mergedAt: null. The eight commits landed on main via rebase-merge of #17901, so nothing further to do here.

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, understood. Closing this PR as merged-by-proxy through #17901 is correct.

The rebase merge preserved the eight commits on main. This matches the repository workflow for multi-commit PRs.

The prior merge-commit option was not available because allow_merge_commit is disabled. Squash-merging stacked PRs would rewrite patch IDs and cause upper branches to replay already-landed changes. The documented exception for worktreeMetaByIdentity remains valid.

🐇


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

Timestamp: 2026-09-02T00:21:03.947Z
Learning: For stacked PRs in `stablyai/orca`, `allow_merge_commit` is disabled. Land multi-commit stacks by rebase-merging the complete upper PR when it contains the stack. Do not squash-merge stack layers in order, because squash commits rewrite patch IDs and later rebases can replay already-landed changes and create identical-hunk conflicts.

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.


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

Timestamp: 2026-09-01T09:32:38.625Z
Learning: In `src/main/persistence/tracking-repos/deregistered-repo-residue.ts`, `collectDeregisteredRepoIds` must derive repository ownership for host-qualified worktree identity rows from `state.worktreeIdentityAliases`. Keys in `state.worktreeMetaByIdentity` are host-qualified identity keys and do not contain a repository locator.

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

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.ts gained an it.each over activeWorktreeId, activeWorkspaceKey (canonical worktree:<id> form), and activeWorktreeIdsOnShutdown, 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 real Store).

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

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