Skip to content

fix(daemon): report Windows SIGTERM daemon exits as forced - #4659

Merged
thymikee merged 2 commits into
callstack:mainfrom
GaspardIV:fix/windows-graceful-daemon-stop
Nov 22, 2026
Merged

thymikee merged 2 commits into
callstack:mainfrom
GaspardIV:fix/windows-graceful-daemon-stop

Conversation

@GaspardIV

@GaspardIV GaspardIV commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On Windows, process.kill(pid, 'SIGTERM') calls TerminateProcess immediately without running Node signal handlers or writing daemon-shutdown.json, yet stopDaemonProcess reported 'graceful'.

  • packages/daemon-contracts/src/daemon-process.ts: signalExitMode() maps SIGTERM on win32 to 'forced' and preserves previousExitMode if the daemon exits before SIGKILL.
  • src/__tests__/daemon-exit-wait.test.ts and src/__tests__/daemon-registration-owner.test.ts: parameterize linux/win32 signal exit modes and match manual stop expectations on win32 (forced / unknown cleanup confidence).
  • src/commands/schema/cli-help.ts and website/docs/docs/commands.md: qualify the 75 s daemon stop teardown grace as non-Windows and state that Windows force-terminates (mode: "forced", cleanupConfidence: "unknown").

Touched files: 5 (+69 / -14). Rebased onto origin/main (d1ace8139 at c47c1af00); earlier prototype archived at archive/pr-4659-rpc-shutdown (d409073d1). Context: e2e-inc/e2e#1723 (client release in e2e-inc/e2e#1900; Windows graceful shutdown tracked in #4822).

Before / after

Windows 11 session list --json -> daemon stop --json:

  • Base (bfc09800b): "mode": "graceful", "cleanupConfidence": "unknown", "The graceful shutdown report is unavailable..."
  • Head (c47c1af00): "mode": "forced", "cleanupConfidence": "unknown", "The daemon was force-killed before provider lease state could be finalized..."

Validation

Tested at c47c1af00 on Windows 11 (globalSetup skipped due to ps not found in PATH):

  • daemon-exit-wait.test.ts 33/33, cli-help-topics.test.ts 23/23, cli-help.test.ts 29/29, command-doc-coverage.test.ts 6/6.
  • check:quick, check:production-exports, check:bundle-owner-files, check:daemon-wire-compat, layering, di-seams, check-doc-prose, command-docs --check, pnpm build, smoke-daemon-clean.test.ts 3/3.
  • CI/risks: daemon-exit-wait.test.ts mocks process.platform; live win32 exit verified by CLI and smoke-daemon-clean.test.ts.

@thymikee

Copy link
Copy Markdown
Member

I reviewed 6e1b790 and found one change to make before merge. The RPC-first stop route itself looks well owned.

readStopPort and readStopEndpoint in daemon-registration.ts re-implement the daemon.json endpoint parser that already lives in daemon-client-metadata.ts. That covers the token check, the both-ports-absent rule, the 1..65535 port check and the transport/capabilities reads. stopRecordedDaemon then rebuilds a DaemonInfo by hand from the second parse. If a new transport field or a stricter token rule lands only in parseDaemonInfo, the stop route will send daemon_shutdown to an endpoint the rest of the client rejects, or skip one it accepts. The rule to satisfy: one parser turns a daemon.json record into a connectable DaemonInfo. Please keep DaemonStopIdentity carrying only the record that readDaemonRegistration already read, and let daemon-client parse it with the existing parseDaemonInfo. That means exporting a record-taking variant, or moving the parser into daemon-contracts. Then DaemonStopEndpoint, readStopEndpoint and readStopPort can go, which removes about 45 production lines. Would it also work to build the hook in one daemon-client helper shared by stop, cleanup and takeover, so every graceful detached retirement tries the RPC first?

Not blocking, take or leave: DaemonStopEndpoint sits between the JSDoc of DaemonStopIdentity and its type, so that type loses its docs; the remote refusal in leave() still says "Daemon quiesce is not available to remote clients" although it now serves daemon_shutdown too; a timeout result maps to unavailable and goes straight to SIGTERM, so a daemon that admitted the shutdown but answered after 2 s can be killed mid-drain on Windows, and waiting the term budget for exit first (as for accepted) would close that; and the graceful takeover path and the startup retire call stopAndRetireDaemon without the hook, so a graceful Windows takeover of a daemon advertising shutdown still uses TerminateProcess and now reports mode forced.

The only reported check was skipped, so nothing yet attributes a pass or failure to this head. The full CI, including the Linux/macOS suites, check:affected, wire-compat and layering, has not run here, and the diff touches the daemon stop and lifecycle route that the integration smoke tests exercise. The TerminateProcess behavior and the WebDriver-mock before/after table rest on your report. The win32 branches are covered only by a process.platform mock. Also, e2e-inc/e2e#1723 is in another repository, and #1723 here is an unrelated PR. Before merge, please fold the duplicate parser into parseDaemonInfo, then a maintainer needs to approve the fork CI run so the full suites and the wire-compat and layering gates run on the new head.

@GaspardIV

Copy link
Copy Markdown
Contributor Author

Thanks @thymikee for the review — addressed the blocking issue and the follow-ups in b04b6bb31:

  1. Deduplicated daemon.json endpoint parsing (blocking)

    • Removed DaemonStopEndpoint, readStopPort, and readStopEndpoint from packages/daemon-contracts/src/daemon-registration.ts (readDaemonStopIdentity now attaches only the raw record already read by readDaemonRegistration, restoring the JSDoc placement on DaemonStopIdentity).
    • Exported parseDaemonInfo in packages/daemon-client/src/daemon-client-metadata.ts and switched stopRecordedDaemon (packages/daemon-client/src/daemon-client-stop.ts) to parse record.record through parseDaemonInfo directly instead of reconstructing DaemonInfo by hand.
    • Updated packages/daemon-contracts/src/daemon-registration.test.ts to assert raw record handling.
  2. Shared graceful-shutdown hook for stop, cleanup, and takeover (and why host is optional)

    • Widened createGracefulDaemonShutdown(info, target, { mode, timeoutMs }) in packages/daemon-client/src/daemon-client-lifecycle-request.ts to accept DaemonInfo | null | undefined and mode?: 'graceful' | 'force', making it the single hook builder shared by stopRecordedDaemon, cleanupDaemonAfterRequest, and stopDaemonForTakeover.
    • Wired stopDaemonForTakeover and retireDaemonForTakeover (packages/daemon-client/src/daemon-client-startup.ts) to accept an optional host?: HostEnvironment parameter, passed explicitly from readReusableLocalDaemon (settings.host) so 'graceful' takeover sends daemon_shutdown RPC first when host is present.
    • Why host is optional rather than switching target to required { paths, host } everywhere:
      1. Layering (R86 process-globals): daemon-client-startup.ts is an internal client module rather than a declared process entry, so calling captureHostEnvironment(process) there is rejected by scripts/layering/check.ts — the caller must supply host.
      2. replaceUnreachable in daemon-client-ensure.ts: replaceUnreachable only runs after observeLocalDaemon(..., { refineUnreachable: true }) has retried 'auto' across all advertised transports and found the daemon unresponsive (replaceIncompatible -> daemon_quiesce handles daemons reachable on an alternate transport). Keeping host optional avoids altering daemon-client-ensure.ts ('force' callers and replaceUnreachable, where sending daemon_shutdown + waiting on timeout to a TCP-hung unresponsive process would add 2 s + 3 s delay) and keeps existing non-RPC takeover test callers intact.
    • Added unit coverage in packages/daemon-client/src/__tests__/daemon-client-stop.test.ts verifying stopDaemonForTakeover sends daemon_shutdown RPC in 'graceful' mode (no signals) and skips it in 'force' mode.
  3. Timeout -> exit wait & remote refusal wording

    • createGracefulDaemonShutdown now returns 'accepted' on result.kind === 'timeout' so slow daemons draining past the 2 s RPC timeout still get the termTimeoutMs exit wait instead of immediate Win32 SIGTERM / TerminateProcess (added an HTTP slow-drain timeout test in daemon-client-stop.test.ts).
    • Updated the publicNetworkOnly error in packages/daemon/src/sessions/server/daemon-idle-reap.ts to report Daemon ${options.requireIdle ? 'quiesce' : 'shutdown'} is not available to remote clients. and added explicit message assertions for both in packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts.
  4. PR cross-reference & Windows checks on b04b6bb31

    • Updated the PR summary to use the full link https://github.com/e2e-inc/e2e/issues/1723 so it isn't confused with callstack/agent-device#1723.
    • Re-ran oxfmt --check, pnpm build, pnpm check:quick, scripts/layering/check.ts, scripts/di-seams/check.ts, pnpm check:production-exports, scripts/wire-compat/run.ts, smoke-daemon-http.test.ts + smoke-daemon-clean.test.ts (4/4), and 16 focused daemon/contracts/client/CLI/host Vitest files (178/178 passed on Windows 11).

Could a maintainer approve the fork CI run for b04b6bb31 so the full Linux/macOS suites, check:affected, and remaining gates run?

@thymikee

Copy link
Copy Markdown
Member

This PR is ready at b04b6bb. The findings from the earlier review (6e1b790, #4659 (comment)) are fixed, and I found nothing new that needs a change.

Not blocking, and you can take or leave these: readReusableLocalDaemon passes settings.host for every non-reuse decision, including an unreachable daemon, so a TCP-hung daemon waits out the 2s RPC timeout and the 3s term window before SIGKILL (https://github.com/callstack/agent-device/blob/b04b6bb/packages/daemon-client/src/daemon-client-startup.ts#L146); passing host only when decision.cause is not unreachable would match the rule in your stopDaemonForTakeover comment. The new mode option and its force guard duplicate stopDaemonProcess, which never calls the hook in force mode (https://github.com/callstack/agent-device/blob/b04b6bb/packages/daemon-client/src/daemon-client-lifecycle-request.ts#L127), so the force half of the takeover test passes without the guard. The takeover test calls stopDaemonForTakeover directly, so deleting settings.host in the startup path keeps every test green (https://github.com/callstack/agent-device/blob/b04b6bb/packages/daemon-client/src/__tests__/daemon-client-stop.test.ts#L478); driving it through readReusableLocalDaemon with an incompatible-version mock daemon would close that gap.

No checks have reported on b04b6bb yet because fork CI is waiting for maintainer approval. The new tests, wire-compat and layering gates have not run yet, and the Windows results rest on your report. A maintainer needs to approve the CI run so the full suites, wire-compat and layering gates can run before merge. There are no conflicts.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 18, 2026
@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 18, 2026
@thymikee

Copy link
Copy Markdown
Member

Thanks for approving the CI run. The full suite has now run at b04b6bb, and one gate fails on this PR's own code, so I removed the ready-for-human label until it is fixed. The Fallow complexity audit in Repo Guards & Compatibility (job) flags two functions over the threshold:

Please reduce both below the threshold rather than adding a baseline entry. The force-mode guard that duplicates stopDaemonProcess (from the earlier non-blocking note) is a natural first cut in the lifecycle hook. Splitting the RPC attempt from the signal fallback in stopDaemonGracefully should handle the second. Everything else from the review still stands. Once the gate is green at the new head, I'll take another look.

@GaspardIV

GaspardIV commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

[Gemini 4 Hydrogen] responding on behalf of @GaspardIV

Thanks @thymikee! Fixed both Fallow complexity findings in 876b1bf0d without adding any baseline entries, and folded in the remaining non-blocking notes from earlier:

  1. Lowered complexity below Fallow thresholds

    • createGracefulDaemonShutdown (packages/daemon-client/src/daemon-client-lifecycle-request.ts): removed the redundant mode option (gated with host && mode === 'graceful' in stopDaemonForTakeover instead), hoisted timeoutMs, and extracted fenceDaemonInfo and requestDaemonShutdownAttempt from the startup retry loop (inner closure now cyclomatic 4 / cognitive 5; helper 10 / 10).
    • stopDaemonGracefully (packages/daemon-contracts/src/daemon-process.ts): extracted tryGracefulShutdownRpc ahead of the SIGTERM signal fallback (stopDaemonGracefully now cyclomatic 4 / cognitive 4; helper 7 / 8).
  2. Takeover follow-ups

    • readReusableLocalDaemon (packages/daemon-client/src/daemon-client-startup.ts): omits settings.host when decision.cause === 'unreachable' so unreachable daemons skip the extra RPC/term grace wait.
    • packages/daemon-client/src/__tests__/daemon-client-stop.test.ts: added readReusableLocalDaemon retires an incompatible-version daemon over RPC without signalling covering an incompatible-version (0.0.0) mock daemon through readReusableLocalDaemon.
  3. Verified locally on Windows 11 at 876b1bf0d

    • fallow audit --base 655ede2796: dead code 0 · complexity 0 · duplication 0 across all 18 PR files (also 0 across recent commits).
    • oxfmt --check on touched files, pnpm lint, pnpm typecheck, pnpm build, scripts/layering/check.ts, scripts/di-seams/check.ts, pnpm check:production-exports, pnpm check:daemon-wire-compat, pnpm check:native-dupes: passed.
    • smoke-daemon-http.test.ts + smoke-daemon-clean.test.ts (4/4 passed) and 8 focused daemon/client/contracts Vitest files (107/107 passed, including daemon-client-stop.test.ts 19/19).

@thymikee

Copy link
Copy Markdown
Member

Thanks for the rework. 876b1bf fixes the two functions that failed the Fallow complexity audit at b04b6bb, and no baseline entry or exemption was added. Daemon shutdown is part of the trust boundary we review most strictly, so this head also got a separate security cross-check. It found four problems that need fixing before merge:

  1. The shutdown RPC sends the daemon's token to whatever is listening on the recorded port, and trusts its reply (daemon-client-lifecycle-request.ts:159). The pid, start-time and command check proves the daemon process is alive. It does not prove that the process still owns the recorded listener. If another local process takes that port while the daemon is still alive, for example after the daemon closes its listener but before teardown finishes, that process receives the daemon's bearer token and identity fence. Its reply can suppress the identity-checked SIGTERM, and a false "draining" answer can skip straight to SIGKILL after the grace period. Before sending credentials or acting on any lifecycle reply, authenticate the listener as that daemon instance. Use an OS-authenticated local control channel, or an exchange that binds the peer to the recorded daemon. Keep the independent process-exit check.
  2. A lost acknowledgment can kill a daemon that accepted the shutdown (:82). The server closes admission and schedules teardown before the reply is known to have arrived. The client treats a connection reset as "gone", and a truncated or unreadable reply as "unavailable", then sends SIGTERM immediately. A second stop can also find the listener closed while the first drain is still running. On Windows that SIGTERM is TerminateProcess, before lease, claim or report finalization. Once the request was sent, treat resets and incomplete replies as possible acceptance and wait the term budget before escalating. Fall back immediately only when the client can rule out an active drain.
  3. An HTTP auth hook blocks a host-operator shutdown (daemon-idle-reap.ts:235). An HTTP-only detached daemon advertises shutdown even when an auth hook is configured. The host CLI then sends the shutdown through the same tenant RPC endpoint that remote clients use. The hook can reject it, and a hook-admitted request is stamped publicNetworkOnly, so lifecycle admission refuses it anyway. The client then falls back to a signal, which on Windows is a forced stop. Route host shutdown through a local control surface that tenant RPC and the relay cannot reach. Add a test that stops an HTTP-only daemon with an auth hook, next to the remote-refusal test.
  4. A malformed HTTP error reply can escape typed handling (daemon-client-rpc.ts:38). The transport clears the timer when the body arrives, then converts the error without awaiting or catching it. A listener that sends invalid nested error fields can make that conversion throw, which leaves the request unsettled and can crash the CLI with an unhandled rejection. Validate the envelope and its field types, keep the deadline running until settlement, and route every parse failure through the same post-dispatch rules as item 2. The decoder predates this PR, but the new stop path now exposes it to whatever answers on the port.

Not blocking: the mode === 'graceful' guard in daemon-client-startup.ts repeats a rule that stopDaemonProcess already owns, and no test reaches the unreachable cause there.

No checks have run on this fork head yet, so a maintainer still needs to approve CI. Items 1 and 3 point toward the same design: a local control channel bound to the daemon instance, instead of the tenant RPC port. That channel would fix both, and probably make the RPC-first stop simpler.

@GaspardIV

Copy link
Copy Markdown
Contributor Author

Thank you so much for the thorough security cross-check @thymikee! Every single one of those 4 points hit a real bug, and I reproduced each of them live against 876b1bf before fixing them in 5490b79bc.

Live reproductions before the fix (876b1bf) & additional gaps uncovered

  1. Rogue listener / bearer token exposure + spoofed draining (Item 1): Confirmed with a live listener bound to the recorded port that it received the plaintext token from daemon.json in the Authorization header on the very first RPC request, and could spoof { outcome: 'draining' } (or daemon-owner-embedded to suppress signalling altogether). Also confirmed the race window in daemon-runtime.ts where tenant servers closed in closeSteps while daemon.json stayed on disk throughout lease/plugin teardown.
  2. Mid-drain kill on dropped/truncated ACK and second stop (Item 2): Confirmed live that an injected ECONNRESET / truncated HTTP reply after dispatch returned 'unavailable', causing stopDaemonProcess to escalate immediately to SIGTERM/TerminateProcess. Also confirmed that a second concurrent stop hitting ECONNREFUSED after the tenant listener closed (while daemon.json and the drain were still active) fell back to immediate forceful termination.
  3. AGENT_DEVICE_HTTP_AUTH_HOOK blocking local stop in HTTP-only mode (Item 3): Confirmed live via CLI E2E with an HTTP-only daemon and an auth hook returning 401: /rpc rejected daemon_shutdown, forcing stop down to an immediate signal.
  4. Malformed HTTP error envelope hang / unhandled rejection (Item 4): Confirmed live that returning {"error":{"code":-32000,"message":"boom","data":{"diagnosticsRecord":123}}} cleared the transport timer before async error decoding, left the RPC promise permanently unsettled, and triggered an UnhandledPromiseRejection in Node.

While auditing around these fixes, I also found and fixed three related gaps:

  • judgeGoneShutdown false positive when daemon.lock is absent: classifyDaemonLockOwnership can return 'unchanged' both when the same daemon still owns daemon.lock and when daemon.lock was missing cleanly; judgeGoneShutdown now requires ownership.state === 'absent' && readDaemonShutdownReport(...) !== null before concluding retirement completed cleanly.
  • quiesce timeout asymmetry on controlPort: When quiesce timed out before completing the challenge or reply on the control channel, it needed explicit rejection as AppError('COMMAND_FAILED', ..., { reason: 'daemon_transport_timeout' }) instead of being conflated with shutdown drain acceptance.
  • Result envelope ok boolean validation: parseDaemonHttpResponseBody in daemon-client-rpc.ts now also validates typeof parsed.result.ok === 'boolean' alongside structured error/data checks so malformed { result: {} } payloads reject cleanly as daemon_response_invalid.

Summary of changes in 5490b79bc

  • Authenticated local control protocol (packages/daemon-contracts/src/daemon-control.ts, daemon-control.test.ts):

    • Added a 2-step HMAC-SHA256 challenge-response protocol (challenge -> challenge_response -> command -> command_response, version 1) with domain-separated digests bound to (pid, processStartTime, clientNonce, serverNonce, requestId).
    • Client proves daemon identity from the server's signed challenge before transmitting any lifecycle command, and never sends the HTTP RPC bearer token.
  • Dedicated daemon control listener & teardown ordering (packages/daemon/src/server/http/control-server.ts, server-startup.ts, daemon-runtime.ts, daemon-registration-owner.ts, daemon-client-metadata.ts):

    • Opens a separate loopback control TCP listener in all server modes (socket, http, dual), persisted as controlPort in 0o600 daemon.json and read by readReusableLocalDaemon.
    • Tenant HTTP/socket servers close at the start of closeSteps, while controlServer stays bound through lease/session teardown and finishDaemonRegistration(), closing only in finally afterwards—eliminating both the port-rebind window and mid-drain ECONNREFUSED for concurrent stop callers.
  • Tenant RPC rejection & auth-hook isolation (packages/daemon/src/sessions/server/daemon-idle-reap.ts, daemon-resolution.ts):

    • Added control(command, fence) on DaemonLifecycleAdmission for authenticated local control commands (quiesce, shutdown), including fail-closed instance fencing when processStartTime is missing or mismatched.
    • Tenant /rpc and socket admit now refuse daemon_shutdown unconditionally with UNAUTHORIZED. Local daemon stop no longer routes through AGENT_DEVICE_HTTP_AUTH_HOOK or tenant endpoints.
  • Client lifecycle transport & takeover cleanup (packages/daemon-client/src/daemon-client-lifecycle-request.ts, daemon-client-stop.ts, daemon-client-startup.ts):

    • Routes both shutdown and quiesce over the authenticated controlPort.
    • Treats post-dispatch socket reset, truncated reply, or timeout on shutdown as 'accepted' so stopDaemonProcess waits termTimeoutMs for graceful drain rather than firing immediate SIGTERM/TerminateProcess.
    • Requires ownership.state === 'absent' plus a valid shutdown report in judgeGoneShutdown, and throws daemon_transport_timeout on quiesce timeouts.
    • Removed the redundant mode === 'graceful' guard when passing gracefulShutdown in stopDaemonForTakeover (daemon-client-startup.ts).
  • HTTP RPC response & deadline hardening (packages/daemon-client/src/daemon-client-transport.ts, daemon-client-rpc.ts, test/wire-compat/ledger.json):

    • Keeps deadline.handle armed until resolveOnce / rejectOnce settles, covering async remote error localization and artifact materialization.
    • Validates envelope shape, nested error/error.data field types, and typeof parsed.result.ok === 'boolean' in parseDaemonHttpResponseBody, attaching .catch(...) to async settlement helpers so malformed payloads reject deterministically instead of causing unhandled rejections.
    • Updated handleDaemonHttpResponseBody digest and compatibleChanges entries in test/wire-compat/ledger.json.
  • Tests added & updated:

    • Unit tests covering protocol challenge/command verification, rogue-listener rejection, mid-drain concurrent stop + post-dispatch reset/truncation/timeout, judgeGoneShutdown absent-lock behavior, quiesce timeouts, readReusableLocalDaemon 'unreachable' path, malformed HTTP error/result envelopes, and tenant /rpc daemon_shutdown refusal.
    • Live CLI E2E test in test/integration/smoke-daemon-http.test.ts verifying an HTTP-only daemon with AGENT_DEVICE_HTTP_AUTH_HOOK rejects /rpc shutdown with 401 while agent-device daemon stop completes gracefully with known cleanup confidence.

Notes outside the scope of this PR

  • Other host-admin HTTP routes (/admin/leases, /admin/human-control): shutdown and quiesce now go exclusively through the authenticated controlPort, whereas those separate host-admin HTTP routes in http-server.ts still run on the HTTP port using the daemon.json bearer token. Not affected by this fix, just worth noting if we ever want to consolidate all local host-admin operations onto controlServer in a follow-up.
  • Pre-existing Windows local test quirks: When running unit-core locally on Windows, 5 files in test/repo-guards/ (android-sdk-setup-action.test.ts, capability-matrix.test.ts, client-api-examples-drift.test.ts, macos-helper-package-contents.test.ts, snapshot-producer-emitters.test.ts) and the 2 AST closure checks in test/wire-compat/wire-compat.test.ts fail due to pre-existing CRLF (\r\n), npm vs npm.cmd, and \ path-separator assumptions (all 8 touched unit test files passed 85/85, smoke-daemon-http.test.ts passed 2/2, and all static/layering/wire-compat ledger checks passed).

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. The earlier findings from 876b1bf are fixed at 5490b79, but one new problem remains in the HTTP deadline change, and a separate security cross-check found two more in the control route (below).

sendHttpRequest no longer clears the request deadline when the response body arrives. It now clears it only when resolveOnce or rejectOnce runs. For a remote daemon, resolveDaemonHttpResult calls resolveOnce only after materializeRemoteArtifacts finishes (daemon-client-transport.ts:273-276). That step downloads every response artifact, each with its own 90 s bound. The envelope leaves only about 30 s of margin after the daemon budget, minus the health probe and upload time. So a remote screenshot, recording or record stop can now reject with daemon_transport_timeout even though the command ran and the download was still within its own budget. The CLI reports a timeout, the artifact is lost, and the download keeps running unobserved. This worked before this change, and remote devices are the main use of the product.

The rule the code must satisfy: the request deadline bounds the daemon answer and the error conversion, and it does not bound artifact materialization of an answered request. The smallest fix is to clear the deadline before materializeRemoteArtifacts on the ok path, for example with a clearDeadline callback passed to handleDaemonHttpResponseBody. Keep it armed for rejectDaemonHttpRpcError, which needs it to bound remote error localization (boundary-fault-transport.test.ts:291). Please add a test where a slow artifact download on an answered request settles successfully past the original deadline. Our earlier review asked to keep the deadline until settlement, so this narrows that request.

Security cross-check, item 2: the control listener accepts the tenant bearer. The control listener authenticates with the same bearer that direct HTTP tenants present after the auth hook attests their tenant ID (daemon-runtime.ts:675, http-server.ts:579-608). A tenant with that bearer and loopback access, for example a client under another OS account on the daemon host, can stop a detached daemon that still has active sessions or leases. Host control needs its own authority: a separate per-instance control secret stored owner-only, or OS peer credentials on an owner-restricted local socket. Please add a test that a hook-attested tenant with the HTTP bearer cannot stop the daemon, while the host still can stop an HTTP-only daemon.

Security cross-check, item 3: a managed takeover can force an active drain. After an accepted shutdown, closeSteps closes the socket and HTTP listeners before request, session and provider cleanup (daemon-runtime.ts:751-764), while the control listener still reports draining. A same-version managed command arriving in that window sees the data transport as unreachable and passes no host at daemon-client-startup.ts:150, so retirement skips the control RPC and can escalate to a signal before the term budget. Please ask the control listener before graceful retirement on every takeover path, wait the term budget when it reports draining or its state is uncertain, and keep the identity check before escalation. Add a test where a managed command arrives after the data listeners close and before the drain finishes.

Not blocking, and fine to take or leave: daemon-control.ts:10 re-exports two constants from daemon-resolution.ts while daemon-idle-reap.ts imports one from each, so import both from one place; leave() in daemon-idle-reap.ts:275 is only called with requireIdle: true, so its shutdown message arm cannot run; and the CLI smoke test at smoke-daemon-http.test.ts:176 also passes when daemon stop falls back to SIGTERM on Linux and macOS, so asserting something only the control route produces (such as the daemon log showing the lifecycle drain with no signal-initiated close) would make it prove the route.

No checks have been reported on 5490b79 yet, so a maintainer needs to approve the fork workflow runs. The diff touches daemon lifecycle, daemon-client transport and wire-compat ledger routes, which unit-core, integration smoke and wire-compat exercise. Once the deadline fix and its test are in and CI is green, this is ready for another look.

@GaspardIV

Copy link
Copy Markdown
Contributor Author

Thank you for the follow-up review and cross-check @thymikee! I have addressed all three blocking items, the three non-blocking notes, and a source-guard regression caught when running the broader daemon suites locally in d409073d1:

Changes in d409073d1

  1. HTTP request deadline vs. remote artifact materialization (packages/daemon-client/src/daemon-client-rpc.ts, daemon-client-transport.ts, test/wire-compat/ledger.json):

    • Passed clearDeadline from sendHttpRequest to handleDaemonHttpResponseBody and invoked it on the parsed.result branch right after validating isRecord(parsed.result) and typeof parsed.result.ok === 'boolean', before calling resolveDaemonHttpResult / materializeRemoteArtifacts.
    • rejectDaemonHttpRpcError keeps the request deadline armed until error decoding and remote error localization settle (so boundary-fault-transport.test.ts still bounds stalled localization).
    • Updated the handleDaemonHttpResponseBody digest and rationale in test/wire-compat/ledger.json.
    • Added a test in packages/daemon-client/src/__tests__/boundary-fault-transport.test.ts verifying that a slow remote artifact download (220 ms) completes past an 80 ms RPC deadline once the response body has arrived.
  2. Dedicated per-instance controlSecret isolated from HTTP bearer token (packages/daemon/src/server/http/daemon-runtime.ts, control-server.ts, packages/daemon-contracts/src/daemon-registration-owner.ts, packages/daemon-client/src/daemon-client-metadata.ts, daemon-client-lifecycle-request.ts):

    • daemon-runtime.ts now generates an independent controlSecret, writes it only into 0o600 daemon.json, and passes it exclusively to createDaemonControlServer({ secret: controlSecret, ... }) (never to http-server.ts, auth hooks, or the proxy).
    • control-server.ts fails closed on an empty secret, and client helpers (createGracefulDaemonShutdown, requestDaemonLifecycle, sendAuthenticatedControlCommand) require info.controlSecret with no fallback to info.token.
    • Added unit and E2E tests covering this boundary:
      • packages/daemon/src/server/http/control-server.test.ts: empty secret fails closed.
      • packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts: control rejects attempts signed with the HTTP token (both challenge verification and direct server command verification with skipChallengeVerify: true).
      • packages/daemon-client/src/__tests__/daemon-client-lifecycle-request-control.test.ts: createGracefulDaemonShutdown returns undefined when controlSecret is missing even if token is set.
      • test/integration/smoke-daemon-http.test.ts: an HTTP-only daemon with AGENT_DEVICE_HTTP_AUTH_HOOK admits session_list for an authenticated tenant, refuses /rpc daemon_shutdown with 401, rejects direct controlPort shutdown attempts forged with the tenant's info.token HTTP bearer, and is still cleanly stopped by host agent-device daemon stop.
  3. Ask the control listener before graceful retirement on every managed takeover path (packages/daemon-client/src/daemon-client-startup.ts, daemon-client-lifecycle-request.ts, daemon-client-stop.test.ts):

    • Removed the decision.cause === 'unreachable' ? undefined : settings.host suppression in readReusableLocalDaemon and updated stopDaemonForTakeover in graceful mode to always build createGracefulDaemonShutdown, so even a same-version takeover arriving after data listeners close still queries controlPort first, waits termTimeoutMs when draining or uncertain, and preserves process-identity verification before any signal escalation.
    • Replaced the old skip test in packages/daemon-client/src/__tests__/daemon-client-stop.test.ts with tests covering both a mid-drain readReusableLocalDaemon (closed data port + live draining control port -> waits cleanly without signalling) and unreachable data+control ports while daemon.json remains active (-> escalates with identity check). Also factored the mock drain helper in daemon-client-stop.test.ts so the file stays within oxlint's 1000-line limit.
  4. Additional source-guard fix & non-blocking notes:

    • Updated the source-order assertion in packages/daemon/src/server/http/daemon-runtime-metadata-ownership.test.ts to match publishDaemonInfo(socketPort, httpPort, controlPort);.
    • Consolidated DAEMON_QUIESCE_COMMAND / DAEMON_SHUTDOWN_COMMAND imports in packages/daemon/src/sessions/server/daemon-idle-reap.ts from @agent-device/daemon-contracts/daemon-resolution and simplified leave() by removing its unreachable shutdown message arm.
    • Recorded daemon_control_shutdown_accepted in daemon.log when control accepts a shutdown (daemon-runtime.ts) and asserted both daemon_control_shutdown_accepted and daemon_shutdown_provider_release_drain in test/integration/smoke-daemon-http.test.ts so the smoke test proves the control route rather than a POSIX SIGTERM fallback.

Local verification on d409073d1 (Windows)

  • Static & build guards: oxfmt --check, scripts/layering/check.ts, pnpm lint (0 errors/warnings across 5222 files), pnpm typecheck, pnpm build, scripts/check-bundle-owner-files.ts, scripts/wire-compat/run.ts, scripts/di-seams/check.ts, pnpm check:production-exports, and fallow audit --base 655ede2796 --quiet all passed.
  • Unit tests (vitest run --project unit-core --maxWorkers=1 --testTimeout=30000 across the 36 daemon/daemon-client/daemon-contracts/cli-daemon/host test files): 36/36 files, 332/332 assertions passed (2 unrelated untouched startup-budget/ensuring tests tripped the 5s slow-test gate due to Windows process-spawn overhead when run together).
  • Wire-compat ledger/digest checks (test/wire-compat/wire-compat.test.ts -t "the ledger|every wire declaration|every compatible-change"): 4 passed, 2 skipped.
  • Live CLI E2E (node --experimental-strip-types --test test/integration/smoke-daemon-http.test.ts test/integration/smoke-daemon-clean.test.ts): 5/5 passed.

Ready for CI workflow approval and another look!

@thymikee

Copy link
Copy Markdown
Member

The follow-up at d409073 separates the shutdown proof key from the HTTP bearer, but the findings below remain. CI is pending: zero checks are reported at this commit, and historical failures do not establish the current gate state. There are no conflicts. Before merge, close both tenant shutdown routes, honor the full drain wait during takeover, verify Windows provider release, and run the required checks at the new head.

On Windows, a custom state directory with inherited read access can expose the control secret to another local account, which can then shut down the host even with active sessions or leases. The staging file inherits directory permissions, and file modes cannot restrict Windows readers. Require owner-only access before the registration owner first writes the key, using an ACL-protected credential location or authenticated peer transport, and fail closed if that access cannot be established. Registration owner, Node.js file modes.

An attested HTTP tenant with loopback access, the bearer and daemon fence can still drain an idle dual-mode daemon through legacy quiesce on the data port. Route both lifecycle operations exclusively through host control when the daemon publishes it, and retain client quiesce fallback only for older daemons without control. Idle reap.

A managed contender can send SIGKILL after the three-second signal budget while a control drain is still within its five-second request cancellation period, before provider release or report publication. Private replay cleanup shares this default, and takeover can truncate an explicit stop. Give accepted or uncertain control drains a lifecycle-owned grace budget shared by takeover and cleanup through the existing bounded drain wait; reserve the signal budget for signal fallback. Startup.

Could a connected control probe that times out before authentication remain an uncertain outcome and receive the identity-fenced drain wait? With data listeners closed, the current two-second timeout can classify a draining daemon as unavailable and cause immediate SIGTERM on Windows. A definite connection refusal can remain eligible for signal fallback. Lifecycle request.

A separate cross-check of this head also found that a checked JSON-RPC error keeps the RPC deadline armed while the client fetches diagnostics and, for a failed batch, settles script artifacts from completed steps (daemon-client-rpc.ts:39). If the timer expires during either step, the caller gets daemon_transport_timeout instead of the daemon's real error. Please disarm the deadline after envelope validation for error responses too, the same as for success, keep typed rejection for invalid envelopes, and let delivery use its own bounds. Add a test that a slow diagnostics fetch on an error response still returns the original error.

The HTTP smoke hook rejects shutdown before lifecycle admission, so the test would still pass if the runtime data-plane shutdown refusal were removed. Have the hook attest shutdown too, assert lifecycle admission returns UNAUTHORIZED, and prove the daemon remains available. HTTP smoke.

The reported head smoke has no active provider allocation, and the runtime test expects no released provider IDs; the older mock WebDriver run was on b04b6bb. On Windows at the corrected head, close a BrowserStack or equivalent WebDriver app while retaining its device lease, start daemon stop, and issue a managed request after the data port closes while provider release is pending. Record the authenticated control path, provider DELETE and release confirmation, the released lease ID in the shutdown report, original process exit and replacement startup, with no premature signal. Also prove a separate local account with the HTTP bearer cannot read the control credential or invoke either lifecycle operation. Runtime.

Could the registration owner parse one optional owner-protected control endpoint and pass it to quiesce and shutdown, validate the server credential at construction, and use the existing drain wait for both operations including unanswered connected probes? This would first require cross-platform owner-only credentials and an accepted-drain budget owned by the existing lifecycle wait; the old-record quiesce decision would remain in the client.

Not blocking: the unused shutdown host parameter and takeover forwarding can be removed by accepting DaemonPaths; take or leave this cleanup.

The linked Windows report confirms the symptoms but does not establish SIGTERM as the cause. Unit-core, daemon CLI smoke, wire compatibility and repository guards exercise the changed code and need results at the new head.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the Windows comparison. Please open an agent-device issue with the exact-main Windows reproduction and link the e2e report. For the BrowserStack failure, please try awaiting the final release of the e2e-owned lease before daemon stop and show the provider DELETE and release result. This PR now changes host control authority and remote HTTP response handling, so please split out the Windows stop-mode reporting correction. If graceful stop with active leases is still needed for independently managed Windows daemons, bring that case to the issue so we can agree on the smallest owner-only close path and its drain budget before another implementation.

@thymikee

Copy link
Copy Markdown
Member

This branch now conflicts with main after recent merges. Please rebase onto main; the earlier review points still apply, and the next review will cover the rebased head.

@GaspardIV
GaspardIV force-pushed the fix/windows-graceful-daemon-stop branch from d409073 to 3e4fe63 Compare November 20, 2026 15:22
@GaspardIV GaspardIV changed the title fix(daemon): shut down detached daemons via RPC before OS signals fix(daemon): report Windows SIGTERM daemon exits as forced Nov 20, 2026
@GaspardIV

GaspardIV commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @thymikee — split this PR onto origin/main (bfc09800b) at 3e4fe6367 so it covers only the Windows stop-mode reporting fix (3 files, +67 / -13).

  • What was reverted / intentionally deferred: I removed the RPC shutdown, isolated control channel, and HTTP error/artifact deadline changes from this PR (preserved in archive/pr-4659-rpc-shutdown at d409073d1), as the scope grew too large and changed host control authority and remote HTTP response handling. Because of that, Windows still does not perform a true graceful shutdown on SIGTERM (TerminateProcess still exits immediately without running runtime.close(), provider teardown, or writing daemon-shutdown.json). The owner-only local control path for graceful shutdown on Windows (and the ACL/auth-hook/drain-budget requirements from the earlier review) is tracked in Support graceful daemon shutdown on Windows (owner-only local control path) #4822.
  • What changed at 3e4fe6367: signalExitMode() in packages/daemon-contracts/src/daemon-process.ts maps SIGTERM on win32 to 'forced' and preserves previousExitMode if the daemon exits after the SIGTERM wait before SIGKILL (ESRCH). daemon-exit-wait.test.ts covers both linux and win32, and daemon-registration-owner.test.ts aligns manual stop expectations on win32 (mode: 'forced', cleanupConfidence: 'unknown').
  • Exact origin/main (bfc09800b) vs 3e4fe6367 on Windows 11:
    • Live CLI (session list --json -> daemon stop --json): bfc09800b returned "mode": "graceful", "cleanupConfidence": "unknown", and "The graceful shutdown report is unavailable..."; 3e4fe6367 returns "mode": "forced", "cleanupConfidence": "unknown", and "The daemon was force-killed before provider lease state could be finalized...".
    • src/__tests__/daemon-registration-owner.test.ts (run with globalSetup bypassed due to the origin/main Windows ps not found in PATH blocker): manual forced stop failed on bfc09800b (Expected: "forced", Received: "graceful") and passes on 3e4fe6367 (41/46, with only the 5 pre-existing POSIX chmod/private-startup failures remaining).
    • Also verified check:quick, check:fallow, check:production-exports, check:bundle-owner-files, check:daemon-wire-compat, scripts/layering/check.ts, scripts/di-seams/check.ts, pnpm build, smoke-daemon-clean.test.ts (3/3), and the focused daemon unit tests (daemon-exit-wait, daemon-stop, daemon-process, daemon-process-takeover, daemon-client-stop, host).

@thymikee

Copy link
Copy Markdown
Member

Thanks for the fix. At 3e4fe63 the code change looks right, but the docs now promise something Windows cannot do.

The versioned help at cli-help.ts:422 says daemon stop lets the daemon run its own teardown for up to 75 seconds before forcing exit. commands.md:97 says the same. On Windows, the first delivered SIGTERM terminates a verified detached daemon at once, and the result reports mode forced with cleanup confidence unknown. Windows operators and agents may rely on a teardown window that does not exist, including for provider lease cleanup. Please qualify the 75-second window as non-Windows in both places, and state that on Windows the stop signal force-terminates the daemon and cleanup confidence is unknown.

CI shows 1 check, passing, at this commit. The fork's full Linux and macOS suites need maintainer approval and have not run yet. The daemon-exit-wait, daemon-registration-owner and daemon-process-takeover unit suites overlap this change, so they matter once they run. There is no Windows lane in CI, so the win32 expectation in daemon-registration-owner.test.ts only runs on a Windows host. The live Windows 11 run was not reproduced here, so the win32 branch rests on the platform-mocked unit tests and the author-reported run. The earlier points about the control-secret ACL, tenant shutdown routes and drain wait no longer apply, because this head removed that code.

Before merge, the fork CI needs approval and the full daemon suites need to pass at 3e4fe63. The docs fix above needs no other code change.

@GaspardIV

Copy link
Copy Markdown
Contributor Author

Thanks @thymikee — updated both src/commands/schema/cli-help.ts (line 422) and website/docs/docs/commands.md (line 97) in 5380f1bb8 to qualify the 75-second teardown grace as non-Windows and state that on Windows the stop signal force-terminates the daemon (mode: forced, cleanupConfidence: unknown). Re-verified check:quick, oxfmt --check, cli-help-topics.test.ts (23/23), and cli-help.test.ts (29/29).

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. The two fixes from the earlier review are in at 5380f1b: the help string and the docs line now match what the code does on Windows, and the review found nothing else to change. There are no conflicts.

No checks have reported on this head: the workflows for this fork need maintainer approval to run. Once CI reports green here, this is ready.

Not verified here: nothing was run on Windows. That SIGTERM ends the process immediately rests on Node's documented win32 process.kill behavior and the PR's mocked-platform tests, which is enough for the docs and help change. The author's local checks were not re-run.

@thymikee

Copy link
Copy Markdown
Member

This head (5380f1b) now conflicts with main. Please rebase onto main and push; the open evidence item from the earlier review still applies to the rebased head.

@GaspardIV
GaspardIV force-pushed the fix/windows-graceful-daemon-stop branch from 5380f1b to 0252850 Compare November 22, 2026 02:24
@GaspardIV

Copy link
Copy Markdown
Contributor Author

Rebased onto origin/main (d6767e091) at 0252850ed, preserving the #4682 macOS/BSD identity-unverified notes alongside the Windows forced-stop wording in cli-help.ts and commands.md.

Re-verified on Windows 11 (check:quick, check:production-exports, check:bundle-owner-files, check:daemon-wire-compat, layering, di-seams, check-doc-prose, command-docs --check, pnpm build, smoke-daemon-clean.test.ts 3/3, live CLI daemon stop --json, and the focused daemon/help suites including daemon-exit-wait.test.ts 33/33 and daemon-registration-owner.test.ts 42/47). Ready for fork CI approval.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update.

The code at 0252850 looks good, and the conflict from the earlier review (#4659 (comment)) is resolved. No conflicts remain. No code change is needed. The hosted checks that ran are green. The fork's full Linux and macOS suites need maintainer approval and have not run at this commit, so the daemon-exit-wait, daemon-registration-owner and daemon-process-takeover suites that overlap daemon-process.ts have not yet run in hosted CI. Not verified here: anything on Windows, because there is no Windows CI lane and the review only read the code. The win32 branch of daemon-registration-owner.test.ts runs only on a Windows host, daemon-exit-wait.test.ts covers win32 through a mocked process.platform, and the live Windows 11 result is author-reported. Before merge, a maintainer needs to approve the fork CI run, and the full daemon suites need to pass at 0252850.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee

Copy link
Copy Markdown
Member

This head (0252850) now conflicts with main. Please rebase onto main and push; the rebased head gets a delta review.

On Windows, cross-process SIGTERM triggers TerminateProcess immediately without running Node signal handlers or flushing a graceful shutdown report.

Map SIGTERM on win32 to 'forced' in stopDaemonProcess and preserve previousExitMode if the daemon exits before SIGKILL so callers report forced shutdown and unknown cleanup confidence.
@GaspardIV
GaspardIV force-pushed the fix/windows-graceful-daemon-stop branch from 0252850 to c47c1af Compare November 22, 2026 10:51
@GaspardIV

Copy link
Copy Markdown
Contributor Author

Rebased onto origin/main (d1ace8139) at c47c1af00 (keeping the #4919 layout in commands.md with the Windows bullet) and updated the PR body (check:pr-body passed). Re-verified local guards, pnpm build, CLI daemon stop --json, and focused daemon/help suites on Windows 11.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. The Windows SIGTERM exit fix at c47c1af looks right in the code, and the earlier conflict is resolved. Checks are green, but they cover only 2 jobs. Not verified here: the live win32 SIGTERM behavior and the smoke-daemon-clean result were not run on Windows, so they rest on the PR body and the rebase comment. Not verified here: the daemon-exit-wait, daemon-registration-owner and daemon-process-takeover suites at this head, because the fork CI suites need maintainer approval to run. Before merge, a maintainer needs to approve that run.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee
thymikee merged commit 62c8aea into callstack:main Nov 22, 2026
16 of 17 checks passed
thymikee added a commit that referenced this pull request Nov 22, 2026
* origin/main:
  fix(auth): send a stored CLI session only to the cloud that issued it (#4921)
  refactor(reasons): declare the daemon reasons in ReasonTable rows (#4936)
  fix(cli): drop --remote-config from auth and skip reading it for unsupported commands (#4957)
  refactor(snapshot): deduplicate system-surface projections and warnings (#4959)
  fix(find): enforce offscreen and non-hittable guarantees on focus (#4954)
  feat(auth): store a rotated CLI session credential and show the login code (#4833)
  fix(daemon): report Windows SIGTERM daemon exits as forced (#4659)

# Conflicts:
#	packages/capture-kit/src/snapshot-quality-verdict.ts
#	packages/command-runtime/src/commands/interaction/runtime/target-visibility-stages.ts
#	packages/contracts/src/device-inventory.ts
#	packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts
#	packages/daemon/src/execution/interaction/internal/find-target-capture.ts
#	packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts
#	website/docs/docs/error-reasons.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants