Repository navigation
fix(gateway): add .catch() to SIGTERM/SIGUSR1 signal handlers - #83131
Conversation
|
Codex review: needs real behavior proof before merge. Latest ClawSweeper review: 2026-05-22 18:27 UTC / May 22, 2026, 2:27 PM ET. Workflow note: Future ClawSweeper reviews update this same comment in place. How this review workflow works
Summary Reproducibility: yes. for source-level reproduction: current main still runs the SIGTERM async handler without a catch, so a thrown lifecycle-runtime load or restart-intent read skips the request path. I did not execute tests in this read-only review. PR rating Rank-up moves:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. Real behavior proof Risk before merge
Maintainer options:
Next step before merge Security Review detailsBest possible solution: Land the SIGTERM catch and focused regression tests after redacted real gateway proof is added and maintainers accept the fail-closed stop fallback, while preserving current main's SIGUSR1 eager-runtime recovery. Do we have a high-confidence way to reproduce the issue? Yes for source-level reproduction: current main still runs the SIGTERM async handler without a catch, so a thrown lifecycle-runtime load or restart-intent read skips the request path. I did not execute tests in this read-only review. Is this the best way to solve the issue? Yes. Catching at the signal-handler boundary, logging, and falling back to the normal stop request is the narrow maintainable SIGTERM fix; SIGUSR1 runtime recovery is already present on main. Label changes:
Label justifications:
What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 86b87df7e3df. |
|
ClawSweeper PR egg 🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat. Where did the egg go?
|
cd0feea to
3ff62ea
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
3ff62ea to
533255f
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
@clawsweeper re-review |
|
🦞👀 Command router queued. I will update this comment with the next step. |
…aw#83131) The SIGTERM handler's fire-and-forget IIFE can reject if the graceful drain or tunnel-teardown throws. Without a catch, this becomes an unhandled promise rejection. Add .catch() that logs the error and falls back to a hard stop request. Same treatment for SIGUSR1. Signed-off-by: Sebastien Tardif <[email protected]>
…aw#83131) The SIGTERM handler's fire-and-forget IIFE can reject if the graceful drain or tunnel-teardown throws. Without a catch, this becomes an unhandled promise rejection. Add .catch() that logs the error and falls back to a hard stop request. Same treatment for SIGUSR1. Signed-off-by: Sebastien Tardif <[email protected]>
…aw#83131) The SIGTERM handler's fire-and-forget IIFE can reject if the graceful drain or tunnel-teardown throws. Without a catch, this becomes an unhandled promise rejection. Add .catch() that logs the error and falls back to a hard stop request. Same treatment for SIGUSR1. Signed-off-by: Sebastien Tardif <[email protected]>
…aw#83131) The SIGTERM handler's fire-and-forget IIFE can reject if the graceful drain or tunnel-teardown throws. Without a catch, this becomes an unhandled promise rejection. Add .catch() that logs the error and falls back to a hard stop request. Same treatment for SIGUSR1. Signed-off-by: Sebastien Tardif <[email protected]>
…fterFailedSignalAdmission The PR updated run-loop.ts to call recoverGatewayRestartDrainAfterFailedSignalAdmission() instead of the simpler rollbackGatewayRestartSignalAdmission() to properly handle the stuck one-way drain case when SIGUSR1 handler fails after markRestartDraining(). This commit updates the test mocks to reflect the new function call: - Add mock for recoverGatewayRestartDrainAfterFailedSignalAdmission - Update all test expectations from rollbackGatewayRestartSignalAdmission to recoverGatewayRestartDrainAfterFailedSignalAdmission in all 3 affected tests Fixes: openclaw#83131
* test(config): deslop r0168 tests Share config fixtures, promotion assertions, and rollback setup while retaining both rollback interleavings as table cases. Consolidate repeated plugin diagnostics assertions. Suspicious promotion remains covered by preserves stored health rows through promotion and baseline compensation; recovery remains covered by the accepted-write truncation and formatting-normalization cases. Non-suspicious external promotion remains covered by keeps a newer last-known-good observation when a rolled-back write restores its baseline. CI-only shard: plain oxlint, oxfmt, and git diff --check pass. Static count: 2779 to 2505 lines, 66 to 63 declarations, 98 to 96 expanded cases. The 35 percent line target is not met; distinct plugin-validation and freshness interleavings are retained. No tests or coverage commands run. * test(config): consolidate r0168 boundary fixtures Consolidate accepted size-drop and formatting cases, pinned sync/foreign snapshot cases, and missing-plugin diagnostics. Remove internal read counts and error-reference identity checks while retaining persistence, conditional-write, and typed-error assertions. Remove the current-producer stored-row replay: accepted-write anomaly cases cover promotion refusal and warning reasons; restores the pre-write baseline after rollback covers persisted baseline compensation. Keep the distinct freshness interleavings and plugin schema/routing boundaries. CI-only: oxfmt, plain oxlint, source parsing, and diff checks pass. No tests or coverage run. Shard now has 2305 lines versus original 2779, a 17.1 percent reduction; the requested 35 percent target remains unmet. * test(config): remove redundant diagnostic variants Keep one Decision capability-skip case and the stronger Decision-named channel override. Utility-route diagnostics remain covered by config.utility-model.test.ts: diagnoses effective utility routes for Codex. Default and keyed Decision classification remain covered by configured-model-refs.test.ts: collects string Decision roles without changing profile suffixes. Keep the positive agent-wildcard diagnostic branch; generic wildcard matching remains covered by model-runtime-policy.test.ts. Share fixture file writing without changing generated content. CI-only static oxlint, oxfmt, and diff checks pass; no tests or coverage run. Original shard 2779 lines, now 2282; 35 percent target remains unmet. * test(agents): deslop r0169 tests Share requester-turn consumption, child retention, and foreground admission fixtures. Reuse the delivery runner and common receipt expectations without removing cases or broadening transport mocks. All distinct ownership, recovery, routing, and cancellation cases remain; this shard falls short of the 35% structural reduction target. * test(agents): consolidate r0169 delivery proof layers Reduce receipt, routing, media and error tables to branch-focused fixtures and remove redundant internal call-shape assertions. Preserve independent source/recipient authority, private consumption and wake recovery checks. Remaining proof: agent-command-restart-recovery.test.ts replays suppression and retains truncated send evidence; server.private-completion.test.ts keeps delayed private admission and fences changed sources; subagent-announce-direct-delivery.test.ts retains queued input through recovery; requester-settle-dispatch keeps real pause ordering. Requester-final-attachment.test.ts and registry requester-wake e2e cover exact-once committed final attachment. attempt-timeout-prepare.test.ts owns budget firing; dispatch retains runtime failure settlement. subagent-requester-store-key.test.ts owns alias normalization. CI-only: oxfmt, plain oxlint and diff checks passed; no test or coverage execution. Cumulative lines 2765 to 1928 (30.3%); below the 35% target because the remaining dispatcher cases protect distinct authority/recovery paths. * test(slack): deslop r0170 tests Share modal metadata and message-update fixtures, compact the authorization table, and consolidate exact field assertions without removing cases. Keep routing assertions because the mocked route does not validate its inputs. Retain acknowledgment proof in the block-action, shortcut, and modal entry tests, including mismatch ordering. Keep the exact UTF-16 boundary expectation; it subsumes the surrogate, length, and URI-encoding checks. Native Stop/title authority and lifecycle cases remain unchanged. * test(slack): consolidate r0170 interaction and session fixtures Table-drive typed and legacy approval outcomes, shortcut variants, and modal lifecycle routes. Share modal field fixtures and paused real-session writers while preserving authorization failures, workspace routing, live-owner revalidation, stream fallback, and ordering assertions. Remove the interaction UTF-16 replay: truncate.test.ts keeps the surrogate-boundary regression, while the retained typed-modal rich-text case proves preview integration. Native command metadata remains covered by slash.test.ts reload-before-Stop and slash.menus.test.ts native command collision cases. Drop internal patch/query snapshots while retaining persisted owner outcomes. CI-only: formatting, plain oxlint, and diff checks passed; no test or coverage execution. Cumulative shard reduction is 2674 to 2054 lines (23.2%), below the requested 35%; the remaining session races and distinct interaction boundaries are retained. * test(slack): finish r0170 structural consolidation Unify early-return controls, workspace approval variants, and shared action-summary branches. Keep modal routing and full-state-before-truncation as separate boundary proofs. Use minimal fixtures and remove repeated tracking, payload-inventory, and error-wording assertions; retain authorization, owner-currentness, rendering, and ordering outcomes. The former typed-modal scalar replay is covered by the shared summary rows in renders confirmation; routes modal lifecycle still proves view-state traversal. Existing lifecycle and native command owner suites cover the removed capture/dispatch plumbing assertions. No obsolete production subject was found; no production or shared support files changed. CI-only validation: plain oxlint, oxfmt, and diff checks pass; no tests, coverage, or typecheck run. Original shard 2674 lines to 1738 (35.0%). This additional commit removes 316 lines: 211 nonblank lines and 105 blank separators. Previous commits remain intact. * test(cli): deslop r0171 tests Remove duplicate readiness coverage already retained in lifecycle-readiness.test.ts: Windows budgets, activated-port selection, managed start results, and restart response contracts. Keep the observed-elapsed timeout and stopped-service cases here. Reuse local status fixtures and exact assertion helpers without dropping credential, TLS, database, or lifecycle authority checks. CI-only campaign: local oxlint, oxfmt, and diff checks passed; tests and coverage intentionally not run. * test(cli): remove duplicate r0171 boundary replays The saved-pin transport replay is covered by src/gateway/probe.tls.test.ts: validates saved pin/matching pin before upgrade, and enforces pins before sending Gateway credentials. Keep status credential isolation and saved transport-policy assertions at the gather boundary. The final restart-owner revalidation is covered by lifecycle.gateway-owner.test.ts: does not send a legacy restart signal when an owner ID appears at intent write. Keep the externally supervised success path and native-action refusals here. Table the two systemd restart outcomes, remove repeated probe config snapshots, and reuse minimal credential fixtures. CI-only: oxfmt, plain oxlint, and diff checks passed; no test/build/coverage runs. * test(cli): trim r0171 fixture and mock layers Share pre-upgrade Linux and Windows restart setup without removing their distinct delivery assertions. Remove unobserved spy wrappers, constant table dimensions, duplicated fixture fields, unsafe test casts, and handwritten mock signatures where the owner type is available. Retain all credential isolation, schema refusal, native-service ownership, lock mismatch, and diagnostic cases. No further equivalent owner tests were found for those paths. CI-only: plain oxlint, oxfmt, and diff checks passed; no test, build, or coverage runs. * test(tui): deslop r0172 tests Consolidate canonical selection persistence into reloads missing initial history and remembers the canonical selected session. Preserve the chat acknowledgement assertion in passes selected-agent global scope through chat methods. Reuse local roster and history fixtures while retaining lifecycle, reset, scope, and error cases. * test(tui): consolidate r0172 behavior coverage Collapse roster, patch, metadata, stale-selection and reset variants into branch-focused tables. Keep real history and rendering checks; trim repeated fixtures and implementation assertions. Run membership ownership remains covered by tui-session-run-coordinator.test.ts (retires only unchanged history observations; keeps concurrent runs after a gap) and tui-event-handlers.test.ts (promotes the confirmed concurrent run; keeps the watchdog busy). Keep direct history membership normalization here. Snapshot replay remains covered by session-projection-conformance.test.ts (replays stale history, same-text sends, duplicates, gaps, and terminal events), session-projection.test.ts (keeps every early same-run reply behind its delayed durable prompt), and chat-log-run-state.test.ts (anchors a delayed prompt after pruning). Keep selected-session live-history rendering here. * test(tui): slim r0172 fixtures and remove inert chat stubs Use real ChatLog operations with call-through spies, simplify private harness arguments, and share fixtures for run rows and live-history replacement without changing the in-flight same-key reset ordering. Share metadata lifetime setup across stop, reconnect and failure cases. No production or support files changed. * test(harness): deslop r0173 tests Share host construction, request fixtures, and guarded question dispatch without dropping distinct authority or lifecycle cases. Keep captured-target injection in the existing local helper. The annotation durable context-engine outbox test retains generation refresh, idempotence, and exact update notification proof removed from the cron selector race. The cron race still proves exact target selection while the same-ID base row changes. Direct-admission identity is covered by tool-authority.runtime.admission.test.ts. CI-only validation: plain oxlint, oxfmt, and git diff --check. No tests or coverage executed. Conservative reduction: 2604 to 2538 lines; security and interleaving contracts prevent the requested 35% cut. * test(harness): consolidate r0173 authority proof layers Retain distinct authority, revocation, projector failure and hidden-allowlist mutation checks. Remove repeated policy-input comparisons, maintenance and active-run projection layers; share deferred calls, prepared tools and existing worker placement setup. Remaining coverage: tool-authority.runtime.continuation.test.ts proves maintenance authority without borrowed reply policy; tool-authority.runtime.admission.test.ts proves admitted publication and backend replacement; session-active-runs.test.ts scopes projected bare runs by owner. reply-tool-authority.test.ts and requester tests retain policy fields and hidden intersection distinctions. bash-tools.github-identity.test.ts retains preview env/store credential scrubbing, with host-capability.environment.test.ts retaining host wiring. Annotation retains persisted bytes, cursor and outbox results; user-turn-transcript.persistence.test.ts retains multi-source collection. CI-only: plain oxlint, oxfmt and diff check passed. No test or coverage runs. Partial PASS16 result: original 2604 to 2215 lines (-14.9%); further removal would need replacement proof for retained security, lifecycle and durability boundaries. * test(harness): consolidate r0173 branch fixtures Unify direct-input contract cases in one branch table while preserving all eight outcomes. Remove duplicated source-guard setup that never revoked its signal. Share annotation entry initialization, reuse the existing completion model builder, and replace repeated revocation conditionals with explicit actions. All distinct cases in these files remain. No test or coverage runs in CI-only mode. Plain oxlint, oxfmt and git diff --check passed. This conservative third pass reaches 2169 lines from the original2604 (-16.7%); the35% target remains unmet without removing distinct authority, lifecycle or durability proof. * test(helpers): deslop r0177 tests Factor repeated listener ownership, native exit observation, readiness fixtures, and timer settlement without deleting distinct lifecycle cases. Retain cancellation, refusal, inherited-pipe, detached-descendant, Windows shutdown, port-claim, and diagnostic-boundary proof. CI-only validation: oxfmt, plain oxlint, and diff check. * test(helpers): consolidate r0177 lifecycle proof Share readiness-clock setup and teardown; table the common terminal-classification and inherited-pipe flows. Keep distinct cancellation, admission, cleanup, redaction, and port-exclusion paths. Remove CLI timer-hook duplication of managed-child-process.drain.test.ts, whose cancellation and deadline cases assert timer release. Complete/large output remains covered by owns complete CLI JSON and diagnostic tails; inherited output remains covered by captures CLI output written after leader exit and managed-child-process.output.test.ts. Port release remains covered by openclaw-test-instance.acquisition.test.ts. Remove maximum-integer receipt formatting and round-trip self-comparison; real readiness diagnostics retain bounds and redaction assertions. CI-only: oxfmt, plain oxlint, and git diff --check passed. No tests or coverage run. Combined shard reduction is 2586 to 2137 lines (17.4%); 35% target remains unmet. * test(helpers): finish r0177 structural consolidation Reduce the original shard from 2586 to 1680 lines. Consolidate bounded retry outcomes and readiness failure categories; trim unasserted fixture diagnostics and duplicate metadata assertions without production changes. Coverage owners retained: reserves its idle port through refusal, CLI work, and stopped restarts now includes reservation connection closure; settles stalled headers/body proves readiness deadlines; allows one retry proves successful and exhausted replacement ownership; concurrent starts around an intervening stop proves queue ordering, with shared-entrypoint cancellation covering preparation ownership. Expired-body snapshot cases retain late-response immutability. Delegate inherited-output drainage to managed-child-process.output.test.ts (starts owned-tree cleanup at leader exit while a descendant holds both output pipes), with CLI capture retained in owns complete CLI JSON and diagnostic tails. Windows unverified-tree/pipe behavior remains in managed-child-process.termination.test.ts and native Job finalization in openclaw-test-instance.windows-job.test.ts; retain local blocking-termination success and sanitized failure diagnostics. CI-only checks passed: oxfmt, plain oxlint, git diff --check. No tests, coverage, or builds run. * test(cli): deslop r0176 tests Remove the narrow SIGTERM handler rejection replay: run-loop-request.test-support.ts retains 'keeps the original SIGTERM deadline after delayed intent consumption fails', which exercises the same run-loop-signals.ts failure callback and proves close plus successful exit after rejected intent consumption. This preserves the behavioral regression from #83131 (99e44f6). Simplify the triage table's invariant recorded-boot fixture and wrapped cleanup failure without removing its three scenarios or assertions. CI-only shard: oxlint, oxfmt, and diff-check passed; no test or coverage execution. Reduction is 22/2606 lines (0.84%); retained distinct authority, startup cleanup, config selection, and restart interleavings prevent the requested 35% cut. * test(cli): consolidate r0176 lifecycle fixtures Share startup settlement scaffolding across five operation/worker cases while preserving all cancellation, failure and repaired-systemd scenarios. Table password sources and trusted-dotenv drift phases; retain their distinct outcomes and authority checks. Remove internal reset/read/pin call inventories and the schema completion assertion supplied by its own mock. Actual completion outcomes remain covered by registerGatewayStartupFailureTests in run-loop-startup.test-support.ts. Keep acquisition authority-call stability, native health probe targeting, privacy, cleanup joins and observable ordering. Shrink the drain category fixture: formatGatewayDrainCounts iterates entries generically, so two categories plus totalActive exclusion and private blocker controls cover the formatter decisions without replaying thirteen category names. No obsolete subjects or additional completely redundant cases found. CI-only: oxlint, oxfmt and git diff --check pass; no tests run. Original shard 2606 lines to 2418 (-7.2%); still below 35%, with distinct auth/config-selection, cleanup, restart ownership and deadline behavior retained. * test(cli): reduce r0176 fixture duplication Centralize isolated option-test environment restoration and use the real auth resolver instead of a handwritten duplicate. Consolidate maintenance and parent-option scenarios. Keep legacy-session refusal routing here; producer preservation is covered by doctor-session-sqlite.targets.test.ts. Remote config recheck drift remains covered by pre-bootstrap.process.test.ts, and stale-boot recovery by crash-loop-recovery.test.ts. Reuse the existing joined-cleanup helper for running-loop fixtures, retain explicit exit-code checks, and replace three repeated startup fixtures with an indexed generation sequence. Remove exact internal log wording while retaining redaction, timing, lifecycle authority and ordering assertions. CI-only validation: plain oxlint, oxfmt and git diff --check passed; no test/build/coverage commands. No production or support files changed. Original shard 2606 to 2196 lines (-15.7%): still short of 35%; independent source review found the remaining apparent duplicates cover different initial/replacement, migrated/unchanged and launchd/systemd branches. * test(daemon): deslop r0179 tests Remove duplicate policy/default and legacy repair groups retained verbatim in service-policy-preservation.test.ts. Keep ordinary XML-refresh warning/activation coverage in schtasks.install.test.ts; retain one running-replacement case per runtime, arguments, and environment change instead of their desktop/unattended cross product. Reuse the stop suite's typed fixture pattern for settlement cases and share repeated transaction hooks and native assertions. Preserve distinct ownership, authority, publication, rollback, and settlement failure paths. CI-only shard: oxfmt, plain oxlint, and diff checks pass. Static cases 133 to 124; test LOC 2651 to 2396 (9.6% reduction). Below 35% because remaining cases cover distinct durability, authority, and lifecycle behavior. No tests or coverage run. * test(daemon): trim duplicated lifecycle proof in r0179 Keep receipt restoration, native cache eviction/reload, interruption, and authority checks in the receipt suite. Leave post-restore activation to systemd-install-rollback.test.ts (cached candidate inputs and retry after failed reload) and launchd.test.ts (policy and supervision after bootstrap failure). Remove task XML rendering inventory duplicated by schtasks.install.test.ts: installs Gateway services with password-free unattended boot and a batch action. Keep actual stopped/revived process state, restored files/XML, and authority guards instead of repeating internal call counts and exact command sequences. CI-only: plain oxlint, oxfmt, and diff checks passed; no tests run. Shard LOC is 2324 versus original 2651. This remains below the requested 35 percent reduction; distinct recovery and ownership cases are retained. * test(commands): consolidate r0181 fixture and proof layers Share remote RPC setup and restart scenarios, replace duplicated WizardSession emulation with wire fixtures, and consolidate Doctor preflight fixtures. Keep distinct custody, credentials, migration, restart identity and recovery boundaries. Retained owner proof: src/config/io.snapshot.test.ts preserves source paths across core-only and prepared plugin reads with a Windows home; src/wizard/session.test.ts owns wizard terminal/cancellation lifecycle; src/system-agent/setup-inference-activate.test.ts keeps working credentials and rotation after rejected replacement. CI-only validation: plain oxlint, oxfmt and git diff --check. No tests or coverage run. Structural reduction remains below the requested 35 percent target. * test: remove unused replay helpers * test: retain distinct boundary coverage and repair replay fixtures * test: preserve independent contracts in reduction batch * test: retain post-restore service startup proof
* test(config): deslop r0168 tests Share config fixtures, promotion assertions, and rollback setup while retaining both rollback interleavings as table cases. Consolidate repeated plugin diagnostics assertions. Suspicious promotion remains covered by preserves stored health rows through promotion and baseline compensation; recovery remains covered by the accepted-write truncation and formatting-normalization cases. Non-suspicious external promotion remains covered by keeps a newer last-known-good observation when a rolled-back write restores its baseline. CI-only shard: plain oxlint, oxfmt, and git diff --check pass. Static count: 2779 to 2505 lines, 66 to 63 declarations, 98 to 96 expanded cases. The 35 percent line target is not met; distinct plugin-validation and freshness interleavings are retained. No tests or coverage commands run. * test(config): consolidate r0168 boundary fixtures Consolidate accepted size-drop and formatting cases, pinned sync/foreign snapshot cases, and missing-plugin diagnostics. Remove internal read counts and error-reference identity checks while retaining persistence, conditional-write, and typed-error assertions. Remove the current-producer stored-row replay: accepted-write anomaly cases cover promotion refusal and warning reasons; restores the pre-write baseline after rollback covers persisted baseline compensation. Keep the distinct freshness interleavings and plugin schema/routing boundaries. CI-only: oxfmt, plain oxlint, source parsing, and diff checks pass. No tests or coverage run. Shard now has 2305 lines versus original 2779, a 17.1 percent reduction; the requested 35 percent target remains unmet. * test(config): remove redundant diagnostic variants Keep one Decision capability-skip case and the stronger Decision-named channel override. Utility-route diagnostics remain covered by config.utility-model.test.ts: diagnoses effective utility routes for Codex. Default and keyed Decision classification remain covered by configured-model-refs.test.ts: collects string Decision roles without changing profile suffixes. Keep the positive agent-wildcard diagnostic branch; generic wildcard matching remains covered by model-runtime-policy.test.ts. Share fixture file writing without changing generated content. CI-only static oxlint, oxfmt, and diff checks pass; no tests or coverage run. Original shard 2779 lines, now 2282; 35 percent target remains unmet. * test(agents): deslop r0169 tests Share requester-turn consumption, child retention, and foreground admission fixtures. Reuse the delivery runner and common receipt expectations without removing cases or broadening transport mocks. All distinct ownership, recovery, routing, and cancellation cases remain; this shard falls short of the 35% structural reduction target. * test(agents): consolidate r0169 delivery proof layers Reduce receipt, routing, media and error tables to branch-focused fixtures and remove redundant internal call-shape assertions. Preserve independent source/recipient authority, private consumption and wake recovery checks. Remaining proof: agent-command-restart-recovery.test.ts replays suppression and retains truncated send evidence; server.private-completion.test.ts keeps delayed private admission and fences changed sources; subagent-announce-direct-delivery.test.ts retains queued input through recovery; requester-settle-dispatch keeps real pause ordering. Requester-final-attachment.test.ts and registry requester-wake e2e cover exact-once committed final attachment. attempt-timeout-prepare.test.ts owns budget firing; dispatch retains runtime failure settlement. subagent-requester-store-key.test.ts owns alias normalization. CI-only: oxfmt, plain oxlint and diff checks passed; no test or coverage execution. Cumulative lines 2765 to 1928 (30.3%); below the 35% target because the remaining dispatcher cases protect distinct authority/recovery paths. * test(slack): deslop r0170 tests Share modal metadata and message-update fixtures, compact the authorization table, and consolidate exact field assertions without removing cases. Keep routing assertions because the mocked route does not validate its inputs. Retain acknowledgment proof in the block-action, shortcut, and modal entry tests, including mismatch ordering. Keep the exact UTF-16 boundary expectation; it subsumes the surrogate, length, and URI-encoding checks. Native Stop/title authority and lifecycle cases remain unchanged. * test(slack): consolidate r0170 interaction and session fixtures Table-drive typed and legacy approval outcomes, shortcut variants, and modal lifecycle routes. Share modal field fixtures and paused real-session writers while preserving authorization failures, workspace routing, live-owner revalidation, stream fallback, and ordering assertions. Remove the interaction UTF-16 replay: truncate.test.ts keeps the surrogate-boundary regression, while the retained typed-modal rich-text case proves preview integration. Native command metadata remains covered by slash.test.ts reload-before-Stop and slash.menus.test.ts native command collision cases. Drop internal patch/query snapshots while retaining persisted owner outcomes. CI-only: formatting, plain oxlint, and diff checks passed; no test or coverage execution. Cumulative shard reduction is 2674 to 2054 lines (23.2%), below the requested 35%; the remaining session races and distinct interaction boundaries are retained. * test(slack): finish r0170 structural consolidation Unify early-return controls, workspace approval variants, and shared action-summary branches. Keep modal routing and full-state-before-truncation as separate boundary proofs. Use minimal fixtures and remove repeated tracking, payload-inventory, and error-wording assertions; retain authorization, owner-currentness, rendering, and ordering outcomes. The former typed-modal scalar replay is covered by the shared summary rows in renders confirmation; routes modal lifecycle still proves view-state traversal. Existing lifecycle and native command owner suites cover the removed capture/dispatch plumbing assertions. No obsolete production subject was found; no production or shared support files changed. CI-only validation: plain oxlint, oxfmt, and diff checks pass; no tests, coverage, or typecheck run. Original shard 2674 lines to 1738 (35.0%). This additional commit removes 316 lines: 211 nonblank lines and 105 blank separators. Previous commits remain intact. * test(cli): deslop r0171 tests Remove duplicate readiness coverage already retained in lifecycle-readiness.test.ts: Windows budgets, activated-port selection, managed start results, and restart response contracts. Keep the observed-elapsed timeout and stopped-service cases here. Reuse local status fixtures and exact assertion helpers without dropping credential, TLS, database, or lifecycle authority checks. CI-only campaign: local oxlint, oxfmt, and diff checks passed; tests and coverage intentionally not run. * test(cli): remove duplicate r0171 boundary replays The saved-pin transport replay is covered by src/gateway/probe.tls.test.ts: validates saved pin/matching pin before upgrade, and enforces pins before sending Gateway credentials. Keep status credential isolation and saved transport-policy assertions at the gather boundary. The final restart-owner revalidation is covered by lifecycle.gateway-owner.test.ts: does not send a legacy restart signal when an owner ID appears at intent write. Keep the externally supervised success path and native-action refusals here. Table the two systemd restart outcomes, remove repeated probe config snapshots, and reuse minimal credential fixtures. CI-only: oxfmt, plain oxlint, and diff checks passed; no test/build/coverage runs. * test(cli): trim r0171 fixture and mock layers Share pre-upgrade Linux and Windows restart setup without removing their distinct delivery assertions. Remove unobserved spy wrappers, constant table dimensions, duplicated fixture fields, unsafe test casts, and handwritten mock signatures where the owner type is available. Retain all credential isolation, schema refusal, native-service ownership, lock mismatch, and diagnostic cases. No further equivalent owner tests were found for those paths. CI-only: plain oxlint, oxfmt, and diff checks passed; no test, build, or coverage runs. * test(tui): deslop r0172 tests Consolidate canonical selection persistence into reloads missing initial history and remembers the canonical selected session. Preserve the chat acknowledgement assertion in passes selected-agent global scope through chat methods. Reuse local roster and history fixtures while retaining lifecycle, reset, scope, and error cases. * test(tui): consolidate r0172 behavior coverage Collapse roster, patch, metadata, stale-selection and reset variants into branch-focused tables. Keep real history and rendering checks; trim repeated fixtures and implementation assertions. Run membership ownership remains covered by tui-session-run-coordinator.test.ts (retires only unchanged history observations; keeps concurrent runs after a gap) and tui-event-handlers.test.ts (promotes the confirmed concurrent run; keeps the watchdog busy). Keep direct history membership normalization here. Snapshot replay remains covered by session-projection-conformance.test.ts (replays stale history, same-text sends, duplicates, gaps, and terminal events), session-projection.test.ts (keeps every early same-run reply behind its delayed durable prompt), and chat-log-run-state.test.ts (anchors a delayed prompt after pruning). Keep selected-session live-history rendering here. * test(tui): slim r0172 fixtures and remove inert chat stubs Use real ChatLog operations with call-through spies, simplify private harness arguments, and share fixtures for run rows and live-history replacement without changing the in-flight same-key reset ordering. Share metadata lifetime setup across stop, reconnect and failure cases. No production or support files changed. * test(harness): deslop r0173 tests Share host construction, request fixtures, and guarded question dispatch without dropping distinct authority or lifecycle cases. Keep captured-target injection in the existing local helper. The annotation durable context-engine outbox test retains generation refresh, idempotence, and exact update notification proof removed from the cron selector race. The cron race still proves exact target selection while the same-ID base row changes. Direct-admission identity is covered by tool-authority.runtime.admission.test.ts. CI-only validation: plain oxlint, oxfmt, and git diff --check. No tests or coverage executed. Conservative reduction: 2604 to 2538 lines; security and interleaving contracts prevent the requested 35% cut. * test(harness): consolidate r0173 authority proof layers Retain distinct authority, revocation, projector failure and hidden-allowlist mutation checks. Remove repeated policy-input comparisons, maintenance and active-run projection layers; share deferred calls, prepared tools and existing worker placement setup. Remaining coverage: tool-authority.runtime.continuation.test.ts proves maintenance authority without borrowed reply policy; tool-authority.runtime.admission.test.ts proves admitted publication and backend replacement; session-active-runs.test.ts scopes projected bare runs by owner. reply-tool-authority.test.ts and requester tests retain policy fields and hidden intersection distinctions. bash-tools.github-identity.test.ts retains preview env/store credential scrubbing, with host-capability.environment.test.ts retaining host wiring. Annotation retains persisted bytes, cursor and outbox results; user-turn-transcript.persistence.test.ts retains multi-source collection. CI-only: plain oxlint, oxfmt and diff check passed. No test or coverage runs. Partial PASS16 result: original 2604 to 2215 lines (-14.9%); further removal would need replacement proof for retained security, lifecycle and durability boundaries. * test(harness): consolidate r0173 branch fixtures Unify direct-input contract cases in one branch table while preserving all eight outcomes. Remove duplicated source-guard setup that never revoked its signal. Share annotation entry initialization, reuse the existing completion model builder, and replace repeated revocation conditionals with explicit actions. All distinct cases in these files remain. No test or coverage runs in CI-only mode. Plain oxlint, oxfmt and git diff --check passed. This conservative third pass reaches 2169 lines from the original2604 (-16.7%); the35% target remains unmet without removing distinct authority, lifecycle or durability proof. * test(helpers): deslop r0177 tests Factor repeated listener ownership, native exit observation, readiness fixtures, and timer settlement without deleting distinct lifecycle cases. Retain cancellation, refusal, inherited-pipe, detached-descendant, Windows shutdown, port-claim, and diagnostic-boundary proof. CI-only validation: oxfmt, plain oxlint, and diff check. * test(helpers): consolidate r0177 lifecycle proof Share readiness-clock setup and teardown; table the common terminal-classification and inherited-pipe flows. Keep distinct cancellation, admission, cleanup, redaction, and port-exclusion paths. Remove CLI timer-hook duplication of managed-child-process.drain.test.ts, whose cancellation and deadline cases assert timer release. Complete/large output remains covered by owns complete CLI JSON and diagnostic tails; inherited output remains covered by captures CLI output written after leader exit and managed-child-process.output.test.ts. Port release remains covered by openclaw-test-instance.acquisition.test.ts. Remove maximum-integer receipt formatting and round-trip self-comparison; real readiness diagnostics retain bounds and redaction assertions. CI-only: oxfmt, plain oxlint, and git diff --check passed. No tests or coverage run. Combined shard reduction is 2586 to 2137 lines (17.4%); 35% target remains unmet. * test(helpers): finish r0177 structural consolidation Reduce the original shard from 2586 to 1680 lines. Consolidate bounded retry outcomes and readiness failure categories; trim unasserted fixture diagnostics and duplicate metadata assertions without production changes. Coverage owners retained: reserves its idle port through refusal, CLI work, and stopped restarts now includes reservation connection closure; settles stalled headers/body proves readiness deadlines; allows one retry proves successful and exhausted replacement ownership; concurrent starts around an intervening stop proves queue ordering, with shared-entrypoint cancellation covering preparation ownership. Expired-body snapshot cases retain late-response immutability. Delegate inherited-output drainage to managed-child-process.output.test.ts (starts owned-tree cleanup at leader exit while a descendant holds both output pipes), with CLI capture retained in owns complete CLI JSON and diagnostic tails. Windows unverified-tree/pipe behavior remains in managed-child-process.termination.test.ts and native Job finalization in openclaw-test-instance.windows-job.test.ts; retain local blocking-termination success and sanitized failure diagnostics. CI-only checks passed: oxfmt, plain oxlint, git diff --check. No tests, coverage, or builds run. * test(cli): deslop r0176 tests Remove the narrow SIGTERM handler rejection replay: run-loop-request.test-support.ts retains 'keeps the original SIGTERM deadline after delayed intent consumption fails', which exercises the same run-loop-signals.ts failure callback and proves close plus successful exit after rejected intent consumption. This preserves the behavioral regression from openclaw#83131 (7c09dac). Simplify the triage table's invariant recorded-boot fixture and wrapped cleanup failure without removing its three scenarios or assertions. CI-only shard: oxlint, oxfmt, and diff-check passed; no test or coverage execution. Reduction is 22/2606 lines (0.84%); retained distinct authority, startup cleanup, config selection, and restart interleavings prevent the requested 35% cut. * test(cli): consolidate r0176 lifecycle fixtures Share startup settlement scaffolding across five operation/worker cases while preserving all cancellation, failure and repaired-systemd scenarios. Table password sources and trusted-dotenv drift phases; retain their distinct outcomes and authority checks. Remove internal reset/read/pin call inventories and the schema completion assertion supplied by its own mock. Actual completion outcomes remain covered by registerGatewayStartupFailureTests in run-loop-startup.test-support.ts. Keep acquisition authority-call stability, native health probe targeting, privacy, cleanup joins and observable ordering. Shrink the drain category fixture: formatGatewayDrainCounts iterates entries generically, so two categories plus totalActive exclusion and private blocker controls cover the formatter decisions without replaying thirteen category names. No obsolete subjects or additional completely redundant cases found. CI-only: oxlint, oxfmt and git diff --check pass; no tests run. Original shard 2606 lines to 2418 (-7.2%); still below 35%, with distinct auth/config-selection, cleanup, restart ownership and deadline behavior retained. * test(cli): reduce r0176 fixture duplication Centralize isolated option-test environment restoration and use the real auth resolver instead of a handwritten duplicate. Consolidate maintenance and parent-option scenarios. Keep legacy-session refusal routing here; producer preservation is covered by doctor-session-sqlite.targets.test.ts. Remote config recheck drift remains covered by pre-bootstrap.process.test.ts, and stale-boot recovery by crash-loop-recovery.test.ts. Reuse the existing joined-cleanup helper for running-loop fixtures, retain explicit exit-code checks, and replace three repeated startup fixtures with an indexed generation sequence. Remove exact internal log wording while retaining redaction, timing, lifecycle authority and ordering assertions. CI-only validation: plain oxlint, oxfmt and git diff --check passed; no test/build/coverage commands. No production or support files changed. Original shard 2606 to 2196 lines (-15.7%): still short of 35%; independent source review found the remaining apparent duplicates cover different initial/replacement, migrated/unchanged and launchd/systemd branches. * test(daemon): deslop r0179 tests Remove duplicate policy/default and legacy repair groups retained verbatim in service-policy-preservation.test.ts. Keep ordinary XML-refresh warning/activation coverage in schtasks.install.test.ts; retain one running-replacement case per runtime, arguments, and environment change instead of their desktop/unattended cross product. Reuse the stop suite's typed fixture pattern for settlement cases and share repeated transaction hooks and native assertions. Preserve distinct ownership, authority, publication, rollback, and settlement failure paths. CI-only shard: oxfmt, plain oxlint, and diff checks pass. Static cases 133 to 124; test LOC 2651 to 2396 (9.6% reduction). Below 35% because remaining cases cover distinct durability, authority, and lifecycle behavior. No tests or coverage run. * test(daemon): trim duplicated lifecycle proof in r0179 Keep receipt restoration, native cache eviction/reload, interruption, and authority checks in the receipt suite. Leave post-restore activation to systemd-install-rollback.test.ts (cached candidate inputs and retry after failed reload) and launchd.test.ts (policy and supervision after bootstrap failure). Remove task XML rendering inventory duplicated by schtasks.install.test.ts: installs Gateway services with password-free unattended boot and a batch action. Keep actual stopped/revived process state, restored files/XML, and authority guards instead of repeating internal call counts and exact command sequences. CI-only: plain oxlint, oxfmt, and diff checks passed; no tests run. Shard LOC is 2324 versus original 2651. This remains below the requested 35 percent reduction; distinct recovery and ownership cases are retained. * test(commands): consolidate r0181 fixture and proof layers Share remote RPC setup and restart scenarios, replace duplicated WizardSession emulation with wire fixtures, and consolidate Doctor preflight fixtures. Keep distinct custody, credentials, migration, restart identity and recovery boundaries. Retained owner proof: src/config/io.snapshot.test.ts preserves source paths across core-only and prepared plugin reads with a Windows home; src/wizard/session.test.ts owns wizard terminal/cancellation lifecycle; src/system-agent/setup-inference-activate.test.ts keeps working credentials and rotation after rejected replacement. CI-only validation: plain oxlint, oxfmt and git diff --check. No tests or coverage run. Structural reduction remains below the requested 35 percent target. * test: remove unused replay helpers * test: retain distinct boundary coverage and repair replay fixtures * test: preserve independent contracts in reduction batch * test: retain post-restore service startup proof
Summary
origin/main; the original conflicting SIGUSR1 fail-closed implementation was replaced by main's cleaner eager-runtime recovery path.Change Type
Scope
Linked Issue/PR
Real behavior proof
Behavior addressed: SIGTERM used a discarded async IIFE in the gateway run-loop. If lifecycle-runtime loading or restart-intent consumption rejected inside that handler, the gateway never called the stop/restart request path. This patch catches that rejection, logs it, and falls back to
request("stop", "SIGTERM").Real environment tested: Local OpenClaw source checkout on macOS, Node 24 toolchain, current branch
fix/signal-handler-catchrebased ontoorigin/mainat372c906c88.Exact steps or command run after this patch:
Step 1 -- build OpenClaw from the patched source. Step 2 -- rename the lazily-loaded lifecycle runtime module to force an import failure. Step 3 -- start the gateway and let
timeoutsend SIGTERM after 12 seconds. Step 4 -- observe the catch handler fire in the gateway log.Evidence after fix: terminal output copied below.
Fault injection proof: SIGTERM catch handler fires in real gateway
Line-by-line analysis:
[gateway] ready: Gateway fully started with 8 plugins.[gateway] signal SIGTERM received:timeoutsent SIGTERM after 12 seconds.[gateway] failed to handle SIGTERM: Error [ERR_MODULE_NOT_FOUND]: The.catch()handler fired. The dynamicimport("./cli/gateway-lifecycle.runtime.js")failed because the module was renamed. The catch logged the error viagatewayLog.error()(compiled line 569).[gateway] received SIGTERM; shutting down: The fallbackrequest("stop", "SIGTERM")in the catch handler (compiled line 570) triggered the normal shutdown path.[shutdown] completed cleanly in 73ms: Gateway shut down gracefully despite the lifecycle module being unavailable.Before this fix, the same scenario would produce an unhandled promise rejection (no
.catch()on the async IIFE), and the gateway would hang indefinitely becauserequest("stop")was never called.Compiled code verification:
Supplemental: Vitest test suite (31 tests)
Observed result after fix: The SIGTERM catch handler fires correctly when the lifecycle runtime module is unavailable, logs the error, and calls the fallback
request("stop", "SIGTERM")to shut down gracefully. The gateway exits cleanly in 73ms. Before the fix, the same error would be an unhandled rejection and the gateway would hang. All 31 tests pass.What was not tested: SIGUSR1 fault injection was not re-run after the rebase. The current branch relies on main's eager lifecycle runtime recovery for SIGUSR1, covered by the run-loop tests.
Security Impact
Compatibility / Migration
Risks and Mitigations