Repository navigation
Fix Windows daemon host pruning on unverifiable liveness - #16908
Conversation
|
Status at exact SHA |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (7)
💤 Files with no reviewable changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe change introduces Merge Risk: 🟡 Moderate · up to 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)
✅ Passed checks (4 passed)
Full details: Description checkExplanation 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.
✨ 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.
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
📒 Files selected for processing (4)
src/main/daemon/daemon-host-relocation.test.tssrc/main/daemon/daemon-host-relocation.tssrc/main/daemon/daemon-incarnation-evidence-types.tssrc/main/daemon/daemon-process-inspection.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Independent adversarial review — head
|
| 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.killthrows non-EPERM (EINVAL/EACCES/…):unverifiable→ kept.- Partially populated record (pid present,
appVersionnull): pins nothing — correct for genuine pre-relocation daemons whose image is not underdaemon-host/. Residual (pre-existing, unchanged by this PR): a live relocated daemon whose record was repaired from a hello lackingappVersionwould 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)
- Test coverage — the four uncovered hunks above.
- Permanent silent prune disable / unbounded disk growth — a permanently unparseable or unreadable pid file now returns top-level
unverifiableforever, so pruning never runs again and ~260MB leaks per superseded version. Old-protocol pid files are never reclaimed (killStaleDaemonsweeps only the current protocol'spidPath; theunlinkDaemonPidFileWhen(… === null)reclaim never reachesdaemon-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). reasonis write-only — nothing logs or reads it;pruneOldDaemonHostsaborts silently and the call site discards the evidence. Log the skip reason atdaemon-init.ts:952or inside prune; otherwise finding 2 is undiagnosable in the field.- Test mock hygiene —
killSpy.mockRestore()sits after the assertions, so a failing assertion leavesprocess.killmocked for subsequent tests; during ablation this reliably produced cascade failures in the unrelatedcollectPinnedDaemonVersionstest. Move restore toafterEach/try-finally. - 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 withappVersionstamped (the two residual windows above). Suggest softening to “is the strongest available local evidence”. - Nit —
readdirSyncENOENT (runtime dir simply absent) is positive local evidence of zero pid records but is folded intounverifiable, 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.
|
Fixed the static-analysis failure at head Decision: the redundant
|
Coverage-gap closure + corrupt-pid-file re-triage (head
|
| # | 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 thatparseDaemonPidFilerejects (failsJSON.parseand 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.
killStaleDaemonreclaims unparseable records only for the current protocol version (daemon-stale-kill.ts:186). Nothing else ever reads, rewrites, or deletesdaemon-vN.pidfor a retired N — not app restart, not upgrade, not host relocation (userData/daemonis 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:
pruneOldDaemonHostsnow 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).
Independent re-review at head
|
| # | 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
.nodeare locked sormSyncfails 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.
|
Hardening pass at exact head Item 1 — prune delete-gate fail-safe (#16900's pattern). The verdict switch in Item 2 — pid-salvage attribution. Decision: validate the salvage instead of probing untrusted digits — 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 Author X handle: @BrennanKB5 |
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.
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.
…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.
Review loop — patched, not supersededHead reviewed: Direct answer to the question this PR exists to settle — can an unverifiable liveness answer still reach the Defect found and fixed
An empty record was not treated as corrupt at all. Two gates added, each independently ablation-pinned:
Fixed locally rather than in Ablation table — every gate reverted individually
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
|
…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.
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.
) * 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)
) * 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]>
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
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
live/unverifiable/exitedprocess-liveness verdict.exitedauthorizes deletion.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
pnpm test src/main/daemon/daemon-host-relocation.test.ts src/main/daemon/daemon-process-inspection.test.ts --run(26/26)pnpm tc:nodepnpm exec oxlinton all changed files14f56edbcf1ec8b9cfca2e4924212d4ec8d126de, 12/12 focused relocation tests passedReliability Contract
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.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
Notes
pnpm run check:code-quality:changedunder an outerpnpm runmixes the Node 26 engine warning into its JSON parsing; runningnode config/scripts/check-changed-code-quality.mjsdirectly passes: 0 new findings (code quality, type-aware, React Doctor).Hardening at d87c20c (fail-safe delete-gate + salvage attribution)
rmSync, protected only by the lint exhaustiveness rule. Deletion is now opted into by a positively matched'exited'viareclaimUnownedDaemonHostDir(same shape as Keep an older terminal helper's files at startup unless it has really exited #16900'sreclaimLegacyDaemonOwnershipFiles); a pinning test feeds an out-of-contract verdict throughpruneOldDaemonHostsand asserts the host dir survives. No default arm added;config/oxlint-code-quality-type-aware.jsonis untouched (diff vs the previous head is empty).Recorded follow-up + scope note
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.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 —killStaleDaemonre-reads current-protocol records itself). If off-win32 work is unwanted, hoisting the platform check around thedaemon-init.tscall site is a safe follow-up.Checklist