Skip to content

fix: finish Gateway shutdown after plugin scope retirement - #198652

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-plugin-runtime-close-watchdog-20260919
Nov 14, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-plugin-runtime-close-watchdog-20260919

Conversation

@steipete

@steipete steipete commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Gateway shutdown refusing memory and channel cleanup when it inherits an expired plugin invocation scope, and waiting for the hard deadline after cleanup has already rejected and settled.

User Impact

Memory, channel transports, and shutdown hooks close under the Gateway lifecycle owner. A settled cleanup failure wakes the run loop and bounds any remaining process tail after CLI finalization, without using SIGKILL. Pending persistence and genuinely retained resources still keep their hard deadline. Restart markers and transcripts keep their existing settlement order.

Why This Change Was Made

The close boundary cleared the current plugin call but left its enclosing invocation scope attached. Clear both at the owner boundary, including the full close prelude and hooks. The cleanup owner now notifies the loop when an asynchronous rejection settles, replacing a later failure check that could not wake the sleeping loop.

Deadline retirement follows retained resources rather than a failed result. Generic failed status 1 uses default SIGUSR2 after the existing one-second settled tail watchdog; SIGTERM would hide failure from an on-failure supervisor. Special supervisor exit codes remain report-only. Production code grows by 7 lines (+29/-22) to carry the owner notification and failure signal; no new config, cache, or schema.

Evidence

  • Three regressions fail on exact base 0b7cd35571e7cbfb7544305379c7c4a1dac26b03: expired-scope memory/four-channel close; settled failed close with a leaked handle; rejected log cleanup leaving the loop asleep. The fixed real Gateway case also verifies all four shutdown hooks.
  • 214 focused CLI tests and 4 Gateway memory/channel/hook tests pass. Process tests preserve pending-cleanup deadlines, special exit codes, restart custody, and finalizer durability.
  • Build passed. pnpm check:changed --base HEAD completed; an introduced unused test import was removed and core typecheck re-passed. All remaining failures are the two exact-parent dead exports listed below. Targeted lint/format and other selected guards passed.
  • Independent Codex autoreview: no actionable P0–P2 findings on the final candidate. Its earlier failure-status finding was fixed before the final review.
  • Built Gateway pilot on synthetic 35 GiB SQLite, 5,026 stored sessions, and 62,000 workspace files / 1.1 GB: 16 streaming chats, 2 active exec children, 4 cron runs, 4 pending RPCs, and four mock channel transports. Baseline and candidate exited naturally after SIGTERM, stopped all four transports, left no child alive, and persisted/resumed all 18 sessions exactly once with durable partial text/tool receipts and cron outcomes. Pilot stop times were 3.14 s / 2.60 s; differing host load means this is not a speedup claim.

The serial campaign passed all 12 runs: two baseline A/A controls, then five interleaved baseline/candidate pairs. Every run exited naturally with code 0, stopped all four mock transports, settled both children, recovered all 18 sessions exactly once, and preserved partial text, tool receipts, and cron outcomes.

Metric (five samples per head) Baseline median / p95 Candidate median / p95 Baseline range Candidate range
SIGTERM to process exit 2,073 / 2,796 ms 2,053 / 2,190 ms 1,379–2,796 ms 1,636–2,190 ms
Gateway-close owner 1,021 / 1,484 ms 1,096 / 1,324 ms 131–1,484 ms 215–1,324 ms
Main-thread CPU after signal 750 / 997 ms 632 / 737 ms 693–997 ms 626–737 ms
Sampled main-isolate allocation 158.6 / 166.5 MiB 155.0 / 171.1 MiB 156.3–166.5 MiB 153.8–171.1 MiB

p95 is the nearest-rank maximum with n=5. The A/A controls were 9,353 / 2,409 ms to exit, 1,432 / 813 ms CPU, and 176.5 / 172.4 MiB sampled allocation. That spread prevents a speedup claim. The Gateway-close median increased 74 ms and allocation p95 increased 4.6 MiB; both are reported rather than hidden. The measured benefit is removal of the reproduced failure/idle-wait paths, with normal loaded durability preserved.

Rerunnable workload: TMPDIR=<safe-synthetic-root> node --import ./scripts/tsx.mjs scripts/perf/shutdown-loaded-measure.ts --checkout <built-head> --fixture <shutdown-loaded-fixture-root> --output <new-directory> --channel-transports --allocation. Allocation sampling uses 32 KiB intervals and includes collected objects. CPU/allocation cover the main isolate, not workers or children. A separate candidate CPU profile was captured with --cpu-profile.

Evidence limits: mock transports exercise the real registry/channel lifecycle, not the bundled Discord/Slack/ClickClack/X adapters. The expired-scope injection establishes a failure mechanism, not the provenance of a production signal's scope. Large-fixture storage is a temporary APFS sparse image on APFS; Linux/btrfs proof is unavailable because the configured remote provider could not allocate without its credential.

Existing main regressions

Both unused-export failures reproduce on the clean exact parent with node --import tsx scripts/check-deadcode-exports.mts; neither file is changed here:

Export Introducing commit / PR
prepareTranscriptFactsBackfillStress 72f90dde293d5e99d6852545a0d7b2590a5aa56e / #194519
MAX_COMPLETION_CLAIMS c1ca2d7b14c6de87939ec0e1207808cf1816d434 / #197471

The existing pending-close process test also contained a main-thread file-write interception made ineffective by the worker logging migration in 5358d05ca2c1dc8c8a4770704a03c1a8f89b5f78 (#197586). That assertion failed on the exact parent. This PR removes the obsolete interception while keeping the real pending-close watchdog test; accepted logging writes remain covered by the finalization process suite.

Run the full Gateway close under its lifecycle owner's plugin context so an
expired requesting invocation cannot refuse memory, channel or hook cleanup.
Wake the loop when retained cleanup rejects, and retire deadline watchdogs
once no resource remains pending. Bound generic failed exits after CLI
finalization with a failure signal while preserving special supervisor codes.

Keep pending persistence, retained resources, restart markers and transcript
settlement with their existing owners. Add regressions that fail on the base
and extend the loaded shutdown fixture with four synthetic channel transports.
@clawsweeper

clawsweeper Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T04:46:22.467544Z 6d09b0c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes scripts Repository scripts size: M labels Nov 14, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review the final code at 6d09b0c, especially Gateway-owned cleanup context, settled-rejection wake-up, and preserving supervisor failure semantics after finalizers settle. Pending or retained resources must keep their hard deadline. The PR body records red-on-base regressions, focused proof, and exact-parent global-check failures.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR clears inherited plugin scopes during Gateway cleanup, wakes the run loop on settled rejection, and bounds failed exits while preserving supervisor failure status.

Example: Gateway close inherits a released plugin invocation scope containing Discord, Slack, ClickClack, and X registrations.

  • Before: The expired scope can refuse memory, transport, and shutdown-hook cleanup.
  • After: Cleanup runs under the Gateway owner and closes those resources independently of the expired request.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is focused and source-consistent, with useful regressions; direct behavior evidence for the changed fault paths remains incomplete.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Gateway stop can refuse plugin cleanup or remain alive until its hard deadline after cleanup has already rejected.
Reason: The maintainer-authored direction restores existing cleanup contracts; the added --channel-transports flag belongs only to the internal measurement script.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses shutdown failures still present on fetched main; the pinned diff has no actionable code findings.

Priority: P2
Reviewed head: 6d09b0c94b64ddea5a115090b559ae5c71d6070f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted terminal output or logs from the shipped Gateway demonstrating expired-scope cleanup and a settled rejection with a leaked handle exiting with failure after finalization; redact IPs, keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

The Gateway lifecycle closes plugin resources and persistence, then the CLI run loop retires watchdogs and finalizes process output before exit.

flowchart TD
  A[Stop or restart request] --> B[Gateway close owner]
  B --> C[Memory channels and hooks]
  C --> D[Run loop cleanup]
  D --> E[Pending work hard deadline]
  D --> F[Settled CLI finalization]
  F --> G[Natural exit or tail signal]
Loading

Technical review

Best possible solution:

Keep shutdown authority in the existing Gateway close owner and distinguish settled failure from retained work in the existing cleanup owner.

Do we have a high-confidence way to reproduce the issue?

Source inspection confirms the expired-scope lookup failure and sleeping-loop rejection path; the author reports three exact-base regressions, but this read-only review executed no target code.

Is this the best way to solve the issue?

The patch is a focused repair using existing lifecycle and exit owners, preserves retained-work handling, and introduces no competing cleanup mechanism.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8c70f579729d.

Provenance checked

  • Gateway cleanup invocation context keeps the original intent (d9837a5: Core shutdown persistence must retain Gateway authority independently of the initiating plugin invocation.)
  • Failed-cleanup deadline retirement changes intended behavior with a stated reason (9344233: The earlier shutdown design retained the hard watchdog for failed cleanup; this PR explicitly separates settled rejection from retained resources.)
  • Settled exit signaling changes intended behavior with a stated reason (d6c8ad3: Nonzero supervisor restart instructions must survive leaked-handle handling; the PR narrowly adds failure signaling for generic cleanup status 1.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit d9837a5 adds src/gateway/server-lifecycle-close.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d9837a55eb7d; files: src/gateway/server-lifecycle-close.ts)

PR surface

Source +7, Tests +57, Docs +5, Other +34. Total +103 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 29 22 +7
Tests 5 85 28 +57
Docs 1 7 2 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 35 1 +34
Total 12 156 53 +103

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +29/-22; tests and support +85/-28 The small production increase uses existing owners; coverage exercises expired-scope cleanup, rejection wake-up, and failed process-tail termination.

Labels

Label changes:

  • add P2: This repairs bounded Gateway lifecycle failures with clear source mechanisms, without evidence of a widespread urgent regression.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This repairs bounded Gateway lifecycle failures with clear source mechanisms, without evidence of a widespread urgent regression.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 13, 2026, 11:52 PM ET / November 14, 2026, 04:52 UTC.

@steipete
steipete enabled auto-merge (squash) November 14, 2026 05:09
@steipete
steipete merged commit ca2bf94 into main Nov 14, 2026
161 of 165 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-plugin-runtime-close-watchdog-20260919 branch November 14, 2026 05:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…w#198652)

Run the full Gateway close under its lifecycle owner's plugin context so an
expired requesting invocation cannot refuse memory, channel or hook cleanup.
Wake the loop when retained cleanup rejects, and retire deadline watchdogs
once no resource remains pending. Bound generic failed exits after CLI
finalization with a failure signal while preserving special supervisor codes.

Keep pending persistence, retained resources, restart markers and transcript
settlement with their existing owners. Add regressions that fail on the base
and extend the loaded shutdown fixture with four synthetic channel transports.
obviyus added a commit that referenced this pull request Nov 15, 2026
… refusing late calls (#199618)

## Problem

A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended.

Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example #196700, #196750, #197658, #197990, #198652, #198732 and #198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches:

- 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`)
- 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run`

## Fix

A released scope stops routing. It no longer refuses calls.

- `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before.
- `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission.
- A released scope drops its instance views, so a stale async context does not retain them.
- Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged.
- The per-hook workarounds are reverted:
  - #198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts`
  - #198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts`
  - #197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope)
  - #196700: activity recap scope exit in `session-activity-summaries.ts`
  - #196750: session-event delivery scope exit
  - #197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts`
  - #198652: Gateway close scope exit in `server-lifecycle-close.ts`
  - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts`
- Kept on purpose: `runInDetachedAsyncContext` for auth publication (#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope.
- `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs.

This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks.

## Proof

| Claim | Tier | Base (`5d5ca9d2ba8c`) | Head |
|---|---|---|---|
| Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once |
| `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted |
| `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the #197990 helper removed) | vitest-source | — | passes |
| Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) |
| All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) |
| `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 |
| Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 |
| `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass |
| `ocx build --dts` | full | — | pass |
| Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries |

The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines.

Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter.

## Net lines

`28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
… refusing late calls (openclaw#199618)

## Problem

A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended.

Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example openclaw#196700, openclaw#196750, openclaw#197658, openclaw#197990, openclaw#198652, openclaw#198732 and openclaw#198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches:

- 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`)
- 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run`

## Fix

A released scope stops routing. It no longer refuses calls.

- `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before.
- `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission.
- A released scope drops its instance views, so a stale async context does not retain them.
- Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged.
- The per-hook workarounds are reverted:
  - openclaw#198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts`
  - openclaw#198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts`
  - openclaw#197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope)
  - openclaw#196700: activity recap scope exit in `session-activity-summaries.ts`
  - openclaw#196750: session-event delivery scope exit
  - openclaw#197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts`
  - openclaw#198652: Gateway close scope exit in `server-lifecycle-close.ts`
  - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts`
- Kept on purpose: `runInDetachedAsyncContext` for auth publication (openclaw#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope.
- `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs.

This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks.

## Proof

| Claim | Tier | Base (`5a640d63290f`) | Head |
|---|---|---|---|
| Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once |
| `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted |
| `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the openclaw#197990 helper removed) | vitest-source | — | passes |
| Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) |
| All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) |
| `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 |
| Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 |
| `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass |
| `ocx build --dts` | full | — | pass |
| Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries |

The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines.

Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter.

## Net lines

`28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464.

Co-authored-by: Ayaan Zaidi <[email protected]>
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
…w#198652)

(cherry picked from commit ca2bf94)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a070447b7ead57d4d6167abd98775858fe5698ab)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant