Skip to content

fix(gateway): keep archive recaps alive after the calling turn ends - #196831

Merged
vincentkoc merged 1 commit into
mainfrom
fix-activity-recap-lifecycle-scope-20261111
Nov 10, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
fix-activity-recap-lifecycle-scope-20261111

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Related: #196700

What Problem This Solves

Fixes Activity recaps staying stale when an agent archives a conversation and its calling turn finishes before recap preparation completes.

User Impact

Archiving catches up the recap with the latest transcript even after the requesting turn ends.

Why This Change Was Made

The recap worker owns its background lifetime. Clear the caller's plugin scope at the shared worker launch while preserving connection cleanup tracking and session-owner policy checks. This also removes the earlier run-end-only detachment. Production code changes by four lines added and four removed.

Evidence

  • Deterministic public sessions.patch regression with real Gateway request context, SQLite transcript/store, and plugin invocation lifetime. On base 0409efbc343c579f3d711f723811c58fa9497f05, archive succeeds but persisted coverage remains 2 messages instead of 4; fixed head 270d0bfe8c26a64a17cfe953eff459f2c2e3ae9e reaches 4/current.
  • Final lifecycle, freshness, retry, and plugin-lifetime run: 50/50 tests, 58.07 seconds test-run duration / 61.23 seconds command wall time; new regression 2.011 seconds.
  • Targeted local lint, Gateway test typecheck, formatting, staged-content guard, whitespace and the test-line ratchet pass on the reviewed branch base. The separate 100-line allocation covers this public-RPC regression; the shared ceiling is unchanged.
  • Fresh independent implementation/fixture review: no findings. Full local ClawSweeper committed-range review, default coverage/high reasoning, base/head above: complete, no correctness or security findings. Author simplification pass complete.

The utility model I/O is fixed by the fixture. This proves the in-process Gateway lifecycle and persistence behavior; no live-provider or device claim.

CI qualification

CI attempt 42888300253/1 is failed (2026-11-10T19:44:36Z to 2026-11-10T19:57:36Z, approximately 780 seconds elapsed wall time, not compute or billing time): the test-line ratchet is the sole root failure, with the CI aggregate downstream; 43 jobs passed and 27 were skipped. The tested merge 93936a8778892449a2f510f3f8c99fd80ebdb600 has baseline 474b4cebd95f1cff30b671cd08f7781ce7b89044 and this exact PR head as its ordered parents.

The merge has 6,635,276 test lines against a 6,635,148 effective ceiling, leaving 128 lines of debt. This PR adds exactly 100 test lines and a separate 100-line allocation; its baseline therefore already had the same 128-line debt (6,635,176 against 6,635,048). The unchanged checker intentionally permits an over-budget change with no test growth, but positive growth activates enforcement. This is a source-verified inherited-debt attribution, not an identical baseline failure or a claim that CI passed. No extra allocation or shared-threshold change is included. Landing uses the documented attributed-failure exception under standing maintainer authority.

security-fast passed independently. The current Security Review publisher passed, with successful dependency and security-sensitive review statuses; the combined CI status remains failed because of the ratchet. Native landing revalidates security and required reviews.

@vincentkoc vincentkoc self-assigned this Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Nov 10, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review November 10, 2026 19:44
@vincentkoc
vincentkoc enabled auto-merge (squash) November 10, 2026 19:51
@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. 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. and removed 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. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR launches Activity recap workers outside the requesting turn’s plugin scope while retaining connection cleanup tracking.

Example: An agent archives agent:main:recap after its transcript grows from 2 to 4 messages, then its calling turn finishes during recap preparation.

  • Before: The archive succeeds, but recap coverage remains at 2 messages.
  • After: The recap finishes independently and reaches 4 messages with state current.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, coherent lifecycle repair with useful integration coverage; confidence is limited to supplied harness evidence and an unresolved CI failure.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied evidence exercises sessions.patch, real SQLite persistence, and plugin-scope closure in process with model preparation and completion stubbed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An archived conversation’s Activity recap can remain stale after the agent’s calling turn finishes.
Reason: The maintainer-authored direction restores existing recap behavior without adding configuration, APIs, or another lifecycle owner.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR repairs a current archive recap failure with a focused change and no identified introduced defect; the failing test-line CI gate remains unclassified.

Priority: P2
Reviewed head: 270d0bfe8c26a64a17cfe953eff459f2c2e3ae9e

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The archive-and-turn-completion scenario is covered by a reported red/green in-process regression, but no built-Gateway execution of this changed archive path is supplied.
Agent review details

How this fits together

The Gateway recap service consumes session lifecycle events, reads transcript content, invokes the utility model under session-owner policy, and persists Activity recaps.

flowchart LR
  A[Archive or turn completion] --> B[Recap queue]
  B --> C[Exit caller plugin scope]
  C --> D[Tracked recap worker]
  D --> E[Session owner policy]
  E --> F[Utility model]
  F --> G[Persist current recap]
Loading

Technical review

Best possible solution:

Keep plugin-scope detachment at the existing shared recap launcher while preserving connection tracking, session-owner checks, and per-recap cleanup.

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

Current-main source exposes the inherited archive scope, and the author reports a deterministic base/head regression through sessions.patch; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch repairs the shared lifecycle boundary with existing owners, removes the superseded caller-specific detachment, and adds one regression for the distinct archive trigger.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Inherited connection cleanup tracking keeps the original intent (7e8deb0: Retain recap slots and inherited connection ownership until tracked child cleanup settles.)
  • Run-end plugin-scope detachment keeps the original intent (4ec97ef: Allow host-owned automatic recaps to continue after the completed run releases its plugin invocation scope.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 35494b6 adds src/gateway/session-activity-summaries.ts:691 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 35494b66324a; files: src/gateway/session-activity-summaries.ts)
  • Vincent Koc: Raw commit 7e8deb0 adds src/gateway/session-activity-summaries.ts:526 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7e8deb02b6b8; files: src/gateway/session-activity-summaries.ts)

PR surface

Source 0, Tests +101, Other +1. Total +102 across 4 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 4 4 0
Tests 2 101 0 +101
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 4 106 4 +102

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:

  • add P2: Archive-triggered Activity enrichment can remain stale, while archiving and ordinary conversation workflows continue to work.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Archive-triggered Activity enrichment can remain stale, while archiving and ordinary conversation workflows continue to work.
  • 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.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Classify the exact-head test-line ratchet failure using its detailed job output.
  • Observe archive-triggered recap completion through a built Gateway after the requesting turn ends.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 10, 2026, 3:00 PM ET / 20:00 UTC.

@vincentkoc
vincentkoc disabled auto-merge November 10, 2026 20:11
@vincentkoc
vincentkoc merged commit 7874e04 into main Nov 10, 2026
235 of 238 checks passed
@vincentkoc
vincentkoc deleted the fix-activity-recap-lifecycle-scope-20261111 branch November 10, 2026 20:13
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

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

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant