Skip to content

Fix Windows daemon host pruning on unverifiable liveness - #16908

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/coercion-win-prune-fix-r1
Aug 28, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/coercion-win-prune-fix-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​438 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​432
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​179 $\color{#cf222e}{\Huge{\mathbf{−}}}$​25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​154

ELI5

Windows keeps versioned daemon host copies so live terminals survive app updates. This change prevents a failed PID/liveness check from being mistaken for proof that a host is dead and safe to delete.

Put another way: on Windows, Orca keeps one copy of its terminal helper per app version, so the
terminals you already had open keep running after you update. At each launch Orca deletes the copies
for versions nobody is using any more. The bug was in how it decided "nobody is using this": if the
check failed — the folder could not be listed, a bookkeeping file could not be read, or Windows
refused to answer whether a process was alive — Orca read that silence as "nothing is running" and
deleted every old version's copy, including the one a still-running helper was executing from.
The terminals that helper owns are exactly the ones you had open before you updated.

Now a check that cannot answer stops the cleanup instead of authorising it, and a bookkeeping file
that is unreadable for good gets set aside after a minute so the cleanup does not stay blocked
forever.

User-facing before / after

Before After
You update Orca on Windows with terminals still running from the old version, and Orca's check on the old helper cannot complete (folder unlistable, record unreadable, process query refused) Orca deleted the old version's helper folder anyway — out from under the helper that was still running your terminals Orca skips the cleanup this launch and tries again next time; the running helper and its terminals are left alone
One old version can't be checked, but another is provably finished Either everything was deleted, or (with the safest possible fix) nothing would be Only the version proved finished is deleted; the unclear one is kept
A bookkeeping file is permanently corrupt It would veto the cleanup on every future launch, so old helper copies pile up on disk forever The corrupt file is renamed aside after a minute (bytes kept for diagnosis) and cleanup resumes
A bookkeeping file is corrupt only because a helper is writing it right now — Left alone; a record younger than a minute is never set aside
Nothing is in doubt Old versions cleaned up Unchanged — still cleaned up

When it bites

Windows users only, on packaged builds, at the moment Orca restarts after an update while terminals
from the previous version are still alive. Antivirus locks, a vanishing file, and permission-denied
process queries are the realistic triggers.

What Changed

  • Added an exhaustive live / unverifiable / exited process-liveness verdict.
  • Carried per-version evidence into the pruning site so only exited authorizes deletion.
  • Kept unrelated, positively absent versions prunable when another version is unverifiable.
  • Added regression coverage for permission denial, unavailable queries, live pins, and genuinely absent hosts.

Why

The prior collector caught process-query and PID-file failures and returned an ordinary empty pin set. The pruning caller then acted on that coerced value by recursively deleting every non-current, unpinned host directory, which could remove the survival substrate for every PTY in a live daemon generation.

Linked Issue

N/A — focused reliability follow-up to the liveness-contract work in #16900.

Visual Proof

N/A — main-process filesystem/liveness behavior with no UI change.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated
  • pnpm test src/main/daemon/daemon-host-relocation.test.ts src/main/daemon/daemon-process-inspection.test.ts --run (26/26)
  • pnpm tc:node
  • pnpm exec oxlint on all changed files
  • Physical Windows high-spec host: exact SHA 14f56edbcf1ec8b9cfca2e4924212d4ec8d126de, 12/12 focused relocation tests passed
  • Windows Electron dev build attached through dedicated CDP port 9467; identity confirmed the validation worktree and branch

Reliability Contract

  • Invariant (daemon-host.update-survival): a live or unverifiable daemon generation retains its versioned Windows host directory; only positively exited or absent evidence authorizes recursive removal.
  • Failure source: a process-query/PID-read failure was coerced into an empty pin set, and the prune caller acted on it as fact.
  • Oracle: the regression test asserts the derived filesystem result: EPERM and unavailable queries preserve the named host, while an unrelated positively absent host and an explicitly exited host are removed.
  • Gate: no matching manifest gate exists; accepted gap is covered by the deterministic focused test plus an exact-SHA physical Windows run.
  • Coverage: packaged Electron Win32 is covered by deterministic tests and physical Windows execution; local PTY/daemon ownership is affected only through host-file survival. SSH, WSL, remote runtime, relay, mobile, macOS, and Linux paths are unaffected by the Win32-packaged guard.
  • Performance budget: one bounded map entry per discovered PID record and one constant-time lookup per host directory; no subprocess, polling, retry, timer, listener, or startup await added.
  • Diagnostics: focused test output and the exact-SHA PR status comment identify both verdict branches; no production telemetry or customer data added.
  • Residual gap: a destructive real auto-update was not run against a live customer-style PTY generation; the lower-layer filesystem oracle directly covers the prune authority decision.

Review

Same-worktree independent review found and drove a per-version evidence refinement; the updated branch was re-tested on macOS and physical Windows. A final in-scope pass found no remaining proven issues.

Agent skill upstream boundary

  • Not applicable.

Notes

  • No mobile-facing, remote-wire, persisted-data, provider, or UI surface changed.
  • SSH/folder workspaces are unaffected; pruning is gated to packaged Electron on Win32.
  • pnpm run check:code-quality:changed under an outer pnpm run mixes the Node 26 engine warning into its JSON parsing; running node config/scripts/check-changed-code-quality.mjs directly passes: 0 new findings (code quality, type-aware, React Doctor).
  • Author X handle: @BrennanKB5

Hardening at d87c20c (fail-safe delete-gate + salvage attribution)

  • The prune verdict switch shared Keep an older terminal helper's files at startup unless it has really exited #16900's delete-gate shape: an unhandled future verdict status fell through into rmSync, protected only by the lint exhaustiveness rule. Deletion is now opted into by a positively matched 'exited' via reclaimUnownedDaemonHostDir (same shape as Keep an older terminal helper's files at startup unless it has really exited #16900's reclaimLegacyDaemonOwnershipFiles); a pinning test feeds an out-of-contract verdict through pruneOldDaemonHosts and asserts the host dir survives. No default arm added; config/oxlint-code-quality-type-aware.json is untouched (diff vs the previous head is empty).
  • Pid salvage from corrupt records now requires the digit run to be terminated by a following non-digit byte. A tear inside the digits leaves a truncated prefix that is a different pid: probing it could quarantine a record on an unrelated process's death, or — when the prefix collides with an immortal pid such as Windows System pid 4 — re-create the permanent prune veto for that one record. Unterminated digits mean the writer died mid-write, so such records quarantine without consulting any probe. Both cases are pinned by failing-first tests (ablation of the terminator check turns 3 tests red; ablation of the delete-gate turns the pinning test red).

Recorded follow-up + scope note

  • Follow-up (deliberately not fixed here): prune-skip reasons are console.warn-only — visible in dev stdout, absent from the diagnostic bundle / main.trace. They should be routed through the daemon milestone/trace log so field skips are diagnosable.
  • Platform asymmetry: collectPinnedDaemonVersions (liveness probes + corrupt-record quarantine renames) runs on all platforms while the prune it feeds is win32-only. The win32 gate deliberately sits at the destructive sink (pruneOldDaemonHosts); the off-win32 side effects were not a design goal but are benign (probes of recorded pids, rename of already-unparseable records nothing else consumes — killStaleDaemon re-reads current-protocol records itself). If off-win32 work is unwanted, hoisting the platform check around the daemon-init.ts call site is a safe follow-up.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Visual proof is N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and compatibility impact considered
  • Focused tests, node typecheck, formatting, and changed-file lint pass; CI will cover full-suite/build gates

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status at exact SHA 14f56edbcf1ec8b9cfca2e4924212d4ec8d126de: focused relocation suite passes 12/12 on macOS and the physical Windows high-spec host; pnpm tc:node, changed-file oxlint, and formatting checks pass. Windows CDP validation used dedicated port 9467 and confirmed identity coercion-win-prune-fix-r1-validation @ brennanb2025/coercion-win-prune-fix-r1; the port was verified closed afterward. Both destructive branches are explicit: unverifiable preserves the named host while unrelated positively absent versions and explicitly exited versions remain prunable.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ecd673d5-5785-4beb-9a4e-c3f2e1df1126

📥 Commits

Reviewing files that changed from the base of the PR and between 14f56ed and d87c20c.

📒 Files selected for processing (7)
  • src/main/daemon/daemon-host-relocation.test.ts
  • src/main/daemon/daemon-host-relocation.ts
  • src/main/daemon/daemon-pid-file-parse.test.ts
  • src/main/daemon/daemon-pid-file-parse.ts
  • src/main/daemon/daemon-pid-record-quarantine.ts
  • src/main/daemon/daemon-process-inspection.test.ts
  • src/main/daemon/daemon-process-inspection.ts
💤 Files with no reviewable changes (1)
  • src/main/daemon/daemon-process-inspection.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change introduces ProcessLivenessVerdict and helpers for inspecting and merging process liveness. collectPinnedDaemonVersions now returns structured evidence and reports unverifiable PID-file or runtime-directory failures. Corrupt PID records can be salvaged and quarantined. pruneOldDaemonHosts skips unverifiable evidence and removes only hosts marked exited. Tests cover these behaviors.

Merge Risk: 🟡 Moderate · up to d87c2

The change correctly preserves daemon hosts when liveness is uncertain, but recursive cleanup still lacks an ownership check and corrupt PID quarantine can race with publication of a replacement record. Either issue could remove or disrupt active daemon state, so merge requires explicit owner acceptance or additional fencing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 and concisely describes the main change: preventing Windows daemon host pruning when liveness is unverifiable.
Description check ✅ Passed The description is detailed and covers the change, rationale, behavior before and after, testing, platform impact, risks, and checklist items. The Linked Issue section is present but marked N/A despit…
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, behavior before and after, testing, platform impact, risks, and checklist items. The Linked Issue section is present but marked N/A despite the template requesting an issue link.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0896d093-8048-4020-8a5b-cbe849d97f36

📥 Commits

Reviewing files that changed from the base of the PR and between 39ac32f and 14f56ed.

📒 Files selected for processing (4)
  • src/main/daemon/daemon-host-relocation.test.ts
  • src/main/daemon/daemon-host-relocation.ts
  • src/main/daemon/daemon-incarnation-evidence-types.ts
  • src/main/daemon/daemon-process-inspection.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent adversarial review — head 14f56edbcf1ec8b9cfca2e4924212d4ec8d126de

Reviewed exactly this head (both commits). Verdict: merge-ready. The core contract fix is correct and proven failing-first; all findings below are P2 (non-blocking).

Contract conformance

  • Vocabulary is exactly live / unverifiable / exited (ProcessLivenessVerdict); the evidence-level complete/unverifiable describes the listing, not a process verdict — no synonyms introduced.
  • No path maps loss of contact to exited: every process.kill(pid, 0) failure other than ESRCH lands on live (EPERM) or unverifiable (anything else), and every collection failure aborts pruning entirely. exited requires a positive ESRCH from the owning (local) host.
  • Dropping startTimeMatches is behavior-neutral here: on win32 (the only platform where prune runs) getProcessStartedAtMs returns null, so the old check was vacuously true; on linux/darwin the collector's result is discarded by prune's platform gate. Side benefit: this removes a sync getconf spawn from linux/darwin startup. startTimeMatches is still live at its two other call sites (daemon-pid-identity.ts, orcad-instance-lock.ts) — not orphaned.

Ablation (each production hunk reverted individually, suite re-run)

New/changed tests fail 4/12 on the parent commit b63c006ae9 — they pin the fix.

Hunk Result
inspectProcessLiveness: EPERM → live (the core fix) RED — covered
inspectProcessLiveness: unknown error → unverifiable RED — covered
prune switch: per-version unverifiable → keep RED — covered
prune: absent version defaults to exited (prune) RED — covered
collect: runtime dir unreadable → top-level unverifiable GREEN — uncovered
collect: pid file unreadable/unparseable → top-level unverifiable GREEN — uncovered
prune: top-level unverifiable early return GREEN — uncovered
mergeProcessLivenessVerdict precedence (live > unverifiable > exited) GREEN — uncovered (replacing the whole body with return next stays green)

The entire collection-level unverifiable channel has zero end-to-end coverage: no test feeds a top-level unverifiable evidence into pruneOldDaemonHosts, and no test exercises an unreadable/garbage pid file or a missing runtime dir. All four uncovered hunks sit in the conservative (keep) direction, so the latent regression risk is disk growth, not wrong deletion — still, please add tests (merge precedence is a 5-line unit test).

Coercion attempts (can anything still delete a live host?)

  • process.kill throws non-EPERM (EINVAL/EACCES/…): unverifiable → kept.
  • Partially populated record (pid present, appVersion null): pins nothing — correct for genuine pre-relocation daemons whose image is not under daemon-host/. Residual (pre-existing, unchanged by this PR): a live relocated daemon whose record was repaired from a hello lacking appVersion would be unrecorded.
  • Probe timeout (ETIMEDOUT): unverifiable → kept (tested).
  • Pid file exists but unreadable: whole collection unverifiable → no pruning at all.
  • Runtime dir on a disconnected share / unreadable: unverifiable → no pruning; host-root readdir failure also aborts.
  • SSH host with contact lost: out of scope by construction — this path only ever judges local pids from local pid files on the local packaged win32 client; no remote process can enter it.

No coercion introduced or left by this PR prunes a live host. The two residual windows (both pre-existing, cross-process only, guarded by the single-instance lock): a live daemon's canonical record briefly renamed to a .swap/.hold claim path during a concurrent claim, and the appVersion-less repair case above.

Findings (all P2)

  1. Test coverage — the four uncovered hunks above.
  2. Permanent silent prune disable / unbounded disk growth — a permanently unparseable or unreadable pid file now returns top-level unverifiable forever, so pruning never runs again and ~260MB leaks per superseded version. Old-protocol pid files are never reclaimed (killStaleDaemon sweeps only the current protocol's pidPath; the unlinkDaemonPidFileWhen(… === null) reclaim never reaches daemon-v<old>.pid), so one corrupt legacy file is a permanent state. The old code skipped the bad file and kept pruning. Global abort is the honest conservative reading (an unreadable record names no version, so coverage is unknown) — but pair it with reclaiming unparseable old-protocol records via the existing rename-claim machinery, or at least surface it (see 3).
  3. reason is write-only — nothing logs or reads it; pruneOldDaemonHosts aborts silently and the call site discards the evidence. Log the skip reason at daemon-init.ts:952 or inside prune; otherwise finding 2 is undiagnosable in the field.
  4. Test mock hygiene — killSpy.mockRestore() sits after the assertions, so a failing assertion leaves process.kill mocked for subsequent tests; during ablation this reliably produced cascade failures in the unrelated collectPinnedDaemonVersions test. Move restore to afterEach/try-finally.
  5. Comment overclaim — “A complete runtime-dir listing with no pid record for this version proves it is unowned” (daemon-host-relocation.ts:368) is stronger than what holds: it is proof only for records published at the canonical path with appVersion stamped (the two residual windows above). Suggest softening to “is the strongest available local evidence”.
  6. Nit — readdirSync ENOENT (runtime dir simply absent) is positive local evidence of zero pid records but is folded into unverifiable, permanently disabling pruning for installs where the daemon never started but host dirs exist. Distinguishing ENOENT (complete-empty) from other errors would be strictly more accurate.

Also verified: full daemon suite green on head (146 files / 1676 tests), typecheck green; ProcessLivenessVerdict and the new exports have no consumers outside the changed files + the single daemon-init.ts:952 call site (additive type change, no wire surface, no renderer/mobile exposure); no newer-version guard exists in prune but the test's surviving 9.9.9 is the stubbed current version — a post-rollback newer version dir is protected only by its pid record, same as before the PR.

All three switches consume ProcessLivenessVerdict/ProcessSignalEvidence values
constructed in-process by inspectProcessSignal/inspectProcessLiveness; the union
is never deserialized from a wire, RPC, or persisted record, so the defaults are
genuinely unreachable.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fixed the static-analysis failure at head 377ef088face88d261dd1479aa67fd6fa1d2e039.

Decision: the redundant default cases were deleted — no boundary validation was needed. All three flagged switches consume values produced in-process, never from a wire, remote host, or cross-version record:

  • daemon-process-inspection.ts inspectProcessLiveness (was :46): switches on ProcessSignalEvidence from inspectProcessSignal, derived from a local process.kill(pid, 0) probe — literals constructed in this process.
  • daemon-process-inspection.ts mergeProcessLivenessVerdict (was :62): its only caller is collectPinnedDaemonVersions, whose next always comes from inspectProcessLiveness and whose current is a prior merge result — same local pipeline throughout.
  • daemon-host-relocation.ts pruneOldDaemonHosts (was :376): switches on map values built by collectPinnedDaemonVersions plus a local { status: 'exited' } fallback. The cross-version input here is the persisted daemon-v<N>.pid file, but it carries no verdict — only a parseDaemonPidFile-validated pid/appVersion, and unreadable/unparseable files short-circuit the whole prune to unverifiable before any switch. The verdict union is never serialized; this path is also win32-local (isPackagedElectronWin32), so no SSH/relay peer is involved.

ProcessLivenessVerdict has no producers outside this local inspection pipeline (grep-verified on this head), so the switches are exhaustive by construction and the satisfies never defaults were unreachable dead code. The prune guard's live/unverifiable→continue semantics are unchanged. Verified locally: oxlint --type-aware (code-quality config) clean on both files, pnpm tc:node clean, daemon-host-relocation.test.ts + daemon-process-inspection.test.ts 26/26 passing.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Coverage-gap closure + corrupt-pid-file re-triage (head e38811a4257a400cefe848470bab442b36046065)

Four uncovered hunks now pinned by failing-first tests

# Hunk Test(s) that now pin it Ablation re-proof (hunk reverted on this head)
1 runtime-directory-unreadable → unverifiable pruneOldDaemonHosts > skips pruning when the runtime directory cannot be read reverted to return {status:'complete',…} → 1 failed
2 bad-pid-file → unverifiable vetoes pruning while a pid salvaged from a corrupt record still answers, quarantines a corrupt record naming no live pid so pruning resumes next launch, vetoes pruning without quarantine when a pid record cannot be read both branches reverted to continue → 4 failed (3 targeted + 1 cascade)
3 prune's top-level unverifiable gate prunes nothing and never throws when the evidence is unverifiable (also asserts the skip is logged) gate deleted → 5 failed (prune throws TypeError)
4 mergeProcessLivenessVerdict precedence unit: keeps a live verdict when a later record … reports exited, … reports unverifiable, never lets an exited record downgrade an unverifiable verdict (+3 agreeing-direction cases); integration: keeps a version live when any of its pid records is live (two daemon-v<N>.pid records, same app version, one live one dead) body replaced with return next → 4 failed (3 unit + the integration test)

Each ablation was run locally against src/main/daemon/daemon-host-relocation.test.ts + daemon-process-inspection.test.ts; all 38 pass with the hunks present, and every hunk now has at least one deterministic red when reverted. Item 4 was the dangerous one: with return next, a dead old-protocol record scanned after a live one flips the version to exited and the prune deletes a live daemon's host dir.

Corrupt-pid-file finding: P1, fixed in this PR

Determinations (with code evidence):

  • Reachable without hand-editing: yes. The daemon publishes its record with a plain non-atomic writeFileSync (publishDaemonPidFile, daemon-spawner.ts); a crash / power loss / disk-full torn write leaves bytes that parseDaemonPidFile rejects (fails JSON.parse and isn't a legacy bare integer). External corruption (disk, AV, backup restore) is a second path.
  • No path back once the protocol version moves on. killStaleDaemon reclaims unparseable records only for the current protocol version (daemon-stale-kill.ts:186). Nothing else ever reads, rewrites, or deletes daemon-vN.pid for a retired N — not app restart, not upgrade, not host relocation (userData/daemon is stable). The veto was eternal.
  • Leak unbounded. With pruning permanently disabled, every update strands another ~260MB daemon-host/<ver> dir, forever — and the reason string was write-only, so the state was undiagnosable in the field. A one-crash entry into a permanent, silent, unbounded leak is not a P2.

Fix (contract untouched — live/unverifiable/exited vocabulary and precedence unchanged):

  • Observable: pruneOldDaemonHosts now logs [daemon] Skipping daemon-host prune: <reason> on every unverifiable skip; quarantine decisions are logged too.
  • Recoverable: an unparseable record is quarantined by rename to <name>.corrupt (bytes preserved for diagnosis) so the next launch scans a complete listing and pruning resumes — but only when no process answers for a pid salvaged from the corrupt bytes (salvagePidFromCorruptDaemonRecord; pid is the first JSON key, so torn writes usually preserve it). If the salvaged pid still answers, the record keeps its conservative veto un-quarantined until that pid exits — the recovery path never licenses deleting a host whose possibly-live owner is evidenced. The quarantining launch itself still prunes nothing.
  • Read failures are not quarantined (AV lock, vanished file): transient by nature; the veto simply re-evaluates next launch from the real bytes.

The quarantine helper lives in daemon-pid-record-quarantine.ts (the relocation module was at the max-lines ceiling). Also rebased onto 377ef08, so the static-analysis red on the switch defaults is upstream-fixed on this head, and replied to the open review thread on daemon-host-relocation.ts (the marker-ownership guard would permanently leak staging/partially-pruned dirs).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent re-review at head e38811a4257a400cefe848470bab442b36046065

Full readiness pass at this exact head (prior independent review only covered 14f56edbcf). Baseline: both touched suites green locally (38/38); full src/main/daemon suite green (1705 tests). CI rollup SUCCESS (28 passing, 10 skipped), 0 unresolved threads.

Ablation re-run (all 10 hunks, each in isolation, each restored before the next)

# Hunk ablated Mutation Result
A1 runtime-dir unreadable → unverifiable catch → complete empty map RED (1: skips pruning when the runtime directory cannot be read)
A2 pid-file read failure → unverifiable catch → continue RED (1: vetoes pruning without quarantine when a pid record cannot be read)
A3 parse failure → quarantine + unverifiable continue RED (2: both quarantine tests)
A4 mergeProcessLivenessVerdict body → return next RED (4, across BOTH files, incl. integration test keeps a version live when any of its pid records is live)
A5 prune top-level unverifiable gate gate → treat as complete-empty RED (5)
A6 per-entry switch: unverifiable prunable unverifiable → delete RED (1: unavailable keep test)
A7 permission_denied → exited RED (1: EPERM keep test)
A8 unavailable → exited RED (1)
A9 quarantine salvage gate removed always quarantine RED (1: live-salvaged-pid veto test)
A10 no-record default ?? exited → ?? live RED (3)

The previously-fatal gap is closed: return next in the merge now fails 4 tests including an order-sensitive on-disk integration case (live record in daemon-v7.pid, exited in daemon-v8.pid — scan order would let the exited record win).

Quarantine path — adversarial results

(a) Salvaged pid belonging to a different process. Yes, reachable: a torn write that truncates inside the pid digit run (e.g. {"pid": 4242… cut after 42) salvages a pid that never owned the record. Two failure directions, both narrow:

  • Truncated pid probes exited → record quarantined while the true owner (an old-version daemon with live terminals) is still running → next launch prunes that version's host dir. On Windows the running exe and mapped .node are locked so rmSync fails partway, but plain JS files in that dir are deletable; a later lazy read by that daemon could fail. Preconditions: packaged win32 + retired-protocol record + tear inside the digits + prefix-pid dead + owner still live. Probabilistic and multi-precondition — residual risk, not blocking; fix(daemon): make pid-record publish atomic via claim-then-link #16924 removes the torn-write source going forward.
  • Truncated pid collides with an immortal pid (e.g. pid 4 = System, which probes EPERM → live) → the permanent-veto behavior this PR fixes persists for that one record. Same narrow tear window. The practically-reachable P1 cases are still fixed (see below).

(b) No pid / live / unverifiable salvage. Live → kept (pinned by test). Unverifiable (non-ESRCH/EPERM probe error) → kept (status !== 'exited'; no dedicated test — minor coverage note). No salvageable pid → the record IS quarantined, not left alone — deliberate and test-pinned ('not a daemon record'). This is the right call: an unattributable record kept forever is exactly the eternal-veto P1; a torn daemon write can only lose the pid prefix if truncated within the first ~9 bytes. Flagging it since it diverges from "quarantine only on a pid probing exited" as sometimes stated.

(c) Quarantine races. <name>.corrupt is a single slot: a second quarantine's renameSync replaces the previous bytes (libuv uses replace-existing semantics on Windows too) — bounded accumulation (≤1 per protocol version, ~100B, never cleaned up), only diagnostic bytes lost. Two concurrent racers: loser's rename fails ENOENT → caught → conservative unverifiable veto. .corrupt names match neither the pid-scan regex (^daemon-v\d+\.pid$) nor any released sweeper pattern. Safe.

(d) Version still in use. The current protocol's record is healed before the prune scan ever runs: ensureRunning() (daemon-init.ts:950) precedes the scan (line 952); killStaleDaemon deletes unparseable current-protocol records under a parse-gated claim, and adoption's reconcileDaemonPidOwnership republishes a mismatched/corrupt record from the authenticated endpoint identity. Quarantine can only touch a current-protocol record if that repair write failed, and the outcome is benign (record republished on next reconcile; the current version's dir is unconditionally exempt from pruning). The live old-version case is (a) above.

P1 recovery — proven, not just mitigated

The two-launch test (quarantines a corrupt record naming no live pid so pruning resumes next launch) proves the full cycle on real files: launch 1 skips pruning once and renames the record; launch 2 gets a complete listing and reclaims the unowned host dir. Post-recovery state: bytes preserved at daemon-vN.pid.corrupt (never rescanned), pruning fully functional. Recovery latency: the scan early-returns on the first bad record, so k corrupt records take k launches — bounded and fine. Residual non-recovery corner: only the immortal-pid collision in (a).

#16924 interaction (atomic pid publish, e0b44cdd6f42)

Zero file overlap; git merge-tree clean; I additionally merged both heads locally and ran the entire src/main/daemon suite: 149 files / 1705 tests green. Neither deadens the other: #16924 prevents new torn writes, but this PR's quarantine stays reachable for field-legacy records, old builds still writing non-atomically, #16924's non-EEXIST degrade path (plain exclusive write, still tearable), and its claim-restore copy. Conversely #16924's scratch names (.publish-/.swap-/.hold-) don't match this PR's scan regex, and a mid-claim vanished record reads as a transient unverifiable veto (safe). Merge order does not matter.

Reason-string observability

Genuinely observable now, with one caveat. Every unverifiable skip reaches console.warn ([daemon] Skipping daemon-host prune: <reason>, plus per-branch quarantine warns), pinned by test. But the main process has no console capture: these lines land on stdout only — visible in dev/terminal launches, absent from main.trace.ndjson and the diagnostic bundle an engineer would pull from the field. That matches the incumbent [daemon] warn idiom (stale-kill etc.), so it's parity, not a regression. Optional follow-up: mirror prune-skip reasons through the startup-diagnostics path so field bundles carry them.

Performance (by hand; $perf not invocable in this context)

One scan per launch, after daemon init: one readdirSync, plus per pid record a ~100B readFileSync + JSON.parse + process.kill(pid, 0) — microseconds, count bounded by protocol history. Quarantine adds one probe + one rename, once ever per corrupt record. The heavyweight op (rmSync of ~260MB host dirs, sync on the main thread) is pre-existing and this PR only ever reduces deletions. No timers, listeners, retained state, or growth. Two P2 notes: (1) collectPinnedDaemonVersions — including its quarantine side effect — runs on every platform while its only consumer no-ops off win32, so macOS/Linux launches now probe/rename too (harmless, but side-effect scope is wider than the feature; hoisting the win32 gate would fix it); (2) the per-entry prune switch falls through to delete for a hypothetical future 4th verdict status — protected today by typescript/switch-exhaustiveness-check in lint, but a fail-closed shape (if (verdict.status !== 'exited') continue) needs no protection at all.

Verdict: MERGE-READY

No P0/P1 candidates (so no counsel escalation needed). All findings above are P2/residual-risk. The evidence model matches the live/unverifiable/exited contract in docs/reference/ssh-execution-boundary.md verbatim, the quarantine follows the in-repo precedent of quarantine-over-delete (terminal-history-recovery-quarantine.ts) with fencing appropriate to its unit, and the from-scratch design would differ only in the two P2 shapes noted above. Not merging/approving per dispatch instructions.

The prune switch shared #16900's delete-gate shape: an unhandled future
verdict status fell through into rmSync, protected only by the lint
exhaustiveness rule. Deletion is now opted into by a positively matched
'exited' via reclaimUnownedDaemonHostDir; a pinning test feeds an
out-of-contract verdict and asserts the host dir survives.

Pid salvage from corrupt records now requires the digit run to be
terminated by a following non-digit byte. A tear inside the digits leaves
a truncated prefix that is a different pid: probing it either quarantined
a record on an unrelated process's death or, when the prefix collided
with an immortal pid (Windows System pid 4), re-created the permanent
prune veto for that record. Unterminated digits mean the writer died
mid-write, so the record quarantines without consulting any probe.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Hardening pass at exact head d87c20c206364d2f51a3ab476344e7b8d5e0bfc6:

Item 1 — prune delete-gate fail-safe (#16900's pattern). The verdict switch in pruneOldDaemonHosts fell through to rmSync on any future unhandled verdict status (lint-only protection). Deletion now requires a positively matched 'exited' behind reclaimUnownedDaemonHostDir; a pinning test feeds an out-of-contract verdict (status: 'suspended') through pruneOldDaemonHosts and asserts the host dir survives, plus the positive direction ('exited' deletes). No default arm added; git diff vs previous head for config/oxlint-code-quality-type-aware.json is empty (0 lines).

Item 2 — pid-salvage attribution. Decision: validate the salvage instead of probing untrusted digits — salvagePidFromCorruptDaemonRecord now requires the digit run to be terminated by a following non-digit byte (/"pid"\s*:\s*(\d+)(?=\D)/). A tear inside the digits leaves digits at end-of-bytes, so a truncated prefix is never mistaken for a whole pid and is never probed; such records take the existing quarantine path (an unterminated digit run means the writer died mid-write, so the owner cannot be live — no probe consulted). This closes both reviewer cases: a dead prefix pid no longer drives quarantine on false evidence, and an immortal prefix pid (e.g. System pid 4) can no longer re-create a permanent per-record veto. Terminated salvaged pids keep the exact prior conservative behavior (existing veto test unchanged and green).

Ablation (all restored): delete-gate reverted to negative-match → pinning test red (1 failed / 20 passed); prune loop reverted to the old fall-through switch → pinning test red; salvage terminator reverted → 3 tests red (both reviewer-case tests + the parse unit test).

Verification: full src/main/daemon suite 1694 passed / 3 skipped; pnpm tc:node clean; changed-code quality gate (code quality, type-aware, React Doctor) 0 new findings across 8 changed files; pre-commit oxlint/oxfmt clean. The #16924 interaction proof from the prior review is untouched (no changes to publish/claim paths).

Author X handle: @BrennanKB5

brennanb2025 added a commit that referenced this pull request Aug 28, 2026
The monitor entered the completion path on children !== 'live' after the
unverifiable early-return — a fall-through, not a positive 'exited' match
(the polarity shape fixed in #16900/#16908). A fourth verdict arm admitted
by a future evidence funnel would have silently read as exit evidence.
Completion now requires children === 'exited'; anything outside the known
vocabulary re-arms like a failed inspection. Pinned by an out-of-contract
monitor test (fails on the previous head) and a funnel-level normalization
unit test that keeps the normalize hunk independently covered.
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
The monitor entered the completion path on children !== 'live' after the
unverifiable early-return — a fall-through, not a positive 'exited' match
(the polarity shape fixed in #16900/#16908). A fourth verdict arm admitted
by a future evidence funnel would have silently read as exit evidence.
Completion now requires children === 'exited'; anything outside the known
vocabulary re-arms like a failed inspection. Pinned by an out-of-contract
monitor test (fails on the previous head) and a funnel-level normalization
unit test that keeps the normalize hunk independently covered.
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
…cabulary guard

The two hardening arms were mutually redundant in coverage: reverting either
alone left the suite green. The out-of-vocabulary guard is now pinned on its
own; this pins the other half.

Given the vocabulary guard, every sample reaching the exit gate already carries
'live' or 'exited'. On a host that builds its wire result with
buildPtyProcessInspectionWireResult the legacy `hasChildProcesses` boolean is
exactly `children.verdict === 'live'`, so reading the boolean and requiring a
positive 'exited' agree — the arm is invisible there.

They part on the shape the reader is written to survive: a peer this client
cannot vouch for, whose two fields disagree. readPtyProcessInspectionEvidence
never cross-checks the legacy scalar against the evidence union, so
`hasChildProcesses: false` can arrive beside a positively observed
`children: 'live'`. That boolean's `false` is the lossy collapse conflating
"no children" with "could not tell" (#16900/#16908). The evidence union is
authoritative, so 'live' must refuse even though the legacy field waves it
through.

Reverting the positive-exited arm alone turns two of these red with a false
`process-exit` completion; reverting the vocabulary guard alone leaves all
three green.
…version

publishDaemonPidFile creates the record before writing it (writeFileSync with
flag 'wx'), so a concurrent launch can read a live daemon's record as empty. A
two-process probe observed the empty window on 7 of 2273 reads.

An empty record was not treated as corrupt at all: the parser's legacy
bare-integer fallback coerces it to pid 0 (Number('') === 0) with appVersion
null, so the scan skipped it as a pre-relocation daemon, left its version
unpinned, and the prune reclaimed a running daemon's host image -- the exact
destructive outcome this change exists to prevent, reached without any
'unverifiable' verdict. A pid that is not a positive integer names no process
(process.kill(0, 0) probes the caller's own process group), so it is now a
veto rather than a skip.

Quarantine additionally refuses any record written in the last minute: an
in-flight publish is by definition fresh, while a record left corrupt by a
dead writer ages past the floor and is quarantined on a later launch. Fixed
locally rather than in parseDaemonPidFile, whose null result also drives an
unlink in daemon-stale-kill.

Each gate is pinned by a test that fails individually when it is reverted.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop — patched, not superseded

Head reviewed: 82272b41a4 (was d87c20c206). Rebase-clean on main @ 94e7586665.

Direct answer to the question this PR exists to settle — can an unverifiable liveness answer still reach the rmSync of a daemon-host/<ver> dir?
No, not through the verdict path. But it could through a path that never produced a verdict at all, and that is fixed here.

Defect found and fixed

publishDaemonPidFile uses writeFileSync(..., flag:'wx'), which creates the record before writing it. A concurrent launch can therefore read a live daemon's record as empty. A two-process probe observed the empty window on 7 of 2273 reads.

An empty record was not treated as corrupt at all. parseDaemonPidFile's legacy bare-integer fallback coerces '' to pid 0 (Number('') === 0, Number.isFinite(0) === true) with appVersion: null, so the scan skipped it as a pre-relocation daemon, left that version unpinned, and the prune then reclaimed a running daemon's host image — the exact destructive outcome this PR exists to prevent, reached without any unverifiable verdict ever being formed.

Two gates added, each independently ablation-pinned:

  • collectPinnedDaemonVersions vetoes on a parsed pid that is not a positive integer. A pid of 0 names no process — process.kill(0, 0) probes the caller's own process group, never a daemon — so it is not liveness evidence.
  • quarantineCorruptDaemonPidRecord refuses any record modified in the last 60s. An in-flight publish is by definition fresh; a record left corrupt by a dead writer ages past the floor and is quarantined on a later launch.

Fixed locally rather than in parseDaemonPidFile, because that function's null result also drives an unlink at daemon-stale-kill.ts:186 — tightening it there would have created a new destructive path.

Ablation table — every gate reverted individually

# Gate reverted to Red?
B1 readdir failure → complete/empty RED
B2 pid read failure → continue RED
B3 unparseable record → continue RED
B4 prune ignores unverifiable evidence RED
B5 host reclaim gate → exclusion form RED
B6 merge: unverifiable no longer defers to prior live RED
B7 merge: exited overrides a prior verdict RED
B8 salvage regex drops the (?=\D) lookahead RED
B9 quarantine skips the salvaged-pid liveness check RED
NEW‑1 non-positive-pid guard removed RED
NEW‑2 quarantine age gate removed RED

No two gates are only jointly pinned. NEW‑1 and NEW‑2 are separated by a dedicated test each: an aged empty record isolates the pid guard, a fresh one isolates the age gate.

Dropped default: … satisfies never arms are safe

Adding a member to ProcessSignalEvidence makes both tsc (TS2366) and typescript/switch-exhaustiveness-check go red, and audit:code-quality:type-aware does cover src. Separately, adding an unhandled ProcessLivenessVerdict member leaves the destructive gates silently preserving — 64/64 still green — confirming the fail-safe polarity is structural, not lint-dependent.

Evidence

pnpm tc, oxlint, audit:code-quality:type-aware, git diff --check all clean. Composed with #16900 on current main: merges clean, 1710 passed / 3 skipped / 0 failed. Launched the composed tree in Electron via CDP: app starts clean (0 console errors), daemon publishes a valid record, no spurious quarantine.

Not verified

The destructive prune arm is win32 && packaged && app.asar only, so it was exercised in tests only — never live. No Windows host was available. Dev-mode CDP is blind to packaged-build regressions.

brennanb2025 added a commit that referenced this pull request Aug 28, 2026
…eld contradicts

The exit gate used to read `if (result.hasChildProcesses)` and refuse on
`true`. Moving it onto the evidence union dropped the legacy field, so the
gate now refuses only on a children verdict other than 'exited'. That is more
conservative in one direction — the direction the positive-exited arm pins —
and less conservative in its mirror: `hasChildProcesses: true` beside
`children: 'exited'` is a shape the boolean-only line refused and the
verdict-only gate dispatches a process-exit completion for.

Only the boolean's `false` pole is the lossy collapse this batch removes; it
conflates "no children" with "could not ask". Its `true` pole is a positive
observation on every producer — buildPtyProcessInspectionWireResult sets it
from `children.verdict === 'live'`, processHasChildren from a pgrep that
exited 0 with output, and the daemon host from an observed non-shell
foreground. Dropping a positive liveness observation to honour a disagreeing
'exited' is the #16900/#16908 polarity bug pointing the other way, so the gate
now refuses whenever either half reports live children.

No conforming host is affected: readPtyProcessInspectionEvidence's legacy
fallback maps `true` to 'live', which the verdict term already refuses, and
the wire builder never emits the disagreeing pair. Only a peer this client
cannot vouch for can, which is the same premise the mirror arm is pinned on.

Pinned by three monitor tests through the real reader with no mock (all three
fail on the previous head, each with a false process-exit completion). The
four-way ablation keeps the arms independent: reverting only this term reddens
its three tests and leaves the vocabulary-guard and positive-exited pins green.
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
The mirror of the children-axis rule, one axis over. Recognition used to read
`recognizeAgentProcess(result.foregroundProcess)`. Moving it onto the evidence
union made it read `evidence.foreground.processName`, so a sample whose union
reports `{observed, processName: null}` beside a legacy `foregroundProcess:
'codex'` no longer recognizes an agent. Its foreground verdict is still inside
the vocabulary, so the out-of-vocabulary guard cannot refuse it either, and the
sample falls through to the exit gate and dispatches a process-exit completion
for an agent the host still names in the foreground.

Only the `null` pole of the legacy scalar is the lossy collapse this batch
removes; it conflates "no agent in the foreground" with "could not ask". A
recognized non-null name is a positive observation on every producer:
buildPtyProcessInspectionWireResult copies it straight off an `observed`
foreground verdict, and the ps/pgrep probes only set it from a command line the
host actually read back. Discarding a positive liveness observation to honour a
union reporting no name is the #16900/#16908 polarity bug on the foreground
axis, so the gate now refuses whenever either half still names an agent.

The refusal is added at the exit gate rather than by widening recognition, so
the arm can only ever withhold a dispatch, never introduce one: reading the
legacy name into handleRecognizedProcess would fire a process-replacement
completion on a disagreeing name, which is less conservative, not more.

No conforming host is affected. To reach the gate the foreground verdict is
already 'observed', so buildPtyProcessInspectionWireResult's legacy scalar is
byte-identical to the union's processName the gate already found unrecognized,
and a host predating the field gets that same scalar through the reader's legacy
fallback. Only a peer this client cannot vouch for can disagree, the same
premise the children-axis arm is pinned on.

Pinned by four monitor tests through the real reader with no mock; all four fail
on the previous head, each with an actual false process-exit completion for
'codex'. The four-way ablation keeps the arms independent: reverting only this
term reddens its four tests and leaves the vocabulary-guard, positive-exited and
legacy-live-children pins green.
@brennanb2025
brennanb2025 merged commit 7abdf03 into main Aug 28, 2026
31 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
)

* Fix Windows daemon host prune liveness contract

* Scope host prune evidence per version

* Drop redundant default cases from exhaustive liveness switches

All three switches consume ProcessLivenessVerdict/ProcessSignalEvidence values
constructed in-process by inspectProcessSignal/inspectProcessLiveness; the union
is never deserialized from a wire, RPC, or persisted record, so the defaults are
genuinely unreachable.

* Cover prune liveness gates and quarantine corrupt pid records

* Make the prune delete-gate fail safe and refuse truncated pid salvage

The prune switch shared stablyai#16900's delete-gate shape: an unhandled future
verdict status fell through into rmSync, protected only by the lint
exhaustiveness rule. Deletion is now opted into by a positively matched
'exited' via reclaimUnownedDaemonHostDir; a pinning test feeds an
out-of-contract verdict and asserts the host dir survives.

Pid salvage from corrupt records now requires the digit run to be
terminated by a following non-digit byte. A tear inside the digits leaves
a truncated prefix that is a different pid: probing it either quarantined
a record on an unrelated process's death or, when the prefix collided
with an immortal pid (Windows System pid 4), re-created the permanent
prune veto for that record. Unterminated digits mean the writer died
mid-write, so the record quarantines without consulting any probe.

* fix(daemon): stop an in-flight pid publish from being read as a dead version

publishDaemonPidFile creates the record before writing it (writeFileSync with
flag 'wx'), so a concurrent launch can read a live daemon's record as empty. A
two-process probe observed the empty window on 7 of 2273 reads.

An empty record was not treated as corrupt at all: the parser's legacy
bare-integer fallback coerces it to pid 0 (Number('') === 0) with appVersion
null, so the scan skipped it as a pre-relocation daemon, left its version
unpinned, and the prune reclaimed a running daemon's host image -- the exact
destructive outcome this change exists to prevent, reached without any
'unverifiable' verdict. A pid that is not a positive integer names no process
(process.kill(0, 0) probes the caller's own process group), so it is now a
veto rather than a skip.

Quarantine additionally refuses any record written in the last minute: an
in-flight publish is by definition fresh, while a record left corrupt by a
dead writer ages past the floor and is quarantined on a later launch. Fixed
locally rather than in parseDaemonPidFile, whose null result also drives an
unlink in daemon-stale-kill.

Each gate is pinned by a test that fails individually when it is reverted.

---------

Co-authored-by: Brennan Benson <[email protected]>
(cherry picked from commit 7abdf03)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
)

* Fix Windows daemon host prune liveness contract

* Scope host prune evidence per version

* Drop redundant default cases from exhaustive liveness switches

All three switches consume ProcessLivenessVerdict/ProcessSignalEvidence values
constructed in-process by inspectProcessSignal/inspectProcessLiveness; the union
is never deserialized from a wire, RPC, or persisted record, so the defaults are
genuinely unreachable.

* Cover prune liveness gates and quarantine corrupt pid records

* Make the prune delete-gate fail safe and refuse truncated pid salvage

The prune switch shared stablyai#16900's delete-gate shape: an unhandled future
verdict status fell through into rmSync, protected only by the lint
exhaustiveness rule. Deletion is now opted into by a positively matched
'exited' via reclaimUnownedDaemonHostDir; a pinning test feeds an
out-of-contract verdict and asserts the host dir survives.

Pid salvage from corrupt records now requires the digit run to be
terminated by a following non-digit byte. A tear inside the digits leaves
a truncated prefix that is a different pid: probing it either quarantined
a record on an unrelated process's death or, when the prefix collided
with an immortal pid (Windows System pid 4), re-created the permanent
prune veto for that record. Unterminated digits mean the writer died
mid-write, so the record quarantines without consulting any probe.

* fix(daemon): stop an in-flight pid publish from being read as a dead version

publishDaemonPidFile creates the record before writing it (writeFileSync with
flag 'wx'), so a concurrent launch can read a live daemon's record as empty. A
two-process probe observed the empty window on 7 of 2273 reads.

An empty record was not treated as corrupt at all: the parser's legacy
bare-integer fallback coerces it to pid 0 (Number('') === 0) with appVersion
null, so the scan skipped it as a pre-relocation daemon, left its version
unpinned, and the prune reclaimed a running daemon's host image -- the exact
destructive outcome this change exists to prevent, reached without any
'unverifiable' verdict. A pid that is not a positive integer names no process
(process.kill(0, 0) probes the caller's own process group), so it is now a
veto rather than a skip.

Quarantine additionally refuses any record written in the last minute: an
in-flight publish is by definition fresh, while a record left corrupt by a
dead writer ages past the floor and is quarantined on a later launch. Fixed
locally rather than in parseDaemonPidFile, whose null result also drives an
unlink in daemon-stale-kill.

Each gate is pinned by a test that fails individually when it is reverted.

---------

Co-authored-by: Brennan Benson <[email protected]>
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