Skip to content

feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) - #24409

Merged
OrcaWin merged 2 commits into
mainfrom
OrcaWin/node-rt-p3-t2-p4b
Oct 1, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
OrcaWin/node-rt-p3-t2-p4b

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​411 $\color{#cf222e}{\Huge{\mathbf{−}}}$​160 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​618 $\color{#cf222e}{\Huge{\mathbf{−}}}$​75 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​543

ELI5

The background terminal process (the "daemon") can now be asked: "if you have no live terminals, shut down cleanly, and don't accept new ones while you check." It can also be opened in a read-only "recovery" mode that reconnects existing terminals but never starts new ones. Nothing in the app calls either feature yet. They are groundwork for a later slice (T6), so today's behavior is unchanged.

This is the T2 P4b slice of porting #16741. It is stacked on #24402 (P4a) and will be retargeted to main after that merges.

What Changed

Idle retirement (inert until T6):

  • DaemonPtyRouter.requestIdleRetirement() stops accepting new terminals and takes a census of every daemon generation (current and legacy). It asks each one to shutdownIfIdle only when every one reports no live session.
  • If any generation can't be reached, the answer is unverifiable, never "idle". The same applies if a spawn is still in flight, or if a reply is lost after the daemon may already have accepted. Spawns stay fenced in that case, because losing contact is not proof the daemon exited.
  • Each adapter fences its own spawns while it retires.

Session census (inert): listLiveDaemonSessions() returns null unless every generation answered. requestIdleDaemonRetirement() returns { state: 'unverifiable' } when no daemon is installed.

Recovery-only provider (inert):

  • createDaemonRecoveryProvider builds adapters marked recoveryOnly. They reattach to and control existing sessions, but refuse to create a process (assertDaemonRecoverySpawnAdmission).
  • They never respawn the daemon.
  • They never kill sessions whose worktree they don't recognise.
  • The current endpoint stays represented even when it is absent, so missing contact can't read as an empty census.

Health coverage:

  • A ptySpawnHealth reply now also carries coverage ('pty-spawn', or 'handshake' on Windows, where main's preflight skips the spawn probe), runtimeKind: 'node' and runtimeVersion.
  • checkDaemonHealthWithCoverage reads these. When a field is missing, as from an older daemon, it falls back to the old meaning: an older Windows daemon counts as handshake-only.
  • checkDaemonHealth and healthCheckDaemon keep their signatures and behavior.

Router refactor: reconcileOnStartup moved unchanged into daemon-router-session-reconciliation.ts. The router test's adapter mock moved into daemon-pty-router-test-fixture.ts.

Why

Wire compatibility (docs/reference/remote-wire-compatibility.md):

  • The new health fields are optional, and they only appear on an existing reply.
  • Retirement reuses the existing shutdownIfIdle and listSessions requests.
  • There is no new request or event type, and no protocol version change. check-daemon-protocol-crossing reports protocol 38, the same as main, and upgrading from v1.4.218 still adopts live terminals.

Verdicts follow docs/reference/ssh-execution-boundary.md: a generation that doesn't answer is unverifiable, not idle or exited.

Adapted from #16741 (a68b6f3), by hunk:

  • Skipped (T7): the PTY ownership-transfer input fence and getOwnershipBridgeCapabilities in daemon-pty-router.ts, plus their test.
  • Node-only runtime report: the branch's daemon-runtime-identity (which detects Bun) is replaced by a small daemon-health-identity.ts. It reports coverage, runtimeKind: 'node' and process.version. The 'bun'/'bun-terminal' unions and ptyBackend are gone.
  • Also ported (needed for correctness and tests): the spawn-admission hunks in daemon-pty-session-spawn.ts, the recovery-only no-prune guard in daemon-pty-process-inspection.ts, and daemon-recovery-spawn-admission.ts.

Linked Issue

Part of the Node runtime plan (Phase 3), porting #16741.

Visual Proof

N/A. This is daemon-side groundwork; nothing calls it yet.

Testing

  • Ported:

    • daemon-router-retirement;
    • daemon-recovery-provider and daemon-recovery-only-adapter;
    • daemon-pty-router (now using the shared fixture, with idle-retirement cases);
    • daemon-health, with the coverage and runtime fields and the legacy Windows fallback;
    • daemon-idle-shutdown.
  • New: daemon-provider-census.test.ts. No daemon, or one generation not answering, reads as unverifiable rather than empty.

  • Regression: every src/main/daemon/*.test.ts. 207 files: 205 passed, 2 skipped. 2306 tests passed, 15 skipped.

  • Checks: check-daemon-protocol-crossing passes, and both CI lint configs (native-plugins and type-aware, --deny-warnings) are clean.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Daemon lifecycle management and session census.

The PR is not yet safe to merge because a lost retirement reply can still prevent callers from receiving a verdict.

Findings

  1. P1 Lost reply rejects retirement ▶

Summary

The PR adds idle-retirement and session-census APIs, a recovery-only daemon provider, and health-reply coverage metadata. The changes since the previous review are empty.

  • Retirement fences spawns while checking daemon generations.
  • Recovery-only adapters permit reattachment but reject fresh processes.
  • Health replies distinguish spawn-probe coverage from handshake-only coverage.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Request idle retirement] --> B[Fence new spawns]
  B --> C[Census all daemon generations]
  C -->|Live sessions| D[Return busy]
  C -->|Reply unavailable| E[Return unverifiable]
  C -->|All empty| F[Request retirement from each generation]
  F --> G[Combine retirement results]
Loading

Reviews (3) · Last reviewed commit: "test(daemon): narrow parsed frames and e..."

}
}
this.retirementAttempted = true
const results = await Promise.all(adapters.map((adapter) => adapter.requestIdleRetirement()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Lost reply rejects retirement When several daemon generations are being retired, one can accept retirement while another loses its reply. Promise.all then rejects the entire request instead of returning unverifiable. The caller receives an exception even though a daemon may already be shutting down, so it cannot use the promised retirement verdict.

@pullfrog pullfrog 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.

ℹ️ No critical issues — two minor observations inline.

Reviewed changes

Reviewed the full 23-file / 1-commit delta (9ff76e3 → a462cbc) and ran all seven changed daemon spec files locally (131 tests pass).

  • Router idle retirement — DaemonPtyRouter.requestIdleRetirement() (daemon-router-retirement.ts, new) fences spawn admission, censuses every generation, and only sends shutdownIfIdle when the whole census is empty; unreachable generations, in-flight spawns, and lost replies resolve to unverifiable and stay fenced once a stop was actually attempted.
  • Adapter retirement state machine — daemon-pty-event-subscriptions.ts adds open/checking/retiring/unverifiable with idleRetirementAdmissionClosed, reopening admission only on a confirmed refusal.
  • Session census — listLiveDaemonSessions() / requestIdleDaemonRetirement() in daemon-provider-state.ts return null/unverifiable unless every generation answers, and unverifiable for the degraded provider.
  • Recovery-only provider — daemon-recovery-provider.ts + initDaemonRecoveryProvider (uncalled) reattach to existing sessions, never respawn (respawnFn nulled), never prune unknown-worktree sessions, and refuse fresh spawns via daemon-recovery-spawn-admission.ts.
  • Health coverage — daemon-health-identity.ts adds optional coverage/runtimeKind/runtimeVersion to the existing ptySpawnHealth reply; checkDaemonHealthWithCoverage falls back to the legacy platform-based meaning for older daemons while checkDaemonHealth/healthCheckDaemon keep their signatures.
  • Refactor — reconcileOnStartup moved verbatim into daemon-router-session-reconciliation.ts; the router test's adapter mock moved into daemon-pty-router-test-fixture.ts.

Test quality note: the new refusal/moved-code tests (daemon-router-retirement.test.ts, daemon-provider-census.test.ts, daemon-recovery-only-adapter.test.ts) pin exact outcomes (liveSessions, admissionReopened presence/absence, spawn rejection) and can fail against a looser implementation — good coverage.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +176 to +179
if (adapter instanceof DaemonPtyRouter) {
return adapter.requestIdleRetirement()
}
return adapter.requestIdleRetirement()

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.

Both branches call adapter.requestIdleRetirement() verbatim, so the DaemonPtyRouter check is dead: after the DegradedDaemonPtyProvider guard the remaining union (DaemonPtyRouter | DaemonPtyAdapter) already exposes the method. Collapse to a single return.

Suggested change
if (adapter instanceof DaemonPtyRouter) {
return adapter.requestIdleRetirement()
}
return adapter.requestIdleRetirement()
return adapter.requestIdleRetirement()

private reopenAfterRefusedIdleRetirement(): void {
this.idleRetirementState = 'open'
this.idleRetirementAdmissionClosed = false
this.respawnAdoptionClosed = false

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.

respawnAdoptionClosed is also the lifetime latch that dispose() and disconnectOnly() set, so clearing it unconditionally here can reopen respawn admission on an adapter that was already closed. This is reachable when a prior attempt ended unverifiable (idleRetirementState !== 'open', so the guard at line 105 does not short-circuit) and the adapter was then disposed while its daemon stayed reachable.

Technical details
# `reopenAfterRefusedIdleRetirement` clears a latch it did not exclusively own

## Affected sites
- `src/main/daemon/daemon-pty-event-subscriptions.ts:152` — unconditional `this.respawnAdoptionClosed = false`
- `src/main/daemon/daemon-pty-event-subscriptions.ts:110` — retirement sets the same flag true
- `src/main/daemon/daemon-pty-event-subscriptions.ts:53,159,171` — `dispose()` / `disconnectOnly()` also set it true as a permanent close

## Required outcome
On a refused retirement, restore the prior `respawnAdoptionClosed` value (or gate respawn on a separate retirement-owned flag) so a refusal cannot resurrect respawn on an adapter that `dispose()`/`disconnectOnly()` already closed.

## Suggested approach (optional)
Capture `const wasClosed = this.respawnAdoptionClosed` before line 110 (or keep the retirement fence on `idleRetirementAdmissionClosed` alone) and restore `wasClosed` here.

## Open questions for the human
Is `dispose()` ever followed by `requestIdleRetirement()` on a still-reachable daemon? If not, this is defensive only.

@pullfrog pullfrog 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.

ℹ️ Delta is clean; the two earlier inline observations still stand.

Reviewed changes

Reviewed the range-diff a462cbc → 0fcf427 (the only new commit since the prior review).

  • Type narrowing replaces assertions — daemon-recovery-provider.ts now uses !(error instanceof Error && 'code' in error && error.code === 'ENOENT') (same meaning as the removed cast), daemon-health.test.ts guards the parsed frame with a typeof / 'type' in check instead of as { type?: string }, and daemon-pty-router-test-fixture.ts keeps its single assertion behind a SAFETY:-documented oxlint-disable-next-line.

Verified locally: check-changed-code-quality.mjs now reports 0 findings across the 23 changed files (previously 4 casting findings), and daemon-health, daemon-recovery-provider, and daemon-pty-router specs all pass.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

m4air added 2 commits October 1, 2026 09:36
…der (#16741 T2 P4b)

- DaemonPtyRouter routes idle retirement through DaemonRouterRetirement: it
  fences new spawns, counts spawns already in flight, takes a census of every
  daemon generation and retires them only when all are idle. A lost reply
  keeps the fence; an unanswered census is unverifiable, never empty.
- Each adapter answers requestIdleRetirement through shutdownIfIdle and fences
  its own spawns while retiring.
- A recovery-only adapter/provider (createDaemonRecoveryProvider) reattaches
  and controls existing sessions but admits no new process, never respawns
  the daemon, and never prunes sessions of unknown worktrees.
- listLiveDaemonSessions and requestIdleDaemonRetirement report null /
  'unverifiable' when any generation cannot answer.
- ptySpawnHealth replies add optional coverage and Node runtime fields;
  checkDaemonHealthWithCoverage reads them and treats an absent coverage from
  an older Windows daemon as handshake-only.
- reconcileOnStartup moves to daemon-router-session-reconciliation unchanged.

No caller uses retirement, the census or the recovery provider yet (T6), so
they are inert. Ported by hunk from #16741 (a68b6f3), without the PTY
ownership-transfer input fence (T7) and with a Node-only runtime report.
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p3-t2-p4b branch from 0fcf427 to ededfae Compare October 1, 2026 16:36
@OrcaWin
OrcaWin changed the base branch from OrcaWin/node-rt-p3-t2-p4a to main October 1, 2026 16:36
@OrcaWin OrcaWin closed this Oct 1, 2026
@OrcaWin OrcaWin reopened this Oct 1, 2026
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 9 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f59cdab8-9bb4-49ae-ab8a-9ed94e87969a

📥 Commits

Reviewing files that changed from the base of the PR and between 817af76 and ededfae.

📒 Files selected for processing (23)
  • src/main/daemon/daemon-health-identity.ts
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts
  • src/main/daemon/daemon-idle-shutdown.test.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/daemon-provider-census.test.ts
  • src/main/daemon/daemon-provider-state.ts
  • src/main/daemon/daemon-pty-event-subscriptions.ts
  • src/main/daemon/daemon-pty-process-inspection.ts
  • src/main/daemon/daemon-pty-router-test-fixture.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-pty-runtime-state.ts
  • src/main/daemon/daemon-pty-session-spawn.ts
  • src/main/daemon/daemon-recovery-only-adapter.test.ts
  • src/main/daemon/daemon-recovery-provider-init.ts
  • src/main/daemon/daemon-recovery-provider.test.ts
  • src/main/daemon/daemon-recovery-provider.ts
  • src/main/daemon/daemon-recovery-spawn-admission.ts
  • src/main/daemon/daemon-request-router.ts
  • src/main/daemon/daemon-router-retirement.test.ts
  • src/main/daemon/daemon-router-retirement.ts
  • src/main/daemon/daemon-router-session-reconciliation.ts
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@OrcaWin
OrcaWin merged commit ff212db into main Oct 1, 2026
55 of 77 checks passed
OrcaWin added a commit that referenced this pull request Oct 2, 2026
* Revert "feat(orcad): source-side dormant export of a relay-hosted SSH target (#16741 T6-8) (#24519)"

This reverts commit 783101b.

* Revert "feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) (#24463)"

This reverts commit 38c2d1d.

* Revert "feat(ssh): deploy and pair an empty managed orcad server over SSH (#16741 T6-5) (#24453)"

This reverts commit 8b76683.

* Revert "fix(ssh): orcad GC honors the activation journal; readiness requires proven daemon coverage (#16741 T6 follow-up) (#24451)"

This reverts commit d3f8c50.

* Revert "feat(ssh): remote orcad stop by request file and journaled decommission (#16741 T6-4) (#24449)"

This reverts commit 43d9b43.

* Revert "feat(orcad): supervisable server: stop requests, managed stop receipts and a lifetime that keeps its lock on failed teardown (#16741 T6-3) (#24433)"

This reverts commit b093d3a.

* Revert "feat(ssh): crash-safe orcad activation, rollback and recovery (#16741 T6-2) (#24423)"

This reverts commit 1a9ac0e.

* Revert "feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)"

This reverts commit 99db2bf.

* Revert "feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) (#24418)"

This reverts commit 34a582b.

* Revert "feat(ssh): track connection-manager drains, test probes and provider continuations (#16741 T2 P3+P8a) (#24407)"

This reverts commit d53063d.

* Revert "feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) (#24409)"

This reverts commit ff212db.

* Revert "feat(ssh): add pty.resumeClient and split SSH PTY process listing (#16741 T2 P5+P6) (#24414)"

This reverts commit 92cb717.

* Revert "feat(relay): await owned watcher and agent children on shutdown (#16741 T2 P1) (#24400)"

This reverts commit 6b36e4f.

* Revert "feat(session): retry failed renderer session writes and verify local folder PTYs (#16741 T2 P9) (#24406)"

This reverts commit d23ecef.

* Revert "feat(ssh): remote orcad primitives on the pinned Node runtime (#16741 T6-1) (#24419)"

This reverts commit dd87ae5.

* Revert "fix(runtime): fence runtime-environment subscriptions and status probes by identity (#16741 T5-3) (#24421)"

This reverts commit ece9e4d.

* Revert "feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) (#24422)"

This reverts commit 3fbdaba.

* Revert "feat(ssh): wire SshConnection through the work and transport close ledgers (#16741 T2 P2) (#24401)"

This reverts commit 4e8edc8.

* Revert "feat(profiles): carry markdown frontmatter visibility in project transfers (#16741 T2 P7) (#24405)"

This reverts commit 60c9326.

* Revert "fix(runtime): project the PTY incarnation onto mobile session tabs (#24413)"

This reverts commit 99e0303.

* Revert "feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) (#24402)"

This reverts commit 817af76.

* Revert "feat(ssh): port the SSH connection work ledger and transport close ledger (#16741 T2) (#24210)"

This reverts commit c991893.

* Revert "feat(relay): fence and drain file and git response streams on shutdown (#24185)"

This reverts commit dc08ffe.

* Revert "refactor(runtime-rpc): extract the Node WebSocket lifecycle; opt-in pinned port (#24186)"

This reverts commit a789233.

* Revert "feat(relay): route relay handlers through work admission; producer publication drain (#24181)"

This reverts commit 0b812bd.

* Revert "feat(relay): land the #16741 T1 seam (work drain, publication drain, release gate) (#24156)"

This reverts commit 3aa2d3a.

---------

Co-authored-by: m4air <[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