Repository navigation
refactor(plugins): released invocation scopes stop routing instead of refusing late calls - #199618
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
@clawsweeper review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesReleased plugin invocation scopes now defer late calls to instance admission, replacing caller-specific scope exits. Example: The child agent:main:subagent:late-cleanup completes after its requesting turn releases its plugin scope.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: the prior blocker is fixed, and the shared lifecycle repair has no remaining actionable findings. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherInvocation scopes route agent work to exact plugin instances; those instances own execution admission, retained consumers, reload settlement, and cleanup. flowchart TD
A[Agent turn] --> B[Invocation scope]
B --> C[Live scope binding]
B --> D[Released scope fallback]
C --> E[Plugin instance admission]
D --> E
E --> F[Hook or deferred operation]
Technical reviewBest possible solution: Let released scopes stop routing while PluginInstance retains admission and consumer-revocation ownership, and remove the superseded caller exits. Do we have a high-confidence way to reproduce the issue? Current-main lookup and run expose the closed-scope rejection, and the supplied regressions report base failure and head success; no target code was executed during this review. Is this the best way to solve the issue? Changing the existing scope owner removes the recurring failure mechanism more completely than adding further caller-specific exits, while explicit consumer closure remains independently enforced. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against db05f080df0d. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -61, Tests -34, Docs -3, Other -281. Total -379 across 27 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 15, 2026, 8:49 AM ET / 13:49 UTC (Revision 2). |
… refusing late calls A released plugin invocation scope no longer throws "Plugin invocation scope is closed". It stops routing, so a late call takes ordinary counted admission on the instance and is refused only while that instance retires; reload drains and generation-overlap custody keep their scope routing. Removes the closed state and the per-hook scope-exit workarounds it required. Co-authored-by: obviyus <[email protected]>
f347687 to
29d2c90
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Landed in 7789e95.
|
… 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]>
Release adaptation: select only the applicable QA request-plan endpoint, streaming response and scenario caller from 7420e1f. Drop the test portion for suite-provider-artifacts, an absent later architecture, while retaining oversized input, plan order and cursor regressions. Baseline tests reproduced missing endpoint HTTP404; the existing bounded consumer also rejects the full16MiB+ log. Lifecycle exits are already covered by #199618; CI hosted dispatch is already covered by the current planner; unrelated visual changes are excluded. (cherry picked from commit 7420e1f) Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vincentkoc <[email protected]> (cherry picked from commit a51c7703f420a2ff3b94d15ffb49b52e57d55b3c)
… inventory has retired" (#207774) ## Problem After a plugin reload, the activity recap for a run that was in flight fails with: ``` Activity recap deferred error="Plugin inventory has retired; begin a new plugin operation." retryScheduled=false ``` A production deployment logged this 8 times. Its logs contain only 2 plugin replacements: one hot config reload and one `plugins.reload` call. Every failure came 0.4 to 110 s after one of them, on two different builds. The recap then shows "unavailable" and does not retry until the next activity. No PR in the deploy window caused this: the recap has always inherited the run's plugin generation, and these were the first reloads with runs in flight. **Users affected:** every Gateway user with activity recaps (a utility model is configured) who reloads plugins or changes config that replaces plugins while a run is active. One-shot CLI runs do not create recaps. ## Cause The run-end lifecycle event starts the recap synchronously when the session is already tracked: `handleEvent` → `requestInBackground` → `schedule` → `pump` → `trackAsyncWork(() => run(state))` (`src/gateway/session-activity-summaries.ts`). That work runs in the ending run's async context, so it inherits the run's plugin runtime generation frame. The reload has already retired that generation's plugin inventory. The recap's utility completion (`runUtilityCompletion` → `runIsolatedCompletionOwned` → `acquireAgentRunPreparedModelRuntime` with `deriveRuntimePluginSelections`) resolves the scoped, retired metadata snapshot (`prepared-model-runtime-lease.ts`). It then builds a new prepared generation on it, and `ownPreparedPluginGeneration` → `retainPluginCache` throws `PluginInventoryRetiredError`. The delayed pump path already runs detached (`runInDetachedAsyncContext`). Only the immediate path inherited the run's frame. ## Fix The recap runs outside the finished run's generation scopes: ```ts trackAsyncWork(() => runOutsidePreparedModelRuntimePluginGenerationScope(() => runOutsidePluginRuntimeGenerationScope(() => run(state)), ), ) ``` Other work that outlives the turn that started it already uses this pattern: session maintenance (`session-maintenance/run.ts`), sticky model writes (`sticky-model-selection.ts`) and simple-completion acquisition (`simple-completion-runtime.ts`). The recap now admits on the current plugin inventory. What the recap leaves, all intended: - the plugin runtime generation frame and the prepared-model-runtime generation scope; - the remote catalog snapshot, so current config is not resolved against the old generation's catalog; - the plugin invocation scope. #199618 removed this exit for the recap (#196700) and kept the generation-scope exits on purpose; this change is one of those generation-scope exits. It keeps connection-work tracking (#196831), because `trackAsyncWork` stays the outer call. Authority is not involved: the recap decides through `createActivitySummaryAuthority` and passes `operatorAuthority` explicitly. ## Known open class (not changed here) `runIsolatedCompletionOwned` does not leave the caller's generation scope, but `acquireSimpleCompletionModelWithSelection` does. Other utility callers (titles, progress narrator, composer prediction, plugin `runtime.llm`) usually run inside a live run whose generation is still retained, so the inherited pin is correct for them. In the production logs, all 8 lines with this error are activity recap lines; no other subsystem logs it. If another subsystem starts to log it, move the exit into `runIsolatedCompletionOwned`. ## Evidence | Claim | Tier | Base (`8cbcc8fa27d6`) | Head | |---|---|---|---| | Real Gateway, isolated state under `env -i`, keyless local OpenAI-compatible stand-in for the main and utility models. Steps: an installed local plugin that the run does not use; `sessions.activitySummary.ensure`; `chat.send` with a 15 s streamed reply; mid-run, a config edit to the plugin's entry (`config change detected` → `Plugin replacement applied` → `config hot reload applied`). Same script on both trees. | dist-nodts | `Activity recap deferred` ×1, error `Plugin inventory has retired; begin a new plugin operation.`; 0 recap requests; recap state `unavailable` | 0 deferrals; 1 recap request; recap state `current` with text | | Recap after a reload, with the run-end event inside the run's open lease and generation frame, then lease disposal and retirement (new test in `session-activity-summaries.plugin-lifetime.test.ts`: real plugin fixture, real prepared runtime lease, local completion server, no model mocks) | vitest-source | fails: `Recap 1.`, 1 model request (the second recap never reaches the model) | passes: `Recap 2.`, 2 model requests | | Mechanism: stack from a scratch probe on base | vitest-source | `retainPluginCache` ← `ownPreparedPluginGeneration` ← `createPreparedPluginGeneration` ← `prepareWorkspaceBuildGroup` ← `buildSnapshotBatch` | n/a | | Archive recap after the calling plugin scope closes (existing test, same file) | vitest-source | passes | passes | | Recap suites (`session-activity-summaries*.test.ts`, `session-activity-summary-*.test.ts`) | vitest-source | n/a | pass: 6 files, 61 tests | | `pnpm check:changed`: format, lint, core typecheck, core test typecheck, import cycles, boundaries | n/a | n/a | pass. The only failure is the dead export scan, on 2 files this PR does not touch (`src/agents/command/types.ts`, `src/plugins/native-module-require.ts`); main has it too. | The behavior benchmark is not applicable. Its one-shot route (`openclaw agent --local`) never creates the recap service, which only the Gateway constructs (`server-runtime-subscriptions.ts`). The change does not touch any agent turn request. ## Net lines Source +8/−1 (`session-activity-summaries.ts`). Test +130 (one regression test). Co-authored-by: Ayaan Zaidi <[email protected]>
… inventory has retired" (openclaw#207774) ## Problem After a plugin reload, the activity recap for a run that was in flight fails with: ``` Activity recap deferred error="Plugin inventory has retired; begin a new plugin operation." retryScheduled=false ``` A production deployment logged this 8 times. Its logs contain only 2 plugin replacements: one hot config reload and one `plugins.reload` call. Every failure came 0.4 to 110 s after one of them, on two different builds. The recap then shows "unavailable" and does not retry until the next activity. No PR in the deploy window caused this: the recap has always inherited the run's plugin generation, and these were the first reloads with runs in flight. **Users affected:** every Gateway user with activity recaps (a utility model is configured) who reloads plugins or changes config that replaces plugins while a run is active. One-shot CLI runs do not create recaps. ## Cause The run-end lifecycle event starts the recap synchronously when the session is already tracked: `handleEvent` → `requestInBackground` → `schedule` → `pump` → `trackAsyncWork(() => run(state))` (`src/gateway/session-activity-summaries.ts`). That work runs in the ending run's async context, so it inherits the run's plugin runtime generation frame. The reload has already retired that generation's plugin inventory. The recap's utility completion (`runUtilityCompletion` → `runIsolatedCompletionOwned` → `acquireAgentRunPreparedModelRuntime` with `deriveRuntimePluginSelections`) resolves the scoped, retired metadata snapshot (`prepared-model-runtime-lease.ts`). It then builds a new prepared generation on it, and `ownPreparedPluginGeneration` → `retainPluginCache` throws `PluginInventoryRetiredError`. The delayed pump path already runs detached (`runInDetachedAsyncContext`). Only the immediate path inherited the run's frame. ## Fix The recap runs outside the finished run's generation scopes: ```ts trackAsyncWork(() => runOutsidePreparedModelRuntimePluginGenerationScope(() => runOutsidePluginRuntimeGenerationScope(() => run(state)), ), ) ``` Other work that outlives the turn that started it already uses this pattern: session maintenance (`session-maintenance/run.ts`), sticky model writes (`sticky-model-selection.ts`) and simple-completion acquisition (`simple-completion-runtime.ts`). The recap now admits on the current plugin inventory. What the recap leaves, all intended: - the plugin runtime generation frame and the prepared-model-runtime generation scope; - the remote catalog snapshot, so current config is not resolved against the old generation's catalog; - the plugin invocation scope. openclaw#199618 removed this exit for the recap (openclaw#196700) and kept the generation-scope exits on purpose; this change is one of those generation-scope exits. It keeps connection-work tracking (openclaw#196831), because `trackAsyncWork` stays the outer call. Authority is not involved: the recap decides through `createActivitySummaryAuthority` and passes `operatorAuthority` explicitly. ## Known open class (not changed here) `runIsolatedCompletionOwned` does not leave the caller's generation scope, but `acquireSimpleCompletionModelWithSelection` does. Other utility callers (titles, progress narrator, composer prediction, plugin `runtime.llm`) usually run inside a live run whose generation is still retained, so the inherited pin is correct for them. In the production logs, all 8 lines with this error are activity recap lines; no other subsystem logs it. If another subsystem starts to log it, move the exit into `runIsolatedCompletionOwned`. ## Evidence | Claim | Tier | Base (`cf08ad382f76`) | Head | |---|---|---|---| | Real Gateway, isolated state under `env -i`, keyless local OpenAI-compatible stand-in for the main and utility models. Steps: an installed local plugin that the run does not use; `sessions.activitySummary.ensure`; `chat.send` with a 15 s streamed reply; mid-run, a config edit to the plugin's entry (`config change detected` → `Plugin replacement applied` → `config hot reload applied`). Same script on both trees. | dist-nodts | `Activity recap deferred` ×1, error `Plugin inventory has retired; begin a new plugin operation.`; 0 recap requests; recap state `unavailable` | 0 deferrals; 1 recap request; recap state `current` with text | | Recap after a reload, with the run-end event inside the run's open lease and generation frame, then lease disposal and retirement (new test in `session-activity-summaries.plugin-lifetime.test.ts`: real plugin fixture, real prepared runtime lease, local completion server, no model mocks) | vitest-source | fails: `Recap 1.`, 1 model request (the second recap never reaches the model) | passes: `Recap 2.`, 2 model requests | | Mechanism: stack from a scratch probe on base | vitest-source | `retainPluginCache` ← `ownPreparedPluginGeneration` ← `createPreparedPluginGeneration` ← `prepareWorkspaceBuildGroup` ← `buildSnapshotBatch` | n/a | | Archive recap after the calling plugin scope closes (existing test, same file) | vitest-source | passes | passes | | Recap suites (`session-activity-summaries*.test.ts`, `session-activity-summary-*.test.ts`) | vitest-source | n/a | pass: 6 files, 61 tests | | `pnpm check:changed`: format, lint, core typecheck, core test typecheck, import cycles, boundaries | n/a | n/a | pass. The only failure is the dead export scan, on 2 files this PR does not touch (`src/agents/command/types.ts`, `src/plugins/native-module-require.ts`); main has it too. | The behavior benchmark is not applicable. Its one-shot route (`openclaw agent --local`) never creates the recap service, which only the Gateway constructs (`server-runtime-subscriptions.ts`). The change does not touch any agent turn request. ## Net lines Source +8/−1 (`session-activity-summaries.ts`). Test +130 (one regression test). Co-authored-by: Ayaan Zaidi <[email protected]>
… inventory has retired" (#207774) ## Problem After a plugin reload, the activity recap for a run that was in flight fails with: ``` Activity recap deferred error="Plugin inventory has retired; begin a new plugin operation." retryScheduled=false ``` A production deployment logged this 8 times. Its logs contain only 2 plugin replacements: one hot config reload and one `plugins.reload` call. Every failure came 0.4 to 110 s after one of them, on two different builds. The recap then shows "unavailable" and does not retry until the next activity. No PR in the deploy window caused this: the recap has always inherited the run's plugin generation, and these were the first reloads with runs in flight. **Users affected:** every Gateway user with activity recaps (a utility model is configured) who reloads plugins or changes config that replaces plugins while a run is active. One-shot CLI runs do not create recaps. ## Cause The run-end lifecycle event starts the recap synchronously when the session is already tracked: `handleEvent` → `requestInBackground` → `schedule` → `pump` → `trackAsyncWork(() => run(state))` (`src/gateway/session-activity-summaries.ts`). That work runs in the ending run's async context, so it inherits the run's plugin runtime generation frame. The reload has already retired that generation's plugin inventory. The recap's utility completion (`runUtilityCompletion` → `runIsolatedCompletionOwned` → `acquireAgentRunPreparedModelRuntime` with `deriveRuntimePluginSelections`) resolves the scoped, retired metadata snapshot (`prepared-model-runtime-lease.ts`). It then builds a new prepared generation on it, and `ownPreparedPluginGeneration` → `retainPluginCache` throws `PluginInventoryRetiredError`. The delayed pump path already runs detached (`runInDetachedAsyncContext`). Only the immediate path inherited the run's frame. ## Fix The recap runs outside the finished run's generation scopes: ```ts trackAsyncWork(() => runOutsidePreparedModelRuntimePluginGenerationScope(() => runOutsidePluginRuntimeGenerationScope(() => run(state)), ), ) ``` Other work that outlives the turn that started it already uses this pattern: session maintenance (`session-maintenance/run.ts`), sticky model writes (`sticky-model-selection.ts`) and simple-completion acquisition (`simple-completion-runtime.ts`). The recap now admits on the current plugin inventory. What the recap leaves, all intended: - the plugin runtime generation frame and the prepared-model-runtime generation scope; - the remote catalog snapshot, so current config is not resolved against the old generation's catalog; - the plugin invocation scope. #199618 removed this exit for the recap (#196700) and kept the generation-scope exits on purpose; this change is one of those generation-scope exits. It keeps connection-work tracking (#196831), because `trackAsyncWork` stays the outer call. Authority is not involved: the recap decides through `createActivitySummaryAuthority` and passes `operatorAuthority` explicitly. ## Known open class (not changed here) `runIsolatedCompletionOwned` does not leave the caller's generation scope, but `acquireSimpleCompletionModelWithSelection` does. Other utility callers (titles, progress narrator, composer prediction, plugin `runtime.llm`) usually run inside a live run whose generation is still retained, so the inherited pin is correct for them. In the production logs, all 8 lines with this error are activity recap lines; no other subsystem logs it. If another subsystem starts to log it, move the exit into `runIsolatedCompletionOwned`. ## Evidence | Claim | Tier | Base (`8cbcc8fa27d6`) | Head | |---|---|---|---| | Real Gateway, isolated state under `env -i`, keyless local OpenAI-compatible stand-in for the main and utility models. Steps: an installed local plugin that the run does not use; `sessions.activitySummary.ensure`; `chat.send` with a 15 s streamed reply; mid-run, a config edit to the plugin's entry (`config change detected` → `Plugin replacement applied` → `config hot reload applied`). Same script on both trees. | dist-nodts | `Activity recap deferred` ×1, error `Plugin inventory has retired; begin a new plugin operation.`; 0 recap requests; recap state `unavailable` | 0 deferrals; 1 recap request; recap state `current` with text | | Recap after a reload, with the run-end event inside the run's open lease and generation frame, then lease disposal and retirement (new test in `session-activity-summaries.plugin-lifetime.test.ts`: real plugin fixture, real prepared runtime lease, local completion server, no model mocks) | vitest-source | fails: `Recap 1.`, 1 model request (the second recap never reaches the model) | passes: `Recap 2.`, 2 model requests | | Mechanism: stack from a scratch probe on base | vitest-source | `retainPluginCache` ← `ownPreparedPluginGeneration` ← `createPreparedPluginGeneration` ← `prepareWorkspaceBuildGroup` ← `buildSnapshotBatch` | n/a | | Archive recap after the calling plugin scope closes (existing test, same file) | vitest-source | passes | passes | | Recap suites (`session-activity-summaries*.test.ts`, `session-activity-summary-*.test.ts`) | vitest-source | n/a | pass: 6 files, 61 tests | | `pnpm check:changed`: format, lint, core typecheck, core test typecheck, import cycles, boundaries | n/a | n/a | pass. The only failure is the dead export scan, on 2 files this PR does not touch (`src/agents/command/types.ts`, `src/plugins/native-module-require.ts`); main has it too. | The behavior benchmark is not applicable. Its one-shot route (`openclaw agent --local`) never creates the recap service, which only the Gateway constructs (`server-runtime-subscriptions.ts`). The change does not touch any agent turn request. ## Net lines Source +8/−1 (`session-activity-summaries.ts`). Test +130 (one regression test). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 86900aa) Co-authored-by: RomneyDa <[email protected]>
… inventory has retired" (#207774) ## Problem After a plugin reload, the activity recap for a run that was in flight fails with: ``` Activity recap deferred error="Plugin inventory has retired; begin a new plugin operation." retryScheduled=false ``` A production deployment logged this 8 times. Its logs contain only 2 plugin replacements: one hot config reload and one `plugins.reload` call. Every failure came 0.4 to 110 s after one of them, on two different builds. The recap then shows "unavailable" and does not retry until the next activity. No PR in the deploy window caused this: the recap has always inherited the run's plugin generation, and these were the first reloads with runs in flight. **Users affected:** every Gateway user with activity recaps (a utility model is configured) who reloads plugins or changes config that replaces plugins while a run is active. One-shot CLI runs do not create recaps. ## Cause The run-end lifecycle event starts the recap synchronously when the session is already tracked: `handleEvent` → `requestInBackground` → `schedule` → `pump` → `trackAsyncWork(() => run(state))` (`src/gateway/session-activity-summaries.ts`). That work runs in the ending run's async context, so it inherits the run's plugin runtime generation frame. The reload has already retired that generation's plugin inventory. The recap's utility completion (`runUtilityCompletion` → `runIsolatedCompletionOwned` → `acquireAgentRunPreparedModelRuntime` with `deriveRuntimePluginSelections`) resolves the scoped, retired metadata snapshot (`prepared-model-runtime-lease.ts`). It then builds a new prepared generation on it, and `ownPreparedPluginGeneration` → `retainPluginCache` throws `PluginInventoryRetiredError`. The delayed pump path already runs detached (`runInDetachedAsyncContext`). Only the immediate path inherited the run's frame. ## Fix The recap runs outside the finished run's generation scopes: ```ts trackAsyncWork(() => runOutsidePreparedModelRuntimePluginGenerationScope(() => runOutsidePluginRuntimeGenerationScope(() => run(state)), ), ) ``` Other work that outlives the turn that started it already uses this pattern: session maintenance (`session-maintenance/run.ts`), sticky model writes (`sticky-model-selection.ts`) and simple-completion acquisition (`simple-completion-runtime.ts`). The recap now admits on the current plugin inventory. What the recap leaves, all intended: - the plugin runtime generation frame and the prepared-model-runtime generation scope; - the remote catalog snapshot, so current config is not resolved against the old generation's catalog; - the plugin invocation scope. #199618 removed this exit for the recap (#196700) and kept the generation-scope exits on purpose; this change is one of those generation-scope exits. It keeps connection-work tracking (#196831), because `trackAsyncWork` stays the outer call. Authority is not involved: the recap decides through `createActivitySummaryAuthority` and passes `operatorAuthority` explicitly. ## Known open class (not changed here) `runIsolatedCompletionOwned` does not leave the caller's generation scope, but `acquireSimpleCompletionModelWithSelection` does. Other utility callers (titles, progress narrator, composer prediction, plugin `runtime.llm`) usually run inside a live run whose generation is still retained, so the inherited pin is correct for them. In the production logs, all 8 lines with this error are activity recap lines; no other subsystem logs it. If another subsystem starts to log it, move the exit into `runIsolatedCompletionOwned`. ## Evidence | Claim | Tier | Base (`8cbcc8fa27d6`) | Head | |---|---|---|---| | Real Gateway, isolated state under `env -i`, keyless local OpenAI-compatible stand-in for the main and utility models. Steps: an installed local plugin that the run does not use; `sessions.activitySummary.ensure`; `chat.send` with a 15 s streamed reply; mid-run, a config edit to the plugin's entry (`config change detected` → `Plugin replacement applied` → `config hot reload applied`). Same script on both trees. | dist-nodts | `Activity recap deferred` ×1, error `Plugin inventory has retired; begin a new plugin operation.`; 0 recap requests; recap state `unavailable` | 0 deferrals; 1 recap request; recap state `current` with text | | Recap after a reload, with the run-end event inside the run's open lease and generation frame, then lease disposal and retirement (new test in `session-activity-summaries.plugin-lifetime.test.ts`: real plugin fixture, real prepared runtime lease, local completion server, no model mocks) | vitest-source | fails: `Recap 1.`, 1 model request (the second recap never reaches the model) | passes: `Recap 2.`, 2 model requests | | Mechanism: stack from a scratch probe on base | vitest-source | `retainPluginCache` ← `ownPreparedPluginGeneration` ← `createPreparedPluginGeneration` ← `prepareWorkspaceBuildGroup` ← `buildSnapshotBatch` | n/a | | Archive recap after the calling plugin scope closes (existing test, same file) | vitest-source | passes | passes | | Recap suites (`session-activity-summaries*.test.ts`, `session-activity-summary-*.test.ts`) | vitest-source | n/a | pass: 6 files, 61 tests | | `pnpm check:changed`: format, lint, core typecheck, core test typecheck, import cycles, boundaries | n/a | n/a | pass. The only failure is the dead export scan, on 2 files this PR does not touch (`src/agents/command/types.ts`, `src/plugins/native-module-require.ts`); main has it too. | The behavior benchmark is not applicable. Its one-shot route (`openclaw agent --local`) never creates the recap service, which only the Gateway constructs (`server-runtime-subscriptions.ts`). The change does not touch any agent turn request. ## Net lines Source +8/−1 (`session-activity-summaries.ts`). Test +130 (one regression test). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 86900aa) Follow-ups: 2d0f744 fix: keep automatic Activity recaps on the session provider (#208460) [not selected for this narrow backport] Co-authored-by: RomneyDa <[email protected]>
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(...)orrunOutsidePluginInvocationScope), 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:context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed(phaseregistry)subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.runFix
A released scope stops routing. It no longer refuses calls.
PluginInvocationScope.lookupreturnsundefinedafter release.runruns 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.assertOpenand both "closed" errors are removed. The cleanup scope (runPluginCleanupScope) and the teardown views frombeginCleanupgive up teardown authority when their owner finishes; later calls take ordinary admission.generationOverlapturns keep their old generation.prepared-model-runtime.plugin-drain.test.tspasses unchanged.subagent_ended/subagent_delivery_targetscope exit inhook-dispatch-replacement.tsrunAccessPolicyscope exit ingateway-access-policy-registration.tsstartAgentHarnessAgentEndHook(agent_end evidence was loaded early only to finish inside the scope)session-activity-summaries.tsserver-lifecycle-runtime-context.tsserver-lifecycle-close.tshook-post-turn-measure.ts,access-policy-scope-measure.ts) and the duplicatesubagent-announce-origin.hook-scope.test.tsrunInDetachedAsyncContextfor auth publication (fix(agents): auth refresh fails after its plugin call ends #197960) and the generation-scope exits. They also detach other async state, not only the plugin scope.docs/plugins/sdk-runtime.mdnow 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
runIdthreaded 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
5d5ca9d2ba8c)onSubagentEndedafter the requesting turn's scope is released (new regression test,subagent-registry-context-cleanup.test.ts)Plugin invocation scope is closedsubagent_endedhook after the requesting turn's scope is released (same file)Plugin invocation scope is closedagent_endhandler after the turn's scope is released (lifecycle-hook-helpers.test.ts, with the #197990 helper removed)generationOverlapcustody (prepared-model-runtime.plugin-drain.test.ts, unchanged)rg 'Plugin (invocation|cleanup) scope is closed' src scripts test extensions docsocx src -- gateway run, isolated HOME, stand-in Responses model, a workspace plugin with asubagent_endedhook and a context engine withonSubagentEnded). One turn spawns a child that answers 15 s after the parent turn ends.agent_end×3pnpm tsgo:core,pnpm check:test-types,pnpm tsgo:scripts, oxlint and oxfmt on the changed filesocx build --dtsscripts/release-check.ts)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
agentroute 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.tsfailed 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.