Repository navigation
fix(gateway): automatic Activity recaps fail after Codex runs with a closed plugin scope - #196700
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR schedules automatic run-end Activity recaps outside the finished run’s plugin invocation scope. Example: A Codex chat turn finishes with Activity recap generation enabled.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness✅ Ready for maintainer review Keep open: this collaborator-authored PR fixes a current Activity recap failure with a focused change and convincing reported Gateway proof; no actionable introduced defects were found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Gateway recap service consumes session lifecycle events, reads bounded transcript excerpts, calls the utility model, and publishes persisted Activity recaps. flowchart LR
A[Codex turn completes] --> B[Gateway lifecycle event]
B --> C[Exit finished plugin context]
C --> D[Existing recap queue]
D --> E[Session owner authorization]
E --> F[Utility model request]
F --> G[Persist and publish recap]
Technical reviewBest possible solution: Retain the existing recap owner and exit only the finished run’s plugin context before scheduling its independent background work. Do we have a high-confidence way to reproduce the issue? The source establishes closed-scope inheritance through warm run-end scheduling, and the author reports repeatable built-Gateway failures and passing controls; this read-only review did not execute target code. Is this the best way to solve the issue? The change repairs the lifecycle boundary at the existing scheduler without weakening released-scope guards or changing recap authorization, routing, or storage. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d290127ec675. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +2, Tests 0. Total +2 across 2 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:
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 Reviewed November 10, 2026, 9:27 AM ET / 14:27 UTC. |
|
Landed in 4ec97ef. |
…with "Plugin invocation scope is closed" (#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 #196700 and #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: #196750 (comment). Closes #196749. Thanks @masatohoshino. Co-authored-by: Ayaan Zaidi <[email protected]>
…"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]>
…closed plugin scope (openclaw#196700) fix(gateway): run the automatic activity recap outside the finished run's plugin scope When a Codex run ended, the automatic Activity recap never sent its request and the recap stayed at "updating". The Codex runtime emits the run-end event inside the run's plugin invocation scope, and the recap service scheduled the recap from that event without leaving the scope (since openclaw#169622). Since openclaw#184243, new prepared-model scopes take the caller's scope as their parent, so when the recap checked utility model auth after the run had finished, it hit "Plugin invocation scope is closed", and its own error handling hit the same closed scope. The run-end recap is now scheduled inside pluginInvocationContext.exit(...), the same pattern openclaw#191126 used for openclaw#191123. The RPC and archive recap paths are unchanged. Evidence: a built Gateway in Docker with the real Codex app-server and a stand-in endpoint. On main, two Codex runs sent no automatic recap request and stayed at "updating"; with debug logging the Gateway logged "Activity recap background work failed {"error":"Plugin invocation scope is closed"}". With this change two Codex runs each sent one recap request and the summary became current. The RPC-requested recap works on both, plain OpenAI runs recap on both, and plugin-invocation-scope.test.ts passes on both, so genuinely closed scopes still throw. Co-authored-by: Ayaan Zaidi <[email protected]>
…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]>
…"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]>
… 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]>
… 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]>
… 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
With the Codex runtime, the automatic Activity recap that runs when a turn ends never sends its model request. It fails with
Plugin invocation scope is closedand the recap stays at "updating". A recap requested throughsessions.activitySummary.ensure(Control UI) still works, and so does the run-end recap on OpenClaw's own runtime with the plain OpenAI provider.Seen on main while proving #196641.
Root cause
The Codex runtime emits the run-end lifecycle event inside the run's plugin invocation scope.
SessionActivitySummaryService.handleEventschedules the recap synchronously from that event when the session is already tracked (warm path added in #169622), so the recap's async work inherits the run's scope. By the time the recap checks utility auth, the run has finished and released that scope. Since #184243, prepared-model leases build their scope withparent: pluginInvocationContext.getStore(), and the constructor'sparent.lookupthrows on the closed parent:The recap's error classification then hits the same closed scope (
classifyProviderFailoverSignalWithPlugin→PluginInstance.run→lookup), so it never even publishes "unavailable".Fix
Schedule the run-end recap with
pluginInvocationContext.exit(...), the same pattern #191126 used for host-owned cleanup that outlives a closed caller scope (#191123). Only the plugin invocation context is dropped; async-work tracking, the ensure RPC path and archive handling are unchanged. Callbacks captured by the finished run stay revoked.Evidence
Built Gateway (
dist/entry.js) in Docker on node 24.22.1 with the bundled Codex plugin and the real Codex app-server. The OpenAI provider stays on the official route with a synthetic key; a local stand-in Responses endpoint is reached throughHTTPS_PROXY. Each run sends one chat turn, waits for the automatic recap without calling any recap RPC, then requests a recap on a second session (chat.inject+sessions.activitySummary.ensure).806e06ccCodex #1 (debug log)updating(stuck)updating(stuck)current,STANDIN_OKcurrent,STANDIN_OKcurrentcurrentMain debug log:
Activity recap background work failed {"error":"Plugin invocation scope is closed"}; the candidate debug run has no such line. Closed-scope control:src/plugins/plugin-invocation-scope.test.ts(which assertsPlugin invocation scope is closedfor released scopes) passes 7/7 on both builds.Regression: the existing context-only terminal test now emits the run-end event inside a real plugin scope that is released immediately, and the model preparation enters that plugin. It fails on main (
expected "vi.fn()" to be called 2 times, but got 1 times) and passes here. Net test lines: 0 (four assertions implied by other checks were dropped).