Skip to content

feat: manage and reload plugins without Gateway restarts - #145484

Merged
steipete merged 2 commits into
mainfrom
codex/plugin-gateway-restart-free-20260911
Sep 12, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/plugin-gateway-restart-free-20260911

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Builds on plugin lifetime foundation #144252. Related: plugin redesign #135599.

Additional instructions

Keep Allow edits from maintainers enabled.

What Problem This Solves

Plugin changes should take effect without restarting the Gateway or disconnecting clients. TypeScript reload must execute edited code—including on Bun, which could report success while retaining old modules—and failed activation needs a clear recovery action.

Why This Change Was Made

Replace plugin restart signaling and UI restart waits with one Gateway-owned prepare, drain, publish, and retire lifecycle, retaining unaffected instances and sharing the startup publisher. Per-instance module capture replaces Bun's global cache-retirement barrier: existing consumers retain their original modules, declared local package targets are acquired before native evaluation, and native resolution conditions and synchronous startup contracts are preserved.

User Impact

Administrators can install, enable, disable, uninstall, and reload through Gateway controls. openclaw plugins reload <id> refreshes TypeScript entries, helpers, and manifests while preserving enablement; the Control UI updates on its existing connection. Results distinguish saved installation from applied runtime and offer Reload after activation fails. Runtime-only reload works with externally managed/Nix config; new consent and configuration writes remain guarded.

Cleanup is best effort: unmanaged globals, timers, or native resources can remain after managed registrations retire. Cleanup failures produce warnings; restart remains available for residual behavior. Reload does not rebuild compiled bundled code or grant ownership of discovered files. Broader agent-turn, installation-source, and Claw batch integrations remain separate slices.

Evidence

The corrective candidate 4d9b6534 passed the canonical changed gate (867 seconds), full build (449 seconds), and all six P2 autoreview passes. The exact previously failing Bun 1.4.0 test passed. Fresh Bun 1.4.2 and Node 24.19.0 source Gateways each executed the real CLI-handler RPC reload: edited TypeScript, same PID, unchanged config, generation 3, clean shutdown and reusable port. This proves the handler/RPC flow, not a spawned CLI parser. The inherited Bun 1.4.0 native ESM/SDK-hook limitation remains qualified separately.

The final branch is rebased onto main 92b9264c. Candidate 562c82c8 (tree 7e700a86) preserves 297 feature files byte-for-byte across this refresh, including the tested plugin loader. Main's test split, cleanup admission check, restart-readiness config and generated protocol changes are preserved. All 376 focused overlap tests passed, along with protocol generation and core types. The CSS removal audit found no applicable plugin markup losing styles; no CSS restore was needed.

The earlier rebased production tree 70398920 passed a fresh full build (470 seconds), the Bun 1.4.0 regression, and both real CLI-handler/Gateway reload probes. Bun 1.4.2 and Node 24.19.0 loaded edited TypeScript under the same PID with unchanged config, generation 3, natural shutdown and reusable ports. These runs retain that source identity; the latest rebase has the source-conformance and focused owner proof above.

The CI corrections replace stale reconnect/global-registry/cleanup expectations, consolidate typed config-writer mocks, synchronize inventory removal with the actual uninstall RPC, and share one lazy Jiti CJS factory. All seven browser shards and the real-Gateway UI lane passed on b53160a3, confirming the earlier plugin/picker failures and previously unreproduced Full Access case. Main's subsequent split resolves the inherited thinking-test line-limit failure; our temporary test consolidation is dropped. Required CI must pass on the final published head.

Earlier full and corrective reviews remain recorded. The seven-pass integration review's raw findings are preserved: the tooltip claim was contradicted by its capture listener, and the inherited cloud-picker OS-selection issue is named below.

Delta against main 92b9264c: +3,197 production lines (6,523 added / 3,326 removed), +15,336 test/support lines, and +282 generated protocol lines. Docs, tooling and baselines are separate. Growth supplies live replacement/config coordination and per-instance native loading; moves offset within these totals.

Historical synthetic captures illustrate the UI flow with different fixtures and earlier sources (9675… / c79…):

Earlier UI Reload and generation receipt
Earlier plugin lifecycle settings Plugin reloaded with generation receipt

The earlier full canonical changed gate (including native-app checks) and normal build passed. On the integrated 18bdff2d candidate, the final correction gate passed, and the real published-upgrade survivor lane upgraded an isolated [email protected] installation through its published updater: the legacy-operator-state/auto-auth scenario passed in 341 seconds, after normal and clean-package builds passed. This remote package proof remains bound to that captured tree.

The startup compatibility regression is covered through a real Gateway: an unchanged failed plugin remains diagnostic while a healthy sibling reloads and disables. Newly failed replacements and explicit retries of the failed plugin still reject; cleanup retains the complete registry. Both the Gateway and loader selection tests failed before the fix and passed afterward. The hosted-catalog transport alone is mocked in this owner test; config, catalog projection and runtime operations stay real.

There are no new operator configuration keys, SQL schema changes, or protocol version bumps. The wire additions are optional runtime projections plus the reload method/event; named UI schemas preserve the existing handshake shape. Internal persistedSourceConfig carries the exact accepted write intent without adding a persisted config key. Existing startup and published-upgrade behavior remain supported.

Follow-up outside this plugin change: Cloud picker: preserve and explain an unavailable selected OS. Main's retained draft OS can disagree with its filtered compact choices after a catalog refresh. The relevant source and tests are now identical to main and absent from this PR's diff. A separate placement-owner repair should retain explicit/recovery intent, show the blocker, and allow choosing an available alternative rather than silently substituting an OS.

@steipete
steipete requested a review from a team as a code owner September 12, 2026 01:19
@steipete steipete self-assigned this Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 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 docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes scripts Repository scripts agents Agent runtime and tooling plugin: file-transfer plugin: team-reports size: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 1:53 AM ET / 05:53 UTC (Revision 5).

ClawSweeper review

What this changes

Adds Gateway-owned plugin replacement, CLI and Control UI reload controls, fresh TypeScript loading, and receipts distinguishing saved changes from applied runtime changes.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a useful, distinct management slice beyond the merged lifetime foundation. The earlier startup-error blocker is resolved; no new blocking defect was established in the inspected paths.

Priority: P2
Reviewed head: 562c82c89a91ccde8dcb3c68acc824d468a98632

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful runtime evidence and coherent lifecycle ownership support a good patch rating, with the third-party cleanup boundary explicitly documented.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Source-qualified Node and Bun Gateway runs report the changed CLI-handler/RPC path executing edited TypeScript with unchanged PID/config and clean shutdown; historical UI captures supplement those observations. Preserve the recorded candidate identities and upgrade-run qualification rather than treating them as fresh execution of the final head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Source-qualified Node and Bun Gateway runs report the changed CLI-handler/RPC path executing edited TypeScript with unchanged PID/config and clean shutdown; historical UI captures supplement those observations. Preserve the recorded candidate identities and upgrade-run qualification rather than treating them as fresh execution of the final head.
Evidence reviewed 11 items Verified introduction and current-main necessity: The local checkout matches the pinned head and the complete local introduction comparison was available. Current-main plugin mutation handlers still return restartRequired: true for install and uninstall; the supplied merged foundation PR explicitly leaves management orchestration to this slice.
Previous finding resolved: Replacement rejection excludes retained error records while still rejecting newly evaluated failures. The Gateway regression exercises healthy sibling reload, failed replacement preservation, explicit retry of the broken plugin, and disablement.
Re-review continuity: GitHub returned blob f0dca2e31da4fd5355ba86ff1fcf07f960c31281 for loader-shared.ts at the prior reviewed head; the current checkout has the same blob. The previous completed review contains no findings or published rank-up moves.
Findings None None.
Security None None.

How this fits together

The Gateway hosts plugin code, registrations, services, and channel connections. Plugin-management requests now pass through a shared replacement lifecycle that publishes updated runtime capabilities to connected clients.

flowchart LR
  A[CLI and Control UI] --> B[Admin and consent checks]
  B --> C[Plugin lifecycle owner]
  D[Config and installed source] --> C
  C --> E[Prepare and drain affected plugins]
  E --> F[Publish runtime generation]
  F --> G[Refresh connected clients]
  F --> H[Retire old resources and report warnings]
Loading

Before merge

  • Resolve merge risk (P1) - Third-party plugins that do not clean up unmanaged resources can retain timers, subscriptions, or native state when replacement replays lifecycle hooks; a Gateway restart may still be necessary.
  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus test growth Reported production +3,197; tests/support +15,336 The PR explains production growth as replacement/config coordination and per-instance loading, with generated protocol output counted separately.
Reload request boundary 1 new reload RPC; 1–64 targets per request The bounded target envelope supports package-coherent replacement while the CLI continues to accept one plugin ID.

Stored data model

Persistent data-model change detected: unknown-data-model-change: packages/gateway-protocol/src/schema/frames.ts, unknown-data-model-change: packages/gateway-protocol/src/schema/plugins.ts, unknown-data-model-change: ui/src/pages/config/memory-page.ts, unknown-truncated-pull-files, vector/embedding metadata: ui/src/pages/config/memory-page.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Retain the documented cleanup boundary (recommended)
    Accept the explicitly documented best-effort plugin contract with cleanup warnings and Gateway restart recovery for residual third-party behavior.

Technical review

Best possible solution:

Keep one Gateway-owned replacement lifecycle, preserving the documented upgrade contract, explicit runtime receipts, and restart recovery for unmanaged plugin resources.

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

Not applicable to the central feature request; current main demonstrably retains restart-based management. This review did not execute the reported Bun regression or Gateway scenarios.

Is this the best way to solve the issue?

Yes: extending the existing Gateway and plugin lifetime owners avoids a competing lifecycle implementation, while preserving unaffected instances and distinguishing persistence from runtime application.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: Restart-free plugin management is a substantial improvement without evidence of an emergency user-facing regression.
  • merge-risk: 🚨 compatibility: Full replacement replays plugin lifecycle hooks, exposing third-party cleanup assumptions that ordinary CI cannot universally establish.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • feature: ✨ showcase: ClawSweeper spotlight: unusually compelling feature idea for maintainer attention. Applying edited plugin code and management changes without disconnecting clients materially improves both plugin development and everyday administration.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Source-qualified Node and Bun Gateway runs report the changed CLI-handler/RPC path executing edited TypeScript with unchanged PID/config and clean shutdown; historical UI captures supplement those observations. Preserve the recorded candidate identities and upgrade-run qualification rather than treating them as fresh execution of the final head.
  • proof: sufficient: Contributor real behavior proof is sufficient. Source-qualified Node and Bun Gateway runs report the changed CLI-handler/RPC path executing edited TypeScript with unchanged PID/config and clean shutdown; historical UI captures supplement those observations. Preserve the recorded candidate identities and upgrade-run qualification rather than treating them as fresh execution of the final head.

Evidence

What I checked:

  • Verified introduction and current-main necessity: The local checkout matches the pinned head and the complete local introduction comparison was available. Current-main plugin mutation handlers still return restartRequired: true for install and uninstall; the supplied merged foundation PR explicitly leaves management orchestration to this slice. (src/gateway/server-methods/plugins-mutations.ts, 9449a1a780e4)
  • Previous finding resolved: Replacement rejection excludes retained error records while still rejecting newly evaluated failures. The Gateway regression exercises healthy sibling reload, failed replacement preservation, explicit retry of the broken plugin, and disablement. (src/plugins/loader-shared.ts:431, 562c82c89a91)
  • Re-review continuity: GitHub returned blob f0dca2e31da4fd5355ba86ff1fcf07f960c31281 for loader-shared.ts at the prior reviewed head; the current checkout has the same blob. The previous completed review contains no findings or published rank-up moves. (src/plugins/loader-shared.ts:431, b53160a3574c)
  • Publication and authority boundaries: Lifecycle handlers compose request cancellation, mutation authority, and the management lease guard. Publication rechecks ownership, prepares node credentials within admitted capabilities, and publishes synchronously before notifying clients. (src/gateway/server-plugin-reload.ts:445, 562c82c89a91)
  • Asset-serving final effect: The inspected asset owner preserves authentication and plugin-specific grants, then resolves the current registry and verifies build authority immediately before sending captured bytes. Retained browser activation receipts remain observations rather than authorization. (src/gateway/control-ui-plugin-assets.ts, 562c82c89a91)
  • Source-bound runtime evidence: The captured PR body reports real CLI-handler/RPC reloads on Bun 1.4.2 and Node 24.19.0: edited TypeScript executed, PID and config remained unchanged, generation reached 3, and shutdown released the port. Evidence remains attributed to corrective candidate 4d9b6534 and earlier production tree 70398920; the final rebase reports source conformance and 376 overlap checks, not a newly executed full runtime campaign.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RomneyDa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-12T01:25:07.262Z sha 3cf609616b604e0fbe304114f01370c386a24486 :: blocked before merge. :: [P1] [P1] Exclude unchanged failed plugins from replacement rejection
  • reviewed 2026-09-12T02:37:01.659Z sha 3cf609616b604e0fbe304114f01370c386a24486 :: blocked before merge. :: [P1] [P1] Exclude unchanged failed plugins from replacement rejection
  • reviewed 2026-09-12T03:21:18.258Z sha 8978eb4 :: blocked before merge. :: none
  • reviewed 2026-09-12T05:18:06.773Z sha b53160a :: blocked before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 12, 2026
@steipete
steipete force-pushed the codex/plugin-gateway-restart-free-20260911 branch from 3cf6096 to 8978eb4 Compare September 12, 2026 03:11
@clawsweeper clawsweeper Bot added feature: ✨ showcase ClawSweeper spotlight: unusually compelling feature idea for maintainer attention. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 12, 2026
@steipete
steipete force-pushed the codex/plugin-gateway-restart-free-20260911 branch from 8978eb4 to b53160a Compare September 12, 2026 05:08
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Sep 12, 2026
obviyus added a commit that referenced this pull request Oct 17, 2026
…ttings changes (#173626)

Related: #173585, #169562

## What Problem This Solves

Fixes: the Gateway main thread blocks for hundreds of milliseconds after a sign-in, sign-out, key removal or plugin settings change, because runtime readers reload plugin metadata from disk although no plugin was installed.

## User Impact

User impact: less main-thread blocking after account and plugin settings changes, so model pickers and other Gateway requests stall less. No config, state or plugin contract changes.

## Why This Change Was Made

Config hot reload holds the plugin lifecycle lease (since #145484). The lease runs in a fresh operation plugin cache, so management sees what other processes committed while it waited. That isolation stays. But two kinds of work inside it reloaded plugin metadata on every event:

1. **A policy change rescanned the whole inventory.** Plugin activation (`enabled`) is the only config-owned fact in the installed plugin index. A changed policy hash (for example auto-enable after a sign-in) made the registry reader treat the persisted index as stale and run full discovery. Activation is now one projection over inventory records (`projectInstalledPluginIndexPolicy`), used by fresh builds and by the registry reader. When the persisted inventory passes its existing freshness checks and only the policy differs, the reader projects the new policy in memory. Install, uninstall, stale files, load paths and the other existing reasons still rediscover. Freshness checks tolerate missing files only for disabled records, so records the new policy enables are rechecked; if any is stale, the reader rediscovers. This matches the documented rule that enablement is evaluated from the current operation's policy, not stored with the facts.
2. **Post-commit Gateway readers could not see the published inventory.** The model-policy comparison (chat metadata lifecycle) and the prepared model runtime refresh inherit the lease's operation cache, so model-id normalization in `resolveDefaultModelForAgent` loaded a metadata snapshot from disk. As in #169562, the Gateway lifecycle owner now passes the snapshot it published. The chat metadata lifecycle hands `getPluginMetadataSnapshot()` to `modelSelectionPoliciesMatch`. The prepared runtime refresh forwards its existing `pluginMetadataSnapshot` option to the configured owner inputs. Readers without an explicit snapshot keep their current behavior.

## Evidence

- Regression tests, each fails on `main` and passes here:
  - `plugin-registry.test.ts`, "projects a config policy change over the persisted inventory without rescanning": on `main` the extensions dir is rescanned.
  - `plugin-registry.test.ts`, "rediscovers when a policy enables a persisted plugin whose files are gone": a projection-only reader would return an enabled plugin with no files.
  - `operator-model-presentation.test.ts`, two tests run inside an operation cache like the reload lease: the policy comparison and prepared runtime input collection load no plugin metadata. On `main` they load 2 and 1 snapshots.
- Focused suites pass: plugin registry, index and cache; capability generation; model selection; operator model policy; chat metadata lifecycle; prepared model runtime; agent database startup. Two kinds of local failure, neither CI-relevant:
  - 4 tests in `plugin-registry` and `installed-plugin-index` fail on macOS on both `main` and this branch (temp-dir environment).
  - One agent-database-startup test timed out at host load ~60 and passes alone.
- Isolated Gateway on a packaged layout (built dist, no `.git`, `src` or `extensions`), compared with the `main` it merges. CPU profile over 20 events (4 each of sign-in, sign-out, key removal, plugin reload and plugin settings change), two interleaved rounds:

| Main-thread CPU | main (round 1 / 2) | this PR (round 1 / 2) |
|---|---|---|
| model-id normalization metadata loads | 22555 / 20521 ms | 2 / 0 ms |
| plugin inventory rediscovery | 16873 / 16489 ms | 3638 / 1518 ms |
| all plugin metadata snapshot loads | 31650 / 29862 ms | 10194 / 8281 ms |
| busy segments ≥ 150 ms | 57 / 67 | 31 / 14 |

  What remains is `resolveConfigWidePluginMetadataSnapshot`: the explicit plugin reload, which is the owner's refresh path, plus startup config preflight.

- `last-heartbeat` lag probe during the event, n = 12 events each, runs interleaved base/PR. Host load was 30–101, so absolute values are inflated:

| Event (during) | main p50 / p99 | this PR p50 / p99 |
|---|---|---|
| sign-in | 1.8 / 698 ms | 2.6 / 329 ms |
| sign-out | 3.2 / 790 ms | 4.2 / 489 ms |
| key removal | 4.1 / 1009 ms | 2.0 / 359 ms |
| plugin reload | 1.4 / 710 ms | 1.0 / 489 ms |
| plugin settings change | 0.8 / 157 ms | 0.8 / 138 ms |

  No run showed a removed provider after its removal (0 violations).

Not covered: plugin reload still blocks, from the reload's own metadata refresh, plugin module re-import and runtime publication. That needs a separate change.

## Notes

A source checkout (`pnpm-workspace.yaml`, `src` and `extensions` at the package root) cannot measure this. There, `isBundledPluginInsideDevSourceRoot` and the private QA plugins make `requiresDerivedRegistryValidation` reject the persisted index on every read, so local dev Gateways still rescan. Packaged installs do not.

## Merge danger

Two-way door: a revert restores the reloads. Nothing is persisted or migrated, and lease isolation is unchanged. Blast radius if wrong:
- Plugin activation as seen by Gateway runtime reads after a config change. The projection uses the same rule and inputs as a fresh index build.
- Model-id normalization in the post-commit policy comparison and prepared runtime refresh. These use the inventory the Gateway published, which is what other runtime readers already use.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…ttings changes (openclaw#173626)

Related: openclaw#173585, openclaw#169562

## What Problem This Solves

Fixes: the Gateway main thread blocks for hundreds of milliseconds after a sign-in, sign-out, key removal or plugin settings change, because runtime readers reload plugin metadata from disk although no plugin was installed.

## User Impact

User impact: less main-thread blocking after account and plugin settings changes, so model pickers and other Gateway requests stall less. No config, state or plugin contract changes.

## Why This Change Was Made

Config hot reload holds the plugin lifecycle lease (since openclaw#145484). The lease runs in a fresh operation plugin cache, so management sees what other processes committed while it waited. That isolation stays. But two kinds of work inside it reloaded plugin metadata on every event:

1. **A policy change rescanned the whole inventory.** Plugin activation (`enabled`) is the only config-owned fact in the installed plugin index. A changed policy hash (for example auto-enable after a sign-in) made the registry reader treat the persisted index as stale and run full discovery. Activation is now one projection over inventory records (`projectInstalledPluginIndexPolicy`), used by fresh builds and by the registry reader. When the persisted inventory passes its existing freshness checks and only the policy differs, the reader projects the new policy in memory. Install, uninstall, stale files, load paths and the other existing reasons still rediscover. Freshness checks tolerate missing files only for disabled records, so records the new policy enables are rechecked; if any is stale, the reader rediscovers. This matches the documented rule that enablement is evaluated from the current operation's policy, not stored with the facts.
2. **Post-commit Gateway readers could not see the published inventory.** The model-policy comparison (chat metadata lifecycle) and the prepared model runtime refresh inherit the lease's operation cache, so model-id normalization in `resolveDefaultModelForAgent` loaded a metadata snapshot from disk. As in openclaw#169562, the Gateway lifecycle owner now passes the snapshot it published. The chat metadata lifecycle hands `getPluginMetadataSnapshot()` to `modelSelectionPoliciesMatch`. The prepared runtime refresh forwards its existing `pluginMetadataSnapshot` option to the configured owner inputs. Readers without an explicit snapshot keep their current behavior.

## Evidence

- Regression tests, each fails on `main` and passes here:
  - `plugin-registry.test.ts`, "projects a config policy change over the persisted inventory without rescanning": on `main` the extensions dir is rescanned.
  - `plugin-registry.test.ts`, "rediscovers when a policy enables a persisted plugin whose files are gone": a projection-only reader would return an enabled plugin with no files.
  - `operator-model-presentation.test.ts`, two tests run inside an operation cache like the reload lease: the policy comparison and prepared runtime input collection load no plugin metadata. On `main` they load 2 and 1 snapshots.
- Focused suites pass: plugin registry, index and cache; capability generation; model selection; operator model policy; chat metadata lifecycle; prepared model runtime; agent database startup. Two kinds of local failure, neither CI-relevant:
  - 4 tests in `plugin-registry` and `installed-plugin-index` fail on macOS on both `main` and this branch (temp-dir environment).
  - One agent-database-startup test timed out at host load ~60 and passes alone.
- Isolated Gateway on a packaged layout (built dist, no `.git`, `src` or `extensions`), compared with the `main` it merges. CPU profile over 20 events (4 each of sign-in, sign-out, key removal, plugin reload and plugin settings change), two interleaved rounds:

| Main-thread CPU | main (round 1 / 2) | this PR (round 1 / 2) |
|---|---|---|
| model-id normalization metadata loads | 22555 / 20521 ms | 2 / 0 ms |
| plugin inventory rediscovery | 16873 / 16489 ms | 3638 / 1518 ms |
| all plugin metadata snapshot loads | 31650 / 29862 ms | 10194 / 8281 ms |
| busy segments ≥ 150 ms | 57 / 67 | 31 / 14 |

  What remains is `resolveConfigWidePluginMetadataSnapshot`: the explicit plugin reload, which is the owner's refresh path, plus startup config preflight.

- `last-heartbeat` lag probe during the event, n = 12 events each, runs interleaved base/PR. Host load was 30–101, so absolute values are inflated:

| Event (during) | main p50 / p99 | this PR p50 / p99 |
|---|---|---|
| sign-in | 1.8 / 698 ms | 2.6 / 329 ms |
| sign-out | 3.2 / 790 ms | 4.2 / 489 ms |
| key removal | 4.1 / 1009 ms | 2.0 / 359 ms |
| plugin reload | 1.4 / 710 ms | 1.0 / 489 ms |
| plugin settings change | 0.8 / 157 ms | 0.8 / 138 ms |

  No run showed a removed provider after its removal (0 violations).

Not covered: plugin reload still blocks, from the reload's own metadata refresh, plugin module re-import and runtime publication. That needs a separate change.

## Notes

A source checkout (`pnpm-workspace.yaml`, `src` and `extensions` at the package root) cannot measure this. There, `isBundledPluginInsideDevSourceRoot` and the private QA plugins make `requiresDerivedRegistryValidation` reject the persisted index on every read, so local dev Gateways still rescan. Packaged installs do not.

## Merge danger

Two-way door: a revert restores the reloads. Nothing is persisted or migrated, and lease isolation is unchanged. Blast radius if wrong:
- Plugin activation as seen by Gateway runtime reads after a config change. The projection uses the same rule and inputs as a fresh index build.
- Model-id normalization in the post-commit policy comparison and prepared runtime refresh. These use the inventory the Gateway published, which is what other runtime readers already use.

Co-authored-by: Ayaan Zaidi <[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 app: android App: android app: web-ui App: web-ui cli CLI command changes commands Command implementations docs Improvements or additions to documentation feature: ✨ showcase ClawSweeper spotlight: unusually compelling feature idea for maintainer attention. gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer plugin: team-reports proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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