Repository navigation
fix(gateway): derive the darwin stop budget from the launchd job - #157007
Conversation
resolveGatewayShutdownBudget derives the stop deadline from restart ownership, so a darwin host running with OPENCLAW_SUPERVISOR_MODE=external resolves drain=315000ms whatever launchd actually enforces. The linux-gated systemd probe becomes a platform dispatch, and a new readLaunchdStopTimeout mirrors readSystemdStopTimeout: it reads the running job's effective exit timeout and accepts it only when the printed pid is this process. run-loop.ts is untouched because the reader detects launchd from the environment itself. Closes openclaw#156968
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 8:19 PM ET / September 29, 2026, 00:19 UTC (Revision 26). ClawSweeper reviewWhat this changesThe branch makes the Gateway size macOS shutdown from its loaded launchd job, shares deadline calculations with its launcher, adds lifecycle coverage and guidance, and completes a frozen tooling import list. Merge readiness✅ Ready for maintainer review Current main still misses the loaded launchd stop deadline. This PR has a distinct fix, real Mac stop evidence, and a recorded acceptance of its short-deadline cleanup tradeoff. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway run loop receives stop and restart requests and allocates time for active work, cleanup, and exit. On macOS, the new reader checks the loaded launchd job before that budget controls shutdown. flowchart LR
A[Stop request] --> B[Gateway run loop]
B --> C[Loaded launchd job]
C --> D[Deadline and launcher cap]
D --> E[Drain and cleanup budget]
E --> F[Gateway exit]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +247, Tests +1487, Docs +72, Other +77. Total +1883 across 17 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep deadline discovery in the Gateway shutdown owner, retain the documented short-job allocation, and land the reviewed head through the normal exact-head gates. Do we have a high-confidence way to reproduce the issue? Yes. Current-main source shows the Darwin gap, and the PR supplies a real scratch LaunchAgent before/after stop trace; this review did not run current main on macOS. Is this the best way to solve the issue? Yes. Reading the loaded job during shutdown addresses the enforcing deadline at the existing budget owner while preserving the direct-signal fallback. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 27de2f87db28. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (25 earlier review cycles; latest 8 shown)
|
The darwin reader accepted the printed job only when its pid was this process. The installed service can keep a launcher parent while the serving Gateway runs as its child, so the job prints the launcher's pid, the enforcing job was rejected, and the Gateway fell back to 20 seconds in the one layout where an operator's ExitTimeOut was meant to apply. Accepting that job at face value would be worse than rejecting it. node-runtime-recovery.mjs builds the launcher's own reap timer from the compile-time LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS rather than from the job, so on a forwarded stop it re-sends SIGTERM to its child at 18000ms and SIGKILLs it at 19000ms. Adopting a 90 second job deadline in that layout would plan a 75000ms drain and then lose it to its own parent, which is the truncated drain this change exists to prevent. The reader now accepts process.pid or process.ppid and takes min(jobExitTimeout, 20000) in the launcher case, naming the cap in the source string only when it binds. A shorter job deadline still applies in both layouts, because launchd reaps the whole job regardless of the launcher. The docs claimed the deadline is read at startup and when accepting shutdown. run-loop.ts gates the budget refresh on linux at both consumption sites, so on darwin it is read once, at startup, and nativeStopBudget has no shutdown-time consumer there. The page now says startup-only and drops the sentence about a failed shutdown reread retaining the startup budget, which described linux behaviour only.
Address the two review findings on the previous revision. The launcher parent is now identified by an explicit OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a bare ppid match, so an unknown parent keeps the job's full deadline instead of being capped on a guess. The darwin reader inspects the launchd job only while a stop is under way, and adopts that job's deadline only when the job reports the SIGTERMed state. An external SIGTERM keeps the platform-neutral drain, because launchd's ExitTimeOut bounds only a stop launchd itself is running. The job state is read with an anchored single-tab pattern. launchctl print emits further "state = active" lines inside the resource and jetsam coalition blocks, and the shared key/value parser keeps the last occurrence, so the shared parser could never observe SIGTERMed. A test fixture reproduces the nested coalition shape.
…dget `readLaunchdStopTimeout` answered a failed job inspection with the Gateway's own 330000ms stop policy wrapped in a non-null result. `resolveGatewayShutdownBudget` classifies every non-null result as a native stop budget, so a probe that established nothing still set `nativeStopBudget`. On an externally supervised darwin Gateway that caps a longer requested restart drain and can arm a forced exit against a deadline no supervisor was confirmed to be enforcing. The reader now reports its two answers separately. `stop` carries a deadline only while launchd is confirmed to be stopping the job; `warning` reaches the operator either way. A failed inspection reports `stop: null` and leaves the caller on the platform-neutral policy it had already resolved, which is the same number as before, now classified honestly. The reader no longer imports GATEWAY_SERVICE_STOP_TIMEOUT_MS, because choosing the Gateway's policy number was never its job. Tests assert the flag and the downstream restart drain in the failure case, paired with a confirmed-deadline case so deleting the read outright cannot pass both. Also fixes TS2532 on the job-state regex: the named group is optional under `noUncheckedIndexedAccess`, so `.trim()` needed the optional chain.
…* count `spawn` is hoisted once per file, so its call log survived across cases and `toHaveBeenCalledExactlyOnceWith` could only hold for the first one. Clear it in `beforeEach`. CI reports `OPENCLAW_* count 488 exceeds budget 487; update config/env-var-count-budget.txt` as a warning. The new name is the launcher's OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration, so the count is correct and the ratchet moves to 488 with the reason recorded in the file.
Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line. `pnpm run format:check` then reports "All matched files use the correct format."
…s out Activating the darwin stop-budget refresh made `run-loop.test.ts` exercise the real `readLaunchdStopTimeout`, which spawns three `launchctl print` calls against live subprocess I/O while the suite holds `vi.useFakeTimers()`. One case ran 120039ms before failing and the abandoned loop leaked into later cases, for eight failures in total. All eight clear by mocking the reader; no existing expectation was wrong. The mock could not simply be added. `run-loop.test.ts` is 3813 lines against a 1000 line cap where `check-line-cap-ratchet` rejects any growth, and an earlier attempt failed with `3501 -> 3510 counted lines`. Taking the remedy that ratchet names, the darwin cases move to `run-loop.launchd.test.ts` and the original file shrinks by 82 lines. It keeps the mock too, because four of those cases are registered into it by shared `register*` helpers whose `it.each` arrays interleave systemd and launchd variants and cannot be split without touching those support files. The new file adds one case the default mock would otherwise hide: a job reporting a 30000ms deadline bounds the stop at 25000ms and arms the force exit there. `node-runtime-recovery.test.ts` asserts the replacement child's spawn env exactly, so it gains the launcher's own OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a loosened matcher. That argv is a non-foreground `doctor --fix`, so the value is the 1s signal exit grace plus the 1s force-kill grace.
…usive Extending the stop-budget refresh to darwin gave the retained-budget safety net a new and wrong trigger. On a launchd-owned Gateway the startup budget is already native, and an in-process restart signals the process without launchd running the stop, so the job still prints `running` and the reader reports `stop: null`. The old condition treated any null as unconfirmed, so every in-process restart of a default macOS install logged "Retaining the startup shutdown budget of 15000ms because the current supervisor stop timeout could not be confirmed." The timeout was confirmed; it was confirmed not to apply. `readNativeStopTimeout` now reports `inconclusive` alongside the deadline, and only an inconclusive probe retains. Linux keeps its exact previous condition, an absent unit or a warned read. The budget number was already unaffected, so this is the message and the wasted `launchctl print` calls, not the deadline. Two cases pin it: a confirmed not-stopping read warns nothing, and a failed inspection still retains and still says so. Also fixes two wording defects found in review. `unresolved()` no longer takes a label it only ever interpolated as "the launchd job the configured label"; each failure already names its own target. And the `readJobState` comment said `state` appears four times in `launchctl print` output when its own next clause counts three, which is what a live LaunchDaemon prints.
Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line. Whitespace only, in a test file, so it cannot change runtime behaviour.
`inconclusive` keyed off the warning alone, so the defaulted-value case counted as a failed probe. There launchd is confirmed to be stopping the job and only its deadline had to be guessed, so a clock is genuinely running and there is nothing to retain. Under launchd ownership that combination logged both "using 20000ms default" and "could not be confirmed" for the same stop, the second being false. Now only a warning with no deadline at all counts as inconclusive. A third case pins it, asserting the defaulted read warns exactly once and about the deadline rather than about confirmation. Also corrects a test fixture comment that still said `launchctl print` emits `state` four times; the arrangement it documents, and a live LaunchDaemon, both show three.
The comment said active work "had time to finish" during the reported 315 second drain. The reporting host's log shows the opposite: that drain hit its own timeout with five tasks still active, and the Sep 20 stop with six. The drain was being used, which is a stronger reason for the guard, not a weaker one.
|
@clawsweeper re-review All four items are closed by measurement. Nothing in this branch's own files changed since Revision 8's reviewed head P3, measured test cost. Single-worker CI seconds are reported at the only granularity CI produces. The node shards run a per-test reporter and emit no per-file duration line: across all 115 shard logs in the cited run, P1 and the maintainer decision, measured under load. Seven real launchd stops, every one of them spending its full drain budget, driving concurrent streaming agent runs through the Gateway's own
Cleanup cost moved 53 ms across a 5.4x change in reserve and tens of milliseconds across a 4x change in load, because it is dominated by the fixed 1000 ms P2 is that same evidence, including the A/B. Two CI notes, both upstream owned, both evidenced in the body rather than asserted:
One further CI note. |
|
🦞👀 Re-review progress:
|
launchctl print reports the job launchd has loaded, not the plist on disk, so editing a loaded job's ExitTimeOut changes nothing until the job is reloaded. Measured on macOS 27 against a scratch job: the plist moves from 20 to 47 while the loaded job keeps reporting 20, and it still reports 20 after launchctl kickstart -k, which restarts the process without reloading the job. Only bootout then bootstrap makes it report 47, and that restarts the Gateway with it. State what reading per stop actually buys instead: the Gateway never plans against a deadline it cached at its own startup.
|
@clawsweeper re-review The P3 is fixed, and the correction is measured rather than reasoned. Corrected the loaded-job timeout guidance (
The doc now says the value applies only after the job is reloaded, notes that a On the narrowed merge risk, "a slower plugin or service close that previously finished in the extra time could now be cut off": that is exactly right, and the body now bounds it instead of waving at it. The affected band on the 20 second template is a cleanup costing between 7500 ms and 10000 ms. Reading the close path's own constants in On the maintainer decision, I am not going to claim evidence can settle it. Your reasoning is correct: accepting less cleanup time for services that already exist is an upgrade tradeoff, and a contributor's captures cannot authorize it on the lifecycle owner's behalf. What I can do is make the ask exact, and the body now does: a lifecycle owner accepting that on stop deadlines under 25 seconds the post-drain reserve shrinks, in exchange for the drain those deadlines currently do not get, with the measured basis, the affected band, and the failure mode of the current policy all stated. That item stays open on purpose until an owner answers it. One update on the CI note from my last comment, now that the runs finished: the shard containing |
|
🦞👀 Re-review progress:
|
The reserve was capped at half the shutdown budget whenever the budget could not fund it outright. That kept a drain on short deadlines, but it also reallocated deadlines that already worked: a 20 second ExitTimeOut, which is both the shipped LaunchAgent template and launchd's own default, moved from a 10 second reserve and a 5 second drain to 7.5 seconds of each. Cleanup costing between 7.5 and 10 seconds finished before and would have been cut off. Bound the reserve by what keeping a drain actually requires instead. The floor is 5 seconds, which is the drain the 20 second template already yields once the fixed margin and reserve are subtracted, so funding the full reserve alongside it takes 15 seconds of budget: exactly what that template resolves to. Every deadline from 20 seconds up therefore keeps the allocation it had, and only a deadline the fixed subtraction had already driven under a 5 second drain gives any reserve up, never below half the budget. Both allocations stay monotone in the deadline, and the 5 second case is unchanged at 1875ms of each.
- gateway-shutdown-budget.mjs: replace the floor-invariant claim with the real bound (reserve unchanged only at a >=15000ms post-margin budget, i.e. a >=20s deadline once the launchd probe's own cost, up to three launchctl print calls at 2000ms each, is subtracted); name the 8-20s sub-band reserve loss the old comment denied, including 16-19s where a flat subtraction already left a positive drain while still funding the reserve in full - docs/gateway/restart-recovery.md: drop the systemd section's "down to the millisecond" promise and the launchd section's "exact allocation ... before this change" claim; both now state the inspection cost that comes off instead - run-loop-shutdown-budget.test.ts: add a real 13ms elapsed-debit case at a 20s exit timeout (asserts reserve=9987, drain=5000, contrasting with the existing acceptedAtMs=MAX_SAFE_INTEGER zero-debit fixtures) and mirror darwin's 19/16/15/10s sub-20s it.each against a systemd stub, which previously had no sub-20s coverage
The sub-20-second systemd cases added in 60e5eb5 left the flat-subtraction comparison on a single line past the formatter's width, which failed oxfmt --check and took check-lint and check-docs down with it. Lint itself reported zero warnings and zero errors. Formatting only, no assertion or value changed.
… debit The previous wording paired 'gives up exactly what the probe cost' with a probe bounded near 6 seconds, and those two cannot both hold. Which allowance pays the debit turns on a 5 second threshold: at or under it the reserve absorbs the whole cost and the 5 second drain floor is untouched, so a 20 second deadline resolves 10000 minus the debit. Past it the floor is share-bounded as well and the two converge on half the remainder, so a 6 second debit splits 9000 into 4500/4500 rather than retaining the old reserve. Documents the threshold in the docs and the root-module comment, and pins the over-threshold case with a test so the boundary is measured rather than reasoned.
The drain-floor comment asserted that a whole 10 second reserve follows for every ExitTimeOut of 20 seconds or more once the probe that reads the deadline is subtracted. The probe cost is charged before the budget is split, so a 20 second ExitTimeOut clears the 15 second budget that a whole reserve needs only when that probe costs nothing. At the 13ms measured on this rig the reserve is 9987, and a whole reserve at that cost needs 20013. The same comment already states this correctly six lines down, where it resolves a 20 second deadline to 10000 - cost. This removes the contradiction by qualifying the claim at its first statement instead of restating the arithmetic twice. Comment-only: no non-comment line changes and the export list is unchanged.
Preserve the observed launcher cap only for launchd-driven stops, and shorten redundant budget documentation without changing the measured split. Co-authored-by: Patrick-Erichsen <[email protected]>
Co-authored-by: Patrick-Erichsen <[email protected]>
Co-authored-by: Patrick-Erichsen <[email protected]>
Co-authored-by: Patrick-Erichsen <[email protected]>
|
@clawsweeper re-review RoboClaw review for the delegated repair-and-land request, at
|
|
🦞👀 Re-review progress:
|
|
Landing review and proof at signed head de0f197: The root cause is that restart ownership and native stop deadlines are independent. Current main and stable v2026.9.6 inspect systemd but omit the enclosing launchd job. The canonical shutdown owner now discovers that deadline without conflating it with installation ownership. Direct SIGTERM does not invent a launchd deadline, zero stays unlimited, and the launcher consumes the same shared budget. Best-fix verdict: the native deadline belongs here, not in a transport/restart wrapper. Existing generic launchctl parsing loses top-level state to nested coalition state; the installation runtime also brings unrelated ownership and port probing. Apple launchd.plist's ExitTimeOut contract was checked directly, including zero=infinite. Reviewed contributor real scratch-Gateway before/after captures:
ClawSweeper Revision 26 reviewed the exact de0 head on September 29 at 00:19 UTC with no remaining findings or before-merge actions. As part of the requested landing, I accept the documented smaller cleanup reserve for custom launchd deadlines below 20 seconds. No new configuration is introduced. The normal 20-second policy keeps more cleanup reserve than the earlier half-reserve variant. Local runtime verification passed 8 files across 3 routed shards in 183 seconds, including 269 CLI cases, real OS-signal subprocess behavior, Linux/systemd siblings, unmanaged/direct signals, queued startup stops, zero/unknown job deadlines, launcher markers and cleanup. The fresh full-Gateway scratch LaunchAgent attempt did not reach readiness within 20 seconds; its labels/processes were removed. This is not claimed as a fresh full-Gateway live pass. The mainline refresh exposed a small CI import-closure defect introduced by ac59199 (Peter Steinberger; introducing PR unknown): the Docker scenario planner imports provider catalog and record-shared, but frozen verification and copied fixtures omitted them. Main independently landed the closure repair in ae1d3da. The latest signed merge of main2a778ef887d2 preserves that fix and newer candidate-provider hydration682ffe55; its only conflict retained both the byte-integrity check and executable-before-verification tamper sentinel. Remaining CI delta removes the redundant child-only requirement/copy and asserts shared evidence. Nine focused integrity/evidence/planner cases, format, lint and diff checks pass. Two tamper regressions failed before the original repair and pass after; package-source preflight reproduced the missing-module failure before and passed after. No launchd runtime logic changed in either refresh. Local broad tooling is not all green: the wide run had 996 pass / 2 fail / 2 skip. Its stale isolation assertion was repaired and passes; the other case passes unchanged in its original file order. That file rerun had 120 pass / 3 other cases hitting unchanged 30-second deadlines / 2 skip. Host load 35/36/43 makes contention plausible, not proven. No timeout or assertion weakening; exact-head hosted CI is required before merge. Fresh runtime and CI-repair autoreviews are scoped-clean at their default P0 threshold; direct owner/caller/callee/sibling review also completed. Current-main delta excludes its independently landed repair: production/declarations+362/-38 (net+324); tests/support+1588/-101; docs+77/-5. The native-job reader and shared parent/child deadline contract justify growth; the remaining CI cleanup removes 5 production lines. No dependency, storage, configuration or protocol surface added. Provenance: raw-parent inspection of cd3c9b9 / #151142 (steipete author and merger, September 17) shows the Linux repair carried the preexisting Darwin gap forward, not that it introduced it. Signed candidate preserves contributor ancestry; launchd runtime bytes are unchanged from the previously reviewed/tested candidate. GitHub now reports the conflict resolved; exact-head CI remains required. CI diagnosis: run 36501803818, compact-large-37, hit a native Bun 1.4.3-canary.1 /6b9148b17 SIGSEGV/139 before named results from its fast cohort. The same bundle's Node core-unit-fast, spawn, reply and security cohorts passed. The Bun binary pin and relevant runner/config/bootstrap files match the actual CI base; this is not a failed launchd assertion. The native root cause is unproven. The run still has active jobs, which are not being cancelled. After terminal completion, one supported failed-job diagnostic retry may establish whether this ordered bundle reproduces; no timeout, assertion or dependency changes are being made to hide it. Exact-head CI remains mandatory. All remaining jobs completed successfully. After the run became terminal with only compact-large-37 and its aggregate gate failing, one failed-job diagnostic retry was requested at unchanged de0f197. It preserves the original ordered bundle. A pass establishes non-reproduction, not a repair or known root cause for the native crash. Result: attempt 2 completed successfully at unchanged de0f197. The original ordered bundle and exact-head aggregate gate are green. The native crash did not reproduce; no native-crash fix is claimed. |
# Conflicts: # test/scripts/preflight-frozen-target-contracts.test.ts
|
Merged via squash.
|
…nclaw#157007) * fix(gateway): derive the darwin stop budget from the launchd job resolveGatewayShutdownBudget derives the stop deadline from restart ownership, so a darwin host running with OPENCLAW_SUPERVISOR_MODE=external resolves drain=315000ms whatever launchd actually enforces. The linux-gated systemd probe becomes a platform dispatch, and a new readLaunchdStopTimeout mirrors readSystemdStopTimeout: it reads the running job's effective exit timeout and accepts it only when the printed pid is this process. run-loop.ts is untouched because the reader detects launchd from the environment itself. Closes openclaw#156968 * fix(gateway): accept the launchd launcher parent and cap its deadline The darwin reader accepted the printed job only when its pid was this process. The installed service can keep a launcher parent while the serving Gateway runs as its child, so the job prints the launcher's pid, the enforcing job was rejected, and the Gateway fell back to 20 seconds in the one layout where an operator's ExitTimeOut was meant to apply. Accepting that job at face value would be worse than rejecting it. node-runtime-recovery.mjs builds the launcher's own reap timer from the compile-time LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS rather than from the job, so on a forwarded stop it re-sends SIGTERM to its child at 18000ms and SIGKILLs it at 19000ms. Adopting a 90 second job deadline in that layout would plan a 75000ms drain and then lose it to its own parent, which is the truncated drain this change exists to prevent. The reader now accepts process.pid or process.ppid and takes min(jobExitTimeout, 20000) in the launcher case, naming the cap in the source string only when it binds. A shorter job deadline still applies in both layouts, because launchd reaps the whole job regardless of the launcher. The docs claimed the deadline is read at startup and when accepting shutdown. run-loop.ts gates the budget refresh on linux at both consumption sites, so on darwin it is read once, at startup, and nativeStopBudget has no shutdown-time consumer there. The page now says startup-only and drops the sentence about a failed shutdown reread retaining the startup budget, which described linux behaviour only. * fix(gateway): scope the darwin stop budget to launchd-driven stops Address the two review findings on the previous revision. The launcher parent is now identified by an explicit OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a bare ppid match, so an unknown parent keeps the job's full deadline instead of being capped on a guess. The darwin reader inspects the launchd job only while a stop is under way, and adopts that job's deadline only when the job reports the SIGTERMed state. An external SIGTERM keeps the platform-neutral drain, because launchd's ExitTimeOut bounds only a stop launchd itself is running. The job state is read with an anchored single-tab pattern. launchctl print emits further "state = active" lines inside the resource and jetsam coalition blocks, and the shared key/value parser keeps the last occurrence, so the shared parser could never observe SIGTERMed. A test fixture reproduces the nested coalition shape. * fix(gateway): keep a failed launchd inspection off the native stop budget `readLaunchdStopTimeout` answered a failed job inspection with the Gateway's own 330000ms stop policy wrapped in a non-null result. `resolveGatewayShutdownBudget` classifies every non-null result as a native stop budget, so a probe that established nothing still set `nativeStopBudget`. On an externally supervised darwin Gateway that caps a longer requested restart drain and can arm a forced exit against a deadline no supervisor was confirmed to be enforcing. The reader now reports its two answers separately. `stop` carries a deadline only while launchd is confirmed to be stopping the job; `warning` reaches the operator either way. A failed inspection reports `stop: null` and leaves the caller on the platform-neutral policy it had already resolved, which is the same number as before, now classified honestly. The reader no longer imports GATEWAY_SERVICE_STOP_TIMEOUT_MS, because choosing the Gateway's policy number was never its job. Tests assert the flag and the downstream restart drain in the failure case, paired with a confirmed-deadline case so deleting the read outright cannot pass both. Also fixes TS2532 on the job-state regex: the named group is optional under `noUncheckedIndexedAccess`, so `.trim()` needed the optional chain. * test(infra): isolate the hoisted spawn mock and ratchet the OPENCLAW_* count `spawn` is hoisted once per file, so its call log survived across cases and `toHaveBeenCalledExactlyOnceWith` could only hold for the first one. Clear it in `beforeEach`. CI reports `OPENCLAW_* count 488 exceeds budget 487; update config/env-var-count-budget.txt` as a warning. The new name is the launcher's OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration, so the count is correct and the ratchet moves to 488 with the reason recorded in the file. * style(infra): apply oxfmt to the new launchd reader assertions Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line. `pnpm run format:check` then reports "All matched files use the correct format." * test(cli): mock the launchd reader and split the darwin run-loop cases out Activating the darwin stop-budget refresh made `run-loop.test.ts` exercise the real `readLaunchdStopTimeout`, which spawns three `launchctl print` calls against live subprocess I/O while the suite holds `vi.useFakeTimers()`. One case ran 120039ms before failing and the abandoned loop leaked into later cases, for eight failures in total. All eight clear by mocking the reader; no existing expectation was wrong. The mock could not simply be added. `run-loop.test.ts` is 3813 lines against a 1000 line cap where `check-line-cap-ratchet` rejects any growth, and an earlier attempt failed with `3501 -> 3510 counted lines`. Taking the remedy that ratchet names, the darwin cases move to `run-loop.launchd.test.ts` and the original file shrinks by 82 lines. It keeps the mock too, because four of those cases are registered into it by shared `register*` helpers whose `it.each` arrays interleave systemd and launchd variants and cannot be split without touching those support files. The new file adds one case the default mock would otherwise hide: a job reporting a 30000ms deadline bounds the stop at 25000ms and arms the force exit there. `node-runtime-recovery.test.ts` asserts the replacement child's spawn env exactly, so it gains the launcher's own OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a loosened matcher. That argv is a non-foreground `doctor --fix`, so the value is the 1s signal exit grace plus the 1s force-kill grace. * fix(gateway): only retain a startup budget when the probe was inconclusive Extending the stop-budget refresh to darwin gave the retained-budget safety net a new and wrong trigger. On a launchd-owned Gateway the startup budget is already native, and an in-process restart signals the process without launchd running the stop, so the job still prints `running` and the reader reports `stop: null`. The old condition treated any null as unconfirmed, so every in-process restart of a default macOS install logged "Retaining the startup shutdown budget of 15000ms because the current supervisor stop timeout could not be confirmed." The timeout was confirmed; it was confirmed not to apply. `readNativeStopTimeout` now reports `inconclusive` alongside the deadline, and only an inconclusive probe retains. Linux keeps its exact previous condition, an absent unit or a warned read. The budget number was already unaffected, so this is the message and the wasted `launchctl print` calls, not the deadline. Two cases pin it: a confirmed not-stopping read warns nothing, and a failed inspection still retains and still says so. Also fixes two wording defects found in review. `unresolved()` no longer takes a label it only ever interpolated as "the launchd job the configured label"; each failure already names its own target. And the `readJobState` comment said `state` appears four times in `launchctl print` output when its own next clause counts three, which is what a live LaunchDaemon prints. * style(cli): apply oxfmt to the new retained-budget assertions Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line. Whitespace only, in a test file, so it cannot change runtime behaviour. * fix(gateway): a defaulted deadline is not an inconclusive probe `inconclusive` keyed off the warning alone, so the defaulted-value case counted as a failed probe. There launchd is confirmed to be stopping the job and only its deadline had to be guessed, so a clock is genuinely running and there is nothing to retain. Under launchd ownership that combination logged both "using 20000ms default" and "could not be confirmed" for the same stop, the second being false. Now only a warning with no deadline at all counts as inconclusive. A third case pins it, asserting the defaulted read warns exactly once and about the deadline rather than about confirmation. Also corrects a test fixture comment that still said `launchctl print` emits `state` four times; the arrangement it documents, and a live LaunchDaemon, both show three. * test(cli): correct the regression guard's account of the reported drain The comment said active work "had time to finish" during the reported 315 second drain. The reporting host's log shows the opposite: that drain hit its own timeout with five tasks still active, and the Sep 20 stop with six. The drain was being used, which is a stronger reason for the guard, not a weaker one. * fix(infra): stop exporting a type nothing outside the module reads Knip's all-exports gate reads LaunchdStopTimeout as dead: the only public surface is readLaunchdStopTimeout's LaunchdStopRead return, and nothing imports the nested shape by name. Keep it module-local. * fix(gateway): keep a proportional drain and cap an undeclared launcher The fixed 10s reserve and 5s exit margin were sized against the 315s policy drain. Subtracting them outright from a launchd job's own ExitTimeOut spent a short deadline entirely on overhead: 5 seconds funded the margin alone and 15 funded margin plus reserve, so active work drained for zero milliseconds in both. Each allowance now takes at most a share of what it is carved from, so a deadline long enough to fund them is unchanged and a shorter one keeps a proportional drain. Drain is now positive for every positive deadline and never decreases as ExitTimeOut grows. The shutdown log also subtracted the unscaled reserve constant when reporting drain, which understated a short budget by the amount the scaled reserve gives back, so it now reports the margin and drain actually spent. An already-running launcher published before OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS existed arms the same reap timer and declares nothing, which is the upgrade shape: replacing files cannot change a launcher that is already running. Reading that silence as "no deadline" let a long custom ExitTimeOut be budgeted past a force-kill the parent was already counting down. The launcher's arithmetic moves into the shared budget module so the serving Gateway reconstructs the same timer, used only where the printed job carries OpenClaw's own label and its pid is this process's immediate parent. In that position the parent is the process launchd started for OpenClaw's job and the recovery launcher is the only path that puts a Gateway underneath it, so an unrelated process manager holding the parent slot still caps nothing. * fix(infra): gate the launcher reconstruction on the recovery respawn marker Holding the launchd job's pid is not evidence of a reap timer. An operator wrapper can keep that pid and start the Gateway itself while running none, so reconstructing a cap from the parent relation alone would cut a drain nothing was going to interrupt. The recovery launcher has stamped OPENCLAW_NODE_UPDATE_RESPAWNED on every child it respawns since long before it declared a stop timer, so that marker is present in exactly the upgrade case and absent for any other parent. * fix(infra): declare the new shared budget helpers for the type checker The root module is typed by a hand-written declaration file rather than being compiled, so new exports are invisible to src without being declared there. * docs(gateway): scope the positive-drain claim to the allocation The elapsed cost of resolving the budget is debited after the allocation, so a deadline shorter than that cost can still leave nothing to spend. Claiming every positive deadline yields a positive drain overstated it. * test(cli): accept the retained-budget attribution on a synthetic launchd label The fixture declares a launchd label with no matching job, so the per-stop re-inspection cannot read one and the startup budget is retained. The deadline is unchanged at 15000ms; only the source attribution differs. The assertion still fails if the budget comes from the platform-neutral policy instead. * fix(gateway): derive the launcher's reap deadline instead of declaring it Measurement showed the declared value and the derived value are the same number: a published launcher and a candidate launcher both arm an 18000ms exit grace, and a candidate Gateway resolved an identical 19000ms cap and 14231ms budget under each. The declaration was therefore carrying no information the child could not compute, while adding an OPENCLAW_* name and leaving the upgrade path conditional on which build of the launcher happened to be running. Both sides now read one expression in gateway-shutdown-budget.mjs, the launcher to arm its escalation and the Gateway to bound its budget, so they cannot disagree and there is no published-versus-candidate launcher distinction left to prove. The cap stays gated on OPENCLAW_NODE_UPDATE_RESPAWNED so a parent that did not respawn this process still caps nothing. Drops the env-var count back to 486, so the name ratchet no longer needs an owner waiver, and takes config/env-var-count-budget.txt out of the diff entirely. Test deadlines move off 90 seconds onto 55, because launchd clamps ExitTimeOut at 60 and a 90-second case cannot occur on macOS 27. * test(infra): restore the recovery spawn-env cases to their base form The launcher no longer declares a deadline, so the assertions these cases grew have nothing left to check and their explanatory comment described behavior that is gone. * fix(gateway): cap every respawning launcher, not just the Node-recovery one All three runRespawnedChild call sites reach the same launcher through the same function and arm the same escalation, but only the Node-recovery one sets OPENCLAW_NODE_UPDATE_RESPAWNED. Gating on that marker alone left the two compile-cache respawns uncapped, and the packaged one can wrap a foreground gateway run on an installed service: the job's deadline would then be budgeted past a force-kill the parent had already armed, which is the hazard this cap exists to prevent. The marker set moves next to the deadline it authorises, so adding a respawn path cannot silently escape the cap. Keeping the literals in the root module also keeps them out of the env-count ratchet's scope: reading the marker from counted production source promoted a previously test-only name and held the count at 487 even after the declared-timer variable was removed. Also applies oxfmt's own wrap to the launcher-relation expression. * fix(infra): re-export the respawn marker set through the infra barrel The constant existed only on the root module, so the test importing it from the barrel got undefined and it.each(undefined) threw during collection: the suite reported zero tests rather than a failure, and typecheck flagged the missing member. Re-exporting the binding adds no OPENCLAW_* literal under src, so the env-var count stays at 486. * fix(gateway): address the pre-review findings on the launchd stop budget Docs were stale or wrong in four places. The systemd section still promised a fixed 10 second reserve and 5 second margin, but the share caps are platform-neutral and do change a Linux unit whose TimeoutStopSec is under 25 seconds; that radius is now stated with the 20 second and 15 second cases spelled out. The direct-SIGTERM paragraph claimed the platform-neutral drain "is the deadline that actually governs that stop", which the branch's own kill -TERM capture contradicts: no supervisor deadline governs that stop at all and the fallback is the template value. The updated-launcher requirement no longer applies to the stop budget and says so. The marker sentence named one marker when three are honoured, and one measured figure was stale. Two claims in the code were too strong. The marker list asserted every setter arms the shared escalation, which is false for the compile-cache name: entry.compile-cache sets it for a runner that reaps on a fixed short grace. That runner refuses a foreground Gateway run off Windows and this deadline is only read during a darwin stop, so it cannot be the parent here, and the comment now says that instead of implying exclusivity. The sync note next to the escalation now records that the other runner keeps its own copies of the graces. An absent job state was indistinguishable from a job launchd is not stopping, so a macOS that printed the block differently would silently revert to the platform-neutral policy. When a deadline parsed but the state did not, that now warns and marks the read inconclusive rather than passing as a positive answer. Tests: launchd cases move off 90 and 315 second deadlines, which launchd clamps to 60 and cannot produce; the marker list is restated locally and tied back to the implementation so dropping a marker fails; and the real-process case now asserts the darwin probe actually ran, which it could not before. Retires five exports with no production consumer that the dead-export scan flagged. * test(infra): move the empty job state onto the missing-state warning An empty value yields no state to recognise, so it reaches the same branch as a missing line and now carries the same warning. Keeping it in the unrecognised-state table asserted the absence of a field the reader deliberately reports. * fix(infra): treat a whitespace-only job state as missing, and sharpen two docs claims The state value is trimmed after matching, so a line carrying only whitespace yielded an empty string rather than undefined and skipped the warning while behaving exactly like a missing line. The systemd section now says the exit margin shrinks below a 20-second deadline, not just the reserve. The direct-signal paragraph distinguished only the launchd-supervised budget; external supervisor mode keeps the platform-neutral policy and arms no force-exit timer, and a signal delivered to the job pid does reach a resident recovery launcher, which arms its own reap timer even though launchd is not stopping the job. * docs(gateway): correct the loaded launchd job deadline guidance launchctl print reports the job launchd has loaded, not the plist on disk, so editing a loaded job's ExitTimeOut changes nothing until the job is reloaded. Measured on macOS 27 against a scratch job: the plist moves from 20 to 47 while the loaded job keeps reporting 20, and it still reports 20 after launchctl kickstart -k, which restarts the process without reloading the job. Only bootout then bootstrap makes it report 47, and that restarts the Gateway with it. State what reading per stop actually buys instead: the Gateway never plans against a deadline it cached at its own startup. * fix(gateway): keep the full cleanup reserve wherever a deadline funds it The reserve was capped at half the shutdown budget whenever the budget could not fund it outright. That kept a drain on short deadlines, but it also reallocated deadlines that already worked: a 20 second ExitTimeOut, which is both the shipped LaunchAgent template and launchd's own default, moved from a 10 second reserve and a 5 second drain to 7.5 seconds of each. Cleanup costing between 7.5 and 10 seconds finished before and would have been cut off. Bound the reserve by what keeping a drain actually requires instead. The floor is 5 seconds, which is the drain the 20 second template already yields once the fixed margin and reserve are subtracted, so funding the full reserve alongside it takes 15 seconds of budget: exactly what that template resolves to. Every deadline from 20 seconds up therefore keeps the allocation it had, and only a deadline the fixed subtraction had already driven under a 5 second drain gives any reserve up, never below half the budget. Both allocations stay monotone in the deadline, and the 5 second case is unchanged at 1875ms of each. * fix(gateway): correct shutdown-budget probe-debit overclaims - gateway-shutdown-budget.mjs: replace the floor-invariant claim with the real bound (reserve unchanged only at a >=15000ms post-margin budget, i.e. a >=20s deadline once the launchd probe's own cost, up to three launchctl print calls at 2000ms each, is subtracted); name the 8-20s sub-band reserve loss the old comment denied, including 16-19s where a flat subtraction already left a positive drain while still funding the reserve in full - docs/gateway/restart-recovery.md: drop the systemd section's "down to the millisecond" promise and the launchd section's "exact allocation ... before this change" claim; both now state the inspection cost that comes off instead - run-loop-shutdown-budget.test.ts: add a real 13ms elapsed-debit case at a 20s exit timeout (asserts reserve=9987, drain=5000, contrasting with the existing acceptedAtMs=MAX_SAFE_INTEGER zero-debit fixtures) and mirror darwin's 19/16/15/10s sub-20s it.each against a systemd stub, which previously had no sub-20s coverage * test(cli): wrap the flat-subtraction assertion to satisfy oxfmt The sub-20-second systemd cases added in 60e5eb5 left the flat-subtraction comparison on a single line past the formatter's width, which failed oxfmt --check and took check-lint and check-docs down with it. Lint itself reported zero warnings and zero errors. Formatting only, no assertion or value changed. * docs(gateway): bound the 20-second allocation claim by the inspection debit The previous wording paired 'gives up exactly what the probe cost' with a probe bounded near 6 seconds, and those two cannot both hold. Which allowance pays the debit turns on a 5 second threshold: at or under it the reserve absorbs the whole cost and the 5 second drain floor is untouched, so a 20 second deadline resolves 10000 minus the debit. Past it the floor is share-bounded as well and the two converge on half the remainder, so a 6 second debit splits 9000 into 4500/4500 rather than retaining the old reserve. Documents the threshold in the docs and the root-module comment, and pins the over-threshold case with a test so the boundary is measured rather than reasoned. * docs(gateway): qualify the full-reserve claim by the probe debit The drain-floor comment asserted that a whole 10 second reserve follows for every ExitTimeOut of 20 seconds or more once the probe that reads the deadline is subtracted. The probe cost is charged before the budget is split, so a 20 second ExitTimeOut clears the 15 second budget that a whole reserve needs only when that probe costs nothing. At the 13ms measured on this rig the reserve is 9987, and a whole reserve at that cost needs 20013. The same comment already states this correctly six lines down, where it resolves a 20 second deadline to 10000 - cost. This removes the contradiction by qualifying the claim at its first statement instead of restating the arithmetic twice. Comment-only: no non-comment line changes and the export list is unchanged. * fix(gateway): honor unlimited launchd stops Preserve the observed launcher cap only for launchd-driven stops, and shorten redundant budget documentation without changing the measured split. Co-authored-by: Patrick-Erichsen <[email protected]> * test(gateway): use action-based drain budget Co-authored-by: Patrick-Erichsen <[email protected]> * style(gateway): format launchd timeout assertions Co-authored-by: Patrick-Erichsen <[email protected]> * fix(ci): complete frozen Docker planner import closures --------- Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Patrick-Erichsen <[email protected]> Co-authored-by: Patrick Erichsen <[email protected]>
Closes #156968
What Problem This Solves
On darwin the Gateway's stop deadline is derived from restart ownership rather than from the supervisor that enforces it. A host running with
OPENCLAW_SUPERVISOR_MODE=externalresolvesdrain=315000msand reportssource=Gateway stop policy=330000ms, whatever launchd actually enforces, becausedetectGatewayRespawnSupervisorshort-circuits to"external"before any platform detection andresolveGatewayShutdownBudgetconsumes that ownership answer for timing.OPENCLAW_SUPERVISOR_MODE=externalis documented supported configuration.docs/cli/gateway/restart-and-supervision.md:144instructs operators to set it when another process manager owns the lifecycle, with a worked command at:154. Any darwin operator following that page reaches this budget.User Impact
A macOS Gateway now plans its drain against the deadline its own launchd job enforces instead of a platform-neutral constant, and it does so per stop rather than once at startup. The stop budget is the time until the supervisor may kill the process; drain is the first portion spent waiting for active work to finish, before reserved cleanup and exit time.
Every job keeps a positive drain. The two fixed allowances that fund cleanup and process exit were sized against the 315 second platform-neutral drain, and against a short
ExitTimeOutthey consumed it entirely. The exit margin is now capped at a quarter of the job's deadline, and the reserve yields only as far as keeping a 5000 ms drain requires, so a short deadline keeps a usable drain instead of spending its whole budget on overhead.On the installed LaunchAgent template's 20 second deadline the drain becomes 5000 ms with a 15000 ms shutdown deadline, rather than a planned 315000 ms the supervisor would cut short. That is the same nominal 5000 ms drain and 10000 ms reserve the current code already allocates at that deadline, so the installed template's split does not change beyond the cost of reading the deadline, measured here as a 13 ms debit that moves from the reserve to the drain, and tracking that cost one-for-one for as long as it stays within 5 seconds; what changes is that the Gateway now plans against 15000 ms instead of 315000 ms. Deadlines below 20 seconds gain drain and give up some reserve: the current code drains nothing at all at 15 seconds and below, and 4000 ms at 19 seconds.
When the job cannot be inspected at all, the Gateway keeps the stop policy it already had and warns with the target and reason. A failed inspection establishes nothing about who is stopping the job, so it is not allowed to shorten a drain that no launchd deadline was bounding.
Why This Change Was Made
Upstream already named this principle and implemented it for Linux only.
src/cli/gateway-cli/run-loop-shutdown-budget.ts:19-20at base reads:The comment states the rule and the next expression gates it to one platform.
run-loop-shutdown-budget.test.ts:29states it again as a describe title, "Gateway stop deadline independent of restart ownership", withplatform: "linux"stubbed at:16and no case overriding it. PR #151142 introduced that gate. This is its darwin half.detectRespawnSupervisoralready answers correctly on darwin, and upstream already asserts the two resolvers disagree atsrc/infra/supervisor-markers.test.ts:137-145. The information needed to fix this was already in the tree.Why the deadline is read per stop, not at startup
ExitTimeOutbounds a stop that launchd is running and nothing else. An externally delivered SIGTERM never starts that clock, and the job outlives the deadline untouched. There is no enforcing deadline to read before a stop is under way, so reading one at startup would spend alaunchctl printonly to adopt a deadline that does not govern the stop the Gateway will actually get.The job's own
stateis what separates the two. launchd reports the job asSIGTERMedfrom the moment it begins its own stop, and keeps reportingrunningwhile the process handles a signal some other sender delivered. Measured on macOS 27 against a job carryingExitTimeOut47:statelaunchctl bootoutSIGTERMedlaunchctl kickstart -kSIGTERMedlast terminating signal = Killed: 9kill -TERMrunningAnything unrecognised counts as not stopping, so an unfamiliar state leaves the Gateway on the budget it already had rather than shortening a drain launchd was never going to interrupt.
Why a short job deadline no longer spends its whole budget on overhead
GATEWAY_SHUTDOWN_RESERVE_MS(10000) andGATEWAY_SUPERVISOR_EXIT_MARGIN_MS(5000) were sized against the 315 second platform-neutral drain, where they are rounding error. Against a job's ownExitTimeOutthey are not: subtracting both fixed values from a short deadline consumed it entirely, sodrainreached zero at everyExitTimeOutat or below 15 seconds. 5 seconds funded the margin alone; 15 funded margin plus reserve.The exit margin is now capped at a quarter of the job's deadline. The reserve keeps its full 10000 ms wherever the budget can fund it, and yields only as far as preserving a 5000 ms drain requires:
The 5000 ms figure is not chosen freely. It is the drain the installed 20 second LaunchAgent template already yields today, once main subtracts its fixed 5000 ms margin and 10000 ms reserve. Funding the full reserve beside it needs 15000 ms of shutdown budget, which is exactly what a 20 second deadline resolves to. Four properties follow.
timeoutMs + margin == ExitTimeOutexactly.This is not a fixed minimum drain. A fixed minimum spent regardless of the deadline gets SIGKILLed mid-drain on short jobs. This floor only ever redistributes budget that launchd is already granting, never extends past it, and yields to the deadline first: at a 5 second job the floor is
min(5000, floor(3726/2)), which is 1863 ms, not 5000 ms.A related reporting bug is fixed in the same expression. The shutdown log computed its
drainfigure by subtracting the unscaled reserve constant rather than the reserve actually held back, so on any short budget it understated drain by the difference. It now reports the margin and drain actually spent.Why the launcher case needs its own ceiling
The installed service can keep a launcher parent while the serving Gateway runs as its child, so
launchctl printreports the launcher'spid. Two things follow, and only taking both is safe.First, a bare
pid === process.pidtest rejects the job that actually enforces the deadline, and the Gateway silently falls back in exactly the layout where an operator'sExitTimeOutwas supposed to apply.Second, accepting that job at face value is worse than rejecting it. On a forwarded stop signal the launcher re-sends SIGTERM to its child, force-kills it one grace later, and exits one grace after that. A reader that adopted a 55 second job deadline in that layout would plan
drain=40000ms shutdown=50000msand then be killed by its own parent around 19 seconds in, truncating the drain it just promised.The launcher does not declare that instant. Both sides derive it from one expression in
gateway-shutdown-budget.mjs, the launcher to arm its escalation and the Gateway to bound its budget, so the two cannot disagree. Deriving rather than declaring is what makes this correct on upgrade: replacing files cannot change a launcher that is already running, so the first Gateway built from any change is started by the previous launcher. A value that had to be announced would be missing exactly then, which is when the mismatch is widest. A launcher that declares the timer through an environment variable was measured to resolve the identical 19000 ms cap and the identical budget, so the variable carried no information the child could not derive and it is not in this PR. The derived case is measured below.Holding the parent slot is not evidence of that timer. An external process manager can start the Gateway from inside the same job and run no reap timer at all, and capping its deadline at OpenClaw's would cut a valid drain short. The cap is therefore gated on the respawn markers a
runRespawnedChildparent stamps on its child. All three call sites are covered, not just the Node-recovery one: the two compile-cache respawns inopenclaw.mjsreach the same launcher through the same function and arm the same escalation, and the packaged one can wrap a foregroundgateway runon an installed service. The marker set lives beside the deadline it authorises so a new respawn path cannot silently escape the cap. A parent that set no marker still caps nothing.A shorter job deadline applies in every layout, because launchd reaps the whole job regardless of the launcher.
launchd clamps
ExitTimeOutat 60 secondsMeasured on macOS 27 against a bare
/bin/sleep 600job with no OpenClaw code involved.plutilreads back the requested value in every case;launchctl printreports what launchd will enforce:ExitTimeOutFor positive finite values the Gateway reads the enforced value rather than the plist; on macOS 27 that caps the launchd branch at a 55000 ms shutdown budget. An explicit
ExitTimeOut=0is different: launchd defines it as infinity. The reader now keeps that job unlimited unless a marked launcher has its own finite reap timer.The change in one sentence
The linux-gated probe becomes a platform dispatch, and a new
readLaunchdStopTimeoutmirrorsreadSystemdStopTimeoutby reading the running job's effectiveexit timeout, accepting it only when launchd is the party stopping the job and the printedpidis this process or the launcher that spawned it, capping the launcher case at the reap timer that launcher derives from the same shared expression, and scaling the fixed reserve and exit margin so a short deadline still funds a drain.At this revision the diff is 2025 additions and 138 deletions across 14 files: 362/-33 production and declarations, 1586/-100 tests, and 77/-5 documentation. The launchd reader is 187 lines and the shared budget module adds 69. Most remaining size is lifecycle test scaffolding: the darwin run-loop cases were split out of the existing line-capped suite.
Contract
exit timeout = 5launchd <domain>/<label> exit timeoutexit timeout = 20launchd <domain>/<label> exit timeoutexit timeout = 19launchd <domain>/<label> exit timeoutexit timeout = 47launchd <domain>/<label> exit timeoutexit timeout = 55,pidis this processlaunchd <domain>/<label> exit timeoutpidis the launcher, respawn marker present, enforcedexit timeout = 60... capped at the launcher's 19000ms stop timerpidis the launcher, respawn marker present,exit timeout = 5launchd <domain>/<label> exit timeoutpidis the launcher, no respawn marker, enforcedexit timeout = 60launchd <domain>/<label> exit timeoutpidis the launcher, respawn marker present, job is not the servicelaunchd <domain>/<label> exit timeoutpidis this process, respawn marker inheritedlaunchd <domain>/<label> exit timeoutstate = runningexit timeout = 0, no launcher timerexit timeout = 0, marked launcherexit timeoutmissing or invalid... exit timeout unavailable; default ExitTimeOutpidis neither this process nor its launcherlaunchctl printfails or throws in every domainnativeStopBudgetfalseThe source string names the cap only when the cap actually binds, so an operator reading the log can tell a clamped deadline from an adopted one.
The allocation across the deadline range, with main's split beside it:
ExitTimeOutFrom the 20 second template upward the split is main's split. Below it the reserve is genuinely lower than main's, for every deadline from roughly 8 seconds to 20, and that is a real reduction rather than only a reallocation of budget main was wasting. At 16 to 19 seconds main does drain positively, 4000 ms at 19 seconds, so those rows trade cleanup reserve for a longer drain. At 15 seconds and below main holds a full or near-full reserve but drains nothing at all. No shipped template or platform default lands in that range; the installed template is 20 seconds and the systemd default is 90.
In live runs the resolved budget is a few milliseconds under its nominal value, because resolving it is itself debited. At the 20 second template that puts the budget at 14987 ms rather than 15000 ms, just below the point where the full reserve fits, so the measured reserve is 9987 ms rather than 10000 ms and the drain is 5000 ms rather than 4990 ms. The reserve given up at the template is the 13 ms probe debit, and it buys back the same 13 ms of drain.
Evidence
One machine, a Mac Studio on macOS 27 with node v26.8.1, base
0ad702eda0c. Scratch LaunchAgents bootstrapped intogui/501from a temp directory, never written to~/Library/LaunchAgents, with a throwawayHOMEand their own profile; they never contact a production Gateway, port, or profile, and every scratch label was booted out of bothuser/501andgui/501afterwards and verified absent, withlaunchctl listending at zero matches.Two scoping facts, stated once here rather than repeated per capture. The captures are at three trees: the before-and-after pair at
b736529385f2, the six reserve-split captures at tree-cleanfdb0608ca1a, and the seven loaded captures at6b5583b6362(treed8c94bd958424416d5488ecda8b044642f3c4ecf); each tree was verified withgit write-treebefore building, and changes togateway-shutdown-budget.mjssince the reserve-split captures are comment-only; its positive finite allowance arithmetic is unchanged. And the allowance arithmetic changed after the state-gate, launcher-upgrade and loaded captures were taken, so thereserveanddrainfields in those three carry the earlier flat half-of-budget cap: on the same budgets the shipped code yieldsreserve=9969ms drain=5000ms(state gate, 14969 ms budget),reserve=9237ms drain=5000ms(launcher, 14237 ms budget) and 9987 ms of reserve at the 20 second template rather than 7488 ms. Each of those captures is cited for a source-selection, cap, or cleanup-cost result that does not depend on the split, and the positive finite split is measured on the cited revision in the reserve-split section; this revision retains that arithmetic and adds the zero-timeout guard. Because the shipped reserve at the template is strictly larger than the one the loaded captures ran against, every headroom conclusion drawn from them is conservative by 2499 ms.Before and after, one variable, through the real service boundary
The only difference between the two builds is the darwin probe this PR adds. The control reverts it to the shape base has, which is
1 insertion, 6 deletionsin one file:if (process.platform === "darwin" && stopping) { - const read = await readLaunchdStopTimeout(); - return { ...read, inconclusive: read.stop === null && read.warning !== undefined }; + return { stop: null, inconclusive: false }; }Both runs used the identical plist carrying
ExitTimeOut 47, and both were stopped bylaunchctl bootout. The job reports that itself, sampled live while the stop was under way:In both runs the printed job is the serving Gateway, not a same-named job in another domain:
psreports68955 1 openclaw-gatewayand69734 1 openclaw-gateway, andlsofputs each pid on127.0.0.1:18799and[::1]:18799.AFTER:
BEFORE, same tree, darwin probe reverted:
Gateway stop policy=330000mslaunchd gui/501/<label> exit timeout=47000mssource=launchdrecords in the logThe BEFORE shutdown record is byte identical to its own startup record. That is the defect: the deadline the Gateway plans against is the one it resolved at startup from restart ownership, and the 47 second deadline launchd is enforcing on that very stop never reaches it.
The AFTER pair also proves the reread happens per stop rather than once at startup. Both records come from the same process in the same run.
The same 47 second configuration re-measured on the shipped arithmetic gives
drain=31986ms shutdown=41986ms reserve=10000ms exitMargin=5000ms, against31983msabove, so the long-deadline case is untouched by the scaling and the pair above still describes the shipped build:margin = min(5000, floor(47000 * 0.25)) = 5000;min(325000, 42000) = 42000; a 14 ms debit gives41986;reserve = min(10000, floor(41986 / 2)) = 10000;drain = 41986 - 10000 = 31986.The reserve split, measured against main's own arithmetic
The compatibility question is about the allowance split rather than the probe, so this pair holds the probe fixed and varies only the two allowance expressions. The control restores base's arithmetic exactly,
2 insertions, 12 deletionsingateway-shutdown-budget.mjs.Base computes both inline in
src/cli/gateway-cli/run-loop-shutdown-budget.tsrather than in named functions, which is what this PR extracted. The two expressions the control restores are base's own, at:43and:49:Base already applies them to a real supervisor deadline on Linux, where
readSystemdStopTimeouthas been wired since #151142, so for a systemdTimeoutStopSecthis is base's live behaviour, not a counterfactual. On darwin base never reaches them with a job deadline at all, which is the defect this PR fixes, so there the control answers the narrower question: what these deadlines get if the probe lands and the allowances stay fixed.Six runs: three
ExitTimeOutvalues against both builds, same plist generator, samelaunchctl bootoutstop, a throwawayHOMEeach. All six printedstate = SIGTERMedwhile the stop was in flight, so launchd enforced each deadline in every cell. All six exited 0, andlaunchctl list | grep -c ai.openclaw.capafterwards is0.ExitTimeOutexitMarginshutdownreservedrainAt the installed template the reserve is unchanged to within the probe debit. 9987 ms against main's 10000 ms is a 13 ms difference, and the drain gains the same 13 ms. The compatibility band at issue, cleanup between 7500 ms and 10000 ms, is therefore not opened: the only cleanup duration that finishes under main and not under this PR at the template is one lasting between 9987 ms and 10000 ms.
At 5 seconds main resolves the entire budget to zero. The two verbatim records, same deadline, same stop:
main's fixed 5000 ms exit margin consumes a 5000 ms deadline in full, leaving no shutdown budget at all. What follows in that run is not a clean stop:
A healthy stop of an idle Gateway files a
gateway.stop_shutdown_timeoutdiagnostic. The candidate build at the same deadline logs neither line. This is the case the proportional margin exists for, and it is the one a lifecycle owner would be trading away by keeping the fixed values.The template rows differ only in the drain they announce:
Candidate arithmetic, so the numbers are checkable rather than asserted:
margin = min(5000, floor(ETO * 0.25));budget = ETO - marginless an elapsed debit;floor = min(5000, floor(budget / 2));reserve = min(10000, budget - floor);drain = budget - reserve.5000,15000less a 13 ms debit is14987, floormin(5000, 7493) = 5000, reservemin(10000, 9987) = 9987, drain5000.4750,14250less 12 ms is14238, floor5000, reservemin(10000, 9238) = 9238, drain5000.1250,3750less 24 ms is3726, floormin(5000, 1863) = 1863, reserve1863, drain1863.Control rows use
margin = 5000fixed andreserve = min(10000, budget): 20s gives14990, reserve10000, drain4990; 19s gives13988, reserve10000, drain3988; 5s gives0, so both are0.The state gate, measured against the same job
Same plist at
ExitTimeOut 47, stopped with a plainkill -TERMinstead oflaunchctl:The job reports
running, so the 47000 ms deadline is refused and the template value kept. This is what establishes that the 5000 ms and 47000 ms adopted above came from launchd driving the stop rather than from the plist merely existing. Thereserveanddrainfields here are the earlier cap, as noted in the preamble; the refusal this capture is cited for does not depend on the split.The launcher upgrade case, measured
The layout that matters on upgrade: an already-running published launcher starting the candidate Gateway. The published launcher is the merge base's own file, extracted with
git show 8dd24e6ec0a:node-runtime-recovery.mjsand confirmed byte-unchanged, so it sets no marker this branch added. It loads unmodified against the candidate tree.The launchd job runs that published launcher, which respawns the candidate Gateway as its child. In both captures the printed job
pidequals the child'sppidand not the child's own pid, so the reader is genuinely on thelauncherrelation, and the child's argv positionals are["gateway","run"]at boot and again at the stop:stateexit timeoutlauncherSIGTERMedlauncherSIGTERMedMarker present, the upgrade case, with
OPENCLAW_LAUNCHER_STOP_TIMEOUT_MSunset in the child:The job's enforced deadline was 60000 ms and the budget resolved to 14237 ms, held down by the launcher rather than the job.
margin = min(5000, floor(19000 * 0.25)) = 4750;min(325000, 19000 - 4750) = 14250; a 13 ms debit gives14237. The cap this capture is cited for is independent of the split; the shipped split on that same 14237 ms budget is the 19 second row measured on an earlier arithmetic-equivalent revision above,14238 / 9238 / 5000.Marker absent, the control, same rig:
No cap clause in the source and the job's enforced 60000 ms adopted, which is the guarantee that a parent holding the job's pid without having respawned this process is never shortened by a timer it does not run.
The reserve under load, measured
Every capture above left the Gateway idle, and idle cleanup cannot establish that a smaller reserve is safe. This round drives real work through the Gateway's own
/v1/chat/completionssurface: N concurrent streaming agent runs, each its own session, each holding an HTTP response and gateway root work open, backed by a loopback stub provider that streams tokens indefinitely so no run can settle inside the drain.Every loaded capture therefore spends its entire drain budget and enters cleanup with exactly the reserve left, which is the worst case the reserve has to survive. The Gateway's own counts at the stop say so:
ExitTimeOutcand20idlecand20http-server[0]cand20heavyhttp-server[0]ctrl20http-server[0]cand5http-server[0]cand5heavyhttp-server[0]ctrl5shutdown deadline reached, stability bundleCleanupis the Gateway's own[shutdown] completed in Nmsmeasure, which starts atactive-work drain settled; beginning server close.ctrl20andctrl5are the same tree with one file reverted to fixed allowances,6 insertions, 10 deletionsingateway-shutdown-budget.mjs, so the only variable between acandrow and itsctrlrow is the share policy itself. Those two control rows reverted the reserve to a flat 10000 ms constant, which is whyctrl5reportsreserve 10000 msagainst a zero budget; base clamps it withmin(GATEWAY_SHUTDOWN_RESERVE_MS, timeoutMs)and reportsreserve 0 msthere, as the newer control does. The drain is 0 ms either way, so the abandoned-cleanup result these rows establish is unaffected. The 5 second rows describe the shipped build: at or below a 10000 ms budget both the earlier and the shipped cap reduce to half the budget, andcand5at 1865 ms is within the debit of the 1863 ms measured on an earlier arithmetic-equivalent revision.Three results follow.
Cleanup cost tracks neither the load nor the reserve. Quadrupling concurrent runs from 8 to 32 moved it by -15 ms at 20 seconds and -30 ms at 5 seconds. Across a reserve range of 1865 ms to 10000 ms, a 5.4x spread, cleanup stayed inside 1164 ms to 1217 ms, a 53 ms spread. What it does track is the fixed
HTTP_CLOSE_GRACE_MSthatserver-close.tsspends before forcing live connections, which the log names directly:That warning appears identically under both allowance policies at the same deadline,
cand20andctrl20, so it is a property of holding live streams open across a stop rather than of the smaller reserve. With no client connections at all it disappears:cand20idlecleans up in 196 ms and completes cleanly.cand20idleis not an idle Gateway, only a Gateway with no client connections; the memory-core plugin's own dreaming cron job was mid-run, so that capture reportsembeddedRuns=1 activeTasks=1and still spends its whole 7489 ms drain. It is the connection count, not the work count, that separates 196 ms from 1185 ms.The per-step close trace isolates it. At 32 live runs, the same single step dominates at both deadlines and costs the same at both, while every other step is sub-millisecond to tens of milliseconds:
Both were driven by launchd, sampled live while the stop was under way:
At the installed template the reserve is 8.5x the measured loaded cleanup cost, 9987 ms against 1170 ms at 32 live runs.
At the short deadline the scaled rule finishes under load and the fixed one does not. On the same 5 second job with eight live runs the candidate drains 1866 ms, completes cleanup in 1194 ms inside its 1865 ms reserve, and is gone 3270 ms into a 5000 ms deadline.
The thinnest margin is the 5 second one: 1194 ms of cleanup inside 1865 ms, 64 % used, 671 ms of slack. Since cleanup is dominated by a fixed 1000 ms grace rather than the reserve, the crossing point is an
ExitTimeOutnear 3.2 seconds, where0.375 x ExitTimeOutstops covering it. Below that the fixed policy is already atdrain=0, so 3.2 seconds is the honest boundary of what is measured.What it would take to land in the affected band
On the 20 second template the band at risk is 13 ms wide: a cleanup costing between 9987 ms and 10000 ms finished before and is cut off now. That is the probe debit, not a policy choice, and the whole residual at the template.
A wider band exists at 19 seconds and below, where the reserve is
budget - 5000: 762 ms at 19 seconds, 3750 ms at 15. That range is the open decision in Gaps.What it would take to reach even the wider band, from the close path's own constants in
src/gateway/server-close.ts: the largest single grace is 5000 ms (GATEWAY_SHUTDOWN_HOOK_TIMEOUT_MS,HTTP_CLOSE_FORCE_WAIT_MS, and the MCP, LSP, embedding-provider and agent-harness closes), withACTIVE_SESSIONS_SHUTDOWN_DRAIN_TIMEOUT_MSat 2000 ms andWEBSOCKET_CLOSE_FORCE_CONTINUE_MSat 250 ms. No single one reaches 9987 ms, so one hung closer cannot enter the template band; it takes two independent closers each running to full grace, and the total would then have to land inside a 13 ms window. Even then the close is warned and bounded, not hung, because every step has its own cap.Part of cleanup is already reserve-aware:
createServiceChildCleanupDeadlineadopts the shutdown budget and escalates bymin(GRACEFUL_CANCEL_TIMEOUT_MS, remaining / 2), so child cleanup compresses with a smaller reserve instead of being truncated, andrunWithProcessCleanupBudgetpulls the close deadline in bymin(HARD_EXIT_WATCHDOG_GRACE_MS / 2, remaining / 2), so a cleanup that runs out reports failure before the hard exit timer fires.Measured whole-path cost with 32 live runs is 1170 ms, 8.5x below the template band's floor.
The rig for the loaded captures
Same machine and isolation rules as the captures above: scratch LaunchAgents bootstrapped into
gui/501from a temp directory, a throwawayHOME, port 18799,OPENCLAW_SUPERVISOR_MODE=external, andOPENCLAW_GATEWAY_RESTART_TRACE=1for the per-step close trace.The load needs a model that never finishes, so the provider is a 60 line loopback HTTP server that answers
/v1/chat/completionswith an SSE stream emitting a token every 400 ms and nofinish_reason. It is a stub because the shutdown path is model agnostic: it only has to keep runs genuinely in flight so the drain is spent rather than skipped. The Gateway confirms it is the one being used,agent model: stub/stub-slow, and the stub confirms the Gateway is really calling it, one open upstream stream per client run. No shared or production model service was contacted.The loaded job, not the plist
launchctl printreports the deadline of the job launchd has loaded, not the value sitting in the plist. Measured on macOS 27 against a scratch/bin/sleepjob ingui/501, with no OpenClaw code involved:ExitTimeOut20launchctl kickstart -k, process restarted, job not reloadedlaunchctl bootoutthenlaunchctl bootstrap, job reloadedSo editing a loaded job changes nothing until the job is reloaded, and reloading it restarts the Gateway anyway. The previous guidance at
docs/gateway/restart-recovery.md:405-406claimed a plist edit took effect on the next stop; it now says what is measured above, and states what reading per stop actually buys: the Gateway never plans against a deadline it cached at its own startup.Other checks
On the contributor's earlier measured revision,
pnpm check:changed --base 0ad702eda0cran 29 lanes on a clean worktree; 28 were ok:typecheck alltsgo:core:all(includingtsgo:infra),tsgo:extensions:all,tsgo:scripts,tsgo:test:rootdead export scanline-cap growth ratchet,max-lines suppression ratchetcore tsgo graph boundary,database-first legacy-store guard,runtime sidecar loader guardcoercion helper declaration guard,deprecated API usage,assertion SAFETY comment ratchetlintOn the earlier reviewed head
3e1d4ac13aee,pnpm format:check,pnpm format:docs:checkandpnpm check:docsexited 0. The latera1e509ecee8ehead introduced a two-assertion formatting difference, corrected by the isolated formatter at0cca02df4cfd; its CI is pending.pnpm check:env-var-countalso reportedOPENCLAW_* count 486/486on that earlier head. This branch leavesconfig/env-var-count-budget.txtuntouched, so no ratchet waiver is needed; the respawn marker names are kept in the root module rather than insrcso reading them does not promote a previously test-only name into the counted set.CI on prior reviewed head
3e1d4ac13aeereported no failing check: 175 success, 45 skipped,CodeQLneutral. Heada1e509ecee8elater failed formatting and unrelated tooling shards. The formatting defect is corrected at current head0cca02df4cfd, whose exact-head CI remains mandatory. That includescheck-additional-boundaries, all fivecheck-lint-coreshards and all 44checks-node-compact-largeshards.Measured test cost
Per-suite counts are quoted because a green vitest exit proves nothing when the path matched nothing: an export missing from a re-export barrel makes a suite report
Tests no testsrather than a failure, which a count check catches and an exit code does not.Cost is measured on one host, a Mac Studio (32 cores, 512 GB) on macOS 27 with node v26.8.1. The five rows other than
run-loop-shutdown-budget.test.tswere measured at treed8c94bd958424416d5488ecda8b044642f3c4ecfwith a clean worktree, and four of those files remain byte identical at this head; the launchd reader test gained two zero-timeout/direct-signal cases, and the budget test was remeasured on an earlier revision before the new zero-timeout cases. Each file runs alone throughnode scripts/run-vitest.mjs run <file> --no-file-parallelism, which is a single worker, after one warm-up run that is discarded. Three timed runs per file; the figure is the median.vitestis the runner's own reportedDuration,wallis the whole process measured from outside it, so the difference between them is process start and teardown.vitesttestssrc/infra/launchd-stop-timeout.test.tssrc/cli/gateway-cli/run-loop.launchd.test.tssrc/cli/gateway-cli/run-loop-shutdown-budget.test.tssrc/cli/gateway-cli/run-loop.model-acquisition.process.test.tssrc/infra/node-runtime-recovery.shutdown.test.tssrc/cli/gateway-cli/run-loop.test.tsBase wallis the same median measured in the merge base's own worktree atceac53a0feaf75eb599e4c310fbd7e35923ba9cf; it is wall only, because that pass did not capture vitest's ownDuration. Every materially changed file is at or below its base cost.run-loop-shutdown-budget.test.tsgains 40 cases, and its figures are reported separately because they are not comparable with the rows above. That pass ran in the same persistent worktree used for the other five rows, checking out each commit in turn with one discarded warm-up before three timed runs per arm; the paired base figure from the same worktree and the same session is given alongside it, which makes the delta the meaningful number:vitestmedian67bc549ab050ad702eda0cThree timed runs per arm after a discarded warm-up, all six exit 0, all six report
Test Files 1 passed (1), andpnpm-lock.yamlis byte identical between the two commits so one install served both arms. The added cases cost about 0.25 ms each of vitest duration; the file's cost is dominated by transforming its module graph, which both arms pay identically. The cited tip row predates the new zero-timeout regression cases and the current-main test API adaptation. Treat its wall time as historical, not current-head measurement.Two further figures deserve their own sentence.
run-loop.launchd.test.tsat 5.24 s is marginally above the 5 s per-file target, and almost none of that is test work. The file exists only because this branch moved the darwin cases out ofrun-loop.test.ts, which is at 3501 counted lines against a 1000 line cap wherecheck-line-cap-ratchetrejects any growth; the three moved cases are byte identical to their originals. Counted honestly, the split costs about 5.8 s of wall on a sequential single-worker run of the pair:run-loop.test.tsfell 21.47 s to 20.59 s when the cases left, and the new file costs 6.63 s. Almost all of that is a second process start and a second load of therun-loopmodule graph, not the cases: in CI the file's four cases sum to 582 ms of reported test time, and the one case this branch adds rather than moves is 134 ms of it. In CI the file does not run alone, so the process start is not paid twice there.run-loop.model-acquisition.process.test.tsat 23.70 s is the one file over the 5 s target by a wide margin, and this branch did not make it so. It costs 25.21 s at the merge base and 25.10 s here, a 0.11 s improvement. It is an out-of-process test that spawns a real Gateway child to assert the shutdown deadline through a real process boundary, which is the contract no cheaper layer proves; this branch adds 16 lines to it.CI seconds. The repository's node shards run a per-test reporter, not the default file-summary reporter, so there is no per-file duration line in any node shard log. Verified rather than assumed: across all 115
Run Node test shardlogs in the run below,grep -E '\([0-9]+ tests?\)'returns 6 hits, all in thecore-toolinglane, and zero in anychecks-node-compact-*shard.config/ci-test-timings.jsonis keyed by group for these files, not by file: onlytoolingFileSecondsandrepoE2eFileSecondsare per-file. So the figure CI can supply is the sum of the per-test durations the reporter did print, which excludes import, transform, setup and teardown and is therefore a lower bound, not a file duration.Measured from CI run 36219672571, at head
6b5583b6362. Four of the six files are byte identical between that head and this one, verified per path. The launchd-reader and shutdown-budget tests have grown since that run; the latter had already grown substantially: the reporter printed 29 cases for it there, against 48 at this head, so its CI figure below was measured before those cases existed and is a lower bound on the current file for that reason as well as the reporter reason. That shard was also cancelled in that run, so 29 is itself a floor. The single-worker cost of the cases this branch adds to the file is +0.01 s, measured in the table above.src/infra/launchd-stop-timeout.test.tscore-runtime-infra-miscchecks-node-compact-large-18src/cli/gateway-cli/run-loop.launchd.test.tsagentic-clichecks-node-compact-small-24src/cli/gateway-cli/run-loop-shutdown-budget.test.tsagentic-clichecks-node-compact-small-24src/cli/gateway-cli/run-loop.test.tsagentic-clichecks-node-compact-small-24src/cli/gateway-cli/run-loop.model-acquisition.process.test.tsagentic-clichecks-node-compact-small-24src/infra/node-runtime-recovery.shutdown.test.tscore-runtime-infra-network-nodechecks-node-compact-large-31Shard assignment is not inferred from output: each shard job carries its own include list in
OPENCLAW_NODE_TEST_GROUPS_GZIP_BASE64, and decoding it across all 115 shard logs puts each of the six files in exactly one job'sincludePatterns. That is also how the two non-executing files are located.The two "did not execute" rows are honest gaps, and they are a cancellation cascade rather than a routing problem.
checks-node-compact-small-13failed that run ontest/scripts/lint-suppressions.test.ts, which cancelled roughly thirty sibling shards at 05:14:36;run-loop.model-acquisition.process.test.tswas still queued behind its shard's 408-file include list, andcore-runtime-infra-network-nodenever launched because the 384 sagentic-agents-support-hosted-1shard ahead of it consumed its job. Neither is routed to a macOS or release-only lane:macos-node,macos-swiftandchecks-windowswere allskippedin that run. That upstream failure is fixed as of256abd76af3,test/scripts/lint-suppressions.test.tsreports4 passed (4)at this head, and CI on the earlier3e1d4ac13aeehead was green on every shard. Current-head CI is tracked separately.The one number the CI table makes plain:
run-loop.test.tsat 37.4 s of reported test time is two orders of magnitude above everything this branch adds, and it is the file the branch made smaller.Gaps, stated plainly
a1e509ecee8ewas red.check-docsandcheck-lintidentified anoxfmtdifference in the new launchd reader test; the formatter-generated two-assertion edit is the only change at0cca02df4cfd. Several tooling shards also failed in untouchedtest/scripts/**files on missing.release-harness/scripts/lib/official-external-provider-catalog.jsonimports. Those failures are not presented as passing or waived; inspect the new exact-head suite and current main before landing.cbx_5887cb73daf3checked outa1e509ecee8e0a16f052d2dd6d983115dc18249a, verified no instance role with the trusted bootstrap, and ran the three affected files together with--maxWorkers=1: 3 files/91 tests passed, 46.33 s wall (run). Two files were also timed individually at that head:src/infra/launchd-stop-timeout.test.ts37/37 in 36.62 s wall, andsrc/cli/gateway-cli/run-loop-shutdown-budget.test.ts50/50 in 13.10 s wall (run). Import/transform dominate those wall times. This Linux mock-boundary proof does not replace the earlier real Mac launchd captures for positive deadlines; the new zero-timeout branch has no real macOS stop capture. CI shard seconds and the final head remain separate gates.launchctl printcalls of 2 seconds each, and past 5 seconds the drain floor is share-bounded too and the two converge on half the remainder. A 6 second debit therefore splits a 20 second job's 9 second budget 4500/4500 rather than retaining the old reserve. Reaching that needslaunchctlto hang on all three domain probes. Both the threshold and the over-threshold split are pinned by tests, including one asserting the over-threshold case is not the old reserve less the debit.ExitTimeOutnear 3.2 seconds.state = runningrefusal or the launcher cap; those two are pinned by unit cases and by the bare-job measurements above.run-loop.test.tsfailed 6 cases on the contributor's measuring host, at its merge base and earlier branch revision alike. Base reports6 failed | 215 passed (221), this head6 failed | 212 passed (218), the 3 test difference being exactly the cases moved intorun-loop.launchd.test.ts, and the sorted failing case names diff empty between the two. The cause ismanaged update handoff returned an invalid readiness response, a managed package lifecycle path unrelated to the shutdown budget. Not claimed fixed, shown not caused; the earlier CI head passed the shard that owns the file. Run it withnode scripts/run-vitest.mjs run: under barepnpm vitest runit reports a seventh failure that is a wrong-runner artifact.lintlane fails locally on four files this branch does not touch. At this head:Found 0 warnings and 4 errors, alleslint(max-lines), onserver-kernel.test.ts(1003),channel-health-monitor.test.ts(1023),mention-inbox.ts(713) andtask-registry-state.ts(702). For each,git diff origin/main HEAD --andgit diff <merge-base> HEAD --are both empty, none is inconfig/max-lines-baseline.txt, and this branch touches neither them nor the lint config, runner or baseline. The set drifts with upstream. CI's owncheck-lintand fivecheck-lint-coreshards were green on the earlier3e1d4ac13aeehead. The later formatting failure and current-head status are called out above; the four unrelated whole-tree local violations are not asserted as passing. The branch-scoped ratchet lanes both pass.state, but the launcher's timer is not. If the recovery launcher is resident and something other than launchd signals the job pid, the launcher arms its reap timer while the printed job still reportsrunning, so the Gateway keeps its existing budget and the launcher force-kills the drain. Unchanged from base, which resolves the identical budget in that layout, and not reachable through supported paths: a CLI restart signals the verified port listener, andopenclaw gateway stopgoes throughlaunchctl bootout, making launchd the stopper. Fixing it means applying the cap from the respawn marker alone on signal-initiated stops, which is a change to when the cap applies rather than how the deadline is read, so not in this PR. The same marker-based cap would also close the case where two launchers sit between the job and the Gateway, which defeatsresolveJobRelation; reaching that needs an unsupported Node version plus an operator-setNODE_COMPILE_CACHE, which no template writes.foregroundbranch is derived from argv in two builds. The resident launcher evaluates its own build's flag tables while the serving Gateway evaluates the candidate's, so a flag they disagree about could select different branches. The tables match today, and the harmful direction needs a token known only to the candidate that the resident plist already carried.ExitTimeOutbuys no extra drain in that layout, measured above as a 60000 ms job held at a 14237 ms budget. That is correct, since the parent really will force-kill at 19000 ms, but it is a ceiling operators should know about and it is now documented.launchctl printcalls on a darwin stop, each bounded at 2 seconds, stopping at the first job whosepidmatches this process or its launcher. The systemd path already spends up to twosystemctl showcalls there. A miss fails fast: an absent job answers immediately, an unavailable domain answers125.launchctl printoutput is not a stable API. The reader depends on three fields.pidandexit timeouteach occur exactly once, which is what makes the last-value-winsparseKeyValueOutputsafe for them.stateoccurs three times, the job's own at one tab plus two nested coalition lines at two tabs, so it is read with an anchored single-tab regex instead. All three were checked against live output in the captures above.