Skip to content

refactor(plugins): released invocation scopes stop routing instead of refusing late calls - #199618

Merged
obviyus merged 1 commit into
mainfrom
refactor/plugin-explicit-run-context
Nov 15, 2026
Merged

obviyus merged 1 commit into
mainfrom
refactor/plugin-explicit-run-context

Conversation

@obviyus

@obviyus obviyus commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

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.

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.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling plugin: file-transfer size: L labels Nov 15, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Released 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.

  • Before: Registry acquisition can throw “Plugin invocation scope is closed,” preventing completion notification.
  • After: The live plugin instance admits the notification; retired instances and explicitly closed consumers remain unavailable.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch resolves the prior finding and has no new actionable defects, with confidence limited by harness-level regression proof and unfinished CI.
Proof confidence 🦐 gold shrimp (3/6) This collaborator-authored PR is outside the contributor proof gate; its reported Gateway control covers late completion compatibility, while the changed failure path is exercised by in-process regressions.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Post-turn hooks and context-engine completion notifications can fail after the requesting turn ends.
Reason: The shared repair addresses reported owned failures and removes duplicated lifecycle handling; collaborator authorship establishes direction without another product approval.

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
Reviewed head: 29d2c90299e4e220cebab20d1eefcc976c6b7513

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported Gateway CLI control does not carry the released scope into child completion, so dashboard or channel ingress recovery remains unproven end to end.
Agent review details

How this fits together

Invocation 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]
Loading

Technical review

Best 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

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 62e0b2b adds src/plugins/plugin-invocation-scope.ts:88 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 62e0b2b7fcf5; files: src/plugins/plugin-invocation-scope.ts)
  • Josh Lehman: Raw commit bd2dbfd adds src/plugins/plugin-invocation-scope.ts:76 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: bd2dbfdeb493; files: src/plugins/plugin-invocation-scope.ts)
  • Ayaan Zaidi: Raw commit 1621a2d adds src/agents/harness/agent-end-side-effects.test.ts:26 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1621a2de8f0a; files: src/agents/harness/agent-end-side-effects.test.ts)
  • Mitchell Etzel: Raw commit cfd0889 adds src/agents/harness/agent-end-side-effects.test.ts:27 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: cfd08895e6ec; files: src/agents/harness/agent-end-side-effects.test.ts)

PR surface

Source -61, Tests -34, Docs -3, Other -281. Total -379 across 27 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 54 115 -61
Tests 15 139 173 -34
Docs 1 6 9 -3
Config 0 0 0 0
Generated 0 0 0 0
Other 2 0 281 -281
Total 27 199 578 -379

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The repair addresses recurring post-turn notification failures without establishing an urgent runtime outage.
  • merge-risk: 🚨 compatibility: Released-scope callbacks and cleanup views deliberately change from rejection to instance admission; the maintainer-authored body accepts and documents this behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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-15T13:40:57.815Z sha f347687 :: needs changes before merge. :: [P2] Restore mock isolation instead of expanding the baseline

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]>
@obviyus
obviyus force-pushed the refactor/plugin-explicit-run-context branch from f347687 to 29d2c90 Compare November 15, 2026 13:44
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 15, 2026
@obviyus
obviyus merged commit 7789e95 into main Nov 15, 2026
148 checks passed
@obviyus
obviyus deleted the refactor/plugin-explicit-run-context branch November 15, 2026 15:18
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 7789e95.

  • Bug: a plugin hook or context-engine callback that ran after a turn ended failed with "Plugin invocation scope is closed". Each failing hook had its own patch, and new paths kept failing.
  • Fix: a released scope stops routing. A late call becomes a normal counted call on the plugin instance, refused only while that instance is retiring. The closed state and seven per-hook patches are deleted.
  • Proof: new tests for onSubagentEnded and subagent_ended fail on base and pass on head; the hot-reload drain test is unchanged. The real-Gateway CLI run showed no regression.

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]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
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)
obviyus added a commit that referenced this pull request Nov 28, 2026
… 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
… 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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 29, 2026
… 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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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.

1 participant