Skip to content

fix(agents): plugin agent_end hooks fail after a turn that called dispatch_action - #197990

Merged
roboclaw-bot merged 1 commit into
openclaw:mainfrom
etzelm:pc/i197940
Nov 14, 2026
Merged

roboclaw-bot merged 1 commit into
openclaw:mainfrom
etzelm:pc/i197940

Conversation

@etzelm

@etzelm etzelm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Closes #197940

Related: #197947 is an open draft for the same issue; this PR carries the regression test and Gateway proof.

What Problem This Solves

Fixes: every plugin agent_end handler fails with Plugin invocation scope is closed after an embedded turn in which the model called a tool through Tool Search dispatch_action.

User Impact

User impact: plugins that keep memory, logs or telemetry at agent_end (including bundled skill-workshop) run again after Tool Search dispatch turns, which is the default tool surface. Turns that call tools directly already worked and behave the same.

Risk: low. Only the bundled asynchronous agent_end path changes ordering, and only when a message loader is bound. A slow transcript read now delays the end of the run instead of losing every handler.

Why This Change Was Made

A turn with nested tool activity (only dispatch_action records it) hands agent_end its messages through a loader that reads that activity back from the transcript store. runAgentEndSideEffectsAsync started hook delivery in a detached launcher, so it returned before the read finished. The run then released its prepared plugin invocation scope, and when the read completed, each handler's admission hit the closed scope and threw. Turns without nested activity got their messages after one microtask, before the release, which is why direct tool calls were fine.

runAgentEndSideEffectsAsync now awaits the message hydration (new internal startAgentHarnessAgentEndHook) and then starts handlers without waiting for them, so they are admitted while the turn's scope is still open. Handler execution stays fire-and-forget with unref timeouts, as before. The closed-scope check, caller context, the SDK-exported runAgentHarnessAgentEndHook and awaitAgentHarnessAgentEndHook, and the deprecated synchronous runAgentEndSideEffects are unchanged.

Cost: on a dispatch turn with an agent_end subscriber, finalization now waits for that one transcript read, which previously ran right after it. before_agent_finalize already awaits the same read in the foreground. No read happens when no plugin subscribes.

config/test-mock-exports-baseline.txt loses the agent-end-side-effects.test.ts entry because that mock now carries a // mock-isolation: reason; the mock export ratchet requires the stale entry to be removed.

Evidence

Regression test, real plugin admission (src/agents/harness/lifecycle-hook-helpers.test.ts): a real plugin instance, a retained PluginInvocationScope and a real hook runner with a wrapped agent_end handler. The message loader resolves after a macrotask, and the scope is released as soon as runAgentEndSideEffectsAsync returns, as the embedded run does.

  • Base 4efd662cc2c with only the new test: 1 failed, 9 passed. The handler is refused with [hooks] agent_end handler from agent-end-probe failed: Plugin invocation scope is closed.
  • Head: passes.

Tests on head (pnpm test <files>, 18 files, 312 tests passed): harness lifecycle helpers, agent-end side effects, plugin invocation scope, embedded-runner nested tool activity, phase lifecycle, stream finalize/settle/prepare, execution and session settle, attempt result, Tool Search executor, code-mode continuation and bridge lifecycle, and CLI agent_end paths. The suggested vitest.unit.config.ts invocation matches none of these files, so they were run through pnpm test, which routes them to the agents and plugins configs.

pnpm check:changed --base 4efd662cc2c: typecheck (core and core tests), lint, format, mock export ratchet, import cycles and the other lanes pass. The dead export scan reports src/gateway/trusted-proxy-git-coauthor.ts: resolveTrustedProxyGitCoauthor, which this change does not touch; pnpm deadcode:exports reports the same on clean 4efd662cc2c.

Real Gateway run: one fresh isolated Gateway per row (/v1/chat/completions, loopback, local OpenAI-compatible model). Two agent_end handlers were registered: a fixture plugin and bundled skill-workshop.

base-dispatch  turn=dispatch tools=tool_search,session_status,dispatch_action(openclaw:core:session_status) agent_end=FAILED handler_failures=2
head-dispatch  turn=dispatch tools=tool_search,session_status,dispatch_action(openclaw:core:session_status) agent_end=ok handler_failures=0
base-direct    turn=direct tools=session_status agent_end=ok handler_failures=0
head-direct    turn=direct tools=session_status agent_end=ok handler_failures=0

The dispatch rows use Tool Search at its default. The direct rows set tools.toolSearch: false and call session_status directly. On base, both handlers log failed: Plugin invocation scope is closed. On head there are no handler failure lines, and the fixture records agent_end with 8 messages. skill-workshop does not log on success, so on head its result is shown only by the absence of a failure line.

Turns that called dispatch_action hydrate nested tool activity for agent_end with an off-thread transcript read. The bundled path started that hydration in a detached launcher, so the run released its plugin invocation scope first and every handler was refused with "Plugin invocation scope is closed".

runAgentEndSideEffectsAsync now awaits hydration before it resolves and then starts handlers without waiting for them, so they are admitted while the scope is open.
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Nov 13, 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. 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. 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. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR finishes agent_end message hydration before releasing the turn’s plugin scope while keeping handler completion asynchronous.

Example: A Gateway turn calls dispatch_action(openclaw:core:session_status).

  • Before: The reply succeeds, but both registered agent_end handlers fail with “Plugin invocation scope is closed.”
  • After: Message hydration completes before scope release, and the fixture agent_end handler receives eight messages without handler failures.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct repair supported by real Gateway output, a relevant admission regression, and passing exact-head CI.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body supplies real isolated Gateway chat-completions output with a local model, showing dispatch_action terminal-hook failure on base and successful fixture delivery on head, alongside successful direct-tool controls; bundled skill-workshop success is evidenced only by absence of its prior failure.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Plugins miss end-of-turn processing after otherwise successful turns that use dispatch_action.
Reason: Restoring documented terminal-hook delivery has clear value and preserves the existing preparation-versus-background-execution contract.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it repairs a current plugin lifecycle bug with a focused change, a meaningful regression test, supplied Gateway proof, and passing exact-head CI; no actionable introduced defect was found.

Priority: P1
Reviewed head: e836c57c0b9f76a627d69b0445a84e5cb25dcfaf

Before merge

None.

Findings

None.

Agent review details

How this fits together

The agent harness prepares completed-turn facts and transcript messages for plugin hooks, then dispatches handlers through the existing plugin admission owner.

flowchart TD
  A[Embedded turn completes] --> B[Prepare completed turn]
  B --> C[Hydrate transcript messages]
  C --> D[Admit plugin handlers]
  D --> E[Release turn scope]
  D --> F[Handlers finish asynchronously]
Loading

Technical review

Best possible solution:

Keep message preparation within the existing turn scope, then admit handlers through the existing hook runner without waiting for their completion.

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

Current source exposes the delayed-hydration admission failure, and the contributor supplies base/head Gateway results plus a base-red/head-green regression; this read-only review executed no target code.

Is this the best way to solve the issue?

This is a focused repair at the existing lifecycle owner: the internal preparation helper preserves public launcher semantics, existing admission checks, and asynchronous handler completion without adding state or configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 28d20f9532f4.

Provenance checked

  • Awaited agent-end preparation keeps the original intent (f9dfa9a: Move transcript-anchor preparation off the Gateway thread while retaining the turn lease and keeping interactive plugin handlers nonblocking, as explained in perf(sessions): read transcript anchors and readiness through the history reader #164747.)
  • Completed-turn context keeps the original intent (7d69dfc: Resolve the final transcript anchor once under the turn lease and expose it to plugin reviewers, as explained in feat(plugins): agent_end hooks receive the completed turn to fork #191599.)
  • Deferred hook-message hydration keeps the original intent (3a8abe6: Keep nested-tool payloads in transcript storage until hook delivery to reduce retained run state; this PR retains lazy loading and changes when finalization joins it.)
  • Consumed loader lifetime keeps the original intent (42d9921: Release loader closures before awaiting long-running hooks so pending handlers do not retain completed attempts; the new preparation helper returns after launching handlers.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 42d9921 adds src/agents/harness/lifecycle-hook-helpers.ts:78 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 42d9921d3332; files: src/agents/harness/lifecycle-hook-helpers.ts)
  • Ayaan Zaidi: Raw commit 7d69dfc adds src/agents/harness/agent-end-side-effects.ts:195 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7d69dfc63c7f; files: src/agents/harness/agent-end-side-effects.ts)
  • Vincent Koc: Raw commit 34e45ec adds src/agents/harness/lifecycle-hook-helpers.ts:68 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 34e45ecfcc79; files: src/agents/harness/lifecycle-hook-helpers.ts)

PR surface

Source +24, Tests +44, Other -1. Total +67 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 26 2 +24
Tests 2 48 4 +44
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 5 74 7 +67

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.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #197940
Summary: This PR and the draft alternative address the same delayed-hydration lifetime defect tracked by the linked issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Default Tool Search dispatch turns can skip every agent_end plugin handler, breaking memory retention and other post-turn workflows despite successfully delivering the reply.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • 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.

Reviewed November 12, 2026, 7:48 PM ET / November 13, 2026, 00:48 UTC.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via squash.

steipete added a commit that referenced this pull request Nov 14, 2026
…198732)

* fix(subagents): preserve completion hooks after the requester turn ends

Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in #197990.

Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation.

* fix(plugins): share post-turn scope exit below the agent layer
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…claw#197990)

Hydrate agent_end messages before foreground finalization releases the turn's plugin invocation scope, then admit handlers while keeping their completion asynchronous. Preserve existing SDK dispatch semantics and unref timeouts.

Validation: independent isolated exact-head focused tests passed (2 files, 19 tests); complete-range independent review and PR-simplify found no actionable changes; exact-head ClawSweeper had no findings. Real Gateway base/head dispatch and direct-tool controls reuse the contributor-supplied exact-head E2E evidence, not a newly executed maintainer Gateway run.

Co-authored-by: Mitchell Etzel <[email protected]>
Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…penclaw#198732)

* fix(subagents): preserve completion hooks after the requester turn ends

Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in openclaw#197990.

Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation.

* fix(plugins): share post-turn scope exit below the agent layer
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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: S 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.

[Bug]: Every plugin agent_end handler fails with "Plugin invocation scope is closed" after a turn that called dispatch_action

2 participants