Repository navigation
fix(memory): release stale session registries - #21734
Conversation
There was a problem hiding this comment.
Important
The bounded generation maps delete a key on eviction, so a later register/advance can reassign a generation value the key already used earlier in the process. These values are the sole fence against stale responses and a component of cache identities, so reuse can let stale state pass as current.
Reviewed changes
- Bounded fence/generation maps —
ssh-git-dispatch.ts,runtime-environment-transport-generation.ts,runtime-environment-ssh.ts,ssh.ts,runtime-repo-catalog-actions.ts,repo-slug-index.tsnow evict the oldest entry past a per-map cap (512–4096). - Explicit retirement —
local-worktree-scan-generation.tsgainsforget/retire;repo-lifecycle-operations.tsretires on repo removal, last-host removal, and orphan pruning. - Sidecar queues —
sidecar-snapshot-file.tsdeletes per-file queue and temp-cleanup entries when they settle instead of retaining them. - Enrichment / fork-sync cleanup —
repo-git-username-enrichment.tsdrops attempted locations for repos no longer live;safe-auto-fork-sync.tsprunes completed attempts and bounds at 512. - Star-nag toast —
StarNagToastHost.tsxdismisses the infinite toast on unmount (resolving first, so no dismissal telemetry). - Workspace cleanup scan —
workspace-cleanup-scan-snapshot.tsbounds its persisted-scan-time cache to 512. - Tests — new bounds/cleanup assertions across seven test files, plus the repo-removal re-probe and unmount-dismiss cases; each assertion would fail without its corresponding change.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ Minor suggestions only.
Reviewed changes (delta since the prior review)
- Five follow-up commits bounded more registries — WSL route quarantine (512 plus a strike-decay sweep), terminal-history repair dedup set (512), profile dev org rosters (64), shell startup env cache (256), locale formatters (32), browser page insets (512), shell relay recovery generations (512), and PTY controller inventory generations (512).
- New shared helper —
src/main/runtime/prune-oldest-map-entry.tsdeletes a single oldest entry; its only caller sets once before pruning, so it stays at the bound. - Retirement and cleanup — unchanged in direction from the first commit; the new caps follow the same FIFO eviction pattern already flagged in the prior review (now also on
sshRelayRecoveryGenerationByTargetIdandptyControllerInventoryGenerationByProvider).
ℹ️ The "known leak" block is stale after the verdict cap
host-mirror-handle-gap-wait.ts documents a retracted-row verdict as a "KNOWN LEAK, deliberately not drained" whose entry "outlives the session" and keeps the store subscription alive. The new 512-entry cap now evicts the oldest verdict, so that claim is no longer guaranteed. Since that block is explicitly written to be re-read against the code and warns that the prose drifts from the invariants, it should name the cap.
Technical details
# Host-mirror verdict comment block predates the eviction cap
## Affected sites
- `src/renderer/src/lib/host-mirror-handle-gap-wait.ts` — the "KNOWN LEAK, deliberately not drained" paragraph (file lines ~80-96) and the "FOUR drains" enumeration (lines ~53-68) do not mention the new `MAX_EXPIRED_HANDLE_GAP_VERDICTS = 512` eviction in `recordExpiredWait` (lines 204-216).
## Required outcome
- The block reflects that an orphaned verdict is now eventually evicted by churn, so it is bounded rather than session-lifetime, and that the cap is a backstop distinct from the four named drains.
## Open questions for the human
- Is the cap meant as a backstop for the known leak, or only as memory protection that should not be read as closing it? The block's existing warning about prose/pretest drift is why this is worth pinning either way.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| } | ||
| const seeded = seedDevRoster() | ||
| devRostersByOrg.set(orgId, seeded) | ||
| while (devRostersByOrg.size > MAX_DEV_ORG_ROSTERS) { |
There was a problem hiding this comment.
devRostersByOrg is not a cache — inviteDevOrcaCloudOrgMember/changeDevOrcaCloudOrgMemberRole/removeDevOrcaCloudOrgMember mutate the roster in place and listDevOrcaCloudOrgMembers reads it back, so evicting an org's entry silently discards that org's pending invites and role changes. Bounding a source-of-truth store this way is a different tradeoff from bounding the other memoization maps; either drop this cap or evict only rosters with no mutations.
Technical details
# Bounding a mutable dev-auth store discards state
## Affected sites
- `src/main/orca-profiles/profile-cloud-dev-org-members.ts:62` — `getDevRoster` seeds then evicts the oldest roster past `MAX_DEV_ORG_ROSTERS`.
- `src/main/orca-profiles/profile-cloud-dev-org-members.ts:93`, `:106`, `:121`, `:136` — mutations write into the retained `DevOrgRoster` object.
## Required outcome
- Dev-auth member state must not be silently reset by an unrelated org's activity, or the cap must be documented as intentionally discarding it.
## Open questions for the human (optional)
- Is 64 orgs in dev-auth mode reachable at all? If not, the cap buys nothing and can be dropped.There was a problem hiding this comment.
ℹ️ No new issues in the latest two commits. The prior review's two notes (the stale host-mirror "known leak" block and the bounded dev-auth roster store) remain open.
Reviewed changes (delta since the prior review)
- GitLab host-context caches bounded —
knownHostsCacheByExecutionContextandunauthenticatedHostExpiriesare each capped at 128, trimmed on every write; eviction only costs a re-probe, and entries already invalidate on provider-generation change. - SSH connection generations released on removal — new
forgetSshConnectionGeneration, called fromSshProfileOperations.removeSshTarget(the store's only production removal path). This is the explicit-removal pattern rather than an arbitrary cap, and it is not prone to value reuse: the session-scoped base plus random per-add target ids (ssh-${Date.now()}-${random}) mean a forgotten id is never minted again.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughThe pull request bounds many backend and renderer caches, generation maps, retained activities, intent stores, and waiter stores. It adds eviction, expiry pruning, lifecycle cleanup, and test-only size accessors. New tests exercise churn beyond configured limits. WSL home caching moves into a bounded shared module. Toast cleanup now dismisses active toasts on unmount. Priority: ➖ Normal 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed summary, rationale, trade-offs, and validation results. However, it omits required template sections and information, including a Linked Issue, Visual Proof or the required N/A explanation, Testing checkboxes and platform details, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist. Resolution Add all required template sections. Provide the linked issue after ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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.
Important
The automation authority-generation eviction guard can still reopen the fence it was added to keep closed: generationFloor is overwritten on every advance, so a brand-new authority resets it to 1, and an evicted authority's reported generation can fall back to a value a request already captured.
Reviewed changes
- Expired ambiguous cloud-refresh replay attempts on read and capped the registry at 512.
- Released plugin worker generations when a key goes idle, and bounded plugin log buffers to 256 keys.
- Bounded automation authority generations with an eviction-aware floor, native chat model enrichment (256 settled entries), web session tracking generations (512, floor-guarded), and codex credential-absence paths (512).
- Bounded web session reorder intents (512 partitions / 256 per partition) and focus intents (512).
- Bounded the WSL canonical-path cache, sparse-checkout cache, configured shared-directory cache, advertised-URL scan snapshots, and external automation manager cache (all 512, with insertion-order refresh on read/write).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one stale doc line worth updating.
Reviewed changes (delta since the prior pullfrog review)
- Bounded the WSL home cache — moved
wslHomeCacheout ofwsl.tsinto the newsrc/main/wsl-home-cache.ts, capped at 64 entries with LRU refresh on read and write;wsl.tsre-exportshasCachedWslHomeand routesgetWslHome/getWslHomeAsyncthrough the module. - Added a churn test —
wsl.test.tsseeds 68 distros, then asserts a recent distro stays cached without re-probing and an evicted one re-probes (69 calls), pinning both eviction and MRU retention.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| export function getWslHome(distro: string): string | null { | ||
| if (wslHomeCache.has(distro)) { | ||
| return wslHomeCache.get(distro)! | ||
| const cachedHome = getCachedWslHome(distro) |
There was a problem hiding this comment.
getWslHome's JSDoc still says the result is cached "per distro for the process lifetime", but rememberWslHome now evicts the oldest entry past 64, so a cached home can be dropped under distro churn. Worth updating the doc to name the bound so it does not contradict the new behavior.
There was a problem hiding this comment.
ℹ️ No critical issues — the four new caps are clean; one scope question on a sibling cache.
Reviewed changes (delta since the prior pullfrog review)
- Bounded the Windows write-capability host cache —
capabilitiesByExecutionHostinsystem-ssh-windows-write-capabilities.tsis capped at 256 and now refreshed on every access, so a frequently used host survives churn. - Bounded Codex trust-grant transient cooldowns —
transientRetryAfterByHostincodex-hook-trust-grant.tsis capped at 256; expired entries are still dropped on read. - Bounded legacy WSL auth-drain distro state —
completedDistroKeysandpendingSessionBridgeRouteByDistroare each capped at 128 inlegacy-wsl-runtime-auth-drain.ts; re-draining an evicted distro re-inspects and re-bridges, which is idempotent. - Bounded Linear workspace credential caches —
cachedTokensandcredentialErrorsare each capped at 128 inlinear-workspace-registry.ts. - Tests — one churn test per registry; all four files run green (
45 passed).
ℹ️ The sibling codex capability cache shares the host key space and is still unbounded
grantManagedCodexHookTrust now bounds transientRetryAfterByHost (256) keyed by CodexAppServerHostKey, but the codexAppServerCapabilityCache it consults on that same key is a process-lifetime singleton whose supportedCapabilities set grows one entry per host key and is never evicted. The Windows write-capability commit in this same PR bounded the analogous host-keyed CapabilityProbeCache map, so it is worth confirming this one is intentionally out of scope rather than missed.
Technical details
# Unbounded codex app-server capability cache keyed by host
## Affected sites
- `src/main/codex/codex-app-server-capability-cache.ts:30` — the `codexAppServerCapabilityCache` singleton is created once and cleared only from tests.
- `src/shared/capability-probe-cache.ts:13-15` — `supportedCapabilities`, `retryAfterByCapability`, and `probesByCapability` are keyed by `TCapability`; only `probesByCapability` is self-clearing (`:85-87`).
- `src/main/codex/codex-hook-trust-grant.ts:43` — this commit bounds `transientRetryAfterByHost` for the same `CodexAppServerHostKey` at 256.
- `src/main/ssh/system-ssh-windows-write-capabilities.ts:15-36` — the sibling pattern that was bounded in this PR.
## Required outcome
- Either confirm `codexAppServerCapabilityCache` is deliberately exempt, or bound it by host key so `wsl:<distro>` churn cannot grow it for the process lifetime.
## Suggested approach (optional)
- Reuse the same FIFO/LRU host-key eviction used by `rememberCapabilityCache`, or evict a host key when its distro/target is retired (the explicit-removal pattern used for `ssh-connection-generation`).
## Open questions for the human
- Is WSL distro churn low enough that this is intentionally left unbounded, or was it overlooked while auditing module-level holders?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the four new caps are clean; one coverage gap worth a small test.
Reviewed changes (delta since the prior pullfrog review)
- Bounded the local Git capability cache —
localCapabilitiesByExecutionHostingit-capability-state.tsis capped at 128, with insertion order refreshed on every access. - Bounded the WSL Git read-environment cache —
wsl-git-read-environment.tsnow prunessettledEnvironmentByDistro,environmentByDistro, andtransientRetryAfterByDistrotogether at 128 fromtouchDistroState. - Bounded the WSL preflight cache — new
preflight-wsl-cache.tsdrops expired entries and capscachedByWslDistro/latestPreflightRunat 128;agent-detection.tscalls it on entry and after caching. The run-generation fence stays sound becausepreflightRunCounteris monotonic, so an evictedlatestPreflightRunentry can only make a run fail to cache, never accept a stale one. - Tests — churn tests for the Git capability and WSL read-environment caps; both files run green (
34 passed).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| cached.delete(key) | ||
| } | ||
| } | ||
| while (cached.size > maxEntries) { |
There was a problem hiding this comment.
Every other cap in this PR ships with a churn test that fails without it, but prunePreflightWslCache has none — preflight-host-cli-status.test.ts only ever uses two distros, so neither the expiry sweep nor the 128-entry cap is exercised. A small unit test over prunePreflightWslCache (or a >128-distro churn test through runPreflightCheck) would pin both loops.
There was a problem hiding this comment.
Actionable comments posted: 6
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: c3d38aae-324a-4bd0-ac3f-5fc950c8c70e
📒 Files selected for processing (95)
src/main/automations/dispatch-tokens.test.tssrc/main/automations/dispatch-tokens.tssrc/main/automations/external-automation-manager-cache.test.tssrc/main/automations/external-automation-manager-cache.tssrc/main/codex-accounts/codex-credential-absence-grace.test.tssrc/main/codex-accounts/codex-credential-absence-grace.tssrc/main/codex-accounts/legacy-wsl-runtime-auth-drain.test.tssrc/main/codex-accounts/legacy-wsl-runtime-auth-drain.tssrc/main/codex/codex-hook-trust-grant.test.tssrc/main/codex/codex-hook-trust-grant.tssrc/main/codex/codex-wsl-hook-install-plan.test.tssrc/main/codex/codex-wsl-hook-install-plan.tssrc/main/daemon/terminal-history-permission-repair.tssrc/main/git/git-capability-state.test.tssrc/main/git/git-capability-state.tssrc/main/git/runner-wsl-direct-read.test.tssrc/main/git/worktree-shared-directories.test.tssrc/main/git/worktree-shared-directories.tssrc/main/git/worktree-sparse-checkout-cache.test.tssrc/main/git/worktree-sparse-checkout-cache.tssrc/main/git/wsl-git-read-environment.tssrc/main/gitlab/gitlab-known-host-probe.test.tssrc/main/gitlab/gitlab-known-host-probe.tssrc/main/ipc/runtime-environment-transport-generation.test.tssrc/main/ipc/runtime-environment-transport-generation.tssrc/main/linear/linear-workspace-registry.test.tssrc/main/linear/linear-workspace-registry.tssrc/main/local-worktree-scan-generation.tssrc/main/native-chat/agent-session-wire/structured-agent-session-activity-retention.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.tssrc/main/native-chat/wsl-transcript-fs-route-quarantine.test.tssrc/main/native-chat/wsl-transcript-fs-route-quarantine.tssrc/main/orca-profiles/profile-cloud-dev-org-members.tssrc/main/orca-profiles/profile-cloud-refresh-replay-guard.test.tssrc/main/orca-profiles/profile-cloud-refresh-replay-guard.tssrc/main/orca-profiles/profile-cloud-session-store.test.tssrc/main/orca-profiles/profile-cloud-session-store.tssrc/main/persistence-repo-lifecycle.test.tssrc/main/persistence/loading-store/repo-lifecycle-operations.tssrc/main/persistence/loading-store/ssh-profile-operations.tssrc/main/plugins/plugin-log-buffer.tssrc/main/plugins/plugin-worker-manager.test.tssrc/main/plugins/plugin-worker-manager.tssrc/main/plugins/plugin-worker-output-retention.test.tssrc/main/ports/advertised-url-watcher.test.tssrc/main/ports/advertised-url-watcher.tssrc/main/preflight-wsl-cache.tssrc/main/preflight/agent-detection.tssrc/main/providers/ssh-git-dispatch.test.tssrc/main/providers/ssh-git-dispatch.tssrc/main/pty/shell-startup-env.test.tssrc/main/pty/shell-startup-env.tssrc/main/repo-git-username-enrichment.test.tssrc/main/repo-git-username-enrichment.tssrc/main/runtime/orca-runtime-notify-ssh-state-changed.tssrc/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.tssrc/main/runtime/prune-oldest-map-entry.tssrc/main/sidecar-snapshot-file.test.tssrc/main/sidecar-snapshot-file.tssrc/main/ssh/ssh-connection-generation.test.tssrc/main/ssh/ssh-connection-generation.tssrc/main/ssh/system-ssh-windows-write-capabilities.test.tssrc/main/ssh/system-ssh-windows-write-capabilities.tssrc/main/workspace-cleanup-scan-snapshot.tssrc/main/wsl-home-cache.tssrc/main/wsl.test.tssrc/main/wsl.tssrc/renderer/src/components/automations/automation-host-catalog-generation.test.tssrc/renderer/src/components/automations/automation-host-catalog-generation.tssrc/renderer/src/components/browser-pane/host-guest/browser-page-viewport.test.tssrc/renderer/src/components/browser-pane/host-guest/browser-page-viewport.tssrc/renderer/src/components/github-project/roadmap-tick-format.tssrc/renderer/src/components/native-chat/native-chat-session-option-enrichment.test.tssrc/renderer/src/components/native-chat/native-chat-session-option-enrichment.tssrc/renderer/src/components/star-nag/StarNagToastHost.test.tsxsrc/renderer/src/components/star-nag/StarNagToastHost.tsxsrc/renderer/src/lib/host-mirror-handle-gap-verdict-union.test.tssrc/renderer/src/lib/host-mirror-handle-gap-wait.tssrc/renderer/src/lib/repo-slug-index.tssrc/renderer/src/runtime/host-session-mirror-hydration-drain.test.tssrc/renderer/src/runtime/host-session-mirror-hydration.tssrc/renderer/src/runtime/web-agent-session-handoff.tssrc/renderer/src/runtime/web-session-close-intent.tssrc/renderer/src/runtime/web-session-focus-intent.tssrc/renderer/src/runtime/web-session-intent-owner.test.tssrc/renderer/src/runtime/web-session-reorder-intent.tssrc/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.tssrc/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.test.tssrc/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.tssrc/renderer/src/store/repos/runtime-repo-catalog-actions.tssrc/renderer/src/store/repos/safe-auto-fork-sync.test.tssrc/renderer/src/store/repos/safe-auto-fork-sync.tssrc/renderer/src/store/slices/runtime-environment-ssh.tssrc/renderer/src/store/slices/ssh.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| while (scheduledBasePaths.size > MAX_SCHEDULED_BASE_PATHS) { | ||
| const oldest = scheduledBasePaths.values().next() | ||
| if (oldest.done) { | ||
| break | ||
| } | ||
| scheduledBasePaths.delete(oldest.value) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Do not evict a path while its repair timer is pending.
The set represents scheduled work, not completed cache state. If more than 512 paths are scheduled during the 10-second delay, the oldest pending path is removed. A repeated call for that path then schedules a second concurrent tree repair.
Keep pending paths until their timers settle. Apply any retention limit only to completed paths.
| while (memorySessions.size > MAX_MEMORY_CLOUD_SESSIONS) { | ||
| const oldest = memorySessions.keys().next() | ||
| if (oldest.done || oldest.value === key) { | ||
| break | ||
| } | ||
| memorySessions.delete(oldest.value) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Do not evict memory-only sessions.
For persistence: 'memory-only', this map is the only session store. Saving more than 64 profile sessions can evict an active profile's access and refresh tokens. A later read then returns missing because no disk copy exists.
Evict only sessions with encrypted or development-plaintext persistence, or keep memory-only sessions until explicit sign-out.
| export function forgetSshConnectionGeneration(targetId: string): void { | ||
| connectionGenerationByTarget.delete(targetId) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
cat -n src/main/ssh/ssh-connection-generation.ts
printf '%s\n' '--- references ---'
rg -n -C 4 'advanceSshConnectionGeneration|forgetSshConnectionGeneration|SshConnectionGeneration|connectionGenerationByTarget|sessionGenerationBase' .
printf '%s\n' '--- ssh files ---'
git ls-files | rg '(^|/)ssh|SSH' | head -80Repository: stablyai/orca
Length of output: 50370
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 40234
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- exact generation references ---'
rg -n 'advanceSshConnectionGeneration|forgetSshConnectionGeneration|initializeSshConnectionGenerationSession|getSshConnectionGeneration|setSshConnectionGeneration|assertSshMutationExpectation' src/main src/renderer mobile --glob '!**/*.json'
printf '%s\n' '--- profile operations ---'
cat -n src/main/persistence/loading-store/ssh-profile-operations.ts
printf '%s\n' '--- generation files/tests ---'
fd -i 'ssh-connection-generation' src
fd -i 'ssh.*generation' src
rg -n -C 5 'targetId|removeSshTarget|addSshTarget|createSshTarget|SshTarget' src/main/ssh src/main/persistence/loading-store --glob '*.ts' | head -500Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target identity ---'
cat -n src/main/ssh/ssh-target-identity.ts
printf '%s\n' '--- target generation helpers ---'
cat -n src/shared/ssh-target-generation.ts
printf '%s\n' '--- target ID creation/reassignment references ---'
rg -n -C 5 'randomUUID|crypto.*random|reassignSshTargetId|addSshTarget\(|id:.*ssh|targetId.*UUID|targetId.*random' src/main src/shared --glob '*.ts' | head -400
printf '%s\n' '--- authority ---'
cat -n src/main/ssh/ssh-provider-authority.ts
printf '%s\n' '--- generation tests ---'
cat -n src/main/ssh/ssh-connection-generation.test.tsRepository: stablyai/orca
Length of output: 48875
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- relevant files ---'
git ls-files src/main src/shared | rg 'ssh-target-state|ssh-target-reassignment|ssh-profile|ssh-target|target-generation|target.*creation|connection.*generation'
printf '%s\n' '--- target state outline and key definitions ---'
ast-grep outline src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts
rg -n -C 8 'function (addSshTarget|removeSshTarget|updateSshTarget)|export function (addSshTarget|removeSshTarget|updateSshTarget)|targetGeneration|id:' src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts
printf '%s\n' '--- reassignment ---'
cat -n src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts
printf '%s\n' '--- target ID and generation creation in persistence ---'
rg -n -C 5 'randomUUID|nextSshTargetGeneration|allocateSshTargetGeneration|targetGeneration|addSshTarget\(' src/main/persistence src/main/ssh --glob '*.ts' | head -500Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target CRUD ---'
cat -n src/main/ipc/ssh-target-crud-handlers.ts
printf '%s\n' '--- target registry ---'
cat -n src/main/ssh/ssh-target-registry.ts
printf '%s\n' '--- target lifecycle queue ---'
cat -n src/main/ipc/ssh-target-lifecycle-queue.ts
printf '%s\n' '--- target add/readoption/migration ID references ---'
rg -n -C 8 'randomUUID|addSshTarget|newTargetId|target\.id|id:|re-add|readd|readopt' src/main/ipc/ssh-target-crud-handlers.ts src/main/ipc/ssh-target-lifecycle-queue.ts src/main/ssh/ssh-target-registry.ts src/main/ssh/ssh-target-readoption.ts src/main/ssh/ssh-target-id-migration.ts --glob '*.ts'Repository: stablyai/orca
Length of output: 32537
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- connection store add/import methods ---'
rg -n -C 12 'addTarget|importFromSshConfig|SshTargetCreateInput|randomUUID|readoptOrphaned' src/main/ssh/ssh-connection-store.ts src/shared/ssh-types.ts src/main --glob '*.ts' | rg -v '(^|:) [0-9]+-.*randomUUID' | head -500
printf '%s\n' '--- store file locations ---'
git ls-files | rg 'ssh-connection-store'Repository: stablyai/orca
Length of output: 39088
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- removal teardown ---'
rg -n -C 20 'removeRegisteredSshTarget|removeSshTarget|runTargetLifecycle|awaitTargetLifecycle|dispose|abort' src/main/ssh/ssh-session-teardown.ts src/main/ipc/ssh.ts src/main/ipc --glob '*.ts' | head -500
printf '%s\n' '--- mutation paths and generation checks ---'
cat -n src/main/ipc/filesystem-mutations.ts | sed -n '1,210p'
cat -n src/main/ipc/filesystem-mutations.ts | sed -n '250,315p'Repository: stablyai/orca
Length of output: 50369
Do not reset the connection-generation fence after target removal. SshConnectionStore.addTarget creates IDs with a timestamp and Math.random() and does not check for collisions. If a removed ID is reused while stale work remains, forgetSshConnectionGeneration deletes its entry, so the next advanceSshConnectionGeneration returns sessionGenerationBase + 1 again. assertSshMutationExpectation can then accept the stale target ID and generation for the new target. Allocate generations from a monotonic session-wide sequence instead of resetting the target to the session floor.
Source: Learnings
| return wslHomeCache.has(distro) | ||
| } | ||
|
|
||
| /** Pure cache lookup — never probes. */ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the getWslHomeAsync documentation.
The function is not a pure cache lookup. On a cache miss, it starts wsl.exe through execFileUtf8().
Proposed fix
-/** Pure cache lookup — never probes. */
+/** Returns a cached home or starts an asynchronous WSL probe. */📝 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.
| /** Pure cache lookup — never probes. */ | |
| /** Returns a cached home or starts an asynchronous WSL probe. */ |
🧰 Tools
🪛 ast-grep (0.45.3)
[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile, execFileSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
| while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) { | ||
| const oldest = safeAutoForkSyncAttempts.keys().next() | ||
| if (oldest.done) { | ||
| return | ||
| } | ||
| safeAutoForkSyncAttempts.delete(oldest.value) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Do not evict in-flight attempts.
If one call schedules more than 512 eligible repositories, this loop removes entries that still contain a promise. A later call then cannot detect that attempt at Lines 43-47 and starts a second concurrent syncRuntimeGitForkDefaultBranch call for the same repository. Evict only settled attempts. Keep pending attempts until their finally handler clears the promise.
Proposed fix
while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) {
- const oldest = safeAutoForkSyncAttempts.keys().next()
- if (oldest.done) {
+ const evictable = [...safeAutoForkSyncAttempts].find(([, attempt]) => !attempt.promise)
+ if (!evictable) {
return
}
- safeAutoForkSyncAttempts.delete(oldest.value)
+ safeAutoForkSyncAttempts.delete(evictable[0])
}📝 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.
| while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) { | |
| const oldest = safeAutoForkSyncAttempts.keys().next() | |
| if (oldest.done) { | |
| return | |
| } | |
| safeAutoForkSyncAttempts.delete(oldest.value) | |
| while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) { | |
| const evictable = [...safeAutoForkSyncAttempts].find(([, attempt]) => !attempt.promise) | |
| if (!evictable) { | |
| return | |
| } | |
| safeAutoForkSyncAttempts.delete(evictable[0]) |
There was a problem hiding this comment.
ℹ️ No critical issues — the warm-on-read change is correct; one small note on test coverage and one inline simplification.
Reviewed changes (delta since the prior pullfrog review)
- Warm-on-read for three FIFO caches —
getGlabKnownHosts(gitlab-known-host-probe.ts),getCachedToken/getCredentialError(linear-workspace-registry.ts), andreadShellStartupEnvVar(shell-startup-env.ts) now delete and re-seton a hit so a frequently read key moves to the newest position. Each still trims past its cap on write, so the size bound is unchanged, and these are pure caches (no generation/fence values), so reordering on read is safe. - Updated JSDoc —
readShellStartupEnvVar's "memoized … for the process lifetime" line now describes the bounded recent window.
ℹ️ The warm-on-read behavior is not asserted by any test
The commit's stated effect — a hot key survives churn because a read moves it newest — is not pinned by the existing tests: gitlab-known-host-probe.test.ts asserts only the cap size, linear-workspace-registry.test.ts asserts only that the oldest key was evicted, and the shell-startup test asserts only that an evicted key is re-read. None would fail if the read-path refresh were removed.
Technical details
# Warm-on-read has no failing test
## Affected sites
- `src/main/gitlab/gitlab-known-host-probe.ts:164-172` — read-path refresh; `gitlab-known-host-probe.test.ts` only checks `_getKnownHostsCacheSize()`.
- `src/main/linear/linear-workspace-registry.ts:29-36,76-83` — read-path refresh; `linear-workspace-registry.test.ts` checks only that `workspace-0` was evicted.
- `src/main/pty/shell-startup-env.ts:238-245` — read-path refresh; the churn test only asserts an evicted key is re-read (`readFileSyncMock` call count grows).
## Required outcome
- A churn test per cache that touches one hot key, overflows the cap, then asserts the hot key is still served without recompute/fault, so a regression to plain FIFO fails.
## Open questions for the human
- Optional: warmth is an optimization, so this can be skipped if you consider the cap tests sufficient.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const { key, cacheKey } = knownHostsCacheContext(connectionId, localGitOptions) | ||
| const cached = knownHostsCacheByExecutionContext.get(cacheKey)?.hosts | ||
| if (cached) { | ||
| const entry = knownHostsCacheByExecutionContext.get(cacheKey) |
There was a problem hiding this comment.
cached and entry are the same lookup: when the outer .hosts was truthy the inner get can never return undefined, so the second get and its if are dead. Collapsing to a single get (returning entry.hosts) reads more directly and matches the single-lookup shape used by getCachedToken/getCredentialError.
There was a problem hiding this comment.
Important
The new CapabilityProbeCache bound is not applied on the path the codex capability cache actually uses, so the cache this PR claims to bound still grows for the process lifetime.
Reviewed changes
- Replaced the per-key
(get ?? 0) + 1generation counters with monotonic sequences plus anevictedGenerationfallback inssh-git-dispatch,runtime-environment-transport-generation,runtime-environment-ssh,ssh.ts,web-session-tabs-sync/tracking-lifecycle, andautomation-host-catalog-generation, removing the automationevictedAuthorityKeys/generationFloorguard. This closes the eviction value-reuse and floor-fallback fences flagged in earlier reviews. - Added a
maxEntriesbound and atrimSettledEntriessweep toCapabilityProbeCache, and passed 256 fromCodexAppServerCapabilityCache. - Tightened
repo-slug-indexso a resolution only commits if it is still the tracked in-flight promise, not merely if its generation is current. - Added eviction-regression tests to the transport-generation, ssh-git-dispatch, automation-catalog, and host-session-mirror-drain suites.
- Rewrote the
host-mirror-handle-gap-wait"KNOWN LEAK" block to describe the 512-entry bounded backstop instead of session-lifetime retention.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Apply the entry limit after a successful preferred probe. · capability-probe-cache.ts:137
src/shared/capability-probe-cache.ts:137
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winApply the entry limit after a successful preferred probe.
runPreferredOrFallbackadds successful capabilities directly tosupportedCapabilities. This path bypassestrimSettledEntries. Distinct hosts with successful probes can therefore grow the set without a bound, despite the configuredmaxEntries.Use
rememberSupported(capability)so this primary success path also refreshes and trims the entry.Proposed fix
const outcome = this.retryAfterByCapability.has(capability) ? 'unsupported' : 'supported' if (outcome === 'supported') { - this.supportedCapabilities.add(capability) + this.rememberSupported(capability) }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: bc722dba-891e-4ac3-9866-63671a0ea15d
📒 Files selected for processing (28)
config/tsconfig.tc.web.jsonsrc/main/agent-hooks/wsl-hook-relay-manager.test.tssrc/main/agent-hooks/wsl-hook-relay-manager.tssrc/main/codex/codex-app-server-capability-cache.test.tssrc/main/codex/codex-app-server-capability-cache.tssrc/main/codex/codex-hook-trust-grant.test.tssrc/main/git/git-capability-state.test.tssrc/main/ipc/runtime-environment-transport-generation.test.tssrc/main/ipc/runtime-environment-transport-generation.tssrc/main/plugins/plugin-log-buffer.tssrc/main/plugins/plugin-worker-manager.tssrc/main/providers/ssh-git-dispatch.test.tssrc/main/providers/ssh-git-dispatch.tssrc/main/runtime/orca-runtime-notify-ssh-state-changed.tssrc/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.tssrc/renderer/src/components/automations/automation-host-catalog-generation.test.tssrc/renderer/src/components/automations/automation-host-catalog-generation.tssrc/renderer/src/lib/host-mirror-handle-gap-wait.tssrc/renderer/src/lib/monaco-setup.tssrc/renderer/src/lib/repo-slug-index.tssrc/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.test.tssrc/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.tssrc/renderer/src/store/repos/runtime-repo-catalog-actions.tssrc/renderer/src/store/slices/runtime-environment-ssh.tssrc/renderer/src/store/slices/ssh.tssrc/shared/capability-probe-cache.tssrc/shared/commit-message-agent-spec.test.tssrc/shared/commit-message-agent-specs-primary.ts
💤 Files with no reviewable changes (2)
- src/renderer/src/lib/monaco-setup.ts
- src/shared/commit-message-agent-spec.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/lib/host-mirror-handle-gap-wait.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| evictedGeneration = Math.max(evictedGeneration, generationByAuthorityKey.get(key) ?? 0) | ||
| generationByAuthorityKey.delete(key) | ||
| fingerprintByAuthorityKey.delete(key) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Preserve fingerprints for active authorities.
When a catalog contains more than 512 authorities, trimAuthorityGenerations deletes fingerprints for authorities that remain in that catalog. The next identical sync treats those authorities as changed and advances their generations again. Frequent catalog synchronization can then invalidate current requests even though the catalog did not change.
Bound retired authority state separately. Do not evict fingerprints for authorities in the current catalog.
| // failure on every poll/search wastes subprocesses and trace space. | ||
| this.supportedCapabilities.delete(capability) | ||
| this.retryAfterByCapability.set(capability, nowMs + this.retryIntervalMs) | ||
| this.trimSettledEntries() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Refresh an unsupported entry before eviction.
Map.set does not change insertion order for an existing key. A newly observed unsupported result can remain the oldest entry and be deleted by this trim when the next capability is added. shouldTry then permits an immediate probe instead of preserving the renewed retry interval.
Delete the key before setting the new deadline.
Proposed fix
rememberUnsupported(capability: TCapability, nowMs = Date.now()): void {
this.supportedCapabilities.delete(capability)
+ this.retryAfterByCapability.delete(capability)
this.retryAfterByCapability.set(capability, nowMs + this.retryIntervalMs)
this.trimSettledEntries()
}There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: c09fcfdb-253d-411b-ba22-46dd3b3b2a77
📒 Files selected for processing (11)
src/main/agent-hooks/wsl-hook-default-distro.tssrc/main/agent-hooks/wsl-hook-relay-manager.tssrc/main/agent-hooks/wsl-hook-relay-resume.tssrc/main/git/source-control/effective-upstream-status-cache.tssrc/main/git/status-upstream-negative-cache.test.tssrc/main/persistence/loading-store/repo-lifecycle-operations.tssrc/main/persistence/loading-store/repo-lifecycle-ui-residue.tssrc/main/plugins/plugin-log-buffer.tssrc/main/plugins/plugin-worker-generation-retention.tssrc/main/plugins/plugin-worker-lifecycle.tssrc/main/plugins/plugin-worker-manager.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| cacheKey, | ||
| (effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0) + 1 | ||
| ) | ||
| effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Trim generations after clearing a key.
Each call creates a generation entry, but this path does not trim it. Clearing more than 512 distinct inactive identities without a later rememberEffectiveUpstreamStatus call leaves effectiveUpstreamStatusWriteGeneration above its configured bound. Call trimEffectiveUpstreamStatusGeneration() after this update.
Proposed fix
effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence)
+ trimEffectiveUpstreamStatusGeneration()📝 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.
| effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence) | |
| effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence) | |
| trimEffectiveUpstreamStatusGeneration() |
| (effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? evictedWriteGeneration) !== | ||
| writeGeneration |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline src/main/git/source-control/effective-upstream-status-cache.ts --items all
ast-grep run --lang typescript \
--pattern 'rememberEffectiveUpstreamStatus($$$)' \
src/main/git
rg -n -C 5 \
'effectiveUpstreamStatusWriteGeneration\.get\(|rememberEffectiveUpstreamStatus\(|writeGeneration' \
src/main/gitRepository: stablyai/orca
Length of output: 12548
Use the eviction floor when starting a probe.
When cacheKey has been evicted, effective-upstream-status-probe.ts initializes writeGeneration to 0, but this check compares it with the nonzero evictedWriteGeneration. The negative result is discarded, so subsequent polls cannot use negative caching for that key. Initialize writeGeneration with the eviction floor, or allocate a new generation before probing.
There was a problem hiding this comment.
Important
The effective-upstream generation fence now compares against an evicted-value fallback that the probe does not use when capturing, so the negative cache silently stops caching new worktrees after the first generation eviction.
Reviewed changes
- Reworked the effective-upstream write generation into a monotonic sequence with an
evictedWriteGenerationfallback, and added a regression test that an evicted strict probe cannot republish a stale negative (status-upstream-negative-cache.test.ts). - Extracted
resolveWslHookDefaultDistro(wsl-hook-default-distro.ts) andresumeStoppedWslHookRelays(wsl-hook-relay-resume.ts) out ofwsl-hook-relay-manager.ts— behavior-preserving. - Extracted
pruneDeregisteredRepoUiResidueintorepo-lifecycle-ui-residue.ts. - Extracted plugin worker generation/lifecycle helpers into
plugin-worker-generation-retention.tsandplugin-worker-lifecycle.ts, and added aPluginLogBuffer.sizegetter.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since the prior pullfrog review at b2b3ae9)
- Aligned the effective-upstream generation fence — added
getEffectiveUpstreamStatusWriteGeneration(map.get(key) ?? evictedWriteGeneration) and switched the probe's capture ineffective-upstream-status-probe.ts:49from?? 0to it, so capture and compare now share the evicted-value floor. This closes the prior[!IMPORTANT]finding: a never-written key captures the floor instead of0, sorememberEffectiveUpstreamStatusno longer rejects every fresh negative after the first generation eviction. - Added a regression test —
status-upstream-negative-cache.test.tsseeds 513 positive writes, then asserts a fresh negative key still caches, pinning the capture/compare agreement.
I ran pnpm test src/main/git/status-upstream-negative-cache.test.ts — 8 passed.
The codex capability cache finding from review 5258748051 (runPreferredOrFallback adding to supportedCapabilities without trimming) is unchanged and remains open, so this review is not an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the prior
[!IMPORTANT]finding is resolved; one coverage note inline.
Reviewed changes (delta since the prior pullfrog review at 9bf533f)
- Routed the preferred-probe success path through the bound —
runPreferredOrFallbacknow callsrememberSupported(capability)instead of adding tosupportedCapabilitiesdirectly, so the codex app-server cache trims on the pathcodex-hook-trust-grant.tsactually uses. This closes the open[!IMPORTANT]finding from review 5258748051; the unsupported-signal guard (only mark supported when no retry cooldown is present) is preserved.
I ran pnpm test src/main/codex/codex-app-server-capability-cache.test.ts src/shared — all green.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const outcome = this.retryAfterByCapability.has(capability) ? 'unsupported' : 'supported' | ||
| if (outcome === 'supported') { | ||
| this.supportedCapabilities.add(capability) | ||
| this.rememberSupported(capability) |
There was a problem hiding this comment.
No test pins the bound on this success path. The churn test in codex-app-server-capability-cache.test.ts only calls rememberUnsupported, and the other success-path tests never overflow the cap, so reverting this line to a direct supportedCapabilities.add would leave every test green. A churn test that resolves successful runWithFallback probes for CODEX_APP_SERVER_CAPABILITY_MAX_ENTRIES + N distinct wsl:<distro> keys and then asserts an early key reports isKnownSupported(...) === false would fail against the pre-fix code.
Technical details
# Bound on the preferred-probe success path is untested
## Affected sites
- `src/shared/capability-probe-cache.ts:136-138` — the newly re-routed success path (`rememberSupported`).
- `src/main/codex/codex-app-server-capability-cache.test.ts:78-86` — churn test exercises only `rememberUnsupported`.
## Required outcome
- A regression test that fails if this success path stops trimming (i.e. reverts to a bare `supportedCapabilities.add`).There was a problem hiding this comment.
Important
The new clock-rollback branch in the replay guard allows a refresh-token replay that the previous code blocked, and deletes the attempt evidence the replay warning depends on. Details inline.
Reviewed changes (delta since the prior pullfrog review at 1aef160)
- Retained expired replay evidence — added a bounded
expiredAmbiguousRefreshAttemptsmap and apreserveKeyparameter topruneAmbiguousRefreshAttempts, so an expired attempt is moved rather than deleted andwasRefreshTokenAmbiguouslyAttemptedstill classifies a later 401 as a possible replay. This restores the behavior the existingprofile-cloud-session-refresh.test.tsreplay-warning test depends on. - Restructured
blocksAmbiguousRefreshReplay— moved pruning off the entry path and added anow < attempt.attemptedAtclock-rollback branch that drops the active attempt and returnsfalse.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| if (now < attempt.attemptedAt) { | ||
| // A clock rollback must not resurrect an already-expired replay window. | ||
| ambiguousRefreshAttempts.delete(key) | ||
| return false | ||
| } |
There was a problem hiding this comment.
This branch turns a call the previous code blocked into an allow, and it deletes the attempt instead of moving it to expiredAmbiguousRefreshAttempts, so the replay warning loses the evidence too. now < attempt.attemptedAt only fires on a backward wall-clock step — it cannot distinguish a stale attempt from a just-recorded one — and the parent returned true there because now - attempt.attemptedAt was negative. If un-blocking on rollback is intended, the attempt should at least be retained as evidence; otherwise clamp now or keep blocking.
Technical details
# Clock rollback now fails open and drops replay evidence
## Affected sites
- `src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts:89-93` — `now < attempt.attemptedAt` deletes the active attempt and returns `false`; the parent (`1aef160d5c`) fell through to `now - attempt.attemptedAt < DELAY`, which is `true` for a negative elapsed time, and kept the entry.
- `src/main/orca-profiles/profile-cloud-session-refresh.ts:182` — the only gate before `refreshOrcaCloudSession`; `false` lets the same refresh token be re-POSTed.
- `src/main/orca-profiles/profile-cloud-session-refresh.ts:106` — `wasRefreshTokenAmbiguouslyAttempted` reads both maps, so after this branch it returns `false` and the 401 is not classified as `orca_cloud_refresh_possible_replay`.
- `src/main/orca-profiles/profile-cloud-refresh-replay-guard.test.ts:14-31` — exercises only forward time (`1_000`, `1_000 + DELAY`); no `now < attemptedAt` case, so this branch is untested.
## Required outcome
- A backward wall-clock step must not lift the replay block for a still-fresh ambiguous attempt, and the attempt should remain available as evidence so a later 401 is still classified as a possible replay.
## Suggested approach (optional)
- Keep blocking on rollback (return `true`), or clamp the effective `now` to `attemptedAt`. If dropping the block is intended, at minimum move the attempt into `expiredAmbiguousRefreshAttempts` before deleting it and add a test asserting `blocksAmbiguousRefreshReplay(key, token, attemptedAt - 1)`.
What users experienced
Orca kept short-lived bookkeeping forever. Over a long session, SSH targets, runtime environments, repositories, browser pages, WSL routes, terminal panes, shell startup paths, and GitHub lookups could leave old keys and callback state behind. The Star-Nag notification could also retain its React tree after it was closed.
This PR makes those lifetimes finite. It closes the notification cleanly, retires repository and runtime state when their owners go away, releases sidecar queues after work settles, and bounds generation, retry, route, locale, browser, recovery, host-mirror, and shell-startup, and GitLab host-context, SSH connection-generation, and sparse-checkout, WSL home, SSH capability, and Codex trust-cooldown registries. The host-mirror cap is conservative: forgetting an old verdict can only cause one extra bounded wait; it cannot resume a terminal early. The shell-startup cap only causes an occasional file reread after extreme home/host churn, the GitLab cap may re-run one auth-status probe after extreme reconnect churn, and the sparse-checkout cap may re-run one small filesystem probe after extreme worktree churn.
ELI5
The app had several todo lists where finished names were never crossed out. This patch crosses out finished names and keeps only a recent safety window. When a notice is closed, we also throw away its old paperwork.
Merge risk
Low. The changes preserve active entries, recent fencing, and all existing teardown behavior. The new caps affect only very old inactive keys after sustained churn. The shell-startup cache may reread a startup file after its old key is evicted, and GitLab may re-run one host discovery probe after an old connection context is evicted; sparse-checkout may re-run one filesystem probe after an old worktree entry is evicted; permanently removed SSH targets also release their generation entry. Results and normal behavior stay the same. Frequently reused cache entries now move to the newest position on reads, so historical churn evicts inactive entries before hot ones.
Negative user-facing tradeoffs
None expected in normal use. Under extreme host-mirror churn, an evicted verdict may make one pane wait for the existing bounded recovery timeout again; it will not create a duplicate terminal or resume an uncertain session. Under extreme home/host churn, Orca may perform one extra small startup-file read, GitLab auth-status probe, WSL/SSH capability probe, Codex trust attempt, or WSL auth-drain pass, Linear credential reread, Git capability reprobe, or WSL Git environment or preflight reprobe; removed SSH targets no longer retain their old generation metadata.
Safety hardening
Generation fences now use monotonic sequences that remain ahead of every evicted value, so bounded maps cannot reuse an old generation after identifier churn. This includes strict effective-upstream probes that bypass normal in-flight coalescing. Repo-slug resolution also requires the original in-flight promise before committing a result. The Codex app-server host capability cache is bounded as well.
Validation
pnpm tc:node,pnpm tc:web, andpnpm tc:clipassed.pnpm run check:code-quality:changedpassed.oxlintpassed with only the repository's two existing mobile warnings.