Skip to content

fix(openrouter): keep prepared thinking efforts current after a catalog refresh - #160918

Open
LiuwqGit wants to merge 4 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-160758-openrouter-stale-efforts
Open

LiuwqGit wants to merge 4 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-160758-openrouter-stale-efforts

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

AI-assisted: yes

Fixes #160758

What Problem This Solves

  • Fixes an issue where OpenRouter models kept offering and selecting a stale reasoning effort (for example xhigh) after OpenRouter dropped it, because the effort metadata was copied into the prepared catalog row at discovery time and the in-process capability cache refreshed later without updating that row.
  • Users had to wait for the model catalog to be rebuilt past the discovery cache window before sessions showed the current effort choices.
  • Follow-up 1 (review finding): route projection copied the catalog provenance marker onto rows that then received an operator-authored thinkingLevelMap from logical overrides, so a warm capability cache could replace that authored map with cached catalog data. The marker is now cleared whenever logical overrides declare effort metadata.
  • Follow-up 2: the host merge of a discovered row with a configured row (mergeProviderModels) had the same leak — an operator-authored thinkingLevelMap or authored effort tiers still inherited the catalog marker from discovery, so a warm cache could clobber the authored settings. The marker is now cleared whenever the configured row declares effort metadata.
  • Follow-up 3 (previous round): both provenance-clearing checks (mergeProviderModels and overlayCatalogMetadata) missed compat.reasoningEffortMap, which is an explicit scalar-effort declaration — resolveCatalogOwnedModelCompat enables scalar support for a mapping-only row. Such a row kept the marker, so a warm catalog generation advertising supportsReasoningEffort: false with an empty ladder replaced the operator's mapping and dropped the mapped effort from session choices. Mapping declarations now clear provenance in both places, restoring the intent of 642b31d (operator effort lists, mappings, and scalar support win over incomplete catalog guesses).
  • Follow-up 4 (previous round): a marked row was only refreshed when the model had a configured entry (preferRuntimeResolvedModel). For a plain discovered canonical model the host returned the stale registry row as the executable model, so the session could offer an effort the row could not carry and the request resolver silently clamped it (xhigh → high). Marked rows are now refreshed through the provider's own dynamic-model resolver during normal host model resolution.
  • Follow-up 5 (this round): the executable-row refresh introduced a fallback regression — with a cold capability cache and a failing /models fetch, buildDynamicOpenRouterModel still returned a synthetic default row (reasoning: false, text-only input, zero prices), and because that result was defined the host never fell back to the registry row. A prepared reasoning/image model lost those capabilities and the completions request omitted its selected effort. The OpenRouter dynamic-model hook now declines whenever capabilities are not loaded and the registry already prepared a row for the model, so normal host resolution retains the prepared metadata; unknown models without a prepared row still resolve dynamically, keeping missing-model runs working.
  • Related: fix(openrouter): configured models send high reasoning effort when xhigh is selected #160651 (merged) brought configured catalog-route rows to parity with non-configured rows and explicitly left this catalog-refresh behavior as follow-up work; this PR completes that follow-up. The issue's review also names the missing distinction between declared and catalog-derived fields as the blocker for the fix.

Why This Change Was Made

  • Intended outcome: Prepared OpenRouter rows still carry the catalog's advertised efforts (existing contract), but rows built from the canonical OpenRouter route are now marked catalogReasoningEfforts, and the OpenRouter thinking hook replaces those catalog-derived effort fields with the currently loaded capabilities (the same catalog's current generation) while keeping operator-authored compat facts. Explicit configured declarations never carry the marker, so they keep winning. The run-side frozen thinking capability also prefers the runtime model's refreshed efforts for marked rows.
  • Authored-setting precedence: the marker is dropped on every path where an operator authors effort metadata — applyLogicalOverrides (route projection), mergeProviderModels (host merge of discovered + configured rows), and overlayCatalogMetadata (configured overlay) — and a declaration counts as authored when it is a thinking map, effort tiers, scalar support, or an effort mapping. This keeps 642b31d's contract intact: operator effort lists, mappings, and scalar support still win over incomplete catalog guesses; only rows whose effort metadata genuinely came from the catalog follow a refresh.
  • Executable-row refresh: resolveModelWithPreparedRegistry / model.ts now treat a catalog-derived registry row like a runtime-preferred row, so the model a run actually uses is re-resolved through the provider hook instead of being frozen at preparation time. Unmarked rows (authored, custom-route, proxy) keep the previous single-lookup behavior.
  • Out of scope: No change to custom/proxy route discovery rows (they keep owning their discovered efforts), no change to the capability cache fetch/refresh behavior, and no new I/O on the synchronous session-read path: the hook still only reads capabilities already loaded in memory, exactly as in fix(openrouter): configured models send high reasoning effort when xhigh is selected #160651.
  • Highest-risk area: Provenance merge points for the new marker (overlayCatalogMetadata, route projection, the discovered/configured merge, model registry rows).
  • How is that risk mitigated? The marker is cleared when a configured overlay declares effort metadata, when logical overrides author a thinking map, when a configured row authors effort metadata, or when capabilities cannot cross a route change — each covered by a dedicated test. The persisted catalog schema is unchanged (the marker is an optional in-memory field and TypeBox model rows stay open), and stored-data compatibility is proven below in both directions.

User Impact

  • Sessions on canonical OpenRouter models now offer and select the reasoning effort levels OpenRouter currently advertises, following a capability refresh without a restart or catalog rebuild, matching the behavior fix(openrouter): configured models send high reasoning effort when xhigh is selected #160651 already established for configured rows.
  • Explicit operator declarations of compat.supportedReasoningEfforts, compat.supportsReasoningEffort, compat.reasoningEffortMap, or thinkingLevelMap are unchanged and still take precedence; authored settings are no longer replaced by refreshed catalog data, whether they arrive through route overrides, a configured overlay, or a configured model row merged with discovery.
  • Existing stored catalogs (models.json, persisted generated plugin catalogs) load unchanged; rows written before this change have no provenance marker and keep behaving exactly as before.
  • Success criteria: After a missing-model load refreshes the capability cache to ["high","medium","low"], a prepared row that still carries xhigh resolves thinking levels without xhigh; with a cold capability cache the prepared row's own snapshot is kept; custom routes are unaffected; a row with an operator-authored thinkingLevelMap keeps that map and its own discovered efforts after the same refresh on the projection, overlay, and config-merge paths; and a row whose only declaration is compat.reasoningEffortMap: { high: "medium" } still offers high after the catalog refreshes to a binary generation with an empty effort ladder; and when a refresh adds an effort, the executable row follows it, so the level a session offers is the level the provider request actually carries (no silent clamp); and when a capability fetch fails against a cold cache, a prepared row keeps its usable metadata (reasoning, input, effort ladder) and the request still carries the selected effort, while a model with no prepared row still resolves dynamically.
  • What should reviewers focus on? extensions/openrouter/index.ts (withOpenRouterCatalogThinking), extensions/openrouter/provider-catalog.ts (buildOpenRouterLiveModel), the marker plumbing in src/agents/model-catalog-*.ts and src/auto-reply/thinking*.ts, the executable-row refresh in src/agents/embedded-agent-runner/model.registry-resolution.ts (isCatalogDerivedRuntimeRow, resolveModelWithPreparedRegistry) and src/agents/embedded-agent-runner/model.ts, the marker-clearing in src/agents/model-catalog-route.ts (applyLogicalOverrides), src/agents/models-config.merge.ts (mergeProviderModels), and src/agents/model-catalog-metadata.ts (overlayCatalogMetadata), and the regression fixtures extensions/openrouter/catalog-reasoning-refresh.test.ts, src/agents/model-catalog-route.test.ts, src/agents/models-config.merge.test.ts, src/agents/model-catalog-metadata.test.ts, src/agents/sessions/model-registry.test.ts, src/agents/embedded-agent-runner/model.compat-route.test.ts.

Evidence

  • Real environment tested: Isolated worktree of this branch rebased onto current main, Node v26. Three evidence layers: (1) the vitest regressions below, (2) a real-path run that drives the real plugin catalog hook, the real host discovery normalization, the real registry projection, the real capability-cache refresh, a real prepared session, and the real final provider request — only the upstream OpenRouter endpoint is impersonated by a local loopback HTTPS endpoint (transport-level redirect; the request URL stays https://openrouter.ai/api/v1, key synthetic), and (3) a data-model compatibility run that loads stored catalogs through the real registry and validates them with both this build's schema and the latest stable release's compiled validator (v2026.10.8, schema source extracted from the tag).
  • Exact steps or commands run after this patch:
    node scripts/run-vitest.mjs run extensions/openrouter/catalog-reasoning-refresh.test.ts \
      extensions/openrouter/provider-catalog.test.ts extensions/openrouter/index.test.ts \
      extensions/openrouter/prefer-runtime-model.test.ts \
      src/agents/embedded-agent-runner/openrouter-model-capabilities.test.ts
    node scripts/run-vitest.mjs run src/agents/models-config.merge.test.ts \
      src/plugins/provider-discovery.test.ts src/agents/sessions/model-registry.test.ts \
      src/agents/model-catalog-metadata.test.ts src/agents/model-catalog-lookup.test.ts \
      src/agents/model-catalog-route.test.ts src/auto-reply/thinking.test.ts \
      src/agents/models-config.providers.implicit.discovery-scope.test.ts \
      src/agents/models-config.provider-policy-registry.test.ts src/agents/model-catalog.test.ts \
      src/agents/prepared-model-catalog.scoped-thinking.test.ts \
      src/agents/prepared-model-catalog.unpublished-thinking.test.ts \
      src/agents/embedded-agent-runner/model.compat-route.test.ts \
      src/plugins/provider-discovery.catalog-copy-work.test.ts src/plugins/provider-discovery.runtime.test.ts
    bash skills/fix-pr/scripts/validate.sh <changed files>   # oxfmt + oxlint + same-dir tests + tsgo:core
    pnpm tsgo:core && pnpm tsgo:extensions
    node --import ./scripts/tsx.mjs <evidence>/real-path-proof-v2.mts        # real-path proof (host handoff + merge path + failed-capability-load)
    node --import ./scripts/tsx.mjs <evidence>/data-model-compat-proof.mts   # stored-data compatibility, baseline + patched
  • Evidence after fix:
    Focused suites on this head (validate.sh merged vitest call, no failures):
    11 test files / 224 tests passed — extensions/openrouter/catalog-reasoning-refresh,
    extensions/openrouter/index, extensions/openrouter/provider-catalog,
    src/agents/model-catalog-lookup, src/agents/model-catalog-metadata,
    src/agents/model-catalog-route, src/agents/models-config.merge,
    src/agents/sessions/model-registry, src/auto-reply/thinking,
    src/plugins/provider-discovery, src/agents/embedded-agent-runner/model.compat-route,
    src/agents/embedded-agent-runner/model.
    Wider host sweep on the same code (models-config providers/policy registry, model-catalog,
    prepared-model-catalog scoped/unpublished thinking, model.compat-route, provider-discovery
    catalog-copy-work/runtime, implicit discovery scope): 9 files / 110 tests passed.
    Test-type shards: tsgo core-test agents-other, agents-root, agents-sessions,
    plugins-platform, messaging, other + extensions.test — exit 0 on the previous head; this
    round ran the full tsgo:core project build plus tsgo:extensions instead (both PASS).
    validate.sh (oxfmt + oxlint + same-dir tests + tsgo:core): all green.
    tsgo:core PASS, tsgo:extensions PASS.
    This round's validate.sh run (failload fix + low-value test removals): 4 test files /
    111 tests passed — extensions/openrouter/index (76, incl. the new hook regression
    "keeps the prepared registry row when capabilities failed to load"),
    src/agents/embedded-agent-runner/model.compat-route (13, incl. the new host regression
    "keeps the prepared catalog-derived row when the provider resolver declines after a
    failed capability load"), src/auto-reply/thinking (17), src/agents/model-catalog-metadata (5).
    tsgo:core PASS, tsgo:extensions PASS on the pre-rebase head (a5fb5d0). Resolved head after
    the rebase onto current main (8a37e6b): affected suites re-run through validate.sh —
    8 test files / 172 tests passed (openrouter catalog-reasoning-refresh + index incl. the new
    hook regression, model-catalog-lookup/metadata/route, models-config.merge, model.compat-route
    incl. the new host regression, model-registry, thinking), and both real-path proofs re-run
    on it: 25/25 and 9/9 -> ALL CHECKS PASS. The tsgo lanes cannot execute on this dev host on
    current main (the new @tsrs native binary requires glibc >= 2.32; host has 2.31) and are
    deferred to CI on the resolved head.
    
    real-path-proof-v2.mts (real modules, real in-process capability cache, no stubs):
    [discovery] gen-1 catalog hook row: efforts ["xhigh","high","medium","low"],
                thinkingLevelMap {"off":null}, catalogReasoningEfforts=true
    [handoff]   normalizePluginDiscoveryResult (host discovery normalization) row:
                providers ["openrouter"], baseUrl https://openrouter.ai/api/v1,
                efforts ["xhigh","high","medium","low"], catalogReasoningEfforts=true
    [registry]  prepared registry row: api=openai-completions, catalogReasoningEfforts=true
    [session]   cold-cache levels = ["low","medium","high","xhigh","ultra"]
    [refresh]   real missing-model load -> real cache efforts ["high","medium","low"]
    [session]   warm-cache levels = ["low","medium","high","ultra"]   <- stale xhigh gone
    [run]       runtime model compat (resolveDynamicModel hook) = ["high","medium","low"]
    [request]   final provider request captured at the endpoint:
                model acme/effort-model, reasoning {"effort":"high"}
    [p1]        authored-map row projected without the marker; warm-cache levels keep
                ["low","medium","high","xhigh","ultra"]; marker-kept counterfactual
                drops to ["low","medium","high","ultra"]
    [merge]     host config merge with an authored thinkingLevelMap:
                thinkingLevelMap {"off":"none","high":"high"}, catalogReasoningEfforts=undefined,
                warm-cache levels ["off","low","medium","high","xhigh","ultra"] (authored kept)
    [mapping]   real cache refresh to a binary generation:
                compat {"supportsReasoningEffort":false,"supportedReasoningEfforts":[]}
    [mapping]   host config merge with a mapping-only declaration
                (compat.reasoningEffortMap {"high":"medium"}):
                merged compat {"supportsReasoningEffort":true,"supportsTools":true,
                  "reasoningEffortMap":{"high":"medium"}}, catalogReasoningEfforts=undefined
    [mapping]   warm binary-cache session levels on the mapped row
                  = ["minimal","low","medium","high","ultra"]   <- mapped "high" kept
    [mapping]   counterfactual (marker kept) = ["low","ultra"]  <- "high" lost
    [run]       executable row from NORMAL host model resolution (resolveModelAsync on an
                unconfigured discovered row; no direct resolveDynamicModel call):
                compat {"supportsReasoningEffort":true,
                        "supportedReasoningEfforts":["high","medium","low"], ...}
    [grow]      refresh that ADDS an effort while the prepared row is still the
                generation-1 snapshot:
                  session levels offered   = ["low","medium","high","xhigh","ultra"]
                  executable row (normal host resolution) efforts
                                           = ["xhigh","high","medium","low"]
                  run-side prepared compat = ["xhigh","high","medium","low"]
                  captured request reasoning = {"effort":"xhigh"}  <- not clamped
    [failload]  cold capability cache + failing /models endpoint (HTTP 500):
                  real missing-model load: threw=null, capabilities loaded=null
                  executable row from NORMAL host resolution (resolveModelAsync):
                    error=undefined, reasoning=true,
                    compat {"supportsReasoningEffort":true,
                            "supportedReasoningEfforts":["xhigh","high","medium","low"]}
                    (the prepared row's own snapshot kept, not the synthetic default)
                  run-side prepared compat = ["xhigh","high","medium","low"]
                  captured request reasoning = {"effort":"high"}  <- still carried
                  hook row for an unknown model (no prepared registry row):
                    id=acme/failload-model, api=openai-completions  <- still dynamic
    [verdict]   25/25 checks true -> RESULT: ALL CHECKS PASS
    
    data-model-compat-proof.mts (real registry load from disk + real validators):
    [schema] stored catalog (pre-change shape): accepted by current build = true,
             accepted by stable v2026.10.8 validator = true
    [schema] catalog written by this build (with marker): accepted by current build = true,
             accepted by stable v2026.10.8 validator = true  (downgrade-safe)
    [load]   stored row loaded by the real registry: efforts ["high","medium","low"],
             thinkingLevelMap {"off":null,"high":"high"}, catalogReasoningEfforts=undefined
    [load]   thinking levels from the stored row = ["low","medium","high","ultra"]
             -> identical to the baseline captured by running the same script in a clean
                origin/main worktree (unpatched): ["low","medium","high","ultra"]
    [round-trip] catalog written by this build, reloaded from disk:
             catalogReasoningEfforts=true, efforts ["xhigh","high","medium","low"],
             levels ["low","medium","high","xhigh","ultra"]
    Baseline (unpatched main) fails only markedRoundTripKeepsProvenance (the marker does not
    exist there); patched head: 9/9 checks -> RESULT: ALL CHECKS PASS
    
  • Observed result after fix: A prepared session on a canonical OpenRouter row resolves current efforts after a real cache refresh and the final chat/completions request carries reasoning: {"effort": "high"} (no stale xhigh); the provenance marker survives the real host discovery-normalization handoff into the registry row; a row whose effort metadata an operator authored — through route overrides, a configured overlay, or a configured model row merged with discovery — keeps that authored metadata across the same refresh; and a mapping-only declaration (reasoningEffortMap: { high: "medium" }) still offers high after the catalog refreshes to a binary generation with an empty ladder (["minimal","low","medium","high","ultra"], versus ["low","ultra"] when the marker is kept).
  • Before evidence (optional, visual changes encouraged): Main symptom: reverting extensions/openrouter/index.ts to main made the refresh regression fail with an extra "xhigh" level. Follow-up 1: running the same real-path script with only the marker-clearing in applyLogicalOverrides reverted produced RESULT: CHECKS FAILED (authored row clobbered to ["low","medium","high","ultra"]). Follow-up 2: with the mergeProviderModels marker-clearing absent, src/agents/models-config.merge.test.ts > drops catalog effort provenance when config authors effort metadata fails RED (expected true to be undefined), and the real-path [merge] step reports catalogReasoningEfforts=true on the authored row. Registry plumbing: removing the marker line from createRegistryRuntimeModel makes src/agents/sessions/model-registry.test.ts > loads stored catalogs without effort provenance and keeps discovered provenance fail RED (expected undefined to be true). Follow-up 4 (this round): with the executable-row refresh reverted, src/agents/embedded-agent-runner/model.compat-route.test.ts > refreshes a catalog-derived row through the provider resolver before offering new efforts fails RED (expected [ 'low', 'medium', 'high' ] to deeply equal [ 'xhigh', 'high', 'medium', 'low' ]), and the real-path run reports the stale executable row ([run] ... supportedReasoningEfforts: ["xhigh","high","medium","low"] after the cache refreshed to ["high","medium","low"]) with runtimeCompatRefreshed:false, preparedCompatRefreshed:false -> RESULT: CHECKS FAILED. Follow-up 3, all three RED before the reasoningEffortMap predicate was added: src/agents/models-config.merge.test.ts > drops catalog effort provenance when config authors effort metadata (expected true to be undefined), src/agents/model-catalog-metadata.test.ts > drops the marker when the overlay declares only an effort mapping (expected true to be undefined), and in the real-path run the mapped row reported catalogReasoningEfforts=true with warm binary-cache session levels ["low","ultra"] (mapped high lost). Follow-up 5 (this round): before the hook decline was added, extensions/openrouter/index.test.ts > keeps the prepared registry row when capabilities failed to load failed RED — the hook returned the synthetic default (reasoning: false, input: ["text"]) instead of undefined with a prepared registry row present — and the real-path run's new [failload] checks (failloadKeepsPreparedRow, failloadWireCarriesEffort) fail on that head for the same reason.
  • What was not tested: No live OpenRouter API call was made (no credentials); the upstream catalog/response endpoint is impersonated by a local loopback HTTPS endpoint at the system boundary while discovery, host normalization, registry projection, refresh, prepared-session resolution, and the transport request all run through the real code paths. No multi-gateway/production upgrade was performed: the compatibility evidence loads real stored catalog bytes through the real registry and validates them with the stable release's own compiled validator rather than upgrading an installed deployment. CI lanes (changed-project tests and full test-type check) are pending on GitHub Actions for this head.
  • Proof tier: L2
  • Proof limitations: The upstream OpenRouter service is simulated at the transport boundary; everything on the client side of that boundary (guarded discovery fetch, host discovery normalization, registry projection, real capability-cache load/refresh, prepared-session thinking resolution, runtime model resolution, request build, and HTTP send) runs the real production code. The stable-release comparison uses the v2026.10.8 schema source compiled with that tag's TypeBox major (1.3.34, present in the lockfile store), not a full install of the previous release.
  • Review state: Rebased onto current main (0ab37d2) to clear the GitHub-reported conflicts, preserving main's newer behavior: applyLogicalOverrides now layers the provenance clearing over main's mergeConfiguredThinkingLevelMap per-key merge (authored maps still own the row and drop the marker), and the openrouter hook regression keeps main's extended decision-model exclusion list; affected checks were re-run on the resolved head (see Evidence). Addressed the current review round (P2 "Retain the prepared model when capability refresh has no row"): the OpenRouter dynamic-model hook now declines to rebuild a row from missing capabilities whenever the registry already prepared one, so normal host model resolution keeps the prepared metadata and the request still carries the selected effort; covered by a hook regression, a host-level regression through resolveModelAsync plus the real openai-completions transport, and the real-path run's new [failload] section (cold cache + failing /models endpoint, unknown models still resolve dynamically). Both low-value tests named in the review were removed (src/auto-reply/thinking.test.ts provenance-forwarding case, src/agents/model-catalog-metadata.test.ts final modelCatalogRowToEntry field-copy case; the overlay precedence and route-change regressions are retained). Previous round: addressed the P2 "refresh discovered executable rows before exposing new efforts" finding: marked rows are now re-resolved through the provider's dynamic-model hook during normal host model resolution, with a regression that captures the outbound request through resolveModelAsync plus the real openai-completions transport (no direct resolveDynamicModel call), and the real-path run's [grow] section proves the same end to end for a refresh that adds an effort. Previous round: compat.reasoningEffortMap now counts as an authored declaration in both provenance-clearing checks (mergeProviderModels, overlayCatalogMetadata), with unit regressions for each path plus the mapping-only thinking-profile scenario added to the real-path run; the low-value field-copy case in src/plugins/provider-discovery.test.ts was removed as requested (the preceding parameterized cases already assert provider/model object identity across normalization, which preserves the field, and the real-path run proves the handoff end to end). Rebased onto current main (merge conflicts resolved; the worker-backed OpenRouter capability owner is retained — the thinking hook still reads getLoadedOpenRouterModelCapabilities from the worker-backed plugin state, and the real-path proof exercises a real capability-cache refresh through it). The P2 finding about copyProviderCatalogModel dropping the marker no longer applies on current main: that lossy copier was removed upstream by refactor(providers): share catalog facts and JSON response ownership #173375 (refactor(providers): share catalog facts and JSON response ownership), and normalizePluginDiscoveryResult now passes discovered provider/model objects through by identity. This head adds regression coverage pinning that handoff (src/plugins/provider-discovery.test.ts) and proves it end to end in the real-path run above. Also addressed: the config-merge provenance leak (new fix + RED/GREEN test) and the requested data-model compatibility proof.

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: openrouter size: M labels Sep 29, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Refresh catalog-derived OpenRouter thinking efforts while preserving operator declarations and prepared metadata when capability loading fails.

Example: OpenRouter removes xhigh from acme/effort-model after its catalog row was prepared.

  • Before: The session continues offering xhigh from the prepared row.
  • After: The session offers the refreshed low, medium, and high efforts without rebuilding the catalog.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with production-boundary request evidence, compatibility coverage, resolved prior findings, and a passing exact-head CI gate.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): Contributor logs exercise real catalog discovery, registry publication, capability-cache refresh, session thinking selection, resolveModelAsync, and HTTP request transmission against a synthetic loopback HTTPS upstream. Removed and added efforts, authored declarations, and cold-cache HTTP 500 fallback produce the expected requests; replay after conflict resolution is recorded. This establishes the production boundary behavior without claiming live OpenRouter inference or an installed deployment upgrade.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: OpenRouter sessions can offer stale reasoning choices or silently clamp a newly offered effort before sending the request.
Reason: Restores agreement between advertised capabilities and requests under the existing documented contract and the collaborator-authored linked issue.

Merge readiness

✅ Ready for maintainer review

This PR fixes an unresolved OpenRouter catalog-refresh bug. Earlier findings are addressed, GitHub reports a clean merge, and the reviewed head passes its CI gate; no new actionable defect was found.

Priority: P2
Reviewed head: 57ec2ddf97d193445dae650780b63c635e0a0375

Before merge

None.

Findings

None.

Agent review details

How this fits together

Provider discovery publishes model metadata into prepared catalogs and registries; thinking selection and executable-model resolution consume those facts to construct provider requests.

flowchart LR
  A[OpenRouter catalog] --> B[Discovery rows]
  B --> C[Prepared catalog and registry]
  A --> D[Capability cache]
  C --> E[Thinking selection]
  D --> E
  C --> F[Runtime model resolution]
  D --> F
  E --> G[Provider request]
  F --> G
Loading

Technical review

Best possible solution:

Keep catalog refresh with the existing provider capability owner and preserve explicit declarations and usable prepared rows.

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

Current-main source supports preparing xhigh, refreshing the separate capability cache without it, and retaining the prepared ladder; contributor before/after traces exercise that path, but this review ran no target code.

Is this the best way to solve the issue?

The provenance distinction is a focused repair using existing discovery, cache, registry, and request owners; it preserves authored precedence without synchronous session I/O or a second refresh mechanism.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Live catalog effort snapshots keeps the original intent (f024e67: Preserve declared thinking restrictions and mandatory OpenRouter reasoning across catalog and runtime consumers.)
  • Prepared thinking hook precedence changes intended behavior with a stated reason (4ddd0e3: Fill missing configured-row capabilities while preserving declared effort metadata and synchronous memory-only reads.)
  • Operator effort lists, mappings, and scalar support keeps the original intent (642b31d: Operator reasoning declarations must survive catalog preparation and incomplete catalog guesses.)
  • Frozen run-side thinking capability changes intended behavior with a stated reason (efc33f8: Carry prepared capabilities to the exact executable model and harness without leaking capabilities across routes.)
  • Configured thinking-map merge keeps the original intent (faa3814: Merge configured maps per key while retaining catalog-owned profile restrictions.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main still contains the stale-row mechanism: The current-main thinking hook returns immediately when the prepared row already supplies effort metadata; the relevant production files have no intervening changes from the reviewed merge base. (extensions/openrouter/index.ts:236, 11a13b63d492)
  • Catalog refresh and authored precedence: Marked rows use loaded capability efforts, while configured lists, scalar-support declarations, thinking maps, and reasoningEffortMap declarations clear inherited provenance at the merge and overlay boundaries. (src/agents/models-config.merge.ts:208, 57ec2ddf97d1)
  • Executable refresh retains the prepared fallback: Catalog-derived executable rows reach the existing provider resolver; when it declines, normal host resolution retains the prepared row. OpenRouter now declines when capabilities are unavailable and a registry row exists. (src/agents/embedded-agent-runner/model.registry-resolution.ts:369, 57ec2ddf97d1)
  • Contributor production-boundary evidence: The full PR body and contributor discussion record real discovery, host normalization, registry publication, cache refresh, thinking selection, normal resolveModelAsync resolution, and captured HTTP requests against loopback HTTPS. The traces cover removed and added efforts, authored mappings, and HTTP 500 with a cold cache; the contributor reports replaying both proofs after conflict resolution. (57ec2ddf97d1)
  • Stored-catalog compatibility: Contributor evidence loads old catalog bytes through the real registry and verifies marked-row round trips and older-validator acceptance. Inspection of v2026.11.2 confirms its model objects remain open to additional fields; this PR changes no registry schema or persisted settings and needs no migration. (src/agents/sessions/model-registry-schema.ts, b556fdf457b0)
  • Prior merge blocker resolved: REST readback confirms the exact reviewed head is mergeable with mergeable_state clean; its openclaw/ci-gate, production types, and test types checks succeed. (57ec2ddf97d1)

Likely related people:

  • Peter Steinberger: Raw commit 8d9152c adds extensions/openrouter/provider-catalog.ts:172 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8d9152c2d5e5; files: extensions/openrouter/provider-catalog.ts)
  • Olli: Raw commit 4ddd0e3 adds extensions/openrouter/index.ts:74 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4ddd0e33973e; files: extensions/openrouter/index.ts)

PR surface

Source +147, Tests +666, Docs 0, Other +1. Total +814 across 27 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 17 161 14 +147
Tests 8 666 0 +666
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 27 829 15 +814

Preflight source

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

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +161/-14 lines; tests +666/-0 lines Production growth carries provenance through existing boundaries; regressions cover refresh, declaration precedence, route isolation, stored catalogs, and failed-load fallback.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #160758
Summary: This PR implements the canonical prepared-row refresh report; configured-row parity and routing variants are related but distinct.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Stale effort choices and silent request clamping affect a limited OpenRouter capability-refresh path.
  • merge-risk: 🚨 compatibility: The patch adds optional provenance to an existing provider-hook contract and changes metadata precedence; declaration and stored-catalog compatibility are covered.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (8 earlier review cycles)
  • reviewed 2026-09-29T03:14:50.022Z sha b27ecfa5b45825165e7255c5424a7a0cb7802753 :: needs real behavior proof before merge. :: [P1] Clear catalog provenance after configured thinking-map overrides
  • reviewed 2026-09-29T04:21:58.951Z sha 5ba44d10e11808e7d00760eb55b6205c4c9d4f9d :: blocked before merge. :: none
  • reviewed 2026-09-29T04:39:10.851Z sha 055b2ce723808cee77776aa1bd9b907a9e441869 :: blocked before merge. :: none
  • reviewed 2026-10-29T02:10:02.378Z sha 055b2ce723808cee77776aa1bd9b907a9e441869 :: needs real behavior proof before merge. :: [P2] Preserve the provenance flag through host catalog normalization
  • reviewed 2026-10-29T07:04:02.447Z sha ed6b28a107d2fc6f6cc218f4961fd280611d759a :: needs changes before merge. :: [P2] Clear catalog provenance for reasoningEffortMap declarations
  • reviewed 2026-10-29T08:33:50.112Z sha a06c336012e3dbd0f700b1e1ee5ea075d53fe458 :: needs changes before merge. :: [P2] Refresh discovered executable rows before exposing new efforts
  • reviewed 2026-10-29T09:48:16.545Z sha 305b28d1caa2d89a1d63aa5bb8b0fa390ea3b949 :: needs changes before merge. :: [P2] Retain the prepared model when capability refresh has no row
  • reviewed 2026-11-09T12:17:32.685Z sha a5fb5d0fc60d0fce13b2e02fcf0dc5de95d2a5c7 :: needs changes before merge. :: none

Reviewed November 9, 2026, 8:30 AM ET / 13:30 UTC (Revision 9).

@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Addressed the review findings on the new head (5ba44d1):

P1 — clear catalog provenance after configured thinking-map overrides

applyLogicalOverrides now drops the catalogReasoningEfforts marker whenever the override declares a thinkingLevelMap, so an operator-authored map stays authoritative across capability refreshes on every projection path (unmanaged, unresolved, selected). Focused coverage added in src/agents/model-catalog-route.test.ts (marker cleared with an authored map, preserved without one) and extensions/openrouter/catalog-reasoning-refresh.test.ts (authored map + warm cache keeps the row's own efforts; the marker-kept counterfactual is clobbered).

Real-path proof (prepared session + final provider request after refresh)

Ran a real-path harness with only the upstream OpenRouter endpoint impersonated by a local HTTPS endpoint (transport-level redirect; request URLs stay https://openrouter.ai/api/v1). Everything on the client side runs the real production code — no stubbed capability cache, no manually constructed hook context:

[discovery] real guarded discovery fetch -> row efforts ["xhigh","high","medium","low"],
            thinkingLevelMap {"off":null}, catalogReasoningEfforts=true
[registry]  real ModelRegistry row (marker threaded through model-registry code)
[session]   cold-cache prepared-session levels = ["low","medium","high","xhigh","ultra"]
[refresh]   real loadOpenRouterModelCapabilities("acme/brand-new-model") (missing-model load)
            -> real in-memory cache efforts ["high","medium","low"]
[session]   warm-cache levels = ["low","medium","high","ultra"]     <- stale xhigh gone
[run]       real resolveDynamicModel hook -> runtime model compat ["high","medium","low"];
            real resolvePreparedModelThinkingCompat -> ["high","medium","low"]
[request]   real openai-completions transport request captured at the endpoint:
            model "acme/effort-model", reasoning {"effort":"high"}
[p1]        authored-map row projected without the marker (fix); warm-cache levels keep
            ["low","medium","high","xhigh","ultra"]; marker-kept counterfactual drops
            to ["low","medium","high","ultra"] (the reported regression)
RESULT: ALL CHECKS PASS

Reverting only the marker-clearing change reproduces the P1 symptom on the same harness (RESULT: CHECKS FAILED; the authored row is clobbered to ["low","medium","high","ultra"] and the projected entry keeps catalogReasoningEfforts=true).

The PR body's Evidence section has been updated with the full transcript and commands. The two failed checks-node-changed-compact-large-19/20 runs on the previous head were setup-stage curl: (22) HTTP 500 infrastructure failures (tool download, no test executed); CI is re-running on the new head.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@LiuwqGit
LiuwqGit force-pushed the feat/issue-160758-openrouter-stale-efforts branch from 5ba44d1 to 055b2ce Compare September 29, 2026 04:30
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 29, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 29, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Oct 29, 2026
@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Follow-up round: rebased onto current main, closed the provenance leak on the config-merge path, and added the two proofs the review asked for (host discovery-normalization handoff, data-model compatibility). Head is now ed6b28a107d.

1. Merge conflicts resolved (rebased onto main @ 540091c8bd8). The worker-backed OpenRouter capability owner is retained: the thinking hook still reads getLoadedOpenRouterModelCapabilities from worker-backed plugin state, and the real-path run below refreshes that cache through a real missing-model load. Upstream had deleted src/agents/model-catalog-entry.test.ts and rewritten model-catalog-route.test.ts / thinking.ts / model-registry.ts; the entry-projection coverage moved into src/agents/model-catalog-metadata.test.ts, the route test was re-expressed against the current projection helper, and the registry marker now flows through createRegistryRuntimeModel.

2. P2 finding (copyProviderCatalogModel drops the marker) no longer applies on current main. That lossy copier was removed upstream by #173375 (refactor(providers): share catalog facts and JSON response ownership); normalizePluginDiscoveryResult now hands discovered provider/model objects through by identity (readProviderCatalogResultEntries). This head pins that handoff with a regression test (src/plugins/provider-discovery.test.ts > keeps catalog-derived effort provenance across the discovery handoff) and proves it end to end in the real-path run.

3. New fix — the same leak on the config-merge path. mergeProviderModels merged a discovered (marked) row with a configured row and kept the marker even when the operator authored thinkingLevelMap or effort tiers, so a warm capability cache could still clobber authored settings. The marker is now cleared whenever the configured row declares effort metadata.

RED (marker-clearing absent in mergeProviderModels):
 × src/agents/models-config.merge.test.ts > models-config merge > drops catalog effort
   provenance when config authors effort metadata
   → AssertionError: expected true to be undefined
   Tests  1 failed | 10 passed (11)
GREEN (with the fix): src/agents/models-config.merge.test.ts — all passed

4. Real behavior proof including the host discovery-normalization handoff (real-path-proof-v2.mts; real plugin catalog hook → real runProviderCatalog → real normalizePluginDiscoveryResult → real registry projection → real capability-cache refresh → real prepared session → real transport request; only the upstream OpenRouter endpoint is impersonated by a local loopback HTTPS endpoint via a transport-level redirect, so the request URL stays https://openrouter.ai/api/v1 and the key is synthetic — no credentials, no private endpoints in this evidence):

[discovery] gen-1 catalog hook row: efforts ["xhigh","high","medium","low"],
            thinkingLevelMap {"off":null}, catalogReasoningEfforts=true
[handoff]   normalizePluginDiscoveryResult row (host discovery normalization):
            providers ["openrouter"], baseUrl https://openrouter.ai/api/v1,
            efforts ["xhigh","high","medium","low"], catalogReasoningEfforts=true
[registry]  prepared registry row: api=openai-completions, catalogReasoningEfforts=true
[session]   cold-cache levels = ["low","medium","high","xhigh","ultra"]
[refresh]   real missing-model load -> real cache efforts ["high","medium","low"]
[session]   warm-cache levels = ["low","medium","high","ultra"]   <- stale xhigh gone
[run]       runtime model compat (resolveDynamicModel hook) = ["high","medium","low"]
[request]   final provider request captured at the endpoint:
            model acme/effort-model, reasoning {"effort":"high"}
[p1]        authored-map row projected without the marker; warm-cache levels keep
            ["low","medium","high","xhigh","ultra"]; marker-kept counterfactual
            drops to ["low","medium","high","ultra"]
[merge]     host config merge with an authored thinkingLevelMap:
            thinkingLevelMap {"off":"none","high":"high"}, catalogReasoningEfforts=undefined,
            warm-cache levels ["off","low","medium","high","xhigh","ultra"] (authored kept)
[verdict]   14/14 checks true -> RESULT: ALL CHECKS PASS

5. Data-model compatibility proof (data-model-compat-proof.mts; real registry load from disk + the real compiled validators, including the latest stable release's schema source extracted from tag v2026.10.8 and compiled with that tag's TypeBox major):

[schema] stored catalog (pre-change shape, no provenance field):
         accepted by this build = true, accepted by stable v2026.10.8 validator = true
[schema] catalog written by this build (with the provenance field):
         accepted by this build = true, accepted by stable v2026.10.8 validator = true
[load]   stored row loaded by the real registry: efforts ["high","medium","low"],
         thinkingLevelMap {"off":null,"high":"high"}, catalogReasoningEfforts=undefined
[load]   thinking levels from the stored row = ["low","medium","high","ultra"]
         baseline (same script in a clean origin/main worktree, unpatched)
                                        = ["low","medium","high","ultra"]  -> identical
[round-trip] catalog written by this build, reloaded from disk:
         catalogReasoningEfforts=true, efforts ["xhigh","high","medium","low"],
         levels ["low","medium","high","xhigh","ultra"]
baseline: fails only markedRoundTripKeepsProvenance (field does not exist there)
patched head: 9/9 checks -> RESULT: ALL CHECKS PASS

The persisted catalog schema itself is unchanged: ModelDefinitionSchema gained no required or renamed field (the only diffs against v2026.10.8 are upstream's own parameterCount / family additions), and the provenance field is an optional in-memory marker, so stored rows from earlier releases load byte-identically.

6. Local verification on this head. validate.sh over all 23 changed files (oxfmt + oxlint + same-directory tests + tsgo:core) is green; focused vitest runs: 5 extension/runner files / 112 tests, 8 host files / 117 tests, 9 host files / 110 tests — no failures; pnpm tsgo:core and pnpm tsgo:extensions pass. Full CI lanes are running on GitHub Actions for this head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 29, 2026
@LiuwqGit
LiuwqGit force-pushed the feat/issue-160758-openrouter-stale-efforts branch 2 times, most recently from 3bd82fc to a06c336 Compare October 29, 2026 08:17
@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Round 3: addressed the P2 finding (mapping-only declarations) and the test note. Head is now a06c336012e.

1. compat.reasoningEffortMap now clears catalog provenance (P2). A mapping-only configured row is an explicit scalar-effort declaration — resolveCatalogOwnedModelCompat enables scalar support and clears an inherited empty ladder for it — but neither provenance-clearing predicate looked at that field, so the merged/overlaid row kept catalogReasoningEfforts: true and a warm binary catalog generation replaced the operator's mapping. Added compat?.reasoningEffortMap !== undefined to both checks:

  • src/agents/models-config.merge.ts (mergeProviderModels, discovered + configured merge)
  • src/agents/model-catalog-metadata.ts (overlayCatalogMetadata, configured overlay)

This restores rather than changes the intent of 642b31d ("preserve operator effort lists, mappings, and scalar support over incomplete catalog guesses"): the marker only ever identifies rows whose effort metadata came from the catalog, so an operator mapping is now treated as authored on every path — route overrides (applyLogicalOverrides), configured overlays, and the host config merge. The refresh behavior for genuinely catalog-derived rows is unchanged.

RED (before adding reasoningEffortMap to the predicates):
 × src/agents/models-config.merge.test.ts > drops catalog effort provenance when config
   authors effort metadata            → AssertionError: expected true to be undefined
 × src/agents/model-catalog-metadata.test.ts > drops the marker when the overlay declares
   only an effort mapping             → AssertionError: expected true to be undefined
GREEN: both suites pass; validate.sh (oxfmt + oxlint + same-dir tests + tsgo:core) all green;
test-type shards agents-other / agents-root / agents-sessions / plugins-platform /
messaging / other / extensions.test all exit 0.

2. Regression covering the resulting thinking profile (real-path run, section [mapping]): the real capability cache is refreshed to a binary generation, a mapping-only configured row is merged with the discovered row through the real host merge, published through the real registry, and resolved through the real host thinking resolver with the real OpenRouter hook installed.

[mapping] real capability cache after the binary-generation refresh:
          compat = {"supportsReasoningEffort":false,"supportedReasoningEfforts":[]}
[mapping] host config merge with a mapping-only declaration:
          compat = {"supportsReasoningEffort":true,"supportsTools":true,
                    "reasoningEffortMap":{"high":"medium"}}
          catalogReasoningEfforts = undefined
[mapping] warm binary-cache session levels on the mapped row
            = ["minimal","low","medium","high","ultra"]   <- operator's mapped "high" kept
[mapping] counterfactual (marker kept on the same row)
            = ["low","ultra"]                             <- "high" lost, the reported defect
[verdict] 17/17 checks true -> RESULT: ALL CHECKS PASS

Before/after on the identical script (only the two predicate lines reverted, then restored):

BEFORE (predicates without reasoningEffortMap):
[mapping] warm binary-cache session levels on the mapped row = ["low","ultra"]
[verdict] ..."mergeClearsMarkerForMappingOnly":false,"mappingDeclarationKeepsMappedEffort":false...
RESULT: CHECKS FAILED
AFTER (this head):
[mapping] warm binary-cache session levels on the mapped row = ["minimal","low","medium","high","ultra"]
[verdict] ..."mergeClearsMarkerForMappingOnly":true,"mappingDeclarationKeepsMappedEffort":true...
RESULT: ALL CHECKS PASS (17/17)
``` The earlier sections of that run are unchanged (real catalog hook → `normalizePluginDiscoveryResult` → registry → real cache refresh → prepared session → captured `reasoning: {"effort":"high"}` request), and the data-model compatibility run still passes 9/9 (stored pre-change catalog loads byte-identically, levels identical to the unpatched-`main` baseline, and catalogs written by this build still validate under the stable `v2026.10.8` validator).

**3. Test note applied.** Removed the added field-copy case from `src/plugins/provider-discovery.test.ts` — the preceding parameterized cases already require provider/model object identity across normalization (`expect(normalized[key]?.models[0]).toBe(model)`), which preserves the field, and the real-path run above exercises the handoff end to end (`[handoff]` section, `catalogReasoningEfforts=true` after `normalizePluginDiscoveryResult`). That file now has no diff against `main`.

The PR body's Evidence section is updated with all of the above.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@LiuwqGit
LiuwqGit force-pushed the feat/issue-160758-openrouter-stale-efforts branch from a06c336 to 305b28d Compare October 29, 2026 09:32
@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Round 4: addressed the P2 finding "refresh discovered executable rows before exposing new efforts". Head is now 305b28d1caa.

The defect. preferRuntimeResolvedModel only returns true for models with a configured models.providers.openrouter.models entry, so for a plain discovered canonical row model.ts returned the registry row as the executable model without dynamic resolution. The session-side hook follows the refreshed capability cache, but resolvePreparedModelThinkingCompat then copied the stale row's ladder, and the request resolver silently clamped the offered level.

The fix. A catalog-derived row is now refreshed through the provider's own dynamic-model resolver during normal host model resolution:

  • src/agents/embedded-agent-runner/model.registry-resolution.ts — new isCatalogDerivedRuntimeRow(model); resolveModelWithPreparedRegistry no longer short-circuits on a resolved registry row when that row carries catalog provenance, so it goes through resolvePluginDynamicModelWithRegistry (falling back to the registry row when the provider resolves nothing).
  • src/agents/embedded-agent-runner/model.ts — the same condition feeds providerRuntimeMetadataShouldWin, so the async path prefers the re-resolved row.

Unmarked rows (authored, custom-route, proxy) keep the previous single-lookup behavior; the change is gated on the provenance marker this PR introduces.

Regression through normal model resolution (no direct resolveDynamicModel call) — src/agents/embedded-agent-runner/model.compat-route.test.ts > refreshes a catalog-derived row through the provider resolver before offering new efforts: an unconfigured discovered openrouter row on the canonical route is registered with a stale ladder ["low","medium","high"] + marker, the provider hook returns the refreshed ladder, resolution goes through resolveModelAsync, and the outbound request is captured through the real openai-completions transport.

RED (host refresh reverted):
 × model route compatibility > refreshes a catalog-derived row through the provider
   resolver before offering new efforts
   → AssertionError: expected [ 'low', 'medium', 'high' ] to deeply equal
     [ 'xhigh', 'high', 'medium', 'low' ]
   Tests  1 failed | 11 passed (12)
GREEN (this head): 12/12 in that file; 54 tests across model.test.ts,
model.forward-compat.test.ts, model.skip-agent-discovery-hooks.test.ts,
openrouter-model-capabilities.test.ts, run/model-setup.selected-model.test.ts.
Asserted on the resolved row: efforts ["xhigh","high","medium","low"],
clampThinkingLevel(model, "xhigh") === "xhigh", and the captured request payload
is [{ reasoning: { effort: "xhigh" } }].

Real-path proof updated — section 7 no longer calls the hook directly; it resolves the executable row through the real host resolveModelAsync for an unconfigured discovered row, and a new [grow] section reproduces the reported scenario (a refresh that adds an effort while the prepared row is still the generation-1 snapshot) all the way to the captured wire request:

[run]  executable row from normal host model resolution: compat
       {"supportsReasoningEffort":true,"supportedReasoningEfforts":["high","medium","low"],...}
[grow] real cache after the effort-adding refresh -> adds "xhigh"
[grow] session levels offered on the stale prepared row = ["low","medium","high","xhigh","ultra"]
[grow] executable row (normal host resolution) efforts  = ["xhigh","high","medium","low"]
[grow] run-side prepared thinking compat                = ["xhigh","high","medium","low"]
[grow] captured request reasoning                       = {"effort":"xhigh"}   <- not clamped
[verdict] 21/21 checks true -> RESULT: ALL CHECKS PASS

BEFORE (only the two host lines reverted, same script):
[run]  executable row ... supportedReasoningEfforts: ["xhigh","high","medium","low"]  <- stale
[verdict] ..."runtimeCompatRefreshed":false,"preparedCompatRefreshed":false...
RESULT: CHECKS FAILED

Local verification on this head: validate.sh over all changed files (oxfmt + oxlint + same-directory tests + tsgo:core) green — 11 test files / 224 tests; test-type shards agents-other, agents-root, agents-sessions, plugins-platform exit 0 (messaging, other, extensions.test exit 0 on the previous head, unchanged files); pnpm tsgo:core and pnpm tsgo:extensions pass. Full CI lanes are running on GitHub Actions for this head.

The PR body's Evidence section carries all of the above.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@LiuwqGit

LiuwqGit commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the current review round (P2 "Retain the prepared model when capability refresh has no row") in commit a5fb5d0fc60.

Fix: extensions/openrouter/index.ts — resolveDynamicModel now declines (returns undefined) whenever capabilities are not loaded (cold cache + failed /models fetch) and the registry already prepared a row for the model, so normal host model resolution retains the prepared metadata instead of substituting the synthetic default (reasoning: false, text-only, zero prices). Models with no prepared registry row still resolve dynamically, so missing-model forward-compat runs are unchanged.

RED before the repair (review acceptance criterion): extensions/openrouter/index.test.ts > keeps the prepared registry row when capabilities failed to load failed on the previous head — the hook returned the synthetic default (reasoning: false, input: ["text"]) with a prepared row present:

 ❯ extensions/openrouter/index.test.ts:381:29
    381|     expect(withPreparedRow).toBeUndefined();
   received: { "id": "acme/effort-model", "input": ["text"], "reasoning": false, ... }
 Test Files  1 failed (1) / Tests  1 failed | 75 skipped (76)

GREEN after, through normal model resolution and request construction:

  • Hook regression: extensions/openrouter/index.test.ts — 76/76 passed.
  • Host regression: src/agents/embedded-agent-runner/model.compat-route.test.ts > keeps the prepared catalog-derived row when the provider resolver declines after a failed capability load — resolver declines → resolveModelAsync retains the prepared row (reasoning true, ladder ["low","medium","high"], contextWindow kept) and the real openai-completions transport request still carries reasoning: {"effort":"high"}. 13/13 passed.
  • validate.sh (oxfmt + oxlint + same-dir tests + tsgo:core): all green; tsgo:core and tsgo:extensions PASS on this head.

Real-path proof (real-path-proof-v2.mts, real modules end to end; only the upstream endpoint is impersonated by the local loopback HTTPS server) — new [failload] section, cold cache + HTTP 500 on /api/v1/models:

[failload] capability load against failing /models endpoint: threw=null, capabilities loaded=null
[failload] executable row from NORMAL host model resolution:
             error=undefined, reasoning=true,
             compat {"supportsReasoningEffort":true,
                     "supportedReasoningEfforts":["xhigh","high","medium","low"]}  <- prepared snapshot kept
[failload] run-side prepared thinking compat = ["xhigh","high","medium","low"]
[failload] captured request reasoning = {"effort":"high"}   <- selected effort still carried
[failload] hook row for an unknown model (no prepared registry row): api=openai-completions <- still dynamic
[verdict]  25/25 checks true -> RESULT: ALL CHECKS PASS

Low-value tests removed as requested: the provenance-forwarding case in src/auto-reply/thinking.test.ts and the final modelCatalogRowToEntry field-copy case in src/agents/model-catalog-metadata.test.ts (overlay precedence and route-change regressions retained).

PR body updated (Follow-up 5, Evidence, Review state). CI lanes are running on GitHub Actions for this head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Nov 9, 2026
…og refresh

OpenRouter discovery copies upstream reasoning efforts into prepared catalog
rows, but the in-process capability cache can refresh later, for example when
a missing model triggers a catalog fetch. Prepared rows kept offering and
selecting the old effort levels, and the OpenRouter thinking hook could not
prefer the refreshed cache because its context could not tell catalog-derived
fields from operator-declared ones.

Mark catalog-derived effort metadata on prepared rows, thread it into the
thinking profile hook context, and let the OpenRouter hook replace those
fields with currently loaded capabilities while explicit declarations keep
winning. The run-side frozen thinking capability also prefers the runtime
model's refreshed efforts for marked rows.

A marked row is also refreshed through the provider's own dynamic-model
resolver during normal host model resolution, even when the model has no
configured entry. Otherwise the session could offer an effort the stale
executable row cannot carry, and the request resolver would silently clamp it.

Fixes openclaw#160758
Catalog provenance lets a provider's runtime capability cache refresh
catalog-derived effort metadata, so any row whose effort metadata an operator
authored must not carry the marker. Two projection paths still copied it onto
authored rows: logical route overrides, and the host merge of a discovered row
with a configured row. The declaration checks also missed `reasoningEffortMap`,
which is an explicit scalar-effort declaration: `resolveCatalogOwnedModelCompat`
enables scalar support for a mapping-only row. On a warm capability cache the
OpenRouter thinking hook then replaced the authored settings with cached catalog
data, so a binary catalog generation dropped the operator's mapped effort.

Clear the marker whenever overrides or configured rows declare effort metadata —
a thinking map, effort tiers, scalar support, or an effort mapping — preserving
the existing rule that operator effort lists, mappings, and scalar support win
over incomplete catalog guesses. Cover both projection paths, the mapping-only
declaration, and the warm-cache hook behavior with focused regression tests.
…s no row

A marked catalog-derived row bypasses the registry fast path so the executable
model follows capability refreshes. When the capability cache was cold and the
/models fetch failed, the OpenRouter dynamic-model hook still rebuilt a
synthetic default (reasoning false, text-only input, zero prices), which then
replaced the usable prepared row and the completions request lost its selected
reasoning effort. The hook now declines whenever capabilities are not loaded
and the registry already prepared a row for the model, so normal host model
resolution retains the prepared metadata; unknown models without a prepared row
still resolve dynamically for missing-model runs.

Also removes the two low-value field-copy test cases flagged in review
(thinking.test.ts provenance forwarding, model-catalog-metadata.test.ts
modelCatalogRowToEntry copy).
@LiuwqGit
LiuwqGit force-pushed the feat/issue-160758-openrouter-stale-efforts branch from a5fb5d0 to 8a37e6b Compare November 9, 2026 12:43
@LiuwqGit

LiuwqGit commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (0ab37d2) to clear the GitHub-reported conflicts — resolved head 8a37e6b.

Conflict resolutions (main's newer behavior preserved):

  • src/agents/model-catalog-route.ts (applyLogicalOverrides): main's mergeConfiguredThinkingLevelMap per-key merge is kept; the provenance clearing for an authored thinkingLevelMap now applies on top of the merged result (authored map owns the row, marker dropped, merged map retained).
  • extensions/openrouter/index.test.ts: main's extended decision-model exclusion list (parallel/decisions-fast cases) is kept alongside the new failload hook regression.
  • src/agents/model-catalog-metadata.ts auto-merged: the overlayDeclaresEfforts provenance predicate coexists with main's contextWindows selection changes.

Affected checks re-run on the resolved head:

validate.sh merged vitest (changed source/test files):
  8 test files / 172 tests passed, 0 failed — including
  "keeps the prepared registry row when capabilities failed to load" (hook) and
  "keeps the prepared catalog-derived row when the provider resolver declines after a
  failed capability load" (host, through resolveModelAsync + real openai-completions transport)
real-path-proof-v2.mts (incl. [failload] cold-cache + HTTP 500 /models):
  [verdict] 25/25 checks true -> RESULT: ALL CHECKS PASS
data-model-compat-proof.mts (stored-catalog load + current/v2026.10.8 validators):
  RESULT: ALL CHECKS PASS (9/9)

The tsgo lanes could not execute on this dev host on current main: the new @tsrs native binary requires glibc ≥ 2.32 and the host has 2.31 — type checks are deferred to CI on this head.

PR body updated (Evidence + Review state).

Record a test-lines allocation for the openclaw#160758 regression suite (666 net
lines across the provenance/refresh/failload regressions demanded by review
rounds) and type the failload fixture's input as a mutable array to match
Model.input in the core test-type stripe.
@LiuwqGit

LiuwqGit commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

The last review's only remaining item (GitHub-reported merge conflicts) is resolved: the branch is rebased onto current main and the resolved head 57ec2dd is fully green on CI (75 checks passed, 0 failed), including the test-lines ratchet (allocation recorded in config/test-lines-allocations/160758-openrouter-effort-refresh.txt for the 666 net regression lines demanded across review rounds) and the core test-type stripes. Main's newer mergeConfiguredThinkingLevelMap behavior is preserved in the conflict resolution, and the affected checks were re-run on the resolved head (172 targeted tests + both real-path proofs, 25/25 and 9/9 — details in the comment above and in the PR body Evidence).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 9, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawtributors PR from a clawtributor docs Improvements or additions to documentation extensions: openrouter merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prepared OpenRouter rows keep catalog-derived thinking efforts after a catalog refresh

2 participants