Skip to content

fix(worktrees): guard lineage pruning from failed scans - #13248

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-worktree-scan-lineage-wipe
Aug 8, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-worktree-scan-lineage-wipe

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A failed git worktree list (spawn failure under resource exhaustion — EAGAIN/ENOMEM, git killed, etc.) is swallowed into an empty list by listWorktreesUnshared, which the local branch of listRepoWorktreesForResolutionUncached then wraps as {ok: true, worktrees: []}. Both prune call sites gate on scan.ok, so pruneLineageForMissingRepoWorktrees treats every lineage child as "proven gone": it purges all worktreeLineageById / workspaceLineageByChildKey entries for the repo and re-mints parent instanceIds.

This is not theoretical: on 2026-08-07 ~19:00 PDT, under system load 579 / 91 MB free RAM, this path wiped all 268 lineage entries on a production profile (1.4.177-hourly), flattening every worktree in the sidebar to root level. Data was recovered only because the hourly orca-data.json.bak.N rotation (5 kept) hadn't yet aged out the pre-wipe snapshot.

Fix

Two independent guards, defense in depth:

  1. Truthful scan results — local runtime scans now propagate Git failures strictly and degrade to ok: false (mirroring the existing SSH-branch behavior), so a failed scan can never masquerade as an authoritative empty catalog. Extracted into repo-worktree-resolution-scan.ts.
  2. Empty-scan circuit breaker — shared, host-aware guard in worktree-lineage-pruning.ts: pruning refuses to act on an empty scan while the store still has registered lineage for the repo. Applied to both consumers (runtime + ipc/worktrees.ts).

Tests

  • Same-model review found and fixed one scoped performance issue in a3899ed9c9: degraded local scans now use the existing 30-second cache, preventing repeated git worktree list spawns under EAGAIN/ENOMEM while remaining ok: false; SSH retry behavior is unchanged. A repeat review returned clean.
  • Reviewer verification: nine affected suites passed (1,441 passed, 1 skipped), plus Node typecheck, affected-file lint/format, max-lines ratchet, and git diff --check.
  • Coordinator verification: full pnpm run typecheck, full pnpm run lint, and git diff --check origin/main...HEAD passed.
  • Focused lineage/scan suites passed 20/20: repo-worktree-resolution-scan.test.ts, worktree-lineage-pruning.test.ts, and worktree-ps-degraded-repo-scan.test.ts.
  • CI is green across Node 24/26 tests, static analysis/typecheck, Git 2.25 compatibility, Windows packaging, shell contracts, remote-wire compatibility, and package checks.
  • Electron-over-SSH QA passed at a3899ed9c98a9fbbd30f362adad227575665f0a4: a real remote parent/child worktree lineage remained intact in the UI, store, and persisted orca-data.json after a forced relay kill, disconnect + refresh, and reconnect + refresh. Parent instanceId remained stable and remote Git still reported all three worktrees. Screenshots and full QA evidence.
  • The live run validates SSH disconnect/degraded behavior. The exact local empty-scan/EAGAIN circuit breaker is covered deterministically by the focused unit suites rather than forcing an in-process spawn failure during Electron QA.

Incident forensics

Root-caused from the hourly state backups (268 → 0 lineage entries between the 18:50 and 19:50 snapshots, worktreeMeta intact, 25 lineage-parent instanceIds re-minted, no crash/restart/migration in the window) plus main-process traces. Happy to share the full writeup.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change centralizes repository worktree lineage pruning in a shared utility. It adds a runtime scanner that uses strict Git worktree listing and supports optional WSL settings. Runtime worktree resolution and pruning now use the shared utilities. IPC worktree handling also uses the shared pruning utility. Tests cover scan failures, empty scans, stale lineage removal, missing-parent identity rotation, and runtime scanner mocking.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly identifies the worktree lineage pruning fix and matches the main change.
Description check ✅ Passed The description clearly explains the incident, fix, implementation, and extensive testing, although it does not follow every template heading.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (1)
src/main/worktree-lineage-pruning.test.ts (1)

117-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert stale workspace lineage cleanup.

The test creates workspace lineage for missingChildId but does not verify its removal. A regression that retains this record will pass.

Proposed test assertions
     expect(store.removeWorktreeLineage).toHaveBeenCalledWith(missingChildId)
     expect(store.removeWorktreeLineage).not.toHaveBeenCalledWith(liveChildId)
+    expect(workspaceLineageByChildKey[worktreeWorkspaceKey(missingChildId)]).toBeUndefined()
+    expect(workspaceLineageByChildKey[worktreeWorkspaceKey(liveChildId)]).toBeDefined()
     expect(store.setWorktreeMeta).toHaveBeenCalledWith(missingParentId, {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e206082e-046f-499c-b161-43734895868e

📥 Commits

Reviewing files that changed from the base of the PR and between 6da7b8e and b1a3e45.

📒 Files selected for processing (7)
  • src/main/ipc/worktrees.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/repo-worktree-resolution-scan.test.ts
  • src/main/runtime/repo-worktree-resolution-scan.ts
  • src/main/worktree-lineage-pruning.test.ts
  • src/main/worktree-lineage-pruning.ts

Comment on lines +661 to +672
scanLocalRepoWorktreesForResolutionMock
.mockReset()
.mockImplementation(async (repoPath: string, options: { wslDistro?: string }) => {
try {
const worktrees = options.wslDistro
? await listWorktrees(repoPath, options)
: await listWorktrees(repoPath)
return { ok: true, worktrees }
} catch {
return { ok: false, worktrees: [] }
}
})

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Locate files and relevant symbols\n'
fd -a 'orca-runtime.*\.ts$' . | sed 's#^\./##'
printf '\nSearch listWorktreesStrict and scanLocalRepoWorktreesForResolutionMock\n'
rg -n "listWorktreesStrict|listWorktrees\(|scanLocalRepoWorktreesForResolutionMock|wslDistro" src/main -S || true

printf '\nRead targeted test section\n'
file="$(fd 'orca-runtime\.test\.ts$' . | head -n1 || true)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  sed -n '620,710p' "$file" | cat -n
fi

printf '\nRead candidate implementation sections\n'
impl="$(fd 'orca-runtime\.ts$' . | head -n1 || true)"
if [ -n "${impl:-}" ]; then
  wc -l "$impl"
  rg -n "listWorktreesStrict|function listWorktrees|const listWorktrees|export .*listWorktreesStrict" "$impl" -A 30 -B 10
fi

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="src/main/runtime/orca-runtime.test.ts"
impl="src/main/runtime/orca-runtime.ts"

printf 'Targeted test section\n'
sed -n '640,690p' "$file" | cat -n

printf '\nDefinitions around listWorktreesStrict/listWorktrees in implementation\n'
rg -n "export .*listWorktreesStrict|function listWorktreesStrict|const listWorktreesStrict|listWorktreesStrict|function listWorktrees|const listWorktrees" "$impl" -A 45 -B 15

printf '\nImports/mock declarations in target test\n'
sed -n '1,120p' "$file" | cat -n

printf '\nRead-only JS behavior probe for omitted options branch\n'
node - <<'JS'
function currentBranch(options) {
  try {
    return options.wslDistro ? "listWorktrees(repo, options)" : "listWorktrees(repo)"
  } catch (err) {
    return "failed -> { ok: false }"
  }
}
function proposedBranch(options) {
  try {
    return options?.wslDistro ? "listWorktreesStrict(repo, options)" : "listWorktreesStrict(repo)"
  } catch (err) {
    return "failed -> { ok: false }"
  }
}
for (const options of [undefined, {}, { wslDistro: undefined }, { wslDistro: "Ubuntu" }]) {
  console.log(JSON.stringify({
    input: options,
    current: currentBranch(options),
    proposed: proposedBranch(options)
  }))
}
JS

Repository: stablyai/orca

Length of output: 17976


🏁 Script executed:

#!/bin/bash
set -euo pipefail

impl="src/main/git/worktree.ts"
printf 'Locate scanLocalRepoWorktreesForResolution and listWorktreesStrict in git/worktree\n'
rg -n "export .*scanLocalRepoWorktreesForResolution|function scanLocalRepoWorktreesForResolution|const scanLocalRepoWorktreesForResolution|scanLocalRepoWorktreesForResolution|export .*listWorktreesStrict|function listWorktreesStrict|const listWorktreesStrict|listWorktreesStrict|export .*listWorktrees|function listWorktrees|const listWorktrees" "$impl" -A 80 -B 20

printf '\nSearch all production scanLocalRepoWorktreesForResolution usages\n'
rg -n "scanLocalRepoWorktreesForResolution\(" src/main -S --glob '!**/*.test.ts' --glob '!**/*.integration.test.ts'

Repository: stablyai/orca

Length of output: 10230


🏁 Script executed:

#!/bin/bash
set -euo pipefail

prod="src/main/runtime/orca-runtime.ts"
scanner="src/main/runtime/repo-worktree-resolution-scan.ts"

printf 'scanner implementation\n'
sed -n '1,80p' "$scanner" | cat -n

printf '\norca-runtime call site around scanLocalRepoWorktreesForResolution\n'
sed -n '28855,28920p' "$prod" | cat -n

printf '\nsearch scanLocalRepoWorktreesForResolution in prod\n'
rg -n "scanLocalRepoWorktreesForResolution|scanLocalRepoWorktreesForResolutionMock" "$prod" -A 20 -B 20

Repository: stablyai/orca

Length of output: 7227


Use listWorktreesStrict in the resolution scan test double.

scanLocalRepoWorktreesForResolution always calls listWorktreesStrict, including when no WSL options are passed. This reset block still calls the non-strict listWorktrees, so a test that makes the strict scanner fail will not fail here.

Proposed fix
-    .mockImplementation(async (repoPath: string, options: { wslDistro?: string }) => {
+    .mockImplementation(async (repoPath: string, options?: { wslDistro?: string }) => {
       try {
-        const worktrees = options.wslDistro
-          ? await listWorktrees(repoPath, options)
-          : await listWorktrees(repoPath)
+        const worktrees = options?.wslDistro
+          ? await listWorktreesStrict(repoPath, options)
+          : await listWorktreesStrict(repoPath)
         return { ok: true, worktrees }
📝 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
scanLocalRepoWorktreesForResolutionMock
.mockReset()
.mockImplementation(async (repoPath: string, options: { wslDistro?: string }) => {
try {
const worktrees = options.wslDistro
? await listWorktrees(repoPath, options)
: await listWorktrees(repoPath)
return { ok: true, worktrees }
} catch {
return { ok: false, worktrees: [] }
}
})
scanLocalRepoWorktreesForResolutionMock
.mockReset()
.mockImplementation(async (repoPath: string, options?: { wslDistro?: string }) => {
try {
const worktrees = options?.wslDistro
? await listWorktreesStrict(repoPath, options)
: await listWorktreesStrict(repoPath)
return { ok: true, worktrees }
} catch {
return { ok: false, worktrees: [] }
}
})

@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-worktree-scan-lineage-wipe branch from 31049ac to a3899ed Compare August 8, 2026 18:59
@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA validation @ a3899ed9c98a9fbbd30f362adad227575665f0a4

Result: PASS (live SSH disconnect/refresh proof) — with explicit scope notes below.

Identity

  • window.api.app.getIdentity() root/branch matched worktree brennanb2025/fix-worktree-scan-lineage-wipe
  • git rev-parse HEAD at identity root = a3899ed9c98a9fbbd30f362adad227575665f0a4
  • Isolated profile: unique ORCA_DEV_USER_DATA_PATH, CDP 9341, renderer 5183
  • pnpm build:relay completed before SSH

Live SSH proof (throwaway Linux Docker, real demo-project)

  1. Registered/connected SSH target qa-lineage-linux (linux-arm64 relay)
  2. Added remote repo /work/demo-project (seeded via local git bundle; container GitHub HTTPS clone blocked)
  3. Created parent qa-parent-mskrlpqp + child qa-child-mskrlpqp over SSH; child lineage set to parent
  4. Captured before screenshot, killed remote relay.js, disconnected SSH, refreshed worktree surface
  5. Reconnected and refreshed again

Lineage integrity

Check Result
Edges before disconnect 1 (child → parent)
Edges after disconnect refresh 1 (unchanged)
Edges after reconnect 1 (unchanged)
Parent instanceId stable yes (f5b59927-...)
Persisted orca-data.json mid-disconnect 1 lineage key retained
Persisted final 1 lineage key retained

Remote git backing (over SSH after reconnect)

worktree /work/demo-project
worktree /work/demo-project-qa-parent-mskrlpqp  [qa-parent-mskrlpqp]
worktree /work/demo-project-qa-child-mskrlpqp   [qa-child-mskrlpqp]

Screenshots (full app window)

01-before-disconnect
02-after-disconnect-refresh
03-after-reconnect

Logs inspected

  • Electron: relay deploy success; Relay channel lost after forced kill; reconnect; node-pty skip (no build-essential on throwaway image — files/git still served)
  • No evidence of lineage wipe in store or persisted maps during disconnect/refresh

Explicit non-claims / gaps

  • This is a live SSH disconnect + refresh proof, not a forced local empty git worktree list spawn-failure (EAGAIN) path. The empty-scan circuit breaker / local strict-scan behavior is covered by the PR’s deterministic unit tests (worktree-lineage-pruning.test.ts, repo-worktree-resolution-scan.test.ts), not re-forced in-process here.
  • Remote PTY unavailable on this throwaway image (missing make/g++); not required for worktree scan/lineage surface under test.

Cleanup

  • Remote test worktrees/branches, container, temp keys/profile, and Electron process from this run will be removed by the QA worker after comment.

@brennanb2025
brennanb2025 merged commit 06144ca into main Aug 8, 2026
45 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(worktrees): guard lineage pruning from failed scans

* fix(worktrees): back off failed local resolution scans
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