Skip to content

fix(gateway): refresh model catalog after auth changes - #134361

Merged
obviyus merged 11 commits into
mainfrom
fix/models-catalog-refresh
Sep 1, 2026
Merged

obviyus merged 11 commits into
mainfrom
fix/models-catalog-refresh

Conversation

@obviyus

@obviyus obviyus commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

After openclaw models auth login succeeds for a new provider, /models and models.authStatus keep serving the catalog that was discovered before the login. The provider's models do not appear until the gateway restarts or an unrelated full rebuild happens. The operator just proved the credential works and then sees no models from it — a silent non-outcome on the default path.

Why This Change Was Made

The auth-mutation listener already fires when profiles change, but its publication rebuilds static content only, so credential-identity changes never refresh catalog content. The naive fix — live discovery inside the mutation publication — is forbidden by a shipped invariant: ordinary run admissions await the owner's pending publication and must stay static (see fix(agents): default run admissions to static catalog, 06c2dc7). OAuth token rotations also fire the same listener frequently; they must never pay for provider discovery.

This change records the distinction where it is produced and moves the live work to the surface that asks for it:

  • saveAuthProfileStoreInTransaction already computes whether the profile set changed (vs. a same-profile token refresh); that fact now travels on the runtime auth mutation event (profileSetChanged).
  • Auth publication stays static-only in every case. A profile-set change additionally marks the affected owners' catalog content stale — a cheap recorded flag, no discovery, no blocking.
  • Explicit read-only catalog reads (/models, models.authStatus, openclaw models list) consume the flag: one owner-local loadFullModelCatalog({ refresh: true }), shared by concurrent readers through the loader's existing single-flight pending promise, generation-checked before the flag clears.
  • Token rotations carry profileSetChanged: false and touch nothing but the static credential projection — identical cost to current main.
  • Turn admission continues to await only the static owner publication; chat latency is unchanged.

User Impact

  • Log in with a new provider → the next /models (any channel) or openclaw models list shows that provider's models, no gateway restart.
  • Token refreshes (frequent, automatic) trigger zero discovery work — no new load on gateways that stay up for weeks.
  • Chat admissions never wait on provider discovery; the static-admission invariant is preserved and now has explicit regression coverage.

Evidence

  • New regression suite src/agents/prepared-model-runtime.reload-auth.test.ts: profile-set change marks the owner stale and an explicit read returns live content; a token-rotation-shaped mutation triggers no live discovery; auth publication stays static even while stale; two concurrent stale reads share one rebuild.
  • Producer coverage in src/agents/auth-profiles/runtime-snapshots.test.ts and src/agents/auth-profiles/external-oauth.test.ts: replacement/set/clear operations carry the correct profileSetChanged fact.
  • Focused suites: 295 tests across prepared-runtime, catalog, owner, lifecycle, startup, and gateway-method suites pass; git diff --check clean.
  • Production diff is +98/−26 (net +72): the stale-read owner boundary and the producer fact; the earlier live-publication plumbing was removed.

ClawSweeper review response (head b919d5b8a23)

P1 fixed — stale refresh no longer blocks request paths. The previous head let any read-only prepared-catalog read trigger a stale full-catalog refresh, so an attachment admission or an HTTP model override could block on provider discovery. Refresh is now opt-in: it requires readOnly === true and an explicit refreshFullCatalog === true (src/agents/prepared-model-catalog.ts:70-98).

  • Browse callers opt in explicitly: /models (src/auto-reply/reply/commands-models.ts:199-210), Control UI models.list (src/gateway/server-methods/models-list-result.ts:431-456 and :474-485), unscoped openclaw models list (src/commands/models/list.rows.ts:377-385).
  • Request paths never pass the flag: attachment admission (src/gateway/session-utils-model.ts:498-510), HTTP model override (src/gateway/http-utils.ts:199-201). models.authStatus stays static by design (src/gateway/server-methods/models-auth-status.ts:557-564); Control UI automatic reads use preparedOnly: true (ui/src/lib/model-catalog-store.ts:206-215).

Regression coverage: src/agents/prepared-model-runtime.reload-auth.test.ts:34-108 marks the catalog stale, blocks the discovery worker, then proves the default read settles without calling it and that an explicit refresh does call it. Independently verified to fail on the pre-fix gate.

Production LOC delta (judged): raw +412 / -282 = net +130 over src/**. Subtracting prepared-model-runtime.test-harness.ts (test support, net +17) gives a production net of +113. Of that, mutation-lineage.ts (+243) is a pure extraction out of runtime-snapshots.ts (−240), so judged growth after discounting the move is roughly +110, concentrated in prepared-model-runtime.ts (+35/−2) and prepared-model-runtime.owner.ts (+24/−3).

That growth is the fix, not overhead: before this PR the prepared catalog had no staleness concept at all — a provider login was invisible until a Gateway restart, with no visible outcome and no recorded reason. There is no existing owner to absorb a fact that did not exist. The two lines the P1 repair itself added are the explicit browse opt-in; collapsing the mutation-lineage extraction back would delete the persisted-mutation token ownership that src/secrets/runtime-state.ts consumes.

Performance: token refreshes (the frequent case) trigger zero discovery work — includeCredentialProviders is already conditional on profileSetChanged (src/agents/prepared-model-runtime.ts:610-617). Chat admission never waits on discovery, and that invariant now has explicit regression coverage.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus
obviyus marked this pull request as ready for review August 31, 2026 18:09
@obviyus
obviyus requested a review from a team as a code owner August 31, 2026 18:09
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 31, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed September 1, 2026, 12:31 AM ET / 04:31 UTC.

ClawSweeper review

What this changes

The branch marks model catalogs stale after authentication profile-set changes and refreshes them only for explicit model-browsing reads.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

The prior P1 is addressed at this head, but the earlier P2 remains: a live auth-republication leaves the new stale flag set after rebuilding a full catalog, so the next browse repeats provider discovery. The protected maintainer PR should stay open for that focused correction.

Priority: P1
Reviewed head: b919d5b8a23ba9b55560d5b467bc6e1f92dff78b

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The static-admission regression is fixed, but live-publication stale-state handling remains incomplete.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository state identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the focused regression tests remain supplemental evidence.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the focused regression tests remain supplemental evidence.
Evidence reviewed 5 items Current main lacks stale-catalog refresh: Current main returns the cached completed catalog for read-only materialization; the proposed branch adds the stale-refresh step before that fallback.
Live publication does not retire stale state: The branch sets catalogStale after a profile-set mutation, while owner-batch publication replaces the snapshot and clears needsRefresh without clearing catalogStale. Live-mode builds produce complete catalog facts, so the next explicit browse rediscovers unnecessarily.
Static-admission regression is covered: The focused test shows ordinary read-only access remains static after the mutation, while an explicit stale-catalog refresh invokes discovery and then clears the flag.
Findings 1 actionable finding [P2] Clear stale state after a live catalog publication
Security None None.

How this fits together

Prepared model runtime snapshots supply static routing facts to requests and fuller catalogs to browsing surfaces. Auth changes republish runtime state; this PR lets explicit catalog reads refresh provider-discovered entries without delaying admissions.

flowchart LR
  A[Authentication profile change] --> B[Auth snapshot publication]
  B --> C[Prepared runtime owner]
  C --> D[Mark catalog stale]
  D --> E[Explicit model browse]
  E --> F[Refresh full catalog]
  C --> G[Static request admission]
Loading

Before merge

  • Clear stale state after a live catalog publication (P2) - A profile-set mutation sets catalogStale, but a subsequent live owner batch publishes a complete catalog and only clears needsRefresh. The next explicit browse consequently rediscovers providers despite already-current catalog content. This is the unresolved prior finding at the same head.
  • Resolve merge risk (P1) - A live-mode owner can retain catalogStale after it has rebuilt current full catalog content, causing a subsequent model browse to repeat provider discovery.
  • Complete next step (P2) - The protected maintainer PR has one concrete lifecycle correction to make; do not route it to automated repair.

Findings

  • [P2] Clear stale state after a live catalog publication — src/agents/prepared-model-runtime.ts:649-650
Agent review details

Security

None.

PR surface

Source +113, Tests +337, Other -1. Total +449 across 31 files.

View PR surface stats
Area Files Added Removed Net
Source 15 373 260 +113
Tests 15 368 31 +337
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 31 741 292 +449

Review metrics

Metric Value Why it matters
Production versus test delta production +113 net before move discount; tests and test support +337 net The branch adds a stale-state lifecycle boundary; its positive production growth needs a complete live-publication invariant.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/agents/auth-profiles/runtime-snapshots.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Reset stale state after live publication (recommended)
    Clear the flag only when the current owner has successfully published a live full catalog, then add a focused sequence regression.
  2. Pause for a lifecycle repair
    Keep the PR open until static and live catalog publications have coherent stale-state ownership.

Technical review

Best possible solution:

Clear catalogStale only after a current live full-catalog publication, preserve it after static publication, and cover the mutation-to-live-publication sequence.

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

Yes. Exercise a profile-set mutation against a live-mode owner, allow the live publication to complete, then browse models; source shows the stale flag remains set.

Is this the best way to solve the issue?

No. The explicit-read approach preserves static admission, but it must retire stale state after a current live publication.

Full review comments:

  • [P2] Clear stale state after a live catalog publication — src/agents/prepared-model-runtime.ts:649-650
    A profile-set mutation sets catalogStale, but a subsequent live owner batch publishes a complete catalog and only clears needsRefresh. The next explicit browse consequently rediscovers providers despite already-current catalog content. This is the unresolved prior finding at the same head.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 16e0dc5d2d46.

Labels

Label justifications:

  • P1: This fixes model browsing after provider login, but the remaining lifecycle defect can repeat costly provider work.
  • merge-risk: 🚨 availability: The new stale flag controls provider discovery and may remain set after a completed live rebuild.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The repository state identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the focused regression tests remain supplemental evidence.

Evidence

What I checked:

  • Current main lacks stale-catalog refresh: Current main returns the cached completed catalog for read-only materialization; the proposed branch adds the stale-refresh step before that fallback. (src/agents/prepared-model-catalog.ts:77, 16e0dc5d2d46)
  • Live publication does not retire stale state: The branch sets catalogStale after a profile-set mutation, while owner-batch publication replaces the snapshot and clears needsRefresh without clearing catalogStale. Live-mode builds produce complete catalog facts, so the next explicit browse rediscovers unnecessarily. (src/agents/prepared-model-runtime.ts:649, b919d5b8a23b)
  • Static-admission regression is covered: The focused test shows ordinary read-only access remains static after the mutation, while an explicit stale-catalog refresh invokes discovery and then clears the flag. (src/agents/prepared-model-runtime.reload-auth.test.ts:34, b919d5b8a23b)
  • Existing CLI contract: The Models CLI documents that provider authentication makes models available and that model listing is a read-only control-plane operation. Public docs: docs/cli/models.md. (docs/cli/models.md:157, b919d5b8a23b)
  • Prepared-runtime history: Feature history identifies the static-admission invariant commit and recent prepared-runtime maintainers; the PR preserves that invariant by making refresh opt-in. (src/agents/prepared-model-runtime.ts:310, 06c2dc7eb105)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Lee: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Clear stale state after a current live publication and add the focused sequence regression.

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 (6 earlier review cycles)
  • reviewed 2026-08-31T18:21:14.477Z sha 1d2a5ae6026c16a35a38c6b6bcd855719b2a78e3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T18:58:21.211Z sha 7c6eda6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T02:31:01.860Z sha a4b73bf :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T03:04:50.569Z sha 942d9eb :: found issues before merge. :: [P1] Keep stale catalog refreshes off attachment admission
  • reviewed 2026-09-01T03:57:54.505Z sha afc787e :: found issues before merge. :: [P2] Clear stale state after a live catalog publication
  • reviewed 2026-09-01T04:21:38.615Z sha b919d5b :: needs changes before merge. :: [P2] Clear stale state after a live catalog publication

@obviyus
obviyus force-pushed the fix/models-catalog-refresh branch from 1d2a5ae to 1b51402 Compare August 31, 2026 18:46
@obviyus
obviyus force-pushed the fix/models-catalog-refresh branch from 1b51402 to 7c6eda6 Compare August 31, 2026 18:52
@openclaw-barnacle openclaw-barnacle Bot added the extensions: memory-lancedb Extension: memory-lancedb label Aug 31, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head 7c6eda6bf4b3. Everything below is diff file:line plus one control-arm measurement I ran locally against main.

1. includeCredentialProviders: true is unconditional, so token rotations are not "identical cost to current main"

The body says rotations "touch nothing but the static credential projection — identical cost to current main" and "trigger zero discovery work — no new load on gateways that stay up for weeks." The first half holds: no live discovery is introduced. The second does not. Every auth mutation — rotation included — now publishes a wider provider set than main does.

invalidateForAuthMutation passes the flag with no reference to the fact this PR just went to the trouble of producing:

await drainPendingAuthMutations({
  includeCredentialProviders: true,   // unconditional
  commit: () => { ... },
});

profileSetChanged is consulted a few lines earlier, but only for owner.catalogStale. From there the flag is threaded straight through publishPreparedModelRuntimeOwnerBatch -> startSerializedSnapshotBuildBatch -> buildSnapshotBatch -> prepareWorkspaceBuildGroup -> prepareAgentFacts -> collectPreparedModelRuntimeProviderIds, and no hop re-checks it. Static and live owners are grouped together in that batch (prepared-model-runtime.owner.ts:497-510), so static owners get the wider set too.

What that third argument actually changes — measured on main, since collectPreparedModelRuntimeProviderIds is untouched by this PR. Config names one provider, auth storage holds four:

{
  "main, auth publication (catalogMode !== live)": ["openai"],
  "this PR, auth publication":                     ["anthropic", "moonshot-cn", "openai", "openrouter"]
}

(real exported function under node --import tsx, no mocks, no test harness)

providerIds becomes providerDiscoveryProviderIds at prepared-model-runtime.facts.ts:615 and flows into ensureOpenClawModelsJson / planOpenClawModelsJsonSource. To be precise about the size of this: static owners keep providerDiscoveryEntriesOnly: true, so this is not live discovery and I am not claiming a network fan-out. What changes on every rotation is the static provider set admission consumes and that gets serialized to models.json.

The gate you parameterized still carries main's comment, unedited, immediately above the call site:

Gateway startup prepares only providers named by config/model selection. An unrelated stored credential must not pull that provider's complete catalog into the admission path.

That line is not incidental — it arrived with a67ad03eea4 (perf(gateway): bound prepared runtime startup work, #116261), i.e. it is the shipped statement of the bound this branch now widens. After this PR the comment describes a rule the code no longer follows on the auth path.

I do think the widening itself is necessary rather than accidental: createFullModelCatalogAccess builds its worker from agentFacts (prepared-model-runtime.build.ts:147-153), so a later loadFullModelCatalog({ refresh: true }) can only surface a provider that was already in providerIds. Drop the flag and the feature stops working. But that is precisely the argument for making it conditional — you only need the wider set on the publications that also set catalogStale:

includeCredentialProviders: <this transaction carried profileSetChanged>

Rotations then stay byte-identical to main, the new provider still lands before the first stale read consumes it, and the flag is derived from the same produced fact rather than from a constant. Either way the facts.ts comment should state whatever the new rule is, otherwise the next person to touch that gate reads a bound that no longer exists.

2. Two of the three surfaces the body names do not consume the flag

Body: "Explicit read-only catalog reads (/models, models.authStatus, openclaw models list) consume the flag."

refreshStalePreparedModelRuntimeCatalog is reachable only from materializeRequestedModelCatalog, and loadPreparedModelCatalogOwnerSnapshotWithPolicy calls that only when params.readOnly and a published owner already exists (prepared-model-catalog.ts:313-317). Tracing the three named surfaces:

  • /models default view and gateway models.list — reach it. Confirmed.
  • models.authStatus — only on the refresh: true arm. The default arm is readPreparedCatalog(...) (models-auth-status.ts:557-563), a cached read that never enters the materializer. That is the surface an operator opens right after models auth login to check the credential took, and it will still answer from the pre-login catalog.
  • openclaw models list with no flags — providerDiscoveryProviderIds is always populated on the default view (list.list-command.ts:147-160), and loadPreparedModelCatalogSnapshot diverts every readOnly + scoped call to loadScopedReadOnlyModelCatalog (prepared-model-catalog.ts:449-451), which never materializes. Only --all takes the owner path.

Narrowing this honestly: the CLI runs in its own process, so an in-memory stale flag was never going to help it, and the default view still renders authored fallback rows for authenticated providers — the CLI item is a body-accuracy issue more than a user-visible one. models.authStatus is the one with a real consequence, and it is cheap to fix by consuming the flag on the non-refresh arm as well.

3. The stale consumption has two silent no-op branches and no test on either

refreshStalePreparedModelRuntimeCatalog resolves its owner by reference identity:

const owner = [...owners.values()].find((candidate) => candidate.snapshot === snapshot);
if (!owner?.catalogStale || !snapshot.loadFullModelCatalog) return undefined;

A miss returns undefined and the caller falls back to readFullModelCatalog?.() — the exact pre-change behavior. The second branch is the params.readOnly && !publishedReadOnlyOwner early return above, which skips the materializer wholesale.

Both are plausibly correct today. The concern is that all four new tests exercise the published-owner, identity-matching path, so if either branch is later taken by a real read the suite stays green while the original bug is back. A test that asserts the flag is still set after a read that took the fallback would pin the boundary you actually rely on.

None of this contests the design — one produced fact, static admission preserved, live work moved to the reader is the right shape, and the single-flight sharing on the stale read is a nice touch.

…snapshots

Split the max-lines boundary by moving persisted mutation lineage out of runtime snapshots; behavior is unchanged.
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Sep 1, 2026
@clawsweeper clawsweeper Bot removed P2 Normal backlog priority with limited blast radius. 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. labels Sep 1, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Sep 1, 2026
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: XL and removed size: L labels Sep 1, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 1, 2026
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

The previous review was against the pre-fix head. Since then:

  • P1 addressed — stale-catalog refresh is now explicit opt-in: it requires both readOnly === true and refreshFullCatalog === true (src/agents/prepared-model-catalog.ts:78-85). Request paths (attachment admission, HTTP model override, models.authStatus, Control UI automatic reads) never pass the flag, so no request path can be made to await full provider discovery.
  • Regression coverage — src/agents/prepared-model-runtime.reload-auth.test.ts:34-108 marks the catalog stale, blocks the discovery worker, asserts the default read settles without calling it, then asserts explicit refresh does call it. It fails on pre-fix code.
  • LOC — judged production delta +113 (raw +130 minus test-support +17); ~+110 after discounting the pure mutation-lineage.ts / runtime-snapshots.ts extraction, which is a move rather than new logic. Tests +329/-9. The justification for the positive delta on a bug fix is in the PR body under "ClawSweeper review response".
  • /models latency — the default read path is unchanged; only the four explicit-refresh callers (/models, Control UI models.list, full models.list escalation, unscoped openclaw models list) can trigger discovery.
  • Autoreview — clean at the current head, no actionable P0.

CI at b919d5b8a23: the one red shard was core-unit-src-security-3 in checks-node-compact-large-8, killed with exit 137 after every test in the shard reported ✓ — a runner OOM, not a test failure. Failed jobs rerun on run 33469062940.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

P2 "Clear stale state after a live catalog publication" — premise does not hold

The finding assumes a live-mode publication produces a current full catalog, so leaving catalogStale set costs a redundant provider rediscovery on the next browse. It does not. needsRefresh and catalogStale track two different subjects with two different lifecycles, and both clear sites are correct as written.

The full catalog is lazy and is never populated by a publication. In src/agents/prepared-model-runtime.build.ts, fullCatalog is declared at line 137 and assigned in exactly one place — line 228, inside loadFullModelCatalog itself. The snapshot build populates routing facts and provider identity; it never fills the browse catalog, in either catalog mode.

  • src/agents/prepared-model-runtime.build.ts:137 — let fullCatalog: ModelCatalogSnapshot | undefined;
  • src/agents/prepared-model-runtime.build.ts:228 — sole assignment, inside the loadFullModelCatalog refresh path
  • src/agents/prepared-model-runtime.build.ts:197-205 — loadFullModelCatalog returns the cached value only when one exists

So after a profile-set mutation the browse catalog really is stale, and the refresh the next explicit browse performs is the required work, not a redundancy.

Measured, not argued. I wrote the regression test the finding implies — profile-set mutation, then a publication, then an explicit browse — parameterized over both catalog modes, counting runPreparedModelCatalogWorker invocations:

mutationListener({ profileSetChanged: true })
await prepareModelRuntimeSnapshot(input)
publicationDiscoveryCount = worker.mock.calls.length   // 0, in BOTH live and static
await loadPreparedModelCatalogOwnerSnapshot({ ...input, readOnly: true, refreshFullCatalog: true })

The publication ran the catalog worker zero times in live mode, exactly as in static mode. Asserting live -> publicationDiscoveryCount (no refresh on browse) fails with expected 1 to be +0, and it keeps failing with the proposed clear applied — because the clear would suppress a refresh that has never happened yet. Clearing catalogStale on publication would not remove redundant work; it would serve an operator a stale model list after an auth change, which is the exact bug this PR fixes.

src/agents/prepared-model-runtime.reload-auth.test.ts:79-80 already pins the same invariant on the shipped path: after publication, buildPreparedModelCatalogSnapshot and runPreparedModelCatalogWorker are both uncalled.

Not applying this rank-up move. The experiment and its revert are recorded here rather than in the diff; head is unchanged at b919d5b8a23ba9b55560d5b467bc6e1f92dff78b.

@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review — the P2 ("clear stale state after a live catalog publication") is refuted with measurement in the comment above; head is unchanged. Requesting a rating refresh.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@obviyus
obviyus merged commit d8f55fa into main Sep 1, 2026
459 of 461 checks passed
@obviyus
obviyus deleted the fix/models-catalog-refresh branch September 1, 2026 05:35
@obviyus

obviyus commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Post-merge note — this landed while I was measuring it, so this is for a follow-up rather than for this PR. My earlier finding 1 is fully addressed — includeCredentialProviders is now carried on the transaction and derived from profileSetChanged (prepared-model-runtime-auth-publication.ts:20/61/234), so a rotation really is byte-identical to main now. Thanks for taking the conditional rather than the flag.

The other half of that same commit introduces a regression, and the whole suite stays green through it.

advancePreparedModelRuntimeOwnerConfig writes owner.snapshot without updating ownersBySnapshot

794c813e349 (merged, now on main) replaced the identity scan in refreshStalePreparedModelRuntimeCatalog with a WeakMap keyed on the snapshot object:

  • prepared-model-runtime.owner.ts:43 — const ownersBySnapshot = new WeakMap<...>()
  • prepared-model-runtime.owner.ts:51 — publishPreparedModelRuntimeOwnerSnapshot, the only writer, called from the two publish paths
  • prepared-model-runtime.ts:379 — const owner = resolvePreparedModelRuntimeOwnerBySnapshot(snapshot)

There is a third assignment to owner.snapshot that does not go through that writer:

// prepared-model-runtime.owner.ts:265, in advancePreparedModelRuntimeOwnerConfig
owner.snapshot = stampPreparedModelRuntimeSnapshotConfig(owner.snapshot, config);

stampPreparedModelRuntimeSnapshotConfig returns Object.freeze({ ...snapshot, config }) — a new object identity whenever the config identity actually changed, which is the only case that reaches this line. The map keeps pointing at the retired snapshot; the snapshot every reader now receives is absent from it. catalogStale is untouched by the advance, so the flag stays set and the lookup that consumes it stops finding its owner.

Both callers are live gateway paths, not test-only:

  • prepared-model-runtime.ts:108 ← advancePreparedModelRuntimeConfig, called from gateway/server-reload-managed.ts:375 on every model-neutral runtime-config commit (canAdvancePreparedModelRuntimeConfigInPlace)
  • prepared-model-runtime.refresh-scope.ts:94 ← the retainedConfig arm of updateOwnersForScopedRefresh, i.e. every owner outside a scoped refresh

So: models auth login → any in-place config commit → /models. The stale flag is set, the refresh is skipped, the operator gets the pre-login catalog. That is the bug this PR exists to fix.

Measured, with a control arm and a mutation arm

Two arms, identical except for one advancePreparedModelRuntimeConfig({}) between the auth publication and the read. Counting runPreparedModelCatalogWorker invocations, catalogMode: "static", profileSetChanged: true.

Direct entry point (the same one all four of the PR's new tests call):

MEASURE advanceConfig=false  staleRefreshCount=1  refreshed=["authenticated-model"]
MEASURE advanceConfig=true   staleRefreshCount=0  refreshed=null

End to end through loadPreparedModelCatalogOwnerSnapshot({ readOnly: true, refreshFullCatalog: true }):

BROWSE advanceConfig=false  -> reaches materializeRequestedModelCatalog
                               (throws "prepared full model catalog omitted its auth generation"
                                at prepared-model-catalog.ts:91 — my fixture's worker result has no
                                auth generation; the refresh itself ran)
BROWSE advanceConfig=true   -> refreshCount=0, entries=[], no throw: the refresh never ran

Mutation arm. Reverting only line 379 to the pre-refactor scan, [...owners.values()].find((candidate) => candidate.snapshot === snapshot), and changing nothing else:

MEASURE advanceConfig=false  staleRefreshCount=1
MEASURE advanceConfig=true   staleRefreshCount=1     <- was 0
BROWSE  advanceConfig=false  -> reaches materializeRequestedModelCatalog
BROWSE  advanceConfig=true   -> reaches materializeRequestedModelCatalog   <- was skipped

and the 15 existing tests in prepared-model-runtime.reload-auth.test.ts all still pass under that revert. The old scan read owner.snapshot at call time, so a re-stamp was invisible to it; the map caches an identity that a re-stamp invalidates. The refactor is what changed behaviour here, not the profileSetChanged threading.

The fix is one line at the assignment, not at the lookup:

// advancePreparedModelRuntimeOwnerConfig
publishPreparedModelRuntimeOwnerSnapshot(owner, stampPreparedModelRuntimeSnapshotConfig(owner.snapshot, config));

That also closes the class rather than this instance: any future owner.snapshot = outside the writer reopens it. Worth a comment on ownersBySnapshot saying the writer is the only permitted assignment site.

Narrowing this honestly: nothing here is a correctness problem for owners that never take a config advance, and the WeakMap is the right structure — the scan was O(owners) on a read path. The defect is that one assignment site was left outside it. And the reason the suite cannot see this is exactly the boundary I raised last round: every test drives refreshStalePreparedModelRuntimeCatalog on the snapshot object returned by the publication that set the flag, so the lookup can only ever hit.

Minor, carried over

prepared-model-runtime.facts.ts:132-133 still carries main's comment unedited:

Gateway startup prepares only providers named by config/model selection. An unrelated stored credential must not pull that provider's complete catalog into the admission path.

With the conditional in place the widened set is now reached only from a profile-set publication, which is a narrower and defensible rule — but the comment still only describes startup and says nothing about the auth path that now also reaches this gate.

@Yigtwxx

Yigtwxx commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Follow-up opened as #134922: routes the advancePreparedModelRuntimeOwnerConfig assignment through publishPreparedModelRuntimeOwnerSnapshot so the config stamp moves the owner index with it, plus a regression test that fails on main and passes with the change.

steipete added a commit that referenced this pull request Sep 1, 2026
Publish config-stamped snapshots through the existing owner registry for config-only updates as well as ordinary and batch builds. Existing leases stay immutable and retain their auth bindings. Extend the stale-catalog regression; all 65 related tests pass. Related: #130324, #134361.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
* fix(models): refresh catalog content after credential-identity changes

* refactor(agents): split auth-profile mutation lineage out of runtime-snapshots

Split the max-lines boundary by moving persisted mutation lineage out of runtime snapshots; behavior is unchanged.

* refactor(agents): annotate the moved test-api global assertion for the safety ratchet

* test(agents): type the catalog worker mock and shrink the assertion baseline

* perf(agents): bound auth publication provider facts

* perf(gateway): keep auth status off catalog discovery

* fix(agents): reject retired catalog owners

* test(gateway): resolve the auth-status handler result before racing it

* fix(models): gate catalog refresh by read intent

* test(models): prove deferred catalog reads stay static

* test(models): type the unscoped catalog-refresh row context
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
…5063)

Publish config-stamped snapshots through the existing owner registry for config-only updates as well as ordinary and batch builds. Existing leases stay immutable and retain their auth bindings. Extend the stale-catalog regression; all 65 related tests pass. Related: openclaw#130324, openclaw#134361.
RomneyDa added a commit that referenced this pull request Sep 29, 2026
* fix(plugins): recover orphan installs without weakening ownership

Closes #134321

## What Problem This Solves

Operators could not run `openclaw plugins update --all` or uninstall a path-source plugin after both tracked plugin paths disappeared. Registry refresh succeeded but left the durable install record behind, so both commands failed on the same ownership check.

## Why This Change Was Made

Plugin lifecycle ownership now distinguishes an active package from an exact orphan record. Update and uninstall may act on an orphan only after duplicate-path and conflicting-plugin checks pass. Inspection, capability consent, active packages, and restored packages keep strict package ownership.

Post-update reconciliation accepts an unchanged safe orphan while another package updates. If an orphan install record changes, the replacement must restore a strictly valid package before any update can commit.

Uninstall removes owner-keyed plugin and channel policy plus the durable install record. Child policy remains based only on authoritative discovered children.

## User Impact

Operators can update their remaining plugins and remove stale path-source install records without editing OpenClaw state by hand. Ambiguous, conflicting, and invalid replacement packages still fail closed.

## Evidence

Current `main` at `77fee957919f06dbaff09dd5cc7f9664d9655651` failed through the real command-line flow after a local plugin was installed and both tracked paths were moved away:

```text
$ openclaw plugins update --all --dry-run
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1

$ openclaw plugins uninstall orphan-proof --force
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1

$ openclaw plugins registry --refresh
Plugin registry refreshed: 0/0 enabled plugins indexed.
Exit 0

$ openclaw plugins update --all --dry-run
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1
```

Exact head `06de2f66734fd338e457f50a3060e2d625288274` passed the same flow:

```text
$ openclaw plugins update --all --dry-run
Skipping "orphan-proof" (source: path).
Exit 0

$ openclaw plugins uninstall orphan-proof --force
Uninstalled plugin "orphan-proof". Removed: config entry, install record.
Exit 0

$ openclaw plugins update --all --dry-run
No tracked plugins or hook packs to update.
Exit 0
```

The contributor head initially accepted a changed orphan install record with no authoritative children. The new owner-boundary regression failed with `{ ok: true }` before the maintainer repair and passes after it.

Validation:

- `node scripts/run-vitest.mjs src/plugins/manifest-registry-installed.test.ts src/plugins/management-service.uninstall-ownership.test.ts src/plugins/plugin-package-update.test.ts src/cli/plugins-cli.update.test.ts src/cli/plugins-cli.uninstall.test.ts` — 129 passed.
- Targeted Oxfmt and Oxlint — passed.
- Max-lines and assertion-safety ratchets — passed.
- Coercion, deprecated-API, dead-export, native-schema, and import-cycle guards — passed.
- `git diff --check` — passed.
- Local type checking was not run because host policy requires CI for OpenClaw type checks.

The proof fixture, isolated states, removed plugin copies, and proof manifest remain in the durable maintainer worktree.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): repair keyed multi-agent rosters without ownership (#134706)

* fix: prevent device pairing migration crash on contaminated records

Closes #134340

## What Problem This Solves

Operators upgrading from the retired JSON device-pairing store can have pending requests or malformed values inside `devices/paired.json`. One bad record aborts the full JSON-to-SQLite import, keeps every valid pairing out of SQLite, and repeats the failed migration on each gateway start.

The pairing migration failure is caught and logged. It does not stop gateway startup by itself. The field report also contained a separate legacy session-store blocker.

## Why This Change Was Made

The migration now validates every field that SQLite binds directly. It skips records with invalid required pairing data. When only optional metadata is malformed, it omits that field and preserves the usable pairing. The original legacy store is archived only after the safe import completes.

Validation includes required timestamps, optional `lastSeenAtMs`, and optional text columns. Separate warnings report skipped records and omitted optional fields. The SQLite mapper remains strict, and no schema or fallback path changes.

## User Impact

Valid device pairings survive an upgrade even when the legacy file also contains pending requests or malformed records. The gateway completes the import once and does not retry it after restart.

## Evidence

- Current-main red at `77fee957919f06dbaff09dd5cc7f9664d9655651`: a normal isolated gateway logged `NOT NULL constraint failed: device_pairing_paired.created_at_ms` for a pending-shaped leaf and retained `paired.json`.
- Anti-cheat red: changing the malformed leaf to `lastSeenAtMs: 1e100` logged `cannot store REAL value in INTEGER column device_pairing_paired.last_seen_at_ms`.
- Regression red on contributor head `ee7ea2bfbc5bde3e1b6f90ea58e4d070b7e7ff61`: the expanded boundary test failed with `Provided value cannot be bound to SQLite parameter 47`.
- Fixed-head boundary proof: `node scripts/run-vitest.mjs src/infra/device-pairing-migration.test.ts` passed 7/7; targeted formatting and Oxlint passed.
- Optional-preservation red on `4f47648f1d6bcf279697d4e8ec5044960bb27cf5`: the corrected regression failed because only one row imported instead of preserving three usable pairings.
- Final real gateway proof: startup returned `status=started`, imported three usable pairings, stored malformed optional metadata as `NULL`, skipped one record with invalid required data, archived `paired.json`, and restarted with no migration log.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): preserve per-agent memory search during upgrades

Closes #134256

Reported by @vdruts.

## What Problem This Solves

Fixes an issue where operators running `openclaw doctor --fix` after an upgrade could silently lose every per-agent memory-search override when Doctor converted `agents.list` to keyed `agents.entries` first. This removed settings such as `extraPaths`, `sources`, `experimental.sessionMemory`, and `enabled`.

## Why This Change Was Made

Doctor now visits both keyed agent entries and legacy list entries at the migration owner. It moves `memorySearch` before unknown-key cleanup, preserves explicit canonical values, and applies the existing provider, nested-field, and retired-path migrations to the moved data.

The shared agent-scope traversal replaces two duplicate traversal implementations. The regression was introduced by #112678, which moved roster normalization before the older list-only migration from #111527.

## User Impact

Per-agent memory-search settings now survive `openclaw doctor --fix` and remain attached to the correct agent. Operators no longer lose per-agent retrieval paths silently during this upgrade path.

## Evidence

- Red on current-main baseline `8abb80073c8648e85d11a0e9bd22b09d1d2bfac2`: [Testbox run 33466170600](https://github.com/openclaw/openclaw/actions/runs/33466170600) removed the legacy block and retained only the pre-existing canonical field.
- Green on exact head `983df6b6ddf33ffad80f32874966ffeeaf0a803f`: [Testbox run 33467597600](https://github.com/openclaw/openclaw/actions/runs/33467597600) ran the real CLI, preserved supported fields and canonical precedence, verified the authored input, and produced byte-identical config on a second Doctor run.
- Regression proof: the strengthened Doctor process test fails on the baseline and passes on the head.
- `node scripts/run-vitest.mjs src/commands/doctor-config-preflight.process.test.ts` — 10 passed.
- `node scripts/run-vitest.mjs src/commands/doctor/shared/legacy-config-migrate.test.ts src/commands/doctor/shared/legacy-config-migrations.runtime.retired.memory-qmd.test.ts src/commands/doctor/shared/legacy-config-migrations.runtime.retired.test.ts` — 294 passed.
- Focused format, Oxlint, Doctor registry, coercion helper, max-lines, assertion safety, import-cycle, temp-directory, conflict-marker, and dead-export checks passed.
- Autoreview on the exact local diff: clean, no actionable P0 findings.

Agent task: https://chatgpt.com/codex/tasks/01a040d7-aa3d-7433-83eb-de7f49979443

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): detect shared auth migration by provenance (#134808)

* fix(cron): refuse stale doctor store rewrites

Prevent `openclaw doctor` from replacing cron definitions or runtime-owned state captured before its interactive repair prompt.

Doctor now rechecks a bounded definition-and-order fingerprint inside the SQLite write transaction. Definition changes stop the repair with a retry warning. Runtime columns and current runtime authority remain owned by the Gateway, while repaired authorization-input changes fail closed into recovery.

Preserve old embedded-authority migration and current quarantine recovery.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(gateway): refresh model catalog after auth changes (#134361)

* fix(models): refresh catalog content after credential-identity changes

* refactor(agents): split auth-profile mutation lineage out of runtime-snapshots

Split the max-lines boundary by moving persisted mutation lineage out of runtime snapshots; behavior is unchanged.

* refactor(agents): annotate the moved test-api global assertion for the safety ratchet

* test(agents): type the catalog worker mock and shrink the assertion baseline

* perf(agents): bound auth publication provider facts

* perf(gateway): keep auth status off catalog discovery

* fix(agents): reject retired catalog owners

* test(gateway): resolve the auth-status handler result before racing it

* fix(models): gate catalog refresh by read intent

* test(models): prove deferred catalog reads stay static

* test(models): type the unscoped catalog-refresh row context

* fix(openai): repair stale doctor route pins

Declare canonical OpenAI session-route ownership at the OpenAI plugin manifest boundary.

Clear automatic fallback-origin provenance when Doctor removes the stale model override. Preserve explicit model choices and valid locked harness sessions.

Fixes #101672.

Credit @849261680 for the original report-driven repair.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): verify shared credential migration receipts (#134952)

Attach expected credential fingerprints to both credential-store receipt
variants so interrupted shared-store imports use the existing verification
and archive recovery flow. State-only receipts retain their own verification.

Regression coverage interrupts archival and removes the destination before
retrying both legacy auth file formats against both SQLite destinations.
The shared-store cases fail before this change; all 90 focused tests pass.

Related to #134608, reported by @erameson. This preserves the existing
non-replay policy for completed receipts; recovery of already-completed
receipts requires a separate maintainer decision.

* fix(cron): keep model aliases scoped to the selected owner (#135069)

Reuse the published model owner metadata for default, agent, subagent, payload, session, and Gmail selections. Consolidate override arguments while retaining agent-specific policy and existing precedence. Six regression cases fail before and pass after; 83 related tests pass. Related: #130324, #130706.

* fix(memory): resolve profile auth for compatible embeddings (#134744)

* fix(memory): resolve profile auth for compatible embeddings

* test(memory): close profile fixture SQLite handles

* fix(memory): preserve credential ownership in embedding auth

Resolve saved profile bindings through the canonical terminal auth capability while preserving literal, blank, explicit-header and destination behavior. Retain general model-auth precedence and shared guard policy; exercise real HTTP, SQLite and public CLI indexing/search. Reuse the canonical doctor CI fixture and repair executable-preflight test isolation.

Co-authored-by: 0x-Parzival <[email protected]>

* fix(memory): preserve auth policy for configured embeddings

Carry the selected provider API into the canonical auth-mode check, so direct OpenAI routes reject saved token profiles before embedding HTTP. Check auth migration readiness before classifying provider-entry credentials, including warm snapshots after a legacy credentials file is restored. Keep explicit remote credentials, literal keys, and canonical SQLite profile ownership intact.

Regression coverage exercises provider/API/credential-mode combinations and cold-empty, warm-empty, and populated canonical stores with real embedding HTTP and SQLite.

Co-authored-by: 0xParzival <[email protected]>

* test(pr): reuse landed cross-checkout fixture

Adopt the exact cross-checkout fixture already landed in main by #134740, resolving the overlapping cleanup while preserving the isolated executable command stubs. The embedding and auth implementation is unchanged.

Co-authored-by: 0xParzival <[email protected]>

---------

Co-authored-by: 0x-Parzival <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: 0xParzival <[email protected]>

* fix(auth): recover credentials stranded by completed migrations (#135346)

* fix(auth): recover inconsistent completed credential migrations

* test(auth): brace completed receipt recovery branches

* fix(auth): relogin repairs stale profile order after upgrade

Closes #135140

Reported by @mattcbianco.

## What Problem This Solves

Fixes an issue where users who signed in to OpenAI again after shared auth-store relocation could still get `Explicit auth order for openai has no usable profiles.` before a model request started.

## Why This Change Was Made

Login credentials and per-agent profile order have separate SQLite owners after relocation. Profile promotion now reads the effective credential view before it updates the agent-local order, and it preserves the inherited profile ID when it saves that order.

This keeps explicit order fail-closed behavior unchanged. It does not add a dispatch fallback or copy shared OAuth credentials into the agent database.

## User Impact

A successful OpenAI relogin now places the new usable profile before stale entries, so the next `openai/*` model call can start with the login that just succeeded.

## Evidence

- Current-main baseline: `2e3f734017b9b1a5a32ba11d844d1fa7a5141de9`.
- Before: Codex reported a healthy ChatGPT login and OpenClaw listed a healthy OAuth profile, but the selected Codex runtime had no effective profile. Real Luna and Sol turns stopped before provider dispatch with `Explicit auth order for openai has no usable profiles.`
- After: OpenClaw device login stored the fresh OAuth profile, agent-local order became `[fresh, stale]`, and status reported a usable Codex runtime route.
- Live exact-head result: a real `openclaw agent --local` Luna turn returned exactly `ISSUE_135140_EXACT_HEAD_GREEN_2` through provider `openai`.
- Shipped CLI regression: `models auth login --provider openai --agent main` failed on the baseline because local order stayed absent; passed after the fix with `[fresh, stale]`.
- Focused CLI, owner, and sibling tests: 131 passed across login promotion, auth upsert/rollback, shared-store relocation, and runtime auth planning.
- Oxfmt, Oxlint, and `git diff --check`: passed.
- Autoreview P0: clean.

Production delta: `+4/-5` (net `-1`). Test delta: `+108/-0`.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): preserve custom provider SecretRefs in Doctor

Fixes #135079.

Thanks @dannevang for the detailed report and two-provider reproduction.

## Problem

After an upgrade, `openclaw doctor` could treat custom-provider environment references and generated catalog values as plaintext API keys. It persisted them as auth profiles, and those profiles could shadow the provider's direct environment credential.

## Root cause

Config substitution discarded the fact that a resolved string came from an authored environment SecretRef. Doctor then classified model catalog strings without the provider's authored resolution facts. Runtime planning and status also treated stored profiles as usable ahead of an unqualified provider SecretRef.

## Fix

- Record resolved environment SecretRef provenance during config substitution.
- Make Doctor keep an authored provider SecretRef authoritative over root and plugin catalogs.
- Remove only persisted profiles whose values exactly match that provider's reference markers.
- Make runtime planning and model status prefer the authored provider SecretRef.
- Reuse the already loaded authored model config during status readback.

The production delta is +122 lines. The added code carries provider-specific pending/resolved provenance across config and worker boundaries and performs exact-value cleanup at the credential-migration owner. A global marker heuristic or downstream guard would not preserve this ownership or safely repair existing rows.

## Proof

- Baseline main `9d10dcb5d39d09be94f48a1bfce1dbfd7a256903`: Doctor migrated two `${VAR}` references plus stale or bare generated values; model status selected stored profiles over fresh direct environment values.
- Exact head `fc74120ab55d071e7c876b2f00c9db47032b8bb8`: Doctor migrated no model credentials, preserved both authored references, left no `authProfiles.store` row, and status selected two distinct environment credentials with zero profiles.
- Main commits after the baseline did not touch any changed file.
- Regression tests were red before the fix and green at the exact head.
- Focused tests, the remote changed-scope gate, and the exact-head remote build passed. The first PR CI run exposed source-authority and max-lines defects; the exact failing tests now pass locally.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(docker): install libgomp1 in the runtime image for managed llama.cpp (#134532)

* fix(docker): install libgomp1 in the runtime image for managed llama.cpp

The official ghcr.io/openclaw/openclaw image (bookworm-slim) never
installed libgomp1. The verified llama.cpp release binaries downloaded
by managed local llama-server setup are linked against libgomp, so the
--version preflight probe fails with "libgomp.so.1: cannot open shared
object file", making local embeddings unreachable in the official
Docker image.

Fixes #134439.

* fix(docker): clarify managed llama-server runtime requirement

Keep the mandatory OpenMP runtime in the image and identify its preflight contract in the existing comment and regression test.

Co-authored-by: chelsealong <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: chelsealong <[email protected]>

* fix(devices): allow authorized scoped node token management (#135617)

* fix(cli): allow authorized node token rotation and revocation

* test(cli): keep token scope fixture indices typed

* test(ui): scope catalog marquee assertions to session rows

* fix(msteams): thread context is dropped when a channel reply has no replyToId (#129345)

* fix(msteams): thread context is dropped when a channel reply has no replyToId

Teams channel activities frequently arrive without `replyToId`. Thread context
resolution keyed exclusively off that field, so parent-message and sibling-reply
context silently never loaded for those turns and the agent answered without any
of the thread it was replying in.

Fall back to the thread root already parsed from the conversation id. The Graph
message URL builder in `attachments/graph.ts` resolves the same value this way
via `threadRootMessageId`, and `resolveMSTeamsRouteSessionKey` likewise accepts
both, so this aligns thread context with the two adjacent call sites rather than
introducing a new source of truth.

The self-comparison guard keeps a top-level post from being treated as its own
parent, mirroring the `threadRootMessageId !== messageId` check in graph.ts.

Behaviour is unchanged whenever `replyToId` is present.

* fix(msteams): resolve thread context against the conversation thread root

Review follow-up: the fallback chose `replyToId` ahead of the conversation's
embedded thread root, which contradicts the canonical precedence used elsewhere
in the plugin.

`resolveMSTeamsRouteSessionKey` reads `conversationMessageId ?? replyToId`, and
`attachments/graph.ts` resolves the Graph message URL from `threadRootMessageId`
the same way. On a deep reply, where both identifiers are present and differ, the
previous ordering routed the session to the thread root while fetching parent and
sibling context beneath the nested reply — attaching context from one message to
the session of another.

Take the conversation root first and keep `replyToId` as the fallback for
activities whose conversation id carries no thread suffix. The self-comparison
guard is retained so a top-level post is not treated as its own parent, matching
the `threadRootMessageId !== messageId` check in graph.ts.

Adds a handler-level regression covering both identifiers present and different;
it fails under the previous ordering.

* refactor(msteams): tighten the thread-root invariant comment

Condenses the nine-line block to the three-line form used elsewhere in this file,
keeping the two load-bearing facts: why the conversation root wins over replyToId,
and that replyToId remains the fallback. No behavior change.

* test(msteams): prove channel thread retrieval at the Graph boundary

The existing thread-parent tests stub ../graph-thread.js, so they pin the
selection rule but never reach the retrieval boundary the repair actually moves.
This asserts on the HTTP requests the process issues instead: thread-context.ts,
graph-thread.ts and graph.ts all run unmocked, and the only stub is globalThis.fetch.

The stub has to be a vi.fn(). fetchWithSsrFGuard treats a fetch carrying a .mock
property as a test-installed mock (isMockedFetch) and lets it win; a plain function
is bypassed in favour of undici dispatcher-aware fetch, and records nothing.

For a channel activity with no replyToId the process now issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent. With threadParentId reverted to
activity.replyToId that set is empty, so the first assertion fails on zero requests.

* test(msteams): prove channel thread retrieval through the registered handler

Replaces the direct-invocation variant with one shaped after
approval-control.mock-gateway.test.ts: the activity enters through
registerMSTeamsHandlers and is driven by the registered Bot Framework onMessage
callback, so the inbound path runs as registered rather than a handler factory
being called directly.

The message handler, thread-context.ts, graph-thread.ts and graph.ts all run
unmocked; Graph is observed at the fetch boundary. The stub has to be a vi.fn()
because fetchWithSsrFGuard only lets a fetch carrying a .mock property win over
undici dispatcher-aware fetch (isMockedFetch).

For a channel activity delivered without replyToId the process issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent as a system event. With threadParentId
reverted to activity.replyToId neither request is issued.

* fix(test): restore ambient fetch and correct the mock-gateway proof signatures

Three defects in the proof added by the previous commit, all caught by CI:

- The fetch stub was never restored, so it leaked into sibling suites sharing the
  worker and extensions/msteams/src/qa/bot-framework-server.test.ts began seeing 200
  for requests it expects to reject. An afterEach now restores the ambient fetch.
  The local full-suite run passed only because vitest happened to order the files
  the other way round; running the two files together reproduces it.
- OpenClawConfig was imported from ./runtime-api.js; the module sits one level up.
- The registered onMessage callback takes (context, next, turnAdoptionLifecycle);
  both call sites passed only the context.

* fix(test): drop redundant String() conversions in the mock-gateway proof

typescript(no-unnecessary-type-conversion) flagged both call sites: the optional
chain already yields a string once defaulted, so String() changes neither type nor
value. The rule is type-aware, so a bare oxlint run over the single file did not
surface it; only the project shard does.

---------

Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>

* fix(ui): ignore tool-only model auth rows (#134218)

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): preserve model accounts when filtering tool credentials

Use canonical monitored-auth evidence for Model Providers cards. Preserve
OAuth and non-expiring token profiles, alias logout targets, configured
models and usage while omitting tool-only API-key rows. Remove duplicate
usage-presence bookkeeping.

Refs #134218. Production LOC -3; tests +56.

Co-authored-by: wantosure <[email protected]>

* test(ui): assert usage failures without provider cards

Replace the stale OpenAI-card readiness wait with the visible usage
failure outcome and assert that an unconfigured provider stays absent.
Preserve the RPC assertion and all configured-provider sibling cases.

Refs #134218. Production unchanged; test LOC net zero.

Co-authored-by: wantosure <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: wantosure <[email protected]>

* fix(cron): kind change fails with "command env must be an object" when env is omitted (#134639)

* fix(cron): omit undefined payload fields

* fix(cron): preserve valid payload kind conversions

Omit absent optional payload fields at the replacement producer and remove
unreachable same-kind fallback branches. Keep strict validation and cover
actual service persistence, malformed env, and tool restrictions.

Co-authored-by: Solomon Neas <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Solomon Neas <[email protected]>

* fix(backup): exclude workspaces before traversal

Carry disabled workspace roots into the shared backup inventory before tar and SQLite traversal. Preserve nested agent state and keep absolute-link rejection for included content.

Fixes #135218. Supersedes #135243 and #133990.

Thanks @jarvismazz and @yubingjiaocn for the reports. Thanks @ericcaiwx-star and @ruel225 for the original repair work.

Co-authored-by: ericcaiwx-star <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(infra): drop empty PATHEXT entries from Windows extension lookup (#135807)

* fix(infra): drop empty PATHEXT entries from Windows extension lookup

resolveWindowsExecutableExtensions split PATHEXT on ";" without dropping
empty components. A trailing ";", which is common in real PATHEXT values,
leaves "" in the list, so an extensionless file matches even when the
caller passed includeExtensionless: false. windows-command.ts and tui.ts
both pass false.

The sibling resolveWindowsExecutableExtSet in the same file already
filters, so this was just the one path missing it.

* fix(infra): reuse normalized Windows executable extensions

Keep extensionless command lookup explicit by sharing the existing PATHEXT parser. Remove duplicate parsing and cover empty suffixes, explicit filenames, and the command-resolution caller.

Co-authored-by: Teddy Tennant <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Teddy Tennant <[email protected]>

* fix(anthropic): context usage is lost when a proxy omits message_delta usage (#135467)

* fix(anthropic): keep context usage when message_delta omits usage

The Anthropic SDK lane guarded the shared usage accumulator against an omitted
message_delta usage object; the managed transport lane called it unconditionally,
where the payload ?? {} fallback overwrote the message_start prompt snapshot with
contextUsage: unavailable. Anthropic-compatible routes whose provider is not
"anthropic" are forced onto that transport, so the population the guard was written
for never had it.

Move the presence check into the accumulator that owns the payload contract and drop
the duplicated guard in the SDK lane, so both lanes follow one rule. A present but
empty usage object still resolves to unavailable, matching the previous SDK check.

* test(anthropic): assert delta context usage through the usage object

expect(usage.contextUsage) narrowed to the object literal returned by the local
emptyUsage helper, which does not declare contextUsage, so the core test-types
stripe rejected it. Read it through toMatchObject like the neighboring cases.

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Yigtwxx <[email protected]>

* fix(systemd): protect credentials in managed backups (#131786)

Sanitize and privatize managed unit backups, restore them atomically on publication failure, surface unsafe remnants, and remove them across uninstall paths.

Closes #131781. Supersedes #131784.

Co-authored-by: vyctorbrzezowski <[email protected]>

Worked on by:
- @vyctorbrzezowski

* fix(agents): preserve requester MCP runtime ownership (#134819)

## What Problem This Solves

Requester-scoped MCP resolution can own serialized work for a runtime key while that runtime has no lease. Idle or cap cleanup could dispose the runtime and its transport before the work finished.

## Why This Change Was Made

The lifecycle owner now treats the existing requester work chain as active ownership. Idle cleanup skips that key, and cap cleanup does not queue an eviction behind that work. Required session disposal still drains the same chain.

## User Impact

Requester-scoped MCP transports and sessions now survive resolver work. Normal idle cleanup still removes the runtime after that work drains.

## Evidence

- Current-main loopback reproduction: the production manager returned one idle eviction while requester resolution was held; expected zero.
- Exact candidate loopback proof: the shipped harness runtime retained the same runtime object and MCP session identifier through the protected sweep, then the later idle sweep removed the runtime and closed the session.
- Cap regression: the original PR head disposed the refreshed requester runtime; the repaired head preserved it.
- [Exact-head agent shard](https://github.com/openclaw/openclaw/actions/runs/33675253407/job/100398989009): 89 files and 1,395 tests passed, including the real loopback boundary.
- Formatting and `git diff --check`: passed.
- Exact-head Autoreview P0: clean.

## Proof Boundary

The proof uses the production MCP runtime manager, the pinned MCP SDK 1.30.0 client and server, and a real loopback Streamable HTTP session. It does not claim external MCP service or provider authentication behavior.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(plugins): refresh persisted registry when source mounts change (#136517)

* fix(plugins): retain mounted source ownership through loading and restart

* ci: refresh checks against current main

* fix: gateway restart hangs while followup drain retries a draining error (#136713)

Closes #136684

## What Problem This Solves

Fixes an issue where operators restarting a Gateway with a queued follow-up could wait several minutes for shutdown. The queued turn retried after restart admission rejected it, so the old Gateway stayed active until its shutdown deadline.

## Why This Change Was Made

The follow-up queue now follows the existing one-way restart signal. When restart drain commits, it retires process-local queue work and its old callback before the Gateway inspects active work. A reversible restart-signal fence still waits for settlement and retries after rollback.

Durable accepted-input recovery remains the restart owner. The old in-memory queue and execution authority do not cross restart, as documented in `docs/gateway/restart-recovery.md`.

## User Impact

A Gateway with a queued follow-up can finish a supervised restart on the normal shutdown path instead of emitting a retry burst until forced termination. If restart signal admission rolls back, the queued follow-up resumes normally.

## Evidence

Current-main red at `3100ba535f1d003d67a6a7536deacf8666367b38`:

- Blacksmith child-Gateway run: https://github.com/openclaw/openclaw/actions/runs/33711422936
- One held model turn, one confirmed queued same-session follow-up, then `SIGTERM`.
- Queued case reached the real follow-up admission path and emitted `7` `followup queue drain failed` events.
- No-queue control emitted `0` drain failures.

Exact repaired tree at `2baff4f9ed3f84dc9493149dcc20fed441c9baea`:

- Blacksmith exact-tree run: https://github.com/openclaw/openclaw/actions/runs/33714572460
- The same child-Gateway scenario emitted no retry burst and exited in `3.465s`.
- `src/auto-reply/reply/queue.drain-restart.test.ts`: `29` passed.
- `test/gateway-queued-session-rotation.e2e.test.ts`: `2` passed.
- Materialized source hashes matched the local commit on https://github.com/openclaw/openclaw/actions/runs/33715159753.
- Type-aware Oxlint passed on all touched files.
- Oxfmt and `git diff --check` passed.

The focused tests also cover:

- a typed draining error while restart admission stays open;
- restart-signal rollback and queue resume;
- restart-signal promotion to one-way drain;
- synchronous retirement of queued turn ownership and stale callbacks.

Production LOC: `+33/-2` (net `+31`). The growth binds queue authority to the existing restart signal and closes the user-visible shutdown lifecycle gap. Tests: `+316/-0`.

## AI Assistance

AI-assisted repair. The contributor's original restart-fence distinction and credit are preserved. Maintainer follow-up added the real Gateway reproduction, lifecycle retirement, and exact-head proof.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): preserve OAuth metadata during session SDK refresh (#127988)

The shipped agent sessions SDK replaced a persisted OAuth credential with the provider refresh result. Providers such as Anthropic return only rotated token fields, so the write removed identity and plan metadata.

Merge the locked stored credential beneath the provider result at the session AuthStorage persistence boundary. Rotated tokens still win, while omitted persisted fields survive.

Tests:
- Published `openclaw/plugin-sdk/agent-sessions` path with real SQLite-backed AuthStorage refresh: red on current main, green on the repaired head.
- `node scripts/run-vitest.mjs src/agents/sessions/auth-storage.test.ts`: 23 passed.
- Focused formatting, lint, and diff checks passed.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): recognize configured memory provider secret references (#137782)

Recognize structured provider SecretRefs at Doctor's mapped-provider credential-presence boundary without resolving secret bytes or accepting empty environment markers.

Preserve missing-key warnings for absent credentials and preserve the live Gateway's owner-specific unresolved-secret diagnostics.

Verified with the real doctor command on baseline main and the exact candidate: provider-owned and remote-memory references, absent keys, bare markers, and two live unresolved-reference controls. All 102 focused tests pass. Synthetic credentials were used with container networking disconnected; no provider authentication is claimed.

Closes #137742.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(sessions): preserve logical shared-store ownership (#138380)

* fix: full-access tasks lose tools after Gateway restart (#138701)

* fix: preserve full access when continuing interrupted tasks

* test: exercise full-access continuation across a live restart

* fix: retain replay safety beyond the recent transcript window

* test: make live restart checkpoints suspend explicitly

* fix: keep unchanged files out of session diffs (#138877)

* fix(auth): recover billing-disabled profiles in minutes instead of hours (#136364)

Reduce the initial billing-disable window from five hours to ten minutes for stored auth profiles and inline API keys. Inline keys become eligible after expiry; another billing failure starts a new ten-minute window. Stored-profile recovery probes and already-active persisted deadlines remain unchanged.

Correct the recovery-policy documentation and source comment. Verified with 598 focused auth/fallback tests and docs checks on Cloudflare, real SQLite persistence and eligibility proof, independent review, and successful CI on c44f81187bd745c70b23a360fe15496c40251bf9. Live provider recharge was not exercised; the maintainer accepted that documented proof limitation.

Fixes #135835. Thanks @holny.

Co-authored-by: holny <[email protected]>
Co-authored-by: Altay <[email protected]>

* fix(auth): keep an unset default model unchanged during login (#139218)

Preserve an absent default model during ordinary provider login, just as existing model values are preserved. Remove only the provider-injected default while keeping connection settings, aliases, and credentials.

Keep --set-default as the explicit model-selection action. Extend the existing command regression across supported model shapes.

Related: #136257

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(gateway): avoid crashes when an upgrading client disconnects (#139061)

* fix(gateway): avoid crashes during interrupted upgrades

* test(gateway): bound upgrade regression websocket payloads

* fix(shell-env): preserve CLI terminal ownership during login imports (#139308)

Start the shared login-shell probe in a separate session so interactive Bash cannot take the CLI's controlling terminal. Preserve interactive startup exports and existing filtering, framing, timeout, executable lookup, and cache behavior.

Verified the current-main Doctor SIGTTOU failure and candidate completion using the built CLI in a real job-control terminal. Added a real-Bash startup regression and verified JSON output, imported keys, terminal restoration, and timeout behavior.

Closes #139257.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auto-reply): fold trailing transcript growth into memory-flush fresh totals (#138928)

* fix(auto-reply): fold trailing transcript growth into memory-flush fresh totals

runMemoryFlushIfNeeded persisted totalTokensFresh=true using only the last
provider usage anchor, ignoring messages appended after it. A later
preflight compaction check trusts totalTokensFresh and skips re-reading the
transcript, so real growth after the anchor could silently escape both the
early memory-flush trigger and the blocking compaction gate.

Project trailing messages the same way runSessionCompactionIfNeeded already
does before persisting the total as fresh.

* refactor(auto-reply): share anchor-plus-trailing prompt token calc

Memory flush duplicated the anchor-plus-trailing-projection calculation
that preflight compaction (estimatePromptTokensFromSessionTranscript)
already used. Extract resolveAnchoredPromptTokens() and have both call
sites use it, so the two calculations can no longer drift.

* fix(auto-reply): share fresh usage projection without duplicate accounting

Include transcript growth after the latest provider usage report before
memory maintenance saves a fresh total for preflight compaction. Reuse the
existing provider-visible estimator and canonical freshness validation,
removing the extra wrapper and redundant freshness check.

Related: #138871
Co-authored-by: chelsealong <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: chelsealong <[email protected]>

* fix(cron): preserve pending paced checks across restart (#140083)

Let the shared missed-slot decision honor the accepted future paced
occurrence before startup admission or backoff repair can replace it.
Keep ordinary unpaced and overdue catch-up behavior unchanged.

* fix(daemon): systemd install no longer aborts on "ownership could not be verified" after a clock step (#137253)

Replace wall-clock deadline arithmetic with `performance.now()` for systemd ownership probes, definition mutation, effective-manager reads, and legacy metadata refresh.

This preserves the existing shared timeout budgets, fallback behavior, and fail-closed ownership checks while preventing NTP, resume, or manual clock steps from collapsing later calls to the 1 ms floor or inflating them beyond the configured budget.

Regression coverage exercises forward and backward wall-clock steps across all four deadline owners. Exact-head CI, Workflow Sanity, independent P0/P1 review, and the durable ClawSweeper review passed.

Co-authored-by: coderdailyone <[email protected]>

* fix(config): apply environment changes after in-process restart (#141296)

## What Problem This Solves

Fixes an issue where users could update or remove a configured environment value after an in-process Gateway restart, but the process kept using its old value. A full process restart applied the saved configuration correctly.

## Why This Change Was Made

Snapshot cleanup discarded environment ownership without removing the values it owned. The next startup could then mistake those surviving values for inherited environment settings. Keep that ownership through snapshot cleanup, fence old rollback transactions, and retain explicit full-reset behavior.

## User Impact

Accepted configuration changes can replace or remove their environment values after restart. Inherited environment values keep their precedence, and config-selected paths remain stable.

## Evidence

- A real Gateway using main dcc68718f57e196bef10a07178fc8061b896140c accepts a replacement after a successful same-process restart, but public config.get still resolves the old value despite matching new applied/config revisions.
- On c7b393e10286b8b43c316cc7229f3bca94786493, the real Gateway completes restart, replacement, and removal. Public reads return the new value after replacement and the normal unresolved placeholder after removal. The inherited control stays unchanged throughout. Both config writes and final shutdown exit 0.
- Both runs use the real source CLI entry with synthetic config and normal token authentication. The candidate uses the Gateway's existing signed-device WebSocket client for public reads and the normal config set/unset CLI for writes. Complete private command, response, lifecycle, source, and resource receipts are retained. The interrupted baseline removal read is not claimed as proof.
- All 58 focused tests pass across runtime-snapshot.env.test.ts, config.env-vars.test.ts, and runtime-snapshot.test.ts. Controls cover late rollback, ambient precedence, aliases, casing, blocked variables, and explicit reset. Pinned formatting and focused lint pass.
- [Required CI passed](https://github.com/openclaw/openclaw/actions/runs/34136580481) on the exact candidate. No provider call or local build was needed for this proof.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix: pasted text is missing in model-locked Codex sessions (#142021)

* test(models): consolidate runtime policy matrix

* test(models): extract registry fixtures to satisfy lint

* fix: deliver pasted text to model-locked harness sessions

* fix(docker): restore source builds after dependency ownership guard (#142073)

* fix(docker): restore source builds after dependency ownership guard

* fix(docker): preserve existing lifecycle copy prefix

* fix(security): preserve existing WhatsApp group allowlists (#142589)

* fix(doctor): avoid installing unselected search providers (#142640)

Respect a normalized explicit web-search provider during plugin repair.
Only derive search plugin candidates from environment credentials when
no provider is selected, retaining independent plugin configuration.

Cover selection normalization, environment-only discovery, and existing
plugin disable and deny controls at the repair boundary.

* fix(doctor): migrate legacy Codex music model selectors (#143235)

Doctor left a legacy music selection such as `openai-codex/gpt-5.4` unchanged after `doctor --fix`. Its media selector scan and repair covered image and video but omitted music.

Include music in both existing loops. Doctor now reports the affected setting and saves eligible references under `openai`, using the same primary/fallback handling and provider blockers as the other media selectors.

Validation:

- Required CI passed on `51f0f308`: [run 34372705782](https://github.com/openclaw/openclaw/actions/runs/34372705782).
- Actual CLI proof reproduced the saved-state failure on baseline build `006aaacc` and verified the fix on candidate merge build `0b17e570`, which contains this PR head.
- Scalar and structured selectors passed repair, public config readback, and repeated repair. Suffixes, fallback order, explicit metadata, and canonical/custom references stayed intact.
- Non-interactive Doctor preview named the music setting without changing saved configuration. A blocked legacy provider retained its selection and authored settings while an eligible fallback migrated.
- All six regression cases passed in [the required CI job](https://github.com/openclaw/openclaw/actions/runs/34372705782/job/102537913364). They cover both legacy aliases, selector shapes, provider/model blockers, and agreement with image/video. The native pre-commit hook passed for all three files.

This completes the music-specific omission left after #142284. Proof uses synthetic configuration and covers stored references; it makes no live generation or authentication claim.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): preserve selected model metadata in diagnostics (#144332)

Keep active tool schema diagnostics on the primary model already selected
from manifest aliases. A second alias pass could use another model's
context window while labeling the tools with the selected model ID.

The regression reproduces middle selecting final's 4096-token context
instead of its own 32000-token context.

Related: #130706

* fix(discord): report parent channel denies for thread permissions (#121144)

* fix(discord): use parent permissions for thread diagnostics

Punchcard-Session: brisk-lantern-meadow-g5

* test(discord): preserve voice send diagnostics

* fix(discord): keep send diagnostics operation-specific

* fix(discord): share thread channel classification

* fix(config): avoid false model changes when saving settings (#144807)

* fix(doctor): preserve legacy registry files when quarantine fails (#144787)

Closes #144773

## What Problem This Solves

Doctor could delete malformed legacy sandbox registry data after its quarantine rename failed, then report a quarantine location that had not received the bytes. Both container and browser registry repair used the same failure path.

## Why This Change Was Made

The existing quarantine owner now reports success only after rename succeeds. It preserves the source and propagates other rename errors; a source that disappears maps to the existing missing result. Doctor retains its normal warning handling for this optional repair.

The regression cases now share the existing migration fixture and real SQLite writers. The separate mocked-writer fixture is removed, and the successful-quarantine test verifies the actual destination bytes.

## User Impact

Failed quarantine leaves the malformed bytes available for manual repair and reports the failure. Valid migration, existing SQLite rows, sharded precedence, read-only inspection, empty/missing inputs, and maintenance ownership retain their contracts. This changes no schema, configuration, retention policy, dependency, or overall Doctor exit policy.

## Evidence

Pinned main `1d4afe39664428308a2c71a64c94dea7b607bc0a` was exercised through the built public `openclaw doctor --fix --non-interactive` command in isolated offline state. For each registry kind, a real nonempty destination directory caused `rename` to return `EISDIR`; the source was then unlinked and Doctor reported successful quarantine. Original synthetic input and destination bytes were preserved independently.

The corrected source was independently exercised through the same public repair for both registry kinds. The native filesystem trace still records `EISDIR`, but the source and existing destination remain byte-for-byte intact, and Doctor reports:

```text
doctor:sandbox run failed: EISDIR: illegal operation on a directory,
```

| Before | After |
| --- | --- |
| Failed rename was followed by source deletion and a successful-quarantine claim. | Failed rename preserves both inputs and reports failure without claiming quarantine. |
| The claimed destination had not received the malformed bytes. | After resolving the owned collision, repair moves the identical bytes to the reported file; a repeat leaves the result unchanged. |

Independent acceptance also verified real-clock quarantine, registered read-only lint, empty/missing inputs, and real SQLite migration with existing-row conflicts and mixed valid/invalid shards. Whole canonical rows, including JSON and update timestamps, remained unchanged; canonical rows take precedence over shards, and shards over monolithic input. No database writer was mocked in this public proof.

An initial fixture reused an old fixed timestamp and was correctly refused by maintenance before reaching quarantine. Its failed and prematurely batched dependent steps are retained. The corrected fixture uses a contemporaneous timestamp and stops dependent actions on nonzero repair exit. Product leases, workers, permission checks and deadlines were unchanged. The original baseline proof remains valid and was not replayed.

The consolidated regressions produced the intended four failures on baseline. All 34 focused tests across three files pass with the repair. Native formatting, syntax lint, line-size and assertion-safety checks, and the complete runtime/UI artifact build passed. Full type checks and broad suites remain hosted. The tested source tree matches published head `84dffef7a099a9918fd08ae63993dfef4df788d9`; signing changed no runtime input. The retained build keeps its original pre-signing stamp.

The source-disappearance test is a deterministic filesystem-spy primitive, not a public concurrent-process claim. No host-power-loss or elapsed lease-expiry behavior is claimed. Complete private proof and failure history are retained; publication omits account and infrastructure details.

Thanks @Alix-007 for the original repair and regression coverage.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix: retain route ownership while discovering conversations (#146927)

* fix(install): preserve runtime links when Node validation fails (#147221)

* fix(install): preserve runtime links when Node validation fails

* fix(install): preserve relative runtime targets and empty aliases

* test(install): preserve runtime fixture tuple types

* fix: doctor reports missing OAuth dir for channel config with no installed plugin (#147888)

Doctor no longer reports a missing OAuth directory or offers to create credentials storage solely because leftover channel configuration requests pairing for an unavailable plugin. Reuse the existing effective installed-plugin set in the state-integrity check, while preserving CRITICAL diagnostics and repair prompts for installed pairing plugins and explicit OAuth-directory overrides.

The missing-plugin regression fails with the production change reverted and passes after restoration. The complete state-integrity test file passes all 30 tests, including an explicit installed-Telegram CRITICAL assertion; exact-head CI is green.

Fixes #147772.

Thanks @zhangguiping-xydt for the implementation.

Co-authored-by: Peter Steinberger <[email protected]>

* fix(doctor): stopped private inputs replay after session repair (#148625)

* fix(doctor): retain private input receipts during canonical repair

* test(doctor): use lint-safe receipt rekey expectation

* fix(channels): settle task-scoped context leases once (#148922)

* fix(push): normalize malformed proxy auth errors (#149112)

* fix(cron): reject invalid stagger before silent schedule changes (#151740)

Closes #146446

## What Problem This Solves

Fixes raw Gateway cron requests reporting success after silently discarding an invalid explicit `staggerMs`, substituting a default or retaining the previous value while other requested changes commit.

## User Impact

Invalid explicit stagger values now return `INVALID_REQUEST` before creating or updating a job. This includes explicit `null`: the existing schedule schema permits an optional integer, not a nullable value. Supported integer strings, zero, numeric flooring/clamping, omitted values, and ordinary CLI duration parsing retain their behavior. No operator migration is required; Doctor's existing legacy schedule repair is unchanged.

## Why This Change Was Made

The shared schedule normalizer rejects an invalid authored value before create defaults or update retention erase it. The fix uses the existing parser and request-error boundary rather than broadening the parser or adding a second validation policy. Non-cron schedules still discard stale stagger fields.

## Evidence

The authenticated comparison used Linux arm64 and Node 24.19.0, with registered `openclaw gateway call` commands, a task-only token, actual Gateway handlers, and SQLite readback. Baseline: `bef4c20d45bdd23c3557eb71962f908c691a7ed6`. Candidate: that same main revision plus this PR's two-file delta from `f9be3cb73438f6f68c4ead73103d413564398210`—not an execution of the full original PR checkout.

| Request | Baseline | Candidate |
| --- | --- | --- |
| Hourly add with `"1e3"` | Success; stored `300000` | `INVALID_REQUEST`; no mutation |
| Non-hourly add with `"1e3"` | Success; stagger omitted | `INVALID_REQUEST`; no mutation |
| Rename/update with `"42.8"`, same expression | Success; rename committed and previous stagger retained | `INVALID_REQUEST`; no mutation |
| Rename/update with `"42.8"`, changed expression | Success; rename/expression committed with default stagger | `INVALID_REQUEST`; no mutation |

For each rejected candidate request, all cron-table rows and authenticated views remained unchanged. All 20 expected-observation checks passed on each side, including integer strings, numeric/string zero, omitted add/update behavior, numeric floor/clamp, non-cron stale fields, explicit `null`, and a wrong-token control. Physical candidate restart preserved authenticated `cron.get` responses and complete serialized cron-table values.

Five focused files passed **167 tests**, covering normalization, stagger behavior, persisted schedules, and Doctor legacy schedule repair. With the original normalizer and the same regression tests, **8 failed and 95 passed**, demonstrating the invalid-input regression. Doctor coverage is focused-test evidence, not a published-updater upgrade test.

The initial fixture attempts are not product failures: the first stopped before mutation checks because native Workshop monitors were enabled in the fixture. Baseline restart initially compared `cron.list` projections with `cron.get` and then compared SQLite null-prototype records with JSON objects. Retained same-API responses and exact serialized row values confirmed persistence without replay; the failed fixture results remain retained.

During the completed comparison, scheduling and all jobs stayed disabled; native Workshop monitor rows were retained disabled. No scheduling timers, jobs, provider requests, channel delivery, or execution-delay measurement were exercised.

Existing hosted CI is not all green: [run 35338846156](https://github.com/openclaw/openclaw/actions/runs/35338846156) reports websocket transcript-event timeouts in `session-message-events.test.ts` in `checks-node-compact-large-4`, with the aggregate CI gate failing. No CI replay or unrelated repair is included in this PR.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(cli): keep model validation out of session execution (#154763)

* fix(agents): treat empty credential environment variables as unresolved (#155558)

Closes #153484

## What Problem This Solves

The session credential resolver returned the environment variable name when the variable existed but was empty.

## Why This Change Was Made

Distinguish a present empty variable from an absent variable in cached and uncached resolution. Empty values remain unresolved; non-empty variables override literals; absent names retain literal fallback.

## User Impact

SDK consumers of `openclaw/plugin-sdk/agent-sessions` no longer receive the variable name as credential/header material for an explicitly empty variable. Required headers use the existing resolution error. This is verified SDK hardening, not a claim that normal CLI provider headers use this resolver.

## Evidence

- Exercised the built public `ModelRegistry` export with an authored models.json provider header. The export is present in release v2026.9.5. Before the fix, empty returned the variable name; after the fix, it returned the existing failed-to-resolve-header error.
- Non-empty resolved the synthetic value; unset preserved the literal name. Repeated after integrating current main.
- Focused resolver suite: six tests passed; command wall 14.43s including worker preparation, test cases 15ms total.
- Simplification kept the two existing resolver owners and corrected the absent-variable test to exercise the deliberately unset name. No new abstraction/config/schema.
- CLI models probes and local agent requests were also inspected but use a different header path; they are not evidence for this fix.

## Compatibility

Shell command resolution and unset-name literal fallback are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): apply ambient-owner fallback to dream diary and all memory target handlers (#156437)

Apply the existing ambient-owner fallback in the shared Doctor memory target resolver, matching doctor.memory.status. Older clients that omit agentId can read the dream diary and run the five maintenance handlers when a configured owner is unambiguous. Explicit selection still wins, and ownerless multi-agent fleets still receive the selection error.

Thanks @Orionation for the fix and @Cyb3rb1ade for reporting the legacy-client failures. The configured-owner case is addressed; selecting an agent remains necessary for ownerless fleets.

Validation: scoped review found no accepted/actionable P0 or P1 findings, the author supplied a resolver comparison, and exact-head hosted CI passed. No fresh after-fix Gateway trace was captured for this landing. Production +6/-1; tests unchanged.

Closes #138369

Co-authored-by: Jonathan Sieling <[email protected]>

* fix(sandbox): unblock scoped recreation across runtime targets (#157808)

* fix(sandbox): unblock scoped recreation across runtime targets

* test(sandbox): validate mocked process arguments

Co-authored-by: Vincent Koc <[email protected]>

* fix(security): parse gpt generation numbers in the audit tier check (#140012)

Fix security audit warnings that incorrectly classify numbered GPT-6 models as below GPT-5. Compare numeric generations in the shared model-hygiene classifier while preserving older-model warnings and Azure's legacy gpt-35-turbo naming contract.

The repair covers primary models, fallbacks, image models, and agent overrides without changing provider routing, authorization, or unknown-name advisory policy. Broader unknown-name behavior remains separate in #160580.

Fixes #139751
Thanks @holny for the fix, regression coverage, and isolated CLI evidence.

Co-authored-by: holny <[email protected]>
Co-authored-by: IWhatsskill <[email protected]>

* fix(doctor): report shared auth health without a default agent (#134902)

* fix(doctor): report shared auth health without a default agent

* fix(ci): stabilize tooling timing and fixture cleanup

Use fake time for the existing readiness-body polling test, preserve explicit
success and delegated return statuses in Bash 5.2 EXIT cleanup, and remove a
repeated seven-compiler declaration invalidation build already covered by
the shared SDK writer.

Validation: 146 readiness/fixture tests and two real declaration-build cases
pass, along with 15 shell controls across Bash 3.2, 5.2, and 5.3. The scoped
changed gate and Codex review pass.

* fix(doctor): converge redundant shared auth relocation subsets (#135096)

* fix(doctor): converge redundant shared auth subsets

Preserve richer canonical credential stores and original source receipts through cleanup. Keep differing credentials and state rows fail-closed with actionable diagnostics. Reported by @jodok and independently reproduced by @felixboenkost-droid in #132605.

* fix(doctor): satisfy shared auth relocation validation

* fix(doctor): report retained device-auth files (#133978)

Surface retained client device-auth JSON in ordinary Doctor output and opted-in
lint checks, including when identity, pairing state, or Gateway health is absent.
Resolve only retired-file diagnostics and profile-aware repair hints from the
original health context environment; keep pairing and token reads on the active
state view.

Describe remaining migration or cleanup debt without inferring import history.
Keep the legacy-file token guard and Doctor-owned migration unchanged, share
friendly and structured findings, and remove redundant string-formatting paths.

Refs: #127973, #133978.
Reported by @yetval.

Co-authored-by: yetval <[email protected]>

* fix(update): stop detached updates after chat ownership is revoked (#137312)

* fix(update): recheck chat ownership before detached update launch

* test(update): keep helper owner cases in lifecycle support

* docs(update): describe the implemented session-less notice route

* test(update): match conditional Vitest API in owner cases

* fix(doctor): inspect source auth stores during full lint (#137610)

* fix(doctor): inspect source auth stores during full lint

* test(ci): freeze release candidate fixture clock

* refactor(doctor): simplify scoped environment restoration

* test(release): preserve elapsed time in fixture clocks

* test(auth): join migration fixture callbacks before teardown

* fix(gateway): recover queued RPC replies across restart (#138565)

Bind RPC and scheduled lifetime resolvers to their exact Gateway host. Reuse the canonical host for HTTP hooks and worker dispatch so shutdown retains pending reply recovery without weakening execution fences.

Fixes #138564

* fix(doctor): preserve legacy ownership during config repair (#138837)

Carry the retained default-agent owner through legacy migration, persist the
canonical roster through the config writer, and verify startup repair with
that same ownership preparation. This prevents a migratable legacy fleet
from being replaced by stale last-known-good configuration during update.

Verify the actual persisted roster and retained settings, keep ambiguous
owners rejected, and document migration before recovery.

Validation: 77 owner tests, changed checks, and independent P0-P2 review.
Release-note context: preserves update settings and legacy default-agent
ownership through automatic Doctor config migration.

* fix: prevent browser profile permission hangs in Doctor (#139612)

* fix: prevent browser profile permission hangs in Doctor

* docs: explain explicit browser registration repair

* fix(gateway): prevent systemd restarts from hanging (#140914)

With OPENCLAW_NO_RESPAWN enabled, a managed restart could reopen the Gateway inside the original process while systemd waited for it to exit. Use the existing external-restart action to drain, close, retain the recorded reason, and exit so the service manager creates the successor.

Verified through real Linux user-systemd restart, all five drain modes, ordinary stop/start, unmanaged SIGUSR1, independent runtime acceptance, and 384 focused lifecycle controls. Preserve existing managed-update ownership and service settings.

Thanks to @rboy1 for the report. Closes #140821.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): recover legacy node tokens with invalid scopes (#143599)

Doctor detects legacy node tokens that inherited operator scopes, but its suggested rotation preserves those scopes and is denied. Add `devices rotate --no-scopes` and use it in Doctor's node recovery guidance. Rotation removes only the matching stale local node…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations extensions: memory-lancedb Extension: memory-lancedb gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants