Skip to content

perf(models-config): unify auth-profile fingerprint cache + targetProvider short-circuit - #90741

Closed
zeroaltitude wants to merge 73 commits into
openclaw:mainfrom
zeroaltitude:perf/models-config-cache-unified
Closed

zeroaltitude wants to merge 73 commits into
openclaw:mainfrom
zeroaltitude:perf/models-config-cache-unified

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Improves models.json preparation so OpenClaw can skip expensive implicit-provider discovery when the relevant inputs are unchanged, while still re-planning when canonical auth state, plugin catalogs, or generated config inputs drift.

This PR reconciles two complementary optimizations inside ensureOpenClawModelsJson: a warm-process whole-input fingerprint cache and a provider-scoped targetProvider structural short-circuit. Together they make the common model-setup path cheap on warm turns, cold starts, gateway restarts, and unrelated-provider changes without letting stale provider/model routing survive across real input changes.

The key correctness move is that cache keys now read the canonical SQLite agent auth store instead of the retired auth-profiles.json file. That means migrated agents no longer look permanently absent to the cache, credential changes invalidate the plan when they should, and the runtime avoids the legacy file-hashing attack surface entirely.

Why

ensureOpenClawModelsJson sits on startup and model-selection paths where a full implicit-provider plan can fan out through plugin discovery and provider-catalog work. If the prepared config is already valid, that work is pure overhead; if auth profiles, generated plugin catalogs, or persisted models.json inputs changed, reusing the old plan is a routing-integrity bug.

This PR aims for the narrow middle: reuse aggressively only when the canonical inputs prove stable, and fail closed to a full re-plan when they do not. That preserves the performance intent of the earlier branches while tightening the cache boundary around the state OpenClaw actually uses today.

What Changed

  • Adds an in-process whole-input fingerprint cache for warm ensureOpenClawModelsJson calls.
  • Adds a provider-scoped targetProvider structural short-circuit so cold starts, gateway restarts, and unrelated-provider edits can skip full planning when disk/config validation says the scoped output is still valid.
  • Fingerprints the canonical SQLite auth store (openclaw-agent.sqlite, via the warm pooled handle) instead of legacy auth-profiles.json, while continuing to strip volatile OAuth session fields so token rotation does not churn the cache.
  • Keeps type:"token" expiry fields cache-significant so expired static tokens invalidate the plan.
  • Threads generated plugin catalogs into the pre-plan parsed models.json and writes them consistently through skip, noop, and write paths.
  • Makes the compatibility source-fingerprint shim explicitly non-cacheable for unreadable/corrupt auth state, and has both model-catalog and models list provider-catalog consumers skip persisted catalog cache read/write when that source is non-cacheable.
  • Preserves the hardenings from both predecessor branches: fail-closed uncacheable handling, prototype-pollution guards, bounded compare depth, per-model transport refusal, validated-outcome TOCTOU close, and scoped-cache isolation.

Relationship to Prior PRs

Supersedes #73260 and #73261 with one reconciled implementation. They were complementary, not redundant:

Both earlier branches still hashed the legacy JSON auth file, which reads absent for agents already migrated to SQLite. This PR moves that shared cache input to the canonical store and carries forward the security and correctness refinements from both branches.

Verification

Exact-head local verification on e5671e9b27:

  • node scripts/run-vitest.mjs src/agents/models-config.fingerprint-cache.test.ts src/agents/model-catalog.test.ts src/commands/models/list.provider-catalog.test.ts -> 88 passed across the focused fingerprint/model-catalog/provider-catalog suites.
  • pnpm tsgo:core -> clean.
  • pnpm tsgo:core:test -> clean.
  • pnpm tsx scripts/proof-90741-plugin-catalog-cache-validation.ts -> all 5 runtime assertions passed.
  • git diff --check -> clean.

Real behavior proof

Real-runtime proof script scripts/proof-90741-plugin-catalog-cache-validation.ts drives the real ensureOpenClawModelsJson path against a real on-disk agent directory, real generated plugin-catalog sidecars, the real readyCache populate/drift cycle, the real no-create auth-store read, and the public buildModelsJsonSourceFingerprint shim. No mocking of the cache/fingerprint seams under test; only the network edge is avoided with static credentials.

  • Behavior or issue addressed: Generated plugin-catalog sidecar drift must bust the warm models-config cache and reconcile rogue files; fingerprint-only auth reads must not create the SQLite auth DB; plugin-catalog-only plans must not rewrite the root models.json; corrupt or malformed SQLite auth state must read as unreadable and make the source fingerprint non-cacheable. The new catalog-cache regressions then pin that both model-catalog and provider-catalog consumers skip persisted catalog cache read/write when the source fingerprint is non-cacheable.
  • Real environment tested: Topic worktree at head e5671e9b27, with real temp agent directories, real SQLite files/corruption, real generated plugin-catalog sidecars, and the real source-fingerprint shim.
  • Exact steps or command run after this patch: pnpm tsx scripts/proof-90741-plugin-catalog-cache-validation.ts, run from the topic worktree.
  • Evidence after fix: Captured stdout from the live run:
[1/5] sidecar-drift-busts-cache-and-reconciles
    rogue sidecar present after re-plan: false
    ok
[2/5] fingerprint-read-does-not-create-agent-db
    auth DB created: false, -wal: false, -shm: false
    ok
[3/5] stable-no-sidecar-still-hits
    models.json mtimeMs cold=1781500389439.0088 warm=1781500389439.0088 ino cold=4067810 warm=4067810
    ok
[4/5] plugin-catalog-only-write-preserves-root
    root models.json ino cold=4067823 warm=4067823 mtimeMs cold=1781500389539.2183 warm=1781500389539.2183
    ok
[5/5] unreadable-auth-store-fails-closed
    no-db outcome.kind=absent
    valid-store outcome.kind=present
    corrupt-db outcome.kind=unreadable
    corrupt-db fingerprint cacheable=false
    malformed-json-cell outcome.kind=unreadable
    malformed-json-cell fingerprint cacheable=false
    ok

All runtime assertions passed.
  • Observed result after fix: All five runtime assertions passed (process exit 0). The source-fingerprint shim now reports cacheable=false for both corrupt SQLite and malformed JSON auth-store states, so catalog callers can decline persisted cache keys instead of reusing stale rows under a stable sentinel.
  • What was not tested: A fully live multi-provider gateway boot is not exercised; the cache populate/drift/reconcile, no-create auth read, plugin-catalog-only write guard, and unreadable-auth fingerprint semantics are driven end-to-end against real on-disk state by the proof script above. Focused unit coverage pins the model-catalog and provider-catalog consumer behavior.

…etection

Replaces mtime-based fingerprinting with content-based hashes for the
implicit-provider-discovery cache key, plus a second-factor models.json
content hash that catches external edits / partial corruption / sibling
process writes between cache hits. Includes the security hardening
findings raised by Aisle on the original combined PR (openclaw#72869).

# Why content hashes

The previous mtime-based key invalidated on every OAuth token refresh
because auth-profiles.json gets rewritten with new access/refresh
timestamps even when the set of available providers doesn't change.
Same for models.json mtime: the file is the OUTPUT of this function,
so each call observed its own write and invalidated the next call.

Now:

- auth-profiles.json: SHA-256 over a stable serialization that strips
  volatile OAuth session fields (access, refresh, expires*, issuedAt,
  refreshed/lastChecked/lastRefresh/lastValidatedAt). Token rotation
  no longer invalidates; structural changes (added/removed profiles,
  rotated static type:token credentials) still do.

- models.json: NOT included in the input fingerprint (would cause
  self-invalidation). Instead its content hash is captured at write
  time and stored alongside the readyCache entry. Every cache check
  recomputes the file hash and compares; any external edit /
  corruption / tamper invalidates the cache and forces re-plan.

# Security hardening (Aisle review on PR openclaw#72869)

- 🟠 High #1 (CWE-59 symlink-following chmod): ensureModelsFileMode
  now lstats first and refuses to chmod symlinks or non-regular files.
  Closes the attack where a symlink at ${agentDir}/models.json points
  at a sensitive owned file and our best-effort chmod follows.

- 🟡 Med #3 (CWE-1321 prototype pollution): stripAuthProfilesVolatile
  now uses Object.create(null) for the result and explicitly filters
  __proto__ / prototype / constructor keys (belt-and-suspenders).

- 🟡 Med #4 (DoS via unbounded fingerprinting): MAX_AUTH_PROFILES_BYTES
  = 8 MiB cap (above which we hash raw bytes), MAX_AUTH_PROFILES_DEPTH
  = 64 with a depth-cap marker so deeply-nested JSON cannot stack-
  overflow the gateway.

- 🟡 Med #5 (CWE-312 secrets in cache): buildModelsJsonFingerprint now
  returns SHA-256 hex of the canonical payload instead of the raw
  stable-stringified payload. The readyCache holds no verbatim secret
  material; heap snapshots / debug telemetry / core dumps cannot leak
  apiKey strings via this path.

# Token-rotation correctness

"token" is intentionally NOT in AUTH_PROFILE_VOLATILE_FIELDS even
though OAuth-style 'token' fields rotate. Profiles with type: 'token'
use the literal token key as a long-lived static credential, and
stripping it would mask real auth-state changes when a user rotates
that credential. Documented inline.

# Tests

Two tests in models-config.fingerprint-cache.test.ts:
- 'does not invalidate the cache when OAuth session fields rotate'
  (rotates access/refresh/expires; cache stays valid)
- 'DOES invalidate the cache when a static type:token credential rotates'
  (rotates the literal token field; cache invalidates)

# Compatibility

MODELS_JSON_STATE.readyCache value shape extended with modelsJsonHash:
{ fingerprint, modelsJsonHash, result }. All three plan return paths
(skip/noop/write) capture the post-write hash. The refreshedFingerprint
re-key path forwards modelsJsonHash through unchanged.

This is one of two PRs split out of openclaw#72869. The targetProvider
short-circuit work landed separately.
… validation

Add a fast path to ensureOpenClawModelsJson for callers that know which
provider/model they're about to use (e.g. the pi-embedded runner).
When set, the implicit-provider-discovery pipeline can be skipped IF
the on-disk models.json provider entry STRUCTURALLY matches what the
current configuration would produce.

# Why structural comparison

A naive 'is configured' check (does any non-empty credential exist on
disk for this provider) silently bypasses several real failure modes:

- Rotated apiKey: cold start with new key in config, old key still on
  disk, presence-only check fires, all calls fail with 401 until
  something else invalidates.
- Attacker-tampered baseUrl: redirect to exfil endpoint kept across
  restarts.
- Attacker-injected headers: arbitrary auth material kept across
  restarts.

The new readExistingProviderMatchesConfig compares all four
security-relevant fields:

  apiKey  - resolved through resolveSecretInputRef (env-ref expansion
            via createConfigRuntimeEnv) before string equality vs. disk
  baseUrl - exact string equality
  headers - stable structural equality (key-order independent)
  auth    - stable structural equality

Any mismatch falls through to full planning + writes.  This is safe to
use on cold start and after gateway restart.

# API

Adds EnsureOpenClawModelsJsonOptions exported type with targetProvider
and targetModel, layered on top of the existing options shape (kept
all of pluginMetadataSnapshot, workspaceDir, providerDiscoveryProviderIds,
providerDiscoveryTimeoutMs).

# Tests

5 cases in models-config.target-provider-short-circuit.test.ts:
- hit-on-match: full structural match short-circuits planning
- miss-on-rotated-key: config apiKey change forces a full plan
- miss-on-baseUrl-change: tampered disk baseUrl rejects short-circuit
- miss-on-tampered-headers: any disk header drift rejects short-circuit
- miss-on-cold-cache: empty in-memory cache + missing disk file forces a plan
- hit-after-warm-fingerprint: warm in-memory cache reuse

# Dependencies

This is one of two PRs split out of the original combined openclaw#72869.
The cache-fingerprint work (auth-profiles content hash, models.json
drift detection, fingerprint hashing, security hardening) landed
separately as perf/models-config-cache-fingerprint.

This branch can land independently.  When both branches land, the
original PR openclaw#72869 can be closed as superseded.
Addresses Codex P1, Greptile P2, and Aisle Med #1/#2/#3 on openclaw#73260:

# Streaming bounded hash (Codex P1 / Aisle Med #2)

The previous oversize-branch in readAuthProfilesStableHash still did
fs.readFile(path) which loaded the entire file into memory \u2014 the
MAX_AUTH_PROFILES_BYTES cap was effectively unenforced.  Same problem
for readModelsJsonContentHash (no cap at all).

New helper safeHashRegularFile():
  - lstat first; reject symlinks and non-regular files
  - bail at lstat-time if size exceeds maxBytes (returns sentinel hash
    so size-change still invalidates the cache)
  - open with O_NOFOLLOW where supported (closes lstat\u2192open TOCTOU)
  - fstat after open to verify it's still a regular file
  - createReadStream(fd) with bounded highWaterMark; destroy if accumulated
    bytes exceed maxBytes (handles the case where attacker grows the
    file between lstat and stream completion)

Both readers now route through safeHashRegularFile.  Models.json gets
a 1 MiB cap (MAX_MODELS_JSON_BYTES); auth-profiles keeps its 8 MiB cap.

# O_NOFOLLOW chmod (Aisle Med #1, CWE-367)

The previous lstat-then-chmod sequence was racy: an attacker who
could rename/replace ${agentDir}/models.json between the two syscalls
could have chmod() follow a swapped-in symlink to an arbitrary file.

Replaced with fs.open(path, O_RDONLY | O_NOFOLLOW) \u2192 fchmod via the
file handle.  The open itself refuses symlinks atomically; the
fchmod operates on the validated fd, eliminating the race.  When
O_NOFOLLOW is unavailable (rare but possible), falls back to plain
O_RDONLY \u2014 the prior lstat protection was already best-effort.

# Symlink-safe reads (Aisle Med #3, CWE-59)

Previous fs.readFile in the hash readers followed symlinks.  With
the safeHashRegularFile refactor above, both auth-profiles.json and
models.json now reject symlinks before reading.

# JSDoc fix (Greptile P2)

readModelsJsonContentHash's prior comment said "forces a re-plan"
when the file is absent, but the call site does null === null
comparison which is a cache hit, not a re-plan (the steady-state
skip case for plan.action === 'skip').  Updated the comment to
explain the actual semantics: stable absence is a stable result;
drift is a re-plan.

# Tests

14/14 existing tests pass.  No new test cases needed \u2014 the existing
file-mode and fingerprint-cache tests cover both the symlink-rejection
paths (via lstat shortcut) and the modelsJsonHash second-factor.
Lint: 0 errors.
…tegration

Addresses Codex P2, Greptile P1+P2x2, and Aisle High #1 + Med #2/#3/#4
on PR openclaw#73261:

# Greptile P1 / Aisle High #1: asymmetric baseUrl (CWE-918, SSRF)

The previous guard:
  if (typeof configuredProvider.baseUrl === 'string' &&
      configuredProvider.baseUrl !== diskProvider.baseUrl)
short-circuited the check entirely when config omitted baseUrl
(common for providers with compiled-in defaults).  An attacker who
could tamper with on-disk models.json could set baseUrl to an exfil
endpoint and the short-circuit would accept it silently \u2014 exactly
the SSRF/credential-exfil vector this PR was meant to close.

Replaced with symmetric stableEqual() so config-undefined vs
disk-string is a mismatch and falls through to full planning, which
re-applies provider/plugin defaults and rewrites the file.

# Codex P2: env-ref API key comparison

resolveConfiguredApiKeyForCompare resolved env refs to the env-var
VALUE (env[ref.id]).  But planOpenClawModelsJson persists env-source
api keys to models.json as the env-var NAME (e.g. 'OPENAI_API_KEY'),
not the value \u2014 that's what resolveApiKeyFromCredential returns for
env source.  Comparing value-vs-name always mismatched, so the
short-circuit never fired for the most common config form
('apiKey: "${env.OPENAI_API_KEY}"').

Now the helper returns the env-var NAME for env-source refs, while
still verifying the env is currently populated (so we don't
short-circuit on a misconfigured environment).  Plaintext values
still compare directly.

# Greptile P2 (perf): readyCache integration

The short-circuit returned before the readyCache check, so warm
callers paid the disk read + JSON.parse cost on every call.
Reordered:
  1. compute fingerprint (cheap)
  2. check readyCache \u2014 warm hit returns immediately, no disk I/O
  3. if cold, attempt short-circuit on disk
  4. if short-circuit succeeds, populate readyCache so subsequent
     calls take the warm path

Net effect: warm callers now skip disk entirely; cold callers with
intact disk state still get the short-circuit benefit; full plan
fires only on real drift.

# Aisle Med #2 (CWE-59): symlink-following short-circuit reads

readExistingProviderMatchesConfig used fs.readFile on a possibly-
symlinked target.  Now lstat-checks first and refuses symlinks /
non-regular files.

# Aisle Med #3 (CWE-1321): prototype-chain key access

explicitProviders[targetProvider] could fall through to a prototype
key like '__proto__' / 'constructor' / 'prototype'.  Now uses
Object.hasOwn at both lookup sites (caller AND
readExistingProviderMatchesConfig) to refuse inherited keys.  Also
explicit string check rejects the three known dangerous keys.

# Aisle Med #4 (CWE-400): unbounded models.json read

Added MAX_MODELS_JSON_SHORT_CIRCUIT_BYTES = 1 MiB cap on the disk
read in the short-circuit path.  Files above the cap fall through
to full planning rather than being parsed.

# Tests

Updated hit-after-warm-fingerprint test (Greptile P2) to use
fs.readFile spy and assert no disk read occurs on the warm path.
Added short-circuit-populates-cache test that drops the in-memory
cache between runs, fires the short-circuit, then verifies the
third call takes the warm path with no disk read.

14/14 tests pass.  Lint: 0 errors.
…rget-provider-short-circuit

# Conflicts:
#	src/agents/models-config.ts
…w feedback)

Codex P2 / Aisle medium #1 on PR openclaw#73260 flagged that `safeHashRegularFile`
returned a deterministic `oversize:${lst.size}` sentinel when a file
exceeded the cap, so an attacker could swap the *contents* of an oversized
`auth-profiles.json` or `models.json` without changing its byte length and
still hit the readyCache via the size-only sentinel comparison (CWE-345).

Switch to fail-closed:

- `safeHashRegularFile` now returns `null` for oversize at lstat time and
  for grow-past-cap mid-read (the latter was already caught via the
  destroy-with-error path; the JSDoc/comment now states that explicitly).
- The return type narrows from `{ hash; raw: Buffer | null } | null` to
  `{ hash; raw: Buffer } | null` — the `raw === null` branch in
  `readAuthProfilesStableHash` is now unreachable and removed.
- JSDoc on the helper and `readAuthProfilesStableHash` now describes the
  fail-closed semantics and links them back to the threat model.

Also:

- Add a regression test that warms the cache with a small, hashable
  `auth-profiles.json`, then grows it past `MAX_AUTH_PROFILES_BYTES`
  (8 MiB) and asserts the implicit-provider-discovery pipeline re-runs
  (i.e. the fingerprint changed instead of stably hitting an
  `oversize:<size>` sentinel).
- Add the missing `Unreleased` CHANGELOG entry covering the
  content-hashed fingerprint, post-write models.json drift hash, the
  oversize fail-closed change, and the existing `O_NOFOLLOW`/streaming/
  prototype-pollution hardening (Codex P3 on the same review).
- Backfill the new `resolveProviderEnvAuthEvidence`/
  `listProviderEnvAuthLookupKeys`/`resolveProviderEnvAuthLookupKeys`
  exports in the fingerprint test's `model-auth-env-vars.js` mock so the
  suite runs at all after the recent `origin/main` merge added those
  call sites in `model-auth-env.ts` / provider secret-helpers.

Validation (from
~/projects/worktrees/openclaw/perf-models-config-cache-fingerprint):

  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts
    Test Files  2 passed (2)
         Tests  12 passed (12)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \
              src/agents/models-config.fingerprint-cache.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-9i0
…rint' into perf/models-config-target-provider-short-circuit
…ransport check + bounded compare (review feedback)

Codex P1+P2 (and matching Aisle High #2 / medium #3) on PR openclaw#73261.
ClawSweeper rejected the previous round's "wrong solution" \u2014 the global
readyCache write after a provider-scoped check, an unbounded recursive
stableEqual on disk-controlled state, no per-model transport drift
check, and a fail-open malformed-apiKey branch.  Redesign:

# Provider-scoped readyCache (Codex P1)

The previous version called
  MODELS_JSON_STATE.readyCache.set(cacheKey, ...)
after the targetProvider short-circuit, where cacheKey was the GLOBAL
fingerprint key.  A later non-targeted ensureOpenClawModelsJson call
would hit that entry and skip the full plan even though only one
provider was validated.  After the redesign, successful short-circuits
populate a SCOPED key:
  `${targetPath}\\0${fingerprint}\\0sc:${targetProvider}`
which non-targeted callers never compute.  Targeted callers consult the
scoped key first, hit it warm if present (with the same modelsJsonHash
two-factor verification as the global cache), and fall through to the
disk-based check otherwise.  Non-targeted callers always run a full
plan to validate every provider.

# Per-model transport drift (Codex P1 / Aisle High #2)

The runtime consumes per-model `baseUrl` / `api` / `headers` from
models.json (`pi-embedded-runner/model.ts` falls back to
`discoveredModel.baseUrl` / `.api` / `.headers` when no provider-level
override is set).  The previous comparison only covered provider-level
fields, so an attacker who could write models.json could keep
provider-level apiKey/baseUrl/headers/auth intact while injecting a
per-model `baseUrl: \"https://attacker.example/v1\"` and the short-
circuit would accept it.  After the redesign, any disk-side per-model
transport field forces a full re-plan that re-applies provider/plugin
defaults and rewrites the file.  This is intentionally strict: the
common case (no per-model transport overrides) still gets the short-
circuit; configurations that legitimately use per-model transport just
skip the fast path.

# Bounded structural equality (Codex P2 / Aisle medium #3)

`stableEqual = stableStringify(a) === stableStringify(b)` recurses
without depth bounds.  A small but pathologically nested
`models.json` (e.g. `{a: {a: {a: ...}}}`) could stack-overflow the
gateway during the short-circuit comparison.  Added
`stableStringifyBounded` (throws on overrun) +
`stableEqualBounded` (catches the overrun and returns false \u2014 fail
closed to the full plan).  Used for baseUrl/headers/auth comparisons
against disk-controlled state with `SHORT_CIRCUIT_COMPARE_MAX_DEPTH =
64`.  The original unbounded `stableEqual` is removed; the trusted-
input fingerprint pipeline still uses unbounded `stableStringify`.

# Fail closed on malformed disk apiKey (Codex P2)

When config has no apiKey, the previous fail-open branch only
rejected non-empty strings on disk \u2014 numbers, null, objects, etc.
were silently accepted.  Now anything other than `undefined` or empty
string forces a re-plan.

# Reuse openclaw#73260's safeHashRegularFile

The disk read in `readExistingProviderMatchesConfig` now uses
`safeHashRegularFile` (the fingerprint-cache primitive) for
O_NOFOLLOW open + lstat/fstat regular-file check + size cap +
fail-closed on grow-past-cap.  Drops the redundant
`MAX_MODELS_JSON_SHORT_CIRCUIT_BYTES` constant in favour of the
shared `MAX_MODELS_JSON_BYTES` from openclaw#73260.

# Tests

13/13 pass in src/agents/models-config.target-provider-short-circuit.test.ts:

- existing 5 (hit-on-match, miss-on-rotated-key, miss-on-baseUrl,
  miss-on-headers, miss-on-cold-cache, hit-after-warm-fingerprint)
  still pass with the new code path.
- `short-circuit-populates-scoped-cache` rewritten: third call hits
  the SCOPED cache entry with no fs.readFile (modelsJsonHash uses
  createReadStream).
- `scoped-cache-isolation` (new): targeted short-circuit followed by
  non-targeted call with same fingerprint runs full plan (does NOT
  hit the scoped entry).
- `miss-on-per-model-baseUrl` / `miss-on-per-model-headers` /
  `miss-on-per-model-api` (new): per-model transport overrides on
  disk reject the short-circuit and fall through to a full plan.
- `miss-on-deep-nested-disk` (new): 200-level-deep adversarial disk
  headers fall through cleanly without throwing/overflowing.
- `miss-on-malformed-disk-apiKey` (new): non-string disk apiKey
  rejects when config has no apiKey.

Also backfills the missing
`resolveProviderEnvAuthEvidence`/`listProviderEnvAuthLookupKeys`/
`resolveProviderEnvAuthLookupKeys` exports in the
`model-auth-env-vars.js` mock so the test suite runs against the
post-merge `model-auth-env.ts` surface (same fix openclaw#73260's follow-up
landed for its fingerprint-cache test).

# Validation (from worktree
~/projects/worktrees/openclaw/perf-models-config-target-provider):

  pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts
    Test Files  1 passed (1)
         Tests  13 passed (13)
  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts \\
                  src/agents/models-config.target-provider-short-circuit.test.ts
    Test Files  2 passed (2)
         Tests  19 passed (19)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \\
              src/agents/models-config.target-provider-short-circuit.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-l5q
…ache on uncacheable auth-profiles (review feedback)

Round-4 follow-up to Codex P1 + P2 on PR openclaw#73260.  Both findings were
real holes in the round-3 "return null on oversize" change:

  1. Codex P1 — "Treat unhashable models.json as cache drift"
     (src/agents/models-config.ts:474):
     The cache-hit predicate accepted
     `currentModelsJsonHash === settled.modelsJsonHash`, but
     `readModelsJsonContentHash` returned `null` for several distinct
     failure modes (oversize >1 MiB, symlinked, non-regular,
     I/O error) IN ADDITION to the legitimate "file absent" case.
     Anyone who could put models.json into one of those states could
     then mutate its contents repeatedly while every read returned
     null, and the cache kept hitting via `null === null`.

  2. Codex P2 — "Distinguish oversize auth-profiles from stable
     fingerprints" (src/agents/models-config.ts:123):
     `readAuthProfilesStableHash` returned `null` for any oversize
     auth-profiles.json, so all >8 MiB variants collapsed to a single
     fingerprint contribution.  Once the file was already oversize,
     credential edits that kept it oversize no longer changed the
     fingerprint and therefore no longer invalidated the ready cache.

Fix: replace the `string | null` return with a discriminated outcome
(`ContentHashOutcome` in `models-config-state.ts`):

    | { kind: "absent" }     // legitimate file-does-not-exist steady state
    | { kind: "hashed"; hash } // successful bounded-stream read
    | { kind: "uncacheable" } // oversize, symlink, non-regular, or I/O error

Predicate (`modelsContentOutcomesMatch`):

  - `absent === absent`         → cache hit (skip-noop on a missing file).
  - `hashed === hashed`         → cache hit iff hashes are identical.
  - `uncacheable` on EITHER side → ALWAYS a miss.  Two `uncacheable`
                                  outcomes do not match each other,
                                  because they could correspond to
                                  different attacker-controlled bodies
                                  that just happen to trip the same
                                  cap.

Auth-profiles cache-bypass: when `readAuthProfilesStableOutcome`
returns `uncacheable`, `ensureOpenClawModelsJson` bypasses the
ready cache entirely — neither reading from it nor writing to it —
and re-plans on every call.  This stops an attacker who keeps the
file oversize from accumulating dead entries in the in-memory cache,
and stops same-size content swaps from riding a stale entry.  When
the file returns to a hashable state the next call lands a fresh
cache entry keyed by the new content fingerprint.

Defensive guard: `buildModelsJsonFingerprint` now refuses to be
called with an `uncacheable` auth-profiles outcome.  Callers
must bypass the cache instead.

Also:

  - Refactor `safeHashRegularFile` → `safeReadFileOutcome` returning
    the discriminated outcome.  ENOENT is the only lstat error
    treated as `absent`; every other error (EACCES, etc.) is
    `uncacheable` so silent permission failures do not masquerade as
    a stable absence.  All other behaviour is preserved
    (O_NOFOLLOW-hardened open, fstat re-check, bounded streaming
    hash, abort-on-grow-past-cap).
  - Update `ContentHashOutcome` JSDoc + the `MODELS_JSON_STATE`
    cache shape from `modelsJsonHash: string | null` to
    `modelsJsonOutcome: ContentHashOutcome`.
  - Rewrite the cache-flow JSDoc (Greptile P2 noted the previous
    JSDoc was the opposite of the actual behaviour).
  - Add two regression tests:
      * "forces a re-plan on every call while auth-profiles.json
        stays oversize (Codex P2 round-4 on openclaw#73260)" — warms the
        cache with a small profile, verifies repeat-call hit, then
        oversizes the file and asserts that EVERY subsequent call
        re-plans (including byte-identical and same-byte-length
        swapped contents).  Restoring the file to a small state
        re-enables caching on the next call.
      * "invalidates the cache when models.json becomes unhashable
        (Codex P1 round-4 on openclaw#73260)" — warms cache with a real
        write, verifies repeat-call hit, then externally grows
        models.json past `MAX_MODELS_JSON_BYTES` and asserts the
        next call re-plans.
  - Update CHANGELOG to describe the round-4 fail-closed contract.

Validation (from
~/projects/worktrees/openclaw/perf-models-config-cache-fingerprint):

  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts
    Test Files  2 passed (2)
         Tests  16 passed (16)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \
              src/agents/models-config-state.ts \
              src/agents/models-config.fingerprint-cache.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-t9l
…rint' into perf/models-config-target-provider-short-circuit

# Conflicts:
#	src/agents/models-config.ts
…hort-circuit (review feedback)

Round-5 follow-up to Codex P1 + P2 on PR openclaw#73261:

  1. Codex P1 — "Compare provider-level api before short-circuiting"
     (openclaw#73261 (comment)):
     readExistingProviderMatchesConfig compared baseUrl, apiKey, headers,
     and auth, but NOT the provider-level `api` field.  The runtime
     consumes `models.providers.<id>.api` at the same priority as the
     other transport fields (see pi-embedded-runner/model.ts and
     models-json/plan.ts), so an attacker who can write models.json
     could swap a provider's transport flavor (e.g.
     `"openai-completions" -> "openai-responses"`) and the short-
     circuit would re-bless it because the per-model loop only flagged
     `api` set on disk-side MODEL rows, not on the provider itself.

  2. Codex P2 — "Treat unhashable models.json as cache miss"
     (openclaw#73261 (comment)):
     the previous round-4 short-circuit used a `string | null` hash so an
     `uncacheable` models.json (oversize, symlink, I/O error) collapsed
     with the legitimate "file absent" case via `null === null`.  This
     overlapped with the round-4 fix on openclaw#73260 (commit 05fda3d) which
     introduced a discriminated `ContentHashOutcome` type; the
     short-circuit's scoped-cache compare and disk-based check both
     needed to consume that contract via `modelsContentOutcomesMatch` and
     `safeReadFileOutcome` to inherit the fail-closed semantics
     (CWE-345).

The merge of origin/perf/models-config-cache-fingerprint into this
branch (commit 9f74081) wired the new `ContentHashOutcome` contract
into the targetProvider short-circuit:

  - readExistingProviderMatchesConfig now uses `safeReadFileOutcome`
    instead of the removed `safeHashRegularFile`, so an `uncacheable`
    models.json on a fresh process (cold readyCache) refuses to bypass
    the planner.
  - Provider-level `api` comparison was added between the apiKey check
    and the headers check, with the same symmetric depth-bounded
    structural comparator already used for baseUrl/headers/auth.  Drift
    (including config-undefined vs. disk-string) falls through to a
    full plan, which re-applies provider/plugin defaults and rewrites
    the file.
  - The scoped-cache compare swapped `currentModelsJsonHash === settled.modelsJsonHash`
    for `modelsContentOutcomesMatch(currentModelsJsonOutcome, settled.modelsJsonOutcome)`,
    so an `uncacheable` outcome on either side never matches itself or
    a captured hash.  The post-validation outcome capture also refuses
    to write a scoped entry when the file is `uncacheable`, preventing
    dead entries from accumulating during oversize states.
  - cache-bypass mode (`!cacheable`) covers the targetProvider hint via
    the same `planAndWrite` sentinel-fingerprint path, so an
    `uncacheable` auth-profiles.json forces a full re-plan even when
    the caller hinted a provider.

This commit adds:

  - 4 targeted regression tests in
    src/agents/models-config.target-provider-short-circuit.test.ts:
      * "miss-on-provider-api-drift" — disk-side provider api flipped
        to a different transport family, planner rewrites.
      * "miss-on-provider-api-config-undefined" — config has no `api`,
        any disk-side `api` rejects the short-circuit.
      * "miss-on-unhashable-models-json" — warm scoped-cache entry +
        models.json grown past MAX_MODELS_JSON_BYTES forces re-plan via
        the `uncacheable` outcome compare.
      * "miss-on-cold-uncacheable-models-json" — fresh process state +
        oversize models.json refuses the disk-based short-circuit via
        `safeReadFileOutcome`.
  - A CHANGELOG.md update on the existing models-config bullet to list
    `api` in the compared provider fields and mention the fail-closed
    `ContentHashOutcome` contract.

Validation (from
~/projects/worktrees/openclaw/perf-models-config-target-provider):

  pnpm vitest run \
    src/agents/models-config.target-provider-short-circuit.test.ts \
    src/agents/models-config.fingerprint-cache.test.ts \
    src/agents/models-config.write-serialization.test.ts \
    src/agents/models-config.skips-writing-models-json-no-env-token.test.ts \
    src/agents/models-config.runtime-source-snapshot.test.ts
    Test Files  10 passed (10)
         Tests  82 passed (82)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \
              src/agents/models-config-state.ts \
              src/agents/models-config.target-provider-short-circuit.test.ts \
              src/agents/models-config.fingerprint-cache.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Real-runtime proof was captured by driving the production
`ensureOpenClawModelsJson` directly via tsx (no test harness, no mocks);
all three scenarios — steady-state hit, provider-api drift forces
re-plan, oversize models.json forces re-plan — printed PROVED lines and
exited 0.  Output recorded on the PR comment.

Beads: openclaw-l5q
…rget-provider-short-circuit

# Conflicts:
#	CHANGELOG.md
#	docs/.generated/plugin-sdk-api-baseline.sha256
#	src/agents/models-config.ts
…g short-circuit (review feedback)

Codex P2 round-6 on PR openclaw#73261: 'Accept implicit env apiKey markers in
short-circuit compare'

Paraphrased problem
-------------------
When configuredProvider.apiKey is unset, the round-5 unset-config
branch rejected ANY non-empty diskProvider.apiKey, but
planOpenClawModelsJson legitimately persists env-derived markers
even with no configured key (via resolveMissingProviderApiKey in
src/agents/models-config.providers.normalize.ts -> secret-helpers.ts).
In the dominant implicit-discovery setup (provider has models, auth
comes from OPENAI_API_KEY env or AWS SDK env chain), the planner
writes apiKey: "OPENAI_API_KEY" (the env-var name marker) to disk
on the first pass. With round-5's strict rejection, every subsequent
restart would miss the targetProvider short-circuit and re-run full
implicit discovery, negating the new perf path despite disk and
config being semantically aligned.

Solution
--------
Extend the unset-config branch to also accept disk apiKey values
that match what resolveMissingProviderApiKey would have persisted.
The decision tree mirrors the planner:

- providerAuth === "aws-sdk": call resolveAwsSdkApiKeyVarName(env);
  accept iff disk equals that env-var name AND env[awsEnvVar] is
  populated (liveness check matches the existing
  resolveConfiguredApiKeyForCompare contract for env-source refs).

- otherwise: call resolveEnvApiKeyVarName(providerKey, env); accept
  iff disk equals that env-var name AND env[envVarName] is
  populated.

- profile-plaintext / non-default providerApiKeyResolver paths are
  NOT covered by this round (we don't have profile or resolver in
  scope at the comparator). Bounded perf cost: one full plan per
  restart that produces an unchanged disk shape; can be extended
  symmetrically in a later round if profile context plumbing makes
  it cheap.

Anything else (number, null, object, array, string not derivable
from the planner's env/aws-sdk paths, name pointing at an
unrelated env var, env var no longer set) still falls through to
full planning.

Result
------
- src/agents/models-config.ts:
  + new helper diskApiKeyMatchesUnsetConfigPlannerOutput documents
    the planner-output decision tree and pins the env / aws-sdk
    branches with explicit liveness checks.
  + unset-config branch in readExistingProviderMatchesConfig now
    consults the helper before rejecting.
  + new imports for resolveAwsSdkApiKeyVarName /
    resolveEnvApiKeyVarName from
    models-config.providers.secret-helpers.

- src/agents/models-config.target-provider-short-circuit.test.ts:
  three new regression tests pin the contract:
  + hit-on-env-marker-with-unset-config: short-circuit accepts disk
    apiKey: 'OPENAI_API_KEY' when config has no apiKey and env
    var is set.
  + miss-on-env-marker-with-unset-env: same setup but with the env
    var deleted between passes; short-circuit rejects (liveness).
  + miss-on-env-marker-name-mismatch: disk apiKey points at an
    unrelated env var that doesn't map to the openai provider;
    short-circuit rejects.
  Pre-existing miss-on-malformed-disk-apiKey kept and still passing.

Validation gate
---------------
- pnpm tsgo:core: clean
- pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts:
  40/40 passed (37 prior + 3 new)
- pnpm oxlint <touched files>: 0 warnings, 0 errors
- pnpm plugin-sdk:api:check: OK
- git diff --check: clean
…ls (Clawsweeper P2 round-6 on openclaw#73261)

Both pi-embedded production callers (compact.ts and run.ts) were passing
only { workspaceDir } to ensureOpenClawModelsJson, so the targetProvider
short-circuit (options.targetProvider being undefined) never fired in
production embedded runs, negating the perf benefit of the entire PR.

Fix: forward the resolved `provider` as `targetProvider` in both call
sites so the scoped-cache short-circuit can skip a full plan when the
provider's disk config already matches.

Regression coverage: export ensureOpenClawModelsJsonMock from
compact.hooks.harness.ts; add two focused tests that pin the
targetProvider wiring for the compact direct path (default openai
provider and caller-supplied provider override).

tsgo:core, tsgo:core:test → clean
git diff --check → clean
…t compare (review feedback)

Codex P2 round-7 on PR openclaw#73261: 'Normalize secret-ref headers before
short-circuit compare'

Paraphrased problem
-------------------
The targetProvider fast path compared configuredProvider.headers
directly against disk, but planner output normalizes secret-ref
headers (env refs like \${ENV_VAR} and SecretRef objects) into
marker strings via normalizeHeaderValues:
  - env refs   -> 'secretref-env:<ENV_VAR_NAME>'
  - non-env    -> 'secretref-managed'

As a result, any provider configured with header SecretRefs (the
common shape for header-auth providers) would always fail the
deep compare and re-run full implicit discovery on every call,
defeating the targetProvider perf win for that entire class of
providers.

Solution
--------
Pre-normalize configuredProvider.headers using the same
normalizeHeaderValues call the planner uses, threading
cfg.secrets?.defaults through readExistingProviderMatchesConfig so
the normalization produces identical markers to what the planner
persisted.

normalizeHeaderValues is idempotent for plain literal values
(returns headers unchanged when no entry resolves as a secret ref),
so this is a safe no-op for the common no-header / literal-header
case.  Anything else (header drift, attacker-injected headers,
markers pointing at unrelated env vars) still falls through to
full planning via the existing stableEqualBounded compare.

Out of scope (deliberately): source-managed enforcement
(enforceSourceManagedProviderSecrets) layers additional marker
rewrites when sourceProviders is set.  The short-circuit doesn't
have sourceProviders in scope today, and the perf cost of falling
through for source-managed providers is bounded.  Can be extended
in a later round if profile/source plumbing makes it cheap.

Result
------
- src/agents/models-config.ts:
  + readExistingProviderMatchesConfig now takes
    secretDefaults: SecretDefaults | undefined.
  + Before the headers compare, configuredProvider.headers (when
    record-shaped or undefined) is run through normalizeHeaderValues
    to produce the same marker strings the planner persists.
  + Call site in ensureOpenClawModelsJson passes
    cfg.secrets?.defaults.
  + New imports for normalizeHeaderValues and the SecretDefaults
    type from models-config.providers.secret-helpers.

- src/agents/models-config.target-provider-short-circuit.test.ts:
  two new regression tests:
  + hit-on-env-ref-header-normalization: short-circuit accepts disk
    headers shaped { 'X-Custom-Auth': 'secretref-env:OPENAI_API_KEY',
    'X-Static': 'literal-value' } when config holds
    { 'X-Custom-Auth': '\${OPENAI_API_KEY}', 'X-Static': 'literal-value' }.
  + miss-on-env-ref-header-mismatch: same env-ref shape in config,
    but disk marker points at UNRELATED_TOKEN \u2014 short-circuit
    rejects (deep compare catches the env-name mismatch).

Validation gate
---------------
- pnpm tsgo:core: clean
- pnpm tsgo:core:test: clean
- pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts:
  44/44 passed (40 prior + 2 new round-6 + 2 new round-7)
- pnpm oxlint <touched files>: 0 warnings, 0 errors
- pnpm plugin-sdk:api:check: OK
- git diff --check: clean
…re short-circuit (review feedback)

Codex P1 round-8 on PR openclaw#73261: 'Compare configured models before
short-circuiting provider hit'

Paraphrased problem
-------------------
The prior per-model loop in readExistingProviderMatchesConfig only
validated that disk-side models carried no transport-override
fields; it never compared configuredProvider.models against
diskProvider.models.  Result: a config edit that adds a new model
id (without touching apiKey / baseUrl / api / headers / auth)
hits the short-circuit, leaves models.json stale, and
resolveModelAsync misses the newly configured model until some
later full reconcile happens.  With the targetProvider path now
wired into the embedded runner, that staleness window is reachable
from gateway hot paths and is a real correctness bug, not just a
perf miss.

Solution
--------
Add a model-id subset check after the existing transport-only loop:

- collectShortCircuitModelIds normalizes a provider's models field
  into a Set<string> of ids.  Accepts the two runtime shapes:
  bare string entries ('gpt-5') and record entries with a string
  id field ({ id: 'gpt-5', ... }).  Returns null on adversarial /
  malformed shapes (non-array with non-undefined value, non-record
  non-string entries, missing id, prototype-key collisions) so
  the comparator can fail closed.

- When configuredProvider.models has any entries, every configured
  id MUST appear in diskProvider.models.  Disk may legitimately
  contain MORE models than config (implicit discovery /
  plugin-contributed entries), so subset check, not strict
  equality.

- Implicit-only mode (configured models is empty array OR omitted)
  legitimately defers to the planner's discovery output.  We skip
  the subset check in that case and rely on the transport-only
  comparisons \u2014 preserving the perf path for the dominant
  implicit-mode setup.

- Adversarial shapes (configuredIds === null OR diskIds === null)
  fail closed: refuse short-circuit, fall through to full planning.

Result
------
- src/agents/models-config.ts:
  + new helper collectShortCircuitModelIds documents the parser
    contract: returns null for fail-closed shapes, empty Set for
    legitimate implicit-only mode, populated Set otherwise.
  + readExistingProviderMatchesConfig adds the subset check after
    the existing per-model transport loop.

- src/agents/models-config.target-provider-short-circuit.test.ts:
  four new round-8 regression tests:
  + miss-on-newly-configured-model: config adds { id: 'gpt-6-newly-configured' };
    short-circuit rejects, full plan re-runs.
  + miss-on-config-only-bare-string-model-add: same shape but with
    bare-string entries; subset check still fires.
  + hit-on-implicit-only-models-list: empty configured.models with
    matching transport still short-circuits (perf path preserved
    for implicit-discovery mode).
  + miss-on-malformed-configured-model-entry: configured.models has
    an entry { id: 1234 }; collector returns null; short-circuit
    refuses (fail-closed for adversarial shape).

Validation gate
---------------
- pnpm tsgo:core: clean
- pnpm tsgo:core:test: clean
- pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts:
  52/52 passed (44 prior + 4 new)
- pnpm oxlint <touched files>: 0 warnings, 0 errors
- pnpm plugin-sdk:api:check: OK
- git diff --check: clean
…ly short-circuit on targetModel (review feedback)

What
----
Round-9 review feedback on PR openclaw#73261 addressing two Codex P2 findings on
the round-8 commit `fed465f466`:

1. [P2] Normalize provider defaults before short-circuit comparison
   (`src/agents/models-config.ts:1282`). The structural compare ran
   `cfg.models.providers[targetProvider]` AS AUTHORED against
   `models.json` AS NORMALIZED — but `planOpenClawModelsJson` writes
   the normalized shape, so any provider whose policy hook injects
   defaults (e.g. `extensions/ollama/provider-policy-api.ts` defaults
   `baseUrl` to `http://localhost:11434`) would always miss the
   short-circuit even when disk was already correct. Every targeted
   call would fall through to a full plan, disabling the perf path
   for that provider.

2. [P2] Check requested model on implicit-only short-circuit hits
   (`src/agents/models-config.ts:997`). When
   `configuredProvider.models` is `[]` / omitted (implicit-discovery
   mode), the prior contract skipped ALL model-id validation and
   could bless a stale disk catalog. With this round wiring
   `targetProvider` into the embedded runner cold paths, a stale
   `models.json` would short-circuit and then `resolveModelAsync`
   would fail with `Unknown model: <provider>/<model>` until another
   path forced a full reconcile.

Why
---
1. Apply the same `normalizeProviderSpecificConfig(targetProvider, cfg)`
   pre-pass that `normalizeProviders` runs before plan writes. The hook
   is a no-op for providers without an opinion, so existing tests stay
   green; ollama and any future bundled provider with a normalize-config
   policy now hit the perf path on the second pass.

2. Thread the resolved model id through the embedded runner via the
   already-defined `EnsureOpenClawModelsJsonOptions.targetModel` (was
   reserved). In implicit-only mode the structural compare now also
   checks `targetModelId` is present on disk; if it isn't, refuse the
   short-circuit and let the planner rediscover. Explicit-mode
   contract (subset check) is unchanged. Folded `targetModelId` into
   the scoped readyCache key so a hit cached for model X cannot be
   reused as a "match" for model Y under the same
   (provider, fingerprint, models.json content) tuple when Y isn't
   on disk.

How
---
- `readExistingProviderMatchesConfig`:
  - Apply `normalizeProviderSpecificConfig` to the configured provider
    after the `isRecord` guard, then compare normalized vs disk.
  - Accept `targetModelId?: string` and, in the implicit-only branch
    (configured `models` empty), require `targetModelId` to be on
    disk; lazily compute `diskIds` so adversarial disk model rows
    still fail closed in both branches without parsing twice.
- `modelsJsonScopedShortCircuitCacheKey`: append `\\0m:<id>` when a
  `targetModelId` is provided so per-model cache scope follows the
  per-model contract above. Keys without `targetModel` keep the prior
  shape.
- `pi-embedded-runner/run.ts` and `pi-embedded-runner/compact.ts`:
  forward the resolved `modelId` as `targetModel` alongside
  `targetProvider`.
- `EnsureOpenClawModelsJsonOptions.targetModel` JSDoc updated from
  "reserved" to the implicit-only contract.

Tests
-----
4 new cases in
`src/agents/models-config.target-provider-short-circuit.test.ts`,
pinning the regressions:

- `hit-on-policy-injected-default-baseUrl` — ollama config without
  `baseUrl` short-circuits on second pass because policy normalizes
  both sides to the default. Without the round-9 fix this falls
  through.
- `miss-on-implicit-only-target-model-not-on-disk` — implicit mode
  with `targetModel` missing from disk now misses the short-circuit
  and triggers a re-plan.
- `hit-on-implicit-only-target-model-on-disk` — symmetric companion;
  short-circuit still hits when the model is on disk.
- `scoped-cache-per-target-model` — model X cached hit does not
  satisfy a follow-up call for model Y under the same fingerprint
  and models.json content when Y is not on disk.

Validation gate
---------------
- `pnpm tsgo:core` clean
- `pnpm tsgo:core:test` clean
- `pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts`:
  60 passed (30 × 2 contexts)
- `pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts src/agents/models-config.providers.policy.test.ts`:
  24 passed
- `pnpm vitest run src/infra/changelog-unreleased.test.ts`: 3 passed
- `pnpm config:schema:check`: ok
- `pnpm plugin-sdk:api:check`: ok
- `pnpm oxlint <touched files>`: 0 new errors (the pre-existing
  `__testing` underscore-dangle finding in
  `pi-embedded-runner/compact.ts:1425` is upstream and unrelated)
- `git diff --check`: clean

Beads: openclaw-8zp
…rt-circuit cache (review feedback)

Round-10 follow-up on Clawsweeper P2 (outstanding since 2026-04-30T22:05,
missed in rounds 6-9): "Cache only the validated models.json snapshot."

Pre-fix, `readExistingProviderMatchesConfig` would safe-read +
structurally validate the on-disk `models.json` once via
`safeReadFileOutcome`, then return a bare `boolean`.  The caller at
models-config.ts:1397-1401 would then issue a SECOND read via
`readModelsJsonContentOutcome(targetPath)` and store THAT outcome's
hash in the provider-scoped readyCache.  Between the two reads, an
attacker (or any external editor) replacing `models.json` could land
hash(swappedBytes) in the scoped cache as "the validated snapshot."  A
later targeted call hitting the cache would compare current disk
against hash(swappedBytes) and accept it as a match, blessing
attacker-controlled provider transport (api / baseUrl / headers
consumed per-call by `pi-embedded-runner/model.ts`).  CWE-345.

This commit collapses the two reads into one by threading the
validated `ContentHashOutcome` straight back from the structural
check.  Concretely:

- `readExistingProviderMatchesConfig` now returns a discriminated
  union: `{ matches: true; validatedModelsJsonOutcome }` on success,
  `{ matches: false }` on every failure path.  The validated outcome
  is derived directly from the `safeReadFileOutcome` the function
  already runs (line 838) — same bytes, same hash, no second disk
  trip.
- The caller uses `matchOutcome.validatedModelsJsonOutcome` for the
  scoped-cache `set` and drops the redundant
  `readModelsJsonContentOutcome(targetPath)` call.
- The `kind !== "uncacheable"` guard is preserved as
  belt-and-suspenders even though, on the success path, the validated
  outcome is provably `hashed` (uncacheable cases early-return
  `{ matches: false }` before we get here).

Three new regression tests pin the contract from independent angles:

- `cache-stores-validated-outcome` — happy path: cold + stable disk +
  reset-cache + targeted call must take the disk-based short-circuit
  exactly once and a follow-up targeted call must hit the warm scoped
  cache without re-running discovery.
- `toctou-swap-cannot-bless-unvalidated-content` — security: after a
  cold short-circuit populates the scoped cache, swap on-disk
  `models.json` to a config-disagreeing baseUrl; the next targeted
  call MUST detect drift, refuse the cache, fail the structural
  check, and fall through to a full plan (resolveImplicit fires).
- `no-cache-on-uncacheable-validated-outcome` — defense-in-depth:
  oversize `models.json` forces a full plan and the post-plan disk
  size returns under cap, confirming the uncacheable branch is
  reachable end-to-end without the redundant second read.

Adds a real-runtime proof script
`scripts/proof-73261-validated-outcome-cache.ts` that drives the
production `ensureOpenClawModelsJson` against a real on-disk
`models.json` in a temp dir, instruments `fs.promises.lstat` to count
reads per scenario, and self-checks that the round-10 contract holds:

  [1/3] cache-stores-validated-outcome
      lstat(models.json) during short-circuit: 1
      lstat(models.json) during scoped-cache hit + drift-check: 1
      ok
  [2/3] toctou-swap-cannot-bless-unvalidated-content
      disk baseUrl after cold plan: https://api.openai.com/v1
      swap was not silently blessed by stale scoped cache
      ok
  [3/3] no-cache-on-uncacheable-validated-outcome
      bloated models.json size: 2102064 bytes (> 1 MiB cap)
      post-plan models.json size: 9105 bytes
      ok

  All runtime assertions passed.

Validation gate (full output captured for the PR comment):
  pnpm tsgo:core                                                   ok
  pnpm tsgo:core:test                                              ok
  pnpm vitest run src/agents/models-config.target-provider-...     66/66
  pnpm vitest run src/agents/models-config.fingerprint-cache,
                  src/agents/models-config.write-serialization     32/32
  pnpm config:schema:check                                         ok
  pnpm plugin-sdk:api:check                                        ok
  pnpm oxlint <touched files>                                      ok
  git diff --check                                                 clean
  pnpm tsx scripts/proof-73261-validated-outcome-cache.ts          ok

Beads: openclaw-8zp
…rget-provider-short-circuit

# Conflicts:
#	CHANGELOG.md
#	src/agents/models-config.ts
…rget-provider-short-circuit

# Conflicts:
#	CHANGELOG.md
#	docs/.generated/plugin-sdk-api-baseline.sha256
@clawsweeper

clawsweeper Bot commented Jun 15, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

…che-unified

# Conflicts:
#	docs/.generated/plugin-sdk-api-baseline.sha256
Restore unrelated WhatsApp, gateway, skill-loading, and shared doctor/session files to the upstream formatting so the models config PR only carries feature-relevant changes.

Beads: openclaw-2d0
Restore unrelated formatting-only files to the branch merge-base so GitHub's three-dot PR diff no longer reports WhatsApp, gateway, skill-loading, and shared doctor/session churn.

Beads: openclaw-2d0
Resolve upstream SDK baseline conflicts while preserving the models config cache changes.

Beads: openclaw-2d0
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Review feedback follow-up — SQLite busy-timeout repair

Addressed ClawSweeper's P2 finding at src/agents/auth-profiles/sqlite.ts: readAuthProfileStoreCellOutcomeReadOnly now applies the same PRAGMA busy_timeout = 30000 policy as the existing read-only auth helper before querying.

Added focused regression coverage in src/agents/auth-profiles.sqlite-store.test.ts proving the outcome-returning fingerprint reader waits through brief rollback-journal contention and returns present instead of misclassifying the store as unreadable.

Validation on commit 4b66fdf9474ae578627dfbf4e34410be82e37c19:

node scripts/run-vitest.mjs src/agents/auth-profiles.sqlite-store.test.ts src/agents/models-config.fingerprint-cache.test.ts
# 2 files passed, 23 tests passed

pnpm exec oxfmt --check src/agents/auth-profiles/sqlite.ts src/agents/auth-profiles.sqlite-store.test.ts
pnpm tsgo:core
pnpm tsgo:core:test
git diff --check
# all clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 21, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

When loadModelCatalog starts from a cacheable source fingerprint but prepareOpenClawModelsJsonSource later reports the prepared source is uncacheable, clear the pending catalogKey before runtime discovery writes results. This prevents persisted model-catalog rows from being stored under a stale pre-prepare trust boundary.

Add focused regression coverage for cacheable-to-uncacheable prepared-source transitions.

Validation: node scripts/run-vitest.mjs src/agents/model-catalog.test.ts; pnpm exec oxfmt --check src/agents/model-catalog.ts src/agents/model-catalog.test.ts; pnpm tsgo:core; pnpm tsgo:core:test; git diff --check

Beads: openclaw-3dq
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Addressed the remaining stale-cache-key issue in 844c9d7d05 (fix(models): drop stale catalog cache key after uncacheable prepare).

What changed:

  • model-catalog now clears the pre-prepare catalogKey when prepareOpenClawModelsJsonSource() returns cacheable: false, instead of continuing to use a stale key computed before preparation.
  • Added a regression test proving an initially cacheable source that becomes uncacheable during prepare does not read/write runtime discovery results under the stale pre-prepare key.

Validation run after the fix:

node scripts/run-vitest.mjs src/agents/model-catalog.test.ts
# 53 passed

pnpm exec oxfmt --check src/agents/model-catalog.ts src/agents/model-catalog.test.ts
# clean

pnpm tsgo:core
# exited 0

pnpm tsgo:core:test
# exited 0

git diff --check
# clean

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 21, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@xuwei-xy

Copy link
Copy Markdown

A potential solution is to modify ui. What do you think?

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Author-side refresh check — exact-head validation

Head checked: 844c9d7d057f6d628c5c5fd9dea328c7b1e03f0a (zeroaltitude:perf/models-config-cache-unified).

What changed in this pass:

  • No code changes were pushed: the branch already contains current zeroaltitude/openclaw:main (896b3c612d61e3e14d6c93e2a6111030a2b91441; git rev-list --count HEAD..origin/main = 0).
  • Re-verified the older inline Codex connector P2/P1 concern about plugin catalog shard revalidation before warm cache hits. Current head validates generated plugin catalog sidecar outcomes on both global and scoped ready-cache hits before returning, and the focused regression/proof script still pins sidecar drift, rogue sidecar reconciliation, and the no-sidecar steady-state hit.
  • I did not merge current openclaw/openclaw:main directly because the author workflow for this fork treats zeroaltitude/openclaw:main / origin/main as the canonical base. At check time openclaw/openclaw:main was ahead of the fork main, so GitHub may still report the PR dirty until that base is synced or a maintainer explicitly accepts an upstream-main refresh.

Validation run from the topic worktree on exact head:

git diff --check
# clean

node scripts/run-vitest.mjs src/agents/models-config.fingerprint-cache.test.ts src/agents/model-catalog.test.ts src/commands/models/list.provider-catalog.test.ts
# 3 files passed, 91 tests passed

node scripts/run-vitest.mjs src/agents/models-config.target-provider-short-circuit.test.ts src/agents/models-config.write-serialization.test.ts src/agents/auth-profiles.sqlite-store.test.ts src/agents/embedded-agent-runner/compact.hooks.test.ts
# 4 files passed, 126 tests passed

pnpm tsx scripts/proof-90741-plugin-catalog-cache-validation.ts
# All runtime assertions passed.

pnpm tsgo:core
# exit 0

pnpm tsgo:core:test
# exit 0

pnpm exec oxfmt --check src/agents/model-catalog.ts src/agents/model-catalog.test.ts src/agents/auth-profiles/sqlite.ts src/agents/auth-profiles.sqlite-store.test.ts src/agents/models-config.ts src/agents/models-config.fingerprint-cache.test.ts src/commands/models/list.provider-catalog.ts src/commands/models/list.provider-catalog.test.ts scripts/proof-90741-plugin-catalog-cache-validation.ts
# All matched files use the correct format.

…che-unified

# Conflicts:
#	docs/.generated/plugin-sdk-api-baseline.sha256
#	src/agents/model-catalog.test.ts
…che-unified

# Conflicts:
#	docs/.generated/plugin-sdk-api-baseline.sha256
…che-unified

2421 commits behind. This branch and main both independently evolved the
same models.json caching subsystem, requiring combining both sides rather
than picking one:

- src/agents/models-config-state.ts: kept our richer ModelsJsonReadyCacheEntry
  (validates cached entries against both the models.json AND plugin-catalog
  sidecars' actual on-disk content hashes before treating a warm hit as
  valid - Codex P1 fixes from PR openclaw#72869/openclaw#73260/openclaw#90741), but adopted main's
  writeQueue: KeyedAsyncQueue in place of our writeLocks: Map<string, Promise<void>>
  - confirmed via the models-config.ts call site (already calling
  writeQueue.enqueue at an unconflicted line) that main's concurrency
  primitive is what the rest of the file already expects.
- src/agents/models-config.ts: dropped main's non-exported
  PreparedOpenClawModelsJsonSource type declaration - this branch already
  has its own, more complete, exported version (a discriminated union with
  a cacheable flag) further down in the file; keeping both would have been
  a duplicate-identifier error.
- src/agents/embedded-agent-runner/compact.hooks.harness.ts: kept our
  ensureOpenClawModelsJsonMock (confirmed still used by real test files),
  adopted main's 2-param maybeCompactAgentHarnessSessionMock signature
  (confirmed the real maybeCompactAgentHarnessSession function already
  takes 2 params) and its new runCompactWithSafetyTimeoutMock/
  compactWithSafetyTimeoutMock addition (a new, unrelated compaction
  timeout feature).

Applied the systematic function-by-function diff-against-main check
documented in refs/openclaw.md after the feat/claude-app-server-extension
incident; only the expected architectural differences from this branch's
own restructuring surfaced, no silent drops.

Validation: tsgo:core, tsgo:extensions, tsgo:core:test, tsgo:extensions:test
all clean. vitest models-config: 173/173. vitest compaction/embedded-agent
suites touching the modified mock harness: 135/135. config:schema:check,
plugin-sdk:api:check, oxlint, git diff --check all clean.
…che-unified

# Conflicts:
#	docs/.generated/plugin-sdk-api-baseline.sha256
#	src/agents/auth-profiles.sqlite-store.test.ts
#	src/agents/auth-profiles/sqlite.ts
@steipete

Copy link
Copy Markdown
Contributor

Thanks for the deep performance work here — the problem you're attacking (models-config/auth-profile resolution cost) is real and acknowledged refactor debt. Closing this implementation after maintainer review, though: the warm path still synchronously reads and hashes SQLite auth state, models.json, and plugin sidecars per request, which keeps the freshness-polling pattern our architecture rules disallow on hot paths (AGENTS.md: carry prepared facts forward; no request-time reread/hash). The structural fast path also duplicates planner rules for provider normalization/credentials/transports, which would drift from the canonical planner over time, and the added auth SQLite reader parallels the canonical inspector.

The fix shape we'd sponsor: lifecycle-owned catalog generation — build the models/auth snapshot once at startup/reload/install (the events that can change it), and carry that prepared object into runtime callers, deleting the per-request discovery instead of caching around it. If you're up for that design, we'd love to see it — your measurements from this PR would be great evidence for it.

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 merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants