Skip to content

fix(subagents): a failed child's result is lost when its parent's turn already ended - #197658

Merged
obviyus merged 2 commits into
mainfrom
fix/announce-history-scope
Nov 12, 2026
Merged

obviyus merged 2 commits into
mainfrom
fix/announce-history-scope

Conversation

@obviyus

@obviyus obviyus commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

What breaks

A cron supervisor (or any turn) spawns a child that owes it a result and then ends its own turn. When the child's model call fails, the Gateway logs Subagent announce failed: Error: Plugin invocation scope is closed and the parent never hears about the failure.

The announce reads the child's history in process (chat.history through the Gateway lifecycle principal). That read asks plugins which agent harness applies, and the plugin call still runs in the parent's finished turn, whose plugin scope is already closed. A child that succeeds is not affected because its announce does not read history.

Fix

The lifecycle principal's session reads (chat.history, chat.abort, sessions.delete) now run outside the caller's plugin invocation scope, the same way #196940 handles direct announce delivery. A plugin call made there is admitted as a fresh call, like any Gateway request; nothing is granted or widened.

Thanks to @dankarization, whose #197335 work on this bug family led to the trace.

Proof

Main twice, this PR twice, plus controls through the built Gateway and openclaw cron: #197658 (comment)

@clawsweeper

clawsweeper Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Nov 12, 2026
@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. labels Nov 12, 2026
@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Proof: built Gateway (openclaw gateway run) in a secretless node:24.22.1 container, stand-in chat-completions model, isolated cron jobs added with openclaw cron add --session isolated --no-deliver --timeout-seconds 40 and run with openclaw cron run. The supervisor turn calls sessions_spawn (the child owes its result) and ends with NO_REPLY. For the failing child the stand-in returns HTTP 400.

main cc8f880704f4 vs this PR 71fd3fed1b0d:

scenario                        main run 1            main run 2            PR run 1                 PR run 2
cron, child model call fails    4x scope closed,      4x scope closed,      0 errors, parent woken   0 errors, parent woken
                                parent never woken    parent never woken    once with the failure    once with the failure
chat turn, child fails          (main run 3) 2x scope closed, no wake       -                        0 errors, one wake
cron, child succeeds            one wake              one wake              one wake                 one wake
cron, fire-and-forget child     ok 0.4 s, silent      ok 0.4 s, silent      ok 0.4 s, silent         ok 0.3 s, silent
cron, no spawn                  ok                    ok                    ok                       ok
chat turn, child succeeds       one wake              one wake              one wake                 one wake

Main log: Subagent announce failed: Error: Plugin invocation scope is closed (the announce retries and fails each time).
PR wake prompt: task: lane-fail-R1 / status: failed: LLM request rejected: stand-in child model rejected the request | 400.

Not changed here: a cron supervisor that spawns an owed child and ends with NO_REPLY still times out at 40 s on both trees, even when the child succeeds, because the child's result only reaches the parent after the cron run ends. That is a separate ordering issue in the isolated cron run.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Run lifecycle session requests outside the completed caller’s plugin scope so failed children can report their results.

Example: A cron supervisor spawns lane-fail-R1, ends its turn, and the child’s model request returns HTTP 400.

  • Before: History lookup throws “Plugin invocation scope is closed” and the parent never receives the failure.
  • After: History lookup succeeds and the parent wakes once with the child’s failure.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused repair with shipped-entry-point proof and the earlier regression request addressed; exact-head CI remains in progress.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied trace exercises the built Gateway and cron CLI with a child HTTP 400 after parent completion, showing repeated failures before the fix and exactly one parent wake afterward; the later commit changes only regression coverage, so that production proof remains applicable.
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 parent receives no failure result from an owed child after its own turn has ended.
Reason: The maintainer-authored repair restores expected result delivery with a narrow change and preserves successful and intentionally silent child behavior.

Merge readiness

✅ Ready for maintainer review

This PR fixes a demonstrated lost-result path that remains on current main. The new regression resolves the earlier review finding; no additional defects were found.

Priority: P1
Reviewed head: 6bc4c9832ff3109acd1e61b62666bc2d1ff648c6

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway lifecycle principal handles detached subagent history, abort, and cleanup requests through the existing in-process router, which invokes independently admitted plugin work.

flowchart LR
  A[Parent turn ends] --> B[Child model fails]
  B --> C[Subagent announcement]
  C --> D[Bound lifecycle request]
  D --> E[Exit completed plugin scope]
  E --> F[Gateway session dispatcher]
  F --> G[History and parent wake]
Loading

Technical review

Best possible solution:

Keep fresh plugin admission at the existing lifecycle request boundary and retain the focused released-scope history regression.

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

The supplied built-Gateway runs reproduce the failure repeatedly, and current main retains the same inherited-scope dispatch path; this read-only review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete repair: the existing lifecycle owner admits plugin work independently while retaining its established Gateway and request guards.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 68b84fa1338b.

Provenance checked

  • Lifecycle session dispatch keeps the original intent (fix: avoid disconnects and delays during hosted tool calls #146369: Detached cleanup and session operations belong to an instance-owned principal that can outlive the originating turn while retaining Gateway and commit guards.)
  • Released-scope lifecycle regression keeps the original intent (62e0b2b: Detached continuations require fresh admission after producer release, without reviving closed consumer callbacks.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 62e0b2b adds src/gateway/hosted-lifecycle-dispatch.test.ts:218 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 62e0b2b7fcf5; files: src/gateway/hosted-lifecycle-dispatch.test.ts)

PR surface

Source +5, Tests 0. Total +5 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 10 5 +5
Tests 1 10 10 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 20 15 +5

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.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A demonstrated agent workflow silently loses failed-child results after the parent turn ends.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-12T09:12:17.990Z sha 71fd3fe :: needs changes before merge. :: [P2] Commit a regression for history reads after caller scope closure

Reviewed November 12, 2026, 4:26 AM ET / 09:26 UTC (Revision 2).

@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 12, 2026
@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Nov 12, 2026
@obviyus
obviyus merged commit 4d9f782 into main Nov 12, 2026
132 checks passed
@obviyus
obviyus deleted the fix/announce-history-scope branch November 12, 2026 09:54
@obviyus

obviyus commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 4d9f782.

Copy link
Copy Markdown
Contributor

Thanks, this fix is now running in our Gateway.

I checked it against our previous installed code in isolation: adding only your test change produced the two closed-scope history-read failures; applying the production fix made all 10 tests pass. Another 42 lifecycle/completion tests and 27 Telegram naming/recovery tests passed in the combined build, followed by the full build. The new Gateway is ready and completed a real model request; its configuration was unchanged.

Commands, revisions and limits: https://github.com/dankarization/openclaw/blob/b104d5d0209577e3ccdae41a4cda8995d74ed5db/docs/assets/qa/2026-11-12/lifecycle-history-197658-d1e2a89.md

That is a local regression check plus installed-build acceptance. I’m relying on your built-Gateway cron proof for the failed-child product flow, and I’m keeping the remaining native tool/continuation reports separate.

dankarization commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this fix. I checked the merged 6bc4c983 revision: both the lifecycle dispatcher and its regression file are byte-for-byte identical to the copies in our installed, locally patched 2026.11.3 build.

I also ran a real managed-child test through that Gateway. The parent yielded at 15:56:24 UTC. The child's own transcript then records successful registered Gateway calls: exec, process, and sessions_list. The session metadata query completed 26 seconds after the yield. The child finished, and the parent received its result and continued at 15:57:06.

Sanitized execution timeline and verification scope.

This was an owner CLI-to-Gateway run, not a fresh Telegram/LDAP-user test or a native Codex-helper reproduction. It adds a successful host-tool case after yield; I am not treating it as proof that every delegation issue is fixed.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 13, 2026
…n already ended (openclaw#197658)

fix(gateway): run subagent announce Gateway calls outside the finished turn's plugin scope

When a child agent failed after its parent's turn had already ended, the completion announce's in-process Gateway calls (chat.history, and the related sessions.delete and chat.abort) ran inside the parent turn's closed plugin invocation scope. The chat.history read asks plugins which harness to use, so it failed with "Subagent announce failed: Plugin invocation scope is closed" and the parent never learned the child had failed. These in-process calls now run outside the closed scope, the same pattern as openclaw#196940, and go through normal Gateway admission, so nothing is granted or widened. No text changes.

Evidence: a built Gateway in a secretless node:24.22.1 container with a stand-in model, two runs each. With an isolated cron run whose owed child's model call returns HTTP 400, main logged the scope error four times per run and the parent was never woken; with this change there are no scope errors and the parent is woken once with the child's failure. A non-cron failing child behaved the same way. A succeeding child, a fire-and-forget child, a cron run without a spawn and a plain non-cron announce deliver exactly once on both, with no duplicate announce. A closed-scope history read in the existing closed-caller test fails on main, at net 0 test lines. Details: openclaw#197658 (comment).

Thanks @dankarization for reporting this bug family in openclaw#197335.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 14, 2026
…#197658)

Exit the completed caller's plugin invocation scope for lifecycle history,
abort and delete dispatch. Retain the captured Gateway owner, least-privilege
method dispatch, request guard and pre/post-effect current-owner checks.

Release adaptation: apply the identical production repair in the release's
server-recovery-runtime-context.ts rather than importing main's renamed
lifecycle runtime. Use the existing hosted Gateway fixture and current
PluginInstance/PluginInvocationScope APIs to prove closed-caller history
reads; no new fixture or runtime architecture. Allocate 31 regression lines.

Companion audit: no later same-path or PR-number follow-ups through
7bccde6. Recovery dispatcher, announcement
history consumer, plugin admission and live owner guards are present.
The related #196940 direct-to-channel repair is a separate sibling path,
not a prerequisite of this lifecycle read; report it for parent disposition.

Proof: 13 hosted lifecycle and recovery-context tests pass (145.94s wrapper,
20ms new regression). Type-aware oxlint, formatting and diff check pass.
Full core compiler and live cron/provider proof remain qualification work.
Baseline negative-control execution was not run.

(cherry picked from commit 4d9f782)

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit 9adc76a6976dc17213eb6d221b2b15ee93015cb0)
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]>
RomneyDa added a commit that referenced this pull request Nov 15, 2026
Preserve the existing 2026.11.5 beta line and its pending test repairs.
Repair transcript admission, terminal SQLite iterators, binary attachment
classification, detached lifecycle calls, cron late wakes and reload handover.
Carry the explicitly requested Bonjour package-integrity fix and release guidance.

Selected backports: #188055, #198309, #190242, #198860, #198011, #197658,
#197484, #197606. #198011 is the operator-required open PR head, not a
merged-main claim. Cron tests are adapted to the existing beta runtime.

(cherry picked from commit e3064bf)
(cherry picked from commit afa871c)
(cherry picked from commit 2c0ab86)
(cherry picked from commit fee19a9)
(cherry picked from commit dbb6f39)
(cherry picked from commit 4d9f782)
(cherry picked from commit 87c10f5)
(cherry picked from commit ce76ed2)

Proof: frozen parent suite passed all 7 shards (265 tests) in 274.45s.
Separate unchanged-production baseline reproduced transcript/lifecycle,
late-wake and live-receipt failures. SQLite already passed on Node 26.12.1.
Independent review found no actionable P0/P1 defects in this snapshot.
The complete beta.4 candidate and stable-profile FRV remain pending.

Co-authored-by: jalehman <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
Co-authored-by: Yun. <[email protected]>
Co-authored-by: ava-perry <[email protected]>
Co-authored-by: Alfred J Berchtold <[email protected]>
Co-authored-by: Stronggenetics <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

2 participants