Skip to content

fix(auto-reply): session-targeted cron and system-event replies fail with "Plugin invocation scope is closed" - #196750

Merged
obviyus merged 3 commits into
openclaw:mainfrom
masatohoshino:fix/session-event-delivery-closed-scope
Nov 10, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
masatohoshino:fix/session-event-delivery-closed-scope

Conversation

@masatohoshino

@masatohoshino masatohoshino commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes #196749

What Problem This Solves

Fixes: a cron job targeted at an existing conversation (sessionTarget: "session:<key>") runs its agent turn, but the reply never reaches the channel. The run records:

deliveryStatus: not-delivered
deliveryError: Error: Plugin invocation scope is closed

System events that wake a conversation go through the same delivery and fail the same way. This started with #196570.

User Impact

User impact: replies of session-targeted cron jobs and of system-event wakes reach their conversation again, on every channel. Before, the answer stayed in the session transcript and only the cron run record showed the failure.

Why This Change Was Made

Since #196570 every prepared model-runtime lease opens a plugin invocation scope, and the dispatch closes it when the turn returns. The session-event reply dispatcher drains its queue after that, still in the closed scope's async context, so the channel send fails the scope's open check. The delivery callback now leaves the finished turn's scope before routing the reply, the same shape #196700 used for automatic Activity recaps.

Where it fails
  • createPreparedModelRuntimeLease (src/agents/prepared-model-runtime.plugin-lifetime.ts) creates a PluginInvocationScope with lazy work bindings for every registry instance; before fix: plugin config edits stall busy gateways and report saved before applying #196570 the scope only covered generation-overlap instances. dispatchReplyFromConfigInner disposes the lease when dispatch returns.
  • withReplyDispatcher then drains the session-event dispatcher. Its delivery callback (prepareSessionEventDelivery in src/auto-reply/reply/session-event-delivery.ts) calls routeReply / routePreparedReply, which reach the channel through PluginInstance.run; PluginInvocationScope.lookup throws "Plugin invocation scope is closed".
  • The callback now runs inside pluginInvocationContext.exit(...).

Behavior to know: a session-event delivery made while the turn is still open now also runs outside the turn's scope. Before #196570 every lease without generation overlap ran this way.

Evidence

Tested at 786811d (baseline 9203388).

Matrix, real homeserver

Why Matrix: it is a supported channel whose server runs locally, so the real Matrix plugin can talk to a real homeserver without any account or paid service. No other channel was run.

How each side ran:

  • Each side was a clean build of its commit. QA Lab's Matrix live lane started a disposable tuwunel 1.9.3 homeserver (ghcr.io/matrix-construct/tuwunel:v1.9.3, server name matrix-qa.test) in a local container, registered synthetic driver, bot and observer users, and ran an isolated Gateway with the real Matrix plugin as the bot. No qa-channel was used.
  • The model was QA Lab's mock OpenAI provider (mock-openai/gpt-5.6-luna), not a real model. No provider keys were used.
  • The scenario was the same on both sides:
    • The driver user mentions the bot in a room ("Reply with only this exact marker: MATRIX_QA_FIRST_…") and waits for the bot's reply.
    • It adds a cron job with sessionTarget: "session:<that room's session key>", wakeMode: "now", a one-shot schedule 3 seconds ahead and the message "Reply with only this exact marker: MATRIX_QA_CRON_…".
    • It reads the run's record from cron.runs and lists the room's messages as a separate observer account sees them through homeserver sync.
  • Both runs exit 0 (wall time 38 s before, 28 s after). The scenario only records what it observed; the verdict is the cron run record and whether the cron marker is in the room.

Text captures: Matrix before, Matrix after.

Before (baseline):

cron.runs record:
  completionStatus: failed
  delivered: false
  deliveryStatus: not-delivered
  deliveryError: Failed to route reply to matrix: Plugin invocation scope is closed

room messages seen by a separate Matrix observer account (homeserver sync):
  inbound  qa-driver (user): @openclaw Reply with only this exact marker: MATRIX_QA_FIRST_A84642AD
  outbound qa-sut (OpenClaw bot): MATRIX_QA_FIRST_A84642AD

cron reply in the room: no

After (head), same steps:

cron.runs record:
  completionStatus: succeeded
  delivered: true
  deliveryStatus: delivered

room messages seen by a separate Matrix observer account (homeserver sync):
  inbound  qa-driver (user): @openclaw Reply with only this exact marker: MATRIX_QA_FIRST_68112913
  outbound qa-sut (OpenClaw bot): MATRIX_QA_FIRST_68112913
  outbound qa-sut (OpenClaw bot): MATRIX_QA_CRON_B952F88E

cron reply in the room: yes

On both sides the cron run's summary holds the cron marker: the model answered, and only the delivery differs. After the fix, the Gateway log shows the Matrix send right after the run (setting pendingEvent status to sent, then Got remote echo for event). Before the fix, the Gateway log has no send between the job being added and shutdown.

QA Lab qa-channel

How each side ran:

  • A before/after harness built each side from its own clean checkout (with the private QA Lab entry points) and ran the same script on both, each in a fresh isolated home.
  • The script runs one QA Lab suite scenario with the qa-channel transport and the QA mock OpenAI provider (no provider keys): it talks once in a group conversation, waits for the first reply, then adds a cron job with sessionTarget: "session:<that session key>", wakeMode: "now", a one-shot schedule 3 seconds ahead and payload: { kind: "agentTurn", message: "reply exactly: QA-CRON-REPLY-OK" }.
  • It waits for the run's deliveryStatus in cron.runs and for the marker reply among the channel's outbound messages, and prints both.

Text captures: qa-channel before, qa-channel after.

Before (baseline):

step: delivers a session-targeted cron reply to its conversation
  status: pass
  details: {"deliveryStatus":"not-delivered","deliveryError":"Error: Plugin invocation scope is closed","eventReplyInChannel":false}

After (head), same steps:

step: delivers a session-targeted cron reply to its conversation
  status: pass
  details: {"deliveryStatus":"delivered","deliveryError":null,"eventReplyInChannel":true}

The step status only records that the observation was made on both sides; the verdict is the harness exit code and deliveryStatus.

Regression test "routes a session-event reply after the finished turn's plugin scope closed" in src/auto-reply/reply/session-event-delivery.test.ts fails on the base ("Plugin invocation scope is closed") and passes with the fix. It prepares the delivery, then delivers a final reply inside a turn scope that was released first, as the reply dispatcher does after the lease closed.

Checks at the head:

  • src/auto-reply/reply/session-event-delivery.test.ts, src/auto-reply/reply/session-event-handoff.test.ts and src/plugins/plugin-invocation-scope.test.ts pass (32 tests).
  • src/gateway/server.cron.test.ts: 15 of 16 pass in the kept run at the head ("persists settled failure-alert outcomes for cron get and list" fails at server.cron.test.ts:936, getActiveGatewayRootWorkCount() 1, expected 0), and it fails the same way with session-event-delivery.ts reverted to the base; two other runs at the head on the same host passed 16 of 16, so the failure is timing-dependent and not caused by this change.
  • The core typecheck (pnpm tsgo:core) and the messaging test typecheck (test/tsconfig/tsconfig.core.test.messaging.json) pass. Lint and format pass on the touched files.
  • No vi.mock was added. Docs already describe this delivery (docs/automation/cron-jobs/delivery.md); the fix restores it.

Local review: autoreview (Codex gpt-6.1-sol, medium), base 9203388 to head 786811d, priority P0–P1: scoped-clean, no remaining findings.

Against the base, scripts/check-test-lines-ratchet.mts reports Test lines OK: 6628983; ceiling: 6628992; slack: 9. The base had 9 lines of slack, so config/test-lines-allocations/session-event-delivery-closed-scope.txt grants exactly the 31 lines of the new regression test; the shared scalar is unchanged.

Test file Added cost
src/auto-reply/reply/session-event-delivery.test.ts new file, 1 case, 31 lines, no module mocks (one vi.spyOn); file run 2.69 s with --maxWorkers=1 (Vitest duration; import and transform take 86% of it, the test itself 13 ms); CI seconds: 14.25 s Vitest duration in checks-node-changed-2 (the file alone, 1 test; transform 80%, import 12%)

CI on this head, two red checks, neither caused by this change:

  • checks-fast-baseline-ratchets (test-lines): Test lines: 6632319; ceiling: 6632301; over by: 18; net delta: +31. The base CI compared against, 543917c, is already over its own ceiling by the same 18 lines: scripts/check-test-lines-ratchet.mts run on that commit alone prints Test lines: 6632288; ceiling: 6632270; over by: 18; net delta: 0. Tree is over the ceiling; this change does not add test lines. This change adds 31 test lines and grants exactly 31, so it neither adds to nor pays off that inherited debt.
  • Security High (process-exec-boundary): the CodeQL analysis finished and the job failed while uploading its results, with API rate limit exceeded for installation. The other five Security High jobs pass.

Not covered:

  • Only Matrix was run against a real server, and both proofs use the QA mock provider, not a real model. Other channels were not run. The fix is in core delivery code that every channel's session-event reply goes through. Before the fix, the same failure (Failed to route reply to discord: Plugin invocation scope is closed) also appeared with a Discord transport stand-in, at main 401a1de (slightly before the base); that stand-in is not a live Discord.
  • The other core callers of routeReply / routePreparedReply were checked by reading only: the dispatch's own routed sends, ACP delivery and the /fork, reset-hook and private-command replies are awaited before the dispatch returns, and follow-up turns run from a mailbox drain that already leaves the plugin scope. Only the session-event reply dispatcher drains after the turn's scope closed.
  • The system-event wake path was reproduced before the fix, but the before/after harness above exercises the cron path only. Both go through the same delivery callback.

@clawsweeper

clawsweeper Bot commented Nov 10, 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.

@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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Routes session-event replies outside the completed turn’s plugin invocation scope.

Example: A session-targeted cron job replies in a Matrix room.

  • Before: The answer remains in the transcript, and delivery fails with “Plugin invocation scope is closed.”
  • After: The observer sees MATRIX_QA_CRON_B952F88E in the room, and cron records delivered.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful minimal repair with inspected real-transport proof and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Inspected Matrix captures exercise the changed delivery callback through an isolated Gateway, real Matrix plugin, local homeserver, session-targeted cron, and independent observer: delivery fails before and succeeds after. The production fix is unchanged at the reviewed head. The disclosed mock model isolates delivery; other channels and an after-fix system-event wake were not separately exercised.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Scheduled and system-event answers remain in the conversation transcript without reaching the external chat.
Reason: Restores documented delivery through the existing owner without new settings, APIs, or persisted formats.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a current delivery regression with a minimal shared-owner fix and convincing Matrix before/after evidence; no actionable findings remain.

Priority: P1
Reviewed head: 8b2106d085bce192476d81d1931404a9b93418d4

Before merge

None.

Findings

None.

Agent review details

How this fits together

Cron and system events enter ordinary session admission, produce agent replies, and drain through shared routing into the destination channel plugin.

flowchart TD
  A[Cron or system event] --> B[Session admission]
  B --> C[Agent turn]
  C --> D[Reply dispatcher]
  D --> E[Session event delivery]
  E --> F[Shared reply routing]
  F --> G[Channel plugin]
Loading

Technical review

Best possible solution:

Keep the shared session-event delivery callback outside the completed turn’s scope while retaining existing final-effect authority checks.

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

Source establishes the closed-scope delivery path, and inspected contributor captures reproduce its failure through a real Matrix transport; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete repair at the shared delivery owner: it removes inherited turn lifetime without extending revoked callbacks, adding retries, or duplicating routing.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 47b0ce478c81.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3d2f7ca adds src/auto-reply/reply/session-event-delivery.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3d2f7ca06b26; files: src/auto-reply/reply/session-event-delivery.ts)

PR surface

Source +4, Tests -1. Total +3 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 2 +4
Tests 1 26 27 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 32 29 +3

Preflight source

Source stale. 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: same_root_cause
Canonical: #196749
Summary: This PR implements the repair for the paired delivery report; the Activity recap repair concerns a separate caller.

Members:

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A current regression prevents session-targeted scheduled replies from reaching their channel despite successful agent execution.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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-10T16:51:12.595Z sha 786811d :: needs real behavior proof before merge. :: none

Reviewed November 10, 2026, 12:43 PM ET / 17:43 UTC (Revision 2).

@masatohoshino

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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 rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 10, 2026
@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

Proof on a built Gateway (node 24.22.1, Docker, no secrets), with a scripted local model and a stand-in Telegram Bot API recording every sendMessage. One Telegram DM conversation, then: a cron job with sessionTarget: "session:agent:main:telegram:direct:123" run via openclaw cron run, a openclaw system event --session-key … --mode now wake, and an isolated announce cron job as a control.

main 0354036 (x2) this fix 786811d (x2)
normal chat turn reply delivered delivered
session-targeted cron reply not delivered; run records deliveryError: "Failed to route reply to telegram: Plugin invocation scope is closed" delivered once
system-event wake reply not delivered; Gateway logs the same scope error delivered once
isolated cron (control) delivered delivered

Both runs on each side matched. plugin-invocation-scope.test.ts passes on main and on this branch, so closed scopes still throw.

Tests: I moved the regression into the existing closed-scope test in session-event-config-readmission.test.ts. It fails on main with Plugin invocation scope is closed and passes here. I also tidied a few branches in that file so test lines go down overall (net -1), and removed the new test file and the allocation file. I merged main into the branch; the production change is unchanged (6 lines added, 2 removed).

@obviyus
obviyus merged commit 8569bd9 into openclaw:main Nov 10, 2026
126 of 127 checks passed
@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

Landed in 8569bd9. Thanks @masatohoshino. Session-targeted cron and system-event replies are delivered again.

obviyus added a commit that referenced this pull request Nov 11, 2026
…"Plugin invocation scope is closed" (#196940)

fix(subagents): deliver direct subagent announcements outside the finished turn's plugin scope

A finished subagent's announcement started from the child's completed turn and kept that turn's plugin invocation scope, which is released when the turn ends. The channel target lookup and send then failed with "Plugin invocation scope is closed", so the result never reached the chat after its retries. sendSubagentAnnounceDirectly now runs inside pluginInvocationContext.exit, the same pattern as #196750 and #196700. ChuLaiTheGreat found this path in #171315 and #178125; #178125 carries the same fix inside a feature.

Evidence: a built Gateway on node:24.22.1 in secretless Docker with a stand-in model and a stand-in Telegram Bot API recording every sendMessage, two runs each. On main a DM subagent result was never delivered and each run logged 4 "Plugin invocation scope is closed" errors. With this change it is delivered once with no scope errors. A normal reply, a group subagent completion, the provider-failure notice, a steered follow-up answered NO_REPLY and a session-targeted cron reply are each delivered once on both, and plugin-invocation-scope tests pass on both, so closed scopes still throw. The two QA Smoke scenarios from #196899 could not run locally because the QA Telegram transport fails before any scenario starts on main and this branch alike.

Closes #196899. Thanks @amittell for the report and @ChuLaiTheGreat for finding the path.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 11, 2026
…with "Plugin invocation scope is closed" (openclaw#196750)

fix(reply): deliver session-targeted cron and system-event replies outside a closed plugin scope

Replies of cron jobs targeted at a conversation (sessionTarget "session:<key>") and replies to system-event wakes were never delivered. Delivery ran inside the triggering run's plugin invocation scope, which had already closed, so the channel send failed with "Plugin invocation scope is closed" and the run recorded a delivery error. Session-event delivery now runs outside that scope with pluginInvocationContext.exit, the same pattern as openclaw#196700 and openclaw#191126.

Evidence: a built Gateway on node 24.22.1 in secretless Docker with a scripted local model and a stand-in Telegram Bot API recording every sendMessage, two runs each. On main a session-targeted cron run (openclaw cron run) and an openclaw system event --mode now wake delivered nothing, and the run recorded "Failed to route reply to telegram: Plugin invocation scope is closed". With this change both replies are delivered once. A normal chat turn and an isolated announce cron job deliver on both, and plugin-invocation-scope tests pass on both, so closed scopes still throw. Details: openclaw#196750 (comment).

Closes openclaw#196749. Thanks @masatohoshino.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 11, 2026
…"Plugin invocation scope is closed" (openclaw#196940)

fix(subagents): deliver direct subagent announcements outside the finished turn's plugin scope

A finished subagent's announcement started from the child's completed turn and kept that turn's plugin invocation scope, which is released when the turn ends. The channel target lookup and send then failed with "Plugin invocation scope is closed", so the result never reached the chat after its retries. sendSubagentAnnounceDirectly now runs inside pluginInvocationContext.exit, the same pattern as openclaw#196750 and openclaw#196700. ChuLaiTheGreat found this path in openclaw#171315 and openclaw#178125; openclaw#178125 carries the same fix inside a feature.

Evidence: a built Gateway on node:24.22.1 in secretless Docker with a stand-in model and a stand-in Telegram Bot API recording every sendMessage, two runs each. On main a DM subagent result was never delivered and each run logged 4 "Plugin invocation scope is closed" errors. With this change it is delivered once with no scope errors. A normal reply, a group subagent completion, the provider-failure notice, a steered follow-up answered NO_REPLY and a session-targeted cron reply are each delivered once on both, and plugin-invocation-scope tests pass on both, so closed scopes still throw. The two QA Smoke scenarios from openclaw#196899 could not run locally because the QA Telegram transport fails before any scenario starts on main and this branch alike.

Closes openclaw#196899. Thanks @amittell for the report and @ChuLaiTheGreat for finding the path.

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

(cherry picked from commit 8569bd9)

Adapt regressions to the release event-delivery harness. Final and block replies remain routable after producer teardown while the closed producer callback stays fenced. Two red regressions; 28 consumer and scope tests pass with the fix. Independent local review omitted by explicit release-owner instruction.

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
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]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 16, 2026
…with "Plugin invocation scope is closed" (openclaw#196750)

Adapt to the 2026.11.4 release owners and fixtures; preserve current safety and timeout contracts. Source inspected by release owner. Independent local review explicitly waived by Dallin; CI qualification remains pending.

(cherry picked from commit 8569bd9)

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

Labels

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]: Replies of cron jobs targeted at a conversation are never delivered ("Plugin invocation scope is closed")

2 participants