Repository navigation
Conversation
Greptile SummaryThis PR replaces repeated stale-worktree metadata cleanup with a single authoritative native-local Git scan followed by bounded filesystem verification and batch persistence updates.
Confidence Score: 5/5The PR appears safe to merge because no concrete changed-code failure remains after reviewing its authority, ownership, race, and fail-closed cleanup paths. Destructive cleanup is confined to fresh native-local scans, uncertain filesystem and routing states retain metadata, persisted owners are comprehensively protected, and each candidate is synchronously revalidated before mutation.
|
| Filename | Overview |
|---|---|
| src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts | Coordinates fresh-scan ownership, generation fencing, metadata pruning, root publication, and lineage cleanup without exposing cached or coalesced scans to destructive side effects. |
| src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts | Restricts batch pruning to current native-local authoritative scans and retains Git-listed, existing, unverifiable, malformed, WSL, folder, and foreign candidates. |
| src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts | Revalidates repository routing, persisted ownership, metadata identity, and aliases before deleting metadata and associated lineage. |
| src/main/persistence/restoring-sessions/session-worktree-ownership.ts | Exhaustively classifies persisted session fields and collects worktree owners across local and host-specific partitions. |
| src/main/local-worktree-path-presence.ts | Adds globally bounded asynchronous path probes whose timeouts, cancellation, and non-absence errors conservatively retain metadata. |
| src/main/worktree-lineage-pruning.ts | Protects retained metadata candidates and path-equivalent live worktrees during synchronous lineage reconciliation. |
Sequence Diagram
sequenceDiagram
participant Caller
participant Cache as Scan cache
participant Git
participant FS as Path probes
participant Store
Caller->>Cache: List local worktrees
Cache->>Store: Capture metadata/routing expectation
Cache->>Git: One fresh worktree list
Git-->>Cache: Non-empty inventory
Cache->>FS: Probe captured candidates absent from Git
FS-->>Cache: Missing or unverifiable results
Cache->>Store: Revalidate authority, owners, rows, and aliases
Store-->>Cache: Batch-remove qualifying metadata
Cache->>Store: Publish roots and prune unprotected lineage
Cache-->>Caller: Authoritative worktree list
Reviews (1): Last reviewed commit: "perf(worktrees): batch-prune stale local..." | Re-trigger Greptile
📝 WalkthroughWalkthroughThis change adds authoritative local worktree metadata pruning with race guards for scan generations, routing, caller currency, and registered-root revisions. It adds bounded filesystem path probing with timeout and abort handling. It preserves session-owned metadata, normalized live paths, WSL roots, and lineage candidates. Persistence operations now invalidate local scan generations when repository or Windows runtime settings change. Listing handlers use centralized guarded side effects, and extensive tests cover pruning, invalidation, ownership, lineage, concurrency, and routing cases. Merge Risk: 🟡 Moderate · up to The batch cleanup can delete persistent worktree metadata after an authorized-root change because that change is detected only after pruning has started, weakening the intended fail-closed behavior. Merge should wait for the authorization check to guard entry to pruning; the positive pruning tests should also pin their platform assumptions so they remain reliable across operating systems. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description follows the required template, explains the change and rationale, documents scope and safety boundaries, links issue Full details: Linked Issues checkExplanation The PR satisfies the local batch-cleanup requirements in Full details: Out of Scope Changes checkExplanation The changes support the stated local metadata-pruning objective. Scan generations, root revisions, path probing, ownership protection, lineage handling, semaphore cancellation, persistence wiring, benchmarks, and tests are directly related to correctness, safety, or performance.
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: Pro Plus
Run ID: 94c50f35-7655-44bb-8d66-0a2616489c02
📒 Files selected for processing (38)
src/main/ipc/registered-worktree-roots-cache.tssrc/main/ipc/worktrees-authoritative-local-metadata-pruning.test.tssrc/main/ipc/worktrees-test-harness.tssrc/main/ipc/worktrees-test-ipc-surface.tssrc/main/ipc/worktrees-test-metadata-pruning-store.tssrc/main/ipc/worktrees-windows.test.tssrc/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.tssrc/main/ipc/worktrees/listing/detected-provider-listing.tssrc/main/ipc/worktrees/listing/detected-worktree-scan-cache.tssrc/main/ipc/worktrees/listing/register-worktree-catalog-handlers.tssrc/main/local-worktree-path-presence.test.tssrc/main/local-worktree-path-presence.tssrc/main/local-worktree-scan-generation.tssrc/main/persistence-initial-load.test.tssrc/main/persistence-repo-lifecycle.test.tssrc/main/persistence-settings-update.test.tssrc/main/persistence-update-repo.test.tssrc/main/persistence/applying-settings/settings-update.tssrc/main/persistence/loading-store/metadata-lineage-batch-pruning.test.tssrc/main/persistence/loading-store/metadata-lineage-operations.tssrc/main/persistence/loading-store/profile-preferences.tssrc/main/persistence/loading-store/project-collection-operations.tssrc/main/persistence/loading-store/repo-lifecycle-operations.tssrc/main/persistence/loading-store/worktree-identity-metadata.tssrc/main/persistence/restoring-sessions/session-worktree-ownership.test.tssrc/main/persistence/restoring-sessions/session-worktree-ownership.tssrc/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.tssrc/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.tssrc/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.tssrc/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.tssrc/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.tssrc/main/persistence/tracking-repos/project-host-operations.tssrc/main/persistence/tracking-repos/repo-update-operations.tssrc/main/worktree-lineage-pruning.test.tssrc/main/worktree-lineage-pruning.tssrc/main/worktree-retention-path-comparison.tssrc/shared/priority-semaphore.test.tssrc/shared/priority-semaphore.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| const hostSessionSnapshot = structuredClone(hostSession) | ||
| const cloneSpy = vi.spyOn(globalThis, 'structuredClone') | ||
|
|
||
| const removed = pruneCaptured(state, scan, staleIds) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Determine whether CI runs the Vitest suites on Windows, and confirm platform-dependent candidate validation.
set -euo pipefail
fd -H -t f -e yml -e yaml . .github/workflows 2>/dev/null | while IFS= read -r file; do
echo "== $file"
rg -n 'runs-on|matrix|windows|os:' "$file"
done
fd -t f 'missing-local-worktree-metadata-pruning.ts' src | while IFS= read -r file; do
echo "== $file"
ast-grep outline "$file" --items all
rg -n -C 5 'isValidCandidateId|win32|isWindowsAbsolutePathLike|startsWith\(.\/.\)' "$file"
doneRepository: stablyai/orca
Length of output: 20994
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '== repository conventions and learnings'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print
echo '== operation-level test context'
sed -n '1,190p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
sed -n '300,365p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
sed -n '455,485p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
echo '== facade test context'
sed -n '1,80p' src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts
echo '== directly bound declarations and call sites'
rg -n -C 4 'function pruneCaptured|const pruneCaptured|pruneCaptured\(|pruneSessionlessMissingLocalWorktreeMetadataForRepo\(' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts src/main/persistenceRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '== applicable conventions'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md
echo '== operation implementation and facade'
sed -n '90,155p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts
sed -n '195,225p' src/main/persistence/loading-store/metadata-lineage-operations.ts
rg -n -C 3 'vitest|unit-tests|test:unit|missing-local-worktree-metadata-pruning|metadata-lineage-batch-pruning' .github/workflows package.json
echo '== workflow test commands on Windows-capable jobs'
sed -n '1,75p' .github/workflows/unit-tests.yml
sed -n '640,715p' .github/workflows/pr.yml
sed -n '715,760p' .github/workflows/pr.yml
sed -n '1,75p' .github/workflows/skill-update-roundtrip.ymlRepository: stablyai/orca
Length of output: 26420
Make the pruning tests independent of the runner OS. pruneSessionlessMissingLocalWorktreeMetadataForRepo defaults to process.platform and rejects /workspace/... paths on win32. Pin 'linux' in the positive pruneCaptured cases. Use platform-appropriate paths in metadata-lineage-batch-pruning.test.ts, because its facade does not expose platform.
📍 Affects 2 files
src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts#L102-L102(this comment)src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts#L44-L47
ELI5
Orca keeps a metadata card for each worktree so it can remember names, pins, links, and activity. Deleted worktrees could leave thousands of cards behind, and cleaning them one at a time repeatedly rescanned Git and copied session state. A fresh local Git inventory can now retire only the cards that are both missing and unused, in one batch.
This fixes the stale-metadata CPU amplifier from #15412. It does not claim to fix every independent source of high CPU described there.
What Changed
git worktree listscan.prunableregistrations, plus the configured repo path as live evidence.fs/promises.stat, using bounded workers and one process-wide two-probe semaphore. A two-second batch deadline and caller abort both settle as unverifiable; existing paths and non-absence errors also fail closed.{ generation, authorizedRootsRevision }side-effect token for every local scan, including WSL, through all three listing callers. Recheck it after probes and immediately before mutation; repo updates, worktree notifications, runtime changes, or newer root publication fence the older observation.WorkspaceSessionStatefield or host partition, mobile selection, SSH lease, migration entry, active automation, or non-final automation run. Session state is neither cloned nor mutated.Why
The old cleanup shape could perform thousands of Git scans, session clones, and persistence schedules for one stale fleet. This keeps the authoritative Git observation singular and makes the persistence work linear while treating uncertainty as retention.
Linked Issue
Fixes #15412
Visual Proof
N/A — this changes main-process listing and persistence behavior only; there is no rendered UI or interaction change.
Safety and provider boundary
The governing invariant is
agent-session.provider-ownership: only the execution host that owns an authoritative observation may retire its metadata. Loss of contact is never proof of process death, and this path does not stop a PTY, agent, process, delete a directory, or delete a Git ref.prunablerowThis is deliberately a native-local, sessionless v1. Remote/WSL/folder cleanup and broader terminal-manager or event-loop diagnostics remain out of scope.
ui.showDotfilesByWorktreeand cleanup dismissal preferences are not treated as live session ownership and remain under their existing cleanup paths.Performance evidence
Opt-in 2,709-row in-memory benchmark:
Command:
ORCA_LOCAL_METADATA_PRUNE_BENCH=1 pnpm exec vitest run \ --config config/vitest.config.ts \ src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts \ --reporter=verboseThe wall times cover only modeled in-memory metadata/session work and vary by machine. They exclude filesystem-presence probes and do not claim end-to-end UI latency. A separate temporary real-Git measurement observed 2,709
git worktree listcalls at 13.77s versus one call at 0.01s; those figures are illustrative, not a CI performance budget.Testing
Local verification:
pnpm tc:nodepassed.pnpm run check:code-quality:changedpassed with 0 findings across the changed files.pnpm run check:reliability-gatespassed for 99 gates.git diff --checkpassed.Full repository lint/build and the platform matrix are left to PR CI.
Coverage includes capture-before-Git ordering, fresh/coalesced/cached behavior, invalidation during Git and filesystem probes, hung-probe timeout, external abort, global two-probe accounting and permit reuse, all three listing-call continuation gaps, WSL setup/root-publication races, native-to-WSL route races, Git-folder-Git repo updates, repo/project/settings/metadata/alias races, persisted JSON projection equality, every persisted session ownership shape, host/provider isolation, Unicode/macOS/Windows path aliases,
prunableretention, symlink spellings, filesystem-error retention, batch save/sidecar behavior, and lineage ordering without rematerialization.No Electron validation was run because this has no UI change. No live physical Windows, WSL, SSH, runtime-remote, or folder-workspace journey was run; those boundaries have deterministic coverage and fail closed.
Residual gaps: Node cannot cancel an already-running
stat, so two permanently wedged filesystem calls can retain the two global permits; current and later batches still settle at their own deadlines and preserve every candidate. Real Windows drive/UNC behavior remains covered by mocks rather than a physical host. Direct-SSH lineage pruning also retains a pre-existing concurrent-create setup gap; this diff does not change that behavior and never enables metadata pruning from an SSH observation.Compatibility notes:
AI Disclosure
Review
Primary risk is deleting metadata without enough authority. The implementation biases false negatives: any ambiguous ownership, changed state, path presence/error, unsupported provider, or stale scan preserves the row for a later scan. Sidecar pruning is best-effort and refetchable.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Reviewed for security, cross-platform behavior, SSH/remote ownership, mobile persisted owners, backwards compatibility, and performance.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)