Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(catalog): stop the incompatibility guard exiting, and let the sentinel expire
Jack Rudenkoeec9e7e156a1
diff --git a/packages/cli/src/launcher/catalog-warm.ts b/packages/cli/src/launcher/catalog-warm.tsindex 32d0a27e..6dcc8f1d 100644--- a/packages/cli/src/launcher/catalog-warm.ts+++ b/packages/cli/src/launcher/catalog-warm.ts@@ -18,6 +18,7 @@import { type DiskCacheV2, readAllModelsCache } from "../providers/all-models-cache.js";import { type RefreshOutcome, refreshCatalog } from "../providers/catalog-client.js";import {+ type CatalogIncompatibility,catalogIncompatibilityMessage,readCatalogIncompatibility,} from "../providers/catalog-compatibility.js";@@ -37,6 +38,12 @@ export type WarmOutcome = "ok" | "warned" | "skipped" | "hard_fail";* Verbatim hard-fail copy from FR-4. Printed when the catalog is missing AND* the network refresh failed — claudish cannot route cloud models without it.*+ * "No cached copy found" is a claim about the disk, so this must never be the+ * message for a contract mismatch: there a copy exists and is merely unreadable,+ * the network is fine, and every line below sends the user to debug the wrong+ * thing. `warmCatalogIfNeeded` checks the sentinel before it can reach here for+ * exactly that reason — see the guard above `reportFetchFailure`.+ ** Trailing newline included so the message reads as one paragraph terminated* cleanly when written to stderr.*/@@ -219,12 +226,22 @@ function startSpinner(label: string, quiet = false): Spinner {* - else (stale, missing, or forceUpdate=true on fresh) → call* `OpenRouterCatalogResolver.refreshCatalog(8000)`:* - refreshed → print indexed-count line, return "ok".+ * - incompatible → contract-mismatch message + return "warned".* - fetch_failed:+ * - a sentinel is already recorded → contract-mismatch message ++ * return "warned" (the cache state is not what it looks like;+ * see the guard at the call to `reportFetchFailure`).* - prior state was "stale" → WARN + return "warned".* - prior state was "missing" → hard-fail message + return "hard_fail".* - prior state was "fresh" → treat as "warned" (we still have* the fresh cache; the user explicitly asked to refresh it).*+ * Only ONE branch here ever returns "hard_fail", and it means one thing: there+ * is no catalog data on this machine at all and none can be fetched. An+ * unreadable catalog is a different failure with a different remedy, and it+ * never exits — routing decides that one per model name, where the explicit+ * `provider@model` carve-out lives.+ ** `--quiet` suppresses the preparing/indexed lines but never WARNINGs or* the hard-fail error (Q2 in architecture.md §10).*/@@ -249,6 +266,13 @@ export async function warmCatalogIfNeeded(opts?.ttlHours ?? Number.parseFloat(process.env.CLAUDISH_CATALOG_TTL_HOURS ?? "24");const ttlHours = Number.isFinite(ttlHoursRaw) && ttlHoursRaw > 0 ? ttlHoursRaw : 24;const now = opts?.now ?? new Date();+ // This read is GATED: it returns null while a contract sentinel is set, so+ // `state` is "missing" for a cache that is sitting right there on disk. Two+ // consequences, both wanted, and both undone by "simplifying" this to an+ // ungated read. (1) A sentinel can never take the `fresh` early-return below,+ // so every launch under one attempts the refresh that would heal it. (2) Every+ // downstream branch that reasons from `state` has to be sentinel-aware — the+ // reason `reportFetchFailure` is guarded rather than trusted.const cache = readAllModelsCache();const state = classifyCatalogState(cache, ttlHours, now);@@ -277,13 +301,48 @@ export async function warmCatalogIfNeeded(return "ok";}- // The server answered in a contract this build cannot read. Checked FIRST, and- // the order is the argument: this variant carries no `reason`, and every branch- // below says some version of "using cached version" — the cached version is- // exactly what `readAllModelsCache` has just stopped handing out, so that line- // would be false at the moment it matters most.- if (outcome.kind === "incompatible") return reportIncompatibleCatalog(outcome);+ return reportUnusableCatalog(outcome, state, cache, now, config.quiet === true);+}+/**+ * The refresh came back with no usable catalog. Decide which failure it was.+ *+ * Extracted from `warmCatalogIfNeeded` purely to hold that function at its+ * pre-existing complexity budget; the branch ORDER is the argument, and it is+ * "unreadable before unreachable" throughout — an unreadable catalog is the+ * finding that survives on disk, so it outranks whatever this one refresh did or+ * did not manage to fetch.+ */+function reportUnusableCatalog(+ outcome: Exclude<RefreshOutcome, { kind: "refreshed" }>,+ state: ReturnType<typeof classifyCatalogState>,+ cache: DiskCacheV2 | null,+ now: Date,+ quiet: boolean+): WarmOutcome {+ // The server answered in a contract this build cannot read. This is NOT a+ // fetch failure and must not fall into the branches below, every one of which+ // says some version of "using cached version" — the cached version is exactly+ // what `readAllModelsCache` has just stopped handing out, so that line would+ // be false at the moment it matters most.+ //+ // "warned", not "hard_fail", and the distinction is the point: hard_fail exits+ // the CLI, which would strand a user running an explicit `gk@grok-code-fast`.+ // That spec names its own provider, infers no subscription, and is safe. So+ // the launcher says it once, plainly, and proceeds; the bare-name path fails+ // loudly per-request in `routeBare` with this same text. Printed regardless of+ // `--quiet`, like every other warning here.+ if (outcome.kind === "incompatible") {+ // `refreshCatalog` has already recorded the finding; the fallback only+ // covers a sentinel whose disk write failed, where the message still has to+ // name the version the server just reported.+ return reportIncompatibleCatalog(+ readCatalogIncompatibility() ?? {+ detectedAt: new Date().toISOString(),+ serverContractVersion: outcome.serverContractVersion,+ }+ );+ }// `disabled` is not a failure and must never reach the branches below. Nobody// attempted a fetch, so the cache state is irrelevant: with no cache at all@@ -302,13 +361,74 @@ export async function warmCatalogIfNeeded(// "skipped" is the accurate answer, and it is the same one// `--models-skip-update` already produces: a refresh nobody attempted.if (outcome.reason === "disabled") {- if (!config.quiet) {+ if (!quiet) {process.stderr.write(" Catalog refresh disabled (CLAUDISH_DISABLE_CATALOG_WARM=1).\n");}return "skipped";}- // Fetch failed. Decide based on prior cache state.+ // The refresh never got an answer — offline, DNS, a corporate proxy, or just+ // slower than the 8s budget. Before classifying that against the cache, ask+ // whether an EARLIER run already recorded a contract mismatch, because if it+ // did, `state` is a lie: `readAllModelsCache()` refuses to hand out a cache+ // while the sentinel is set, so a present-but-unreadable catalog classifies as+ // "missing" and `reportFetchFailure` would hard-fail with "no cached copy+ // found" — false, unactionable, and pointing at the network when the remedy is+ // `claudish update`.+ //+ // Exiting is wrong on its own terms too. `hard_fail` ends the launch before+ // routing runs, so an explicit `gk@grok-4` dies with it — and that spec names+ // its own provider, infers no subscription and substitutes nothing, so there+ // is nothing to protect it from. Deciding per name is the routing gate's job+ // and it already does it: `routeBare` throws, `routeExplicit` proceeds. The+ // launcher's job is to say so once, and get out of the way.+ const recorded = readCatalogIncompatibility();+ if (recorded !== null) return reportIncompatibleCatalog(recorded);++ return reportFetchFailure(state, cache, now);+}++/**+ * Announce a catalog this build cannot read, and let the launch proceed.+ *+ * "warned", not "hard_fail", and the distinction is the point: hard_fail exits+ * the CLI, which would strand a user running an explicit `gk@grok-code-fast`.+ * That spec names its own provider, so claudish infers no subscription and+ * substitutes nothing — there is no mis-billing to protect them from. The+ * launcher therefore says it once, plainly, and proceeds; the bare-name path+ * fails loudly per request in `routeBare` with this same text.+ *+ * Both callers reach this with the RECORD rather than the refresh outcome, so+ * the two paths in — the server answered in a contract we cannot read, and a+ * previous run already found that out — print the identical text. The second is+ * the common one after a cutover: most launches never get an answer at all.+ *+ * Printed regardless of `--quiet`, like every other warning in this file.+ */+function reportIncompatibleCatalog(recorded: CatalogIncompatibility): WarmOutcome {+ process.stderr.write(`${catalogIncompatibilityMessage(recorded)}\n`);+ return "warned";+}++/**+ * The fetch-failed decision tree, keyed on what was already on disk.+ *+ * Split out of `warmCatalogIfNeeded` unchanged. Every branch here ends in some+ * form of "using cached version" or "no cached copy found", which is what makes+ * it the wrong home for a contract mismatch: there, the cached version is+ * precisely what stopped being usable while still sitting on disk. Keeping the+ * two apart is the whole reason `incompatible` is not a `fetch_failed` variant.+ *+ * PRECONDITION, and the caller enforces it: no sentinel is set. `state` is+ * computed from the GATED `readAllModelsCache()`, so under a sentinel it reads+ * "missing" for a cache that exists — every branch below would then be+ * describing a different failure than the one that happened.+ */+function reportFetchFailure(+ state: ReturnType<typeof classifyCatalogState>,+ cache: DiskCacheV2 | null,+ now: Date+): WarmOutcome {if (state === "stale") {const ageMs = now.getTime() - Date.parse(cache!.lastUpdated);const ageStr = humanizeAge(ageMs);@@ -334,27 +454,3 @@ export async function warmCatalogIfNeeded(process.stderr.write(HARD_FAIL_MESSAGE);return "hard_fail";}---/**- * Announce a catalog this build cannot read, and let the launch proceed.- *- * "warned", not "hard_fail", and the distinction is the point: hard_fail exits- * the CLI, which would strand a user running an explicit `gk@grok-code-fast`.- * That spec names its own provider, so claudish infers no subscription and- * substitutes nothing — there is no mis-billing to protect them from. The- * launcher therefore says it once, plainly, and proceeds; the bare-name path- * fails loudly per request in `routeBare` with this same text.- *- * Printed regardless of `--quiet`, like every other warning in this file.- */-function reportIncompatibleCatalog(- outcome: Extract<RefreshOutcome, { kind: "incompatible" }>-): WarmOutcome {- const recorded = readCatalogIncompatibility() ?? {- detectedAt: new Date().toISOString(),- serverContractVersion: outcome.serverContractVersion,- };- process.stderr.write(`${catalogIncompatibilityMessage(recorded)}\n`);- return "warned";-}\ No newline at end of filediff --git a/packages/cli/src/providers/catalog-compatibility.ts b/packages/cli/src/providers/catalog-compatibility.tsindex 9b18b005..193b78de 100644--- a/packages/cli/src/providers/catalog-compatibility.ts+++ b/packages/cli/src/providers/catalog-compatibility.ts@@ -25,6 +25,23 @@* back on every subsequent start, until a compatible response is seen again and* {@link clearCatalogIncompatibility} removes it.*+ * ## Why the record is RE-JUDGED on every read, never merely read back+ *+ * What is persisted is not a fact about the world. It is a RELATIONSHIP between+ * two versions — what the server was serving, and what the build that met it+ * could read — and persisting a relationship only freezes one half of it. The+ * other half, {@link SUPPORTED_CONTRACT_VERSION}, changes underneath the file+ * the moment `claudish update` runs.+ *+ * Keyed on presence alone, a record written by a v2 build against a v3 server+ * still fires on the v3 build shipped to end it, and+ * {@link catalogIncompatibilityMessage} then reads "the catalog serves contract+ * version 3; this build reads version 3 ... run `claudish update`" — naming the+ * remedy the user has just applied. That is a permanent brick delivered by the+ * release meant to fix the problem, and it needs no network to happen. So every+ * read re-evaluates the record against the CURRENT constant+ * ({@link isSentinelStale}) and drops it once this build has caught up.+ ** ## Why the disk write is best-effort but the flag is not** A read-only home, a full disk or a sandboxed test must never turn a billing@@ -62,6 +79,21 @@ export interface CatalogIncompatibility {serverContractVersion: number | null;/** The lowest version the server will serve, when it said one. */minimumContractVersion?: number;+ /**+ * The {@link SUPPORTED_CONTRACT_VERSION} of the build that WROTE this record.+ *+ * Stamped by {@link markCatalogIncompatible} like `detectedAt`, never supplied+ * by a caller. It exists for the one case the server-side fields cannot+ * decide: a 426 with no body records `serverContractVersion: null`, so the+ * record says nothing about what the server wanted, and only the writer's own+ * version can tell a later build whether the finding is about a build that no+ * longer exists.+ *+ * Optional because a record written before this field existed is still a valid+ * finding. Absent, it means "written by a build older than this scheme", which+ * licenses no conclusion in either direction — see {@link isSentinelStale}.+ */+ clientContractVersion?: number;}/** Where the sentinel lives. Sibling of `~/.claudish/all-models.json`. */@@ -178,16 +210,22 @@ export function isIncompatibleContractVersion(version: number | null): version i* best-effort write must not make the guard best-effort), then attempts the* file.*- * @param info Everything but `detectedAt`, which is stamped here.+ * `detectedAt` and `clientContractVersion` are stamped here rather than passed+ * in: both describe the act of recording, not the response, and a caller that+ * could set `clientContractVersion` could write a record that outlives its own+ * staleness test.+ *+ * @param info What the RESPONSE said. Everything else is stamped here.* @param path Override the sentinel path. Only tests should pass this.*/export function markCatalogIncompatible(- info: Omit<CatalogIncompatibility, "detectedAt">,+ info: Omit<CatalogIncompatibility, "detectedAt" | "clientContractVersion">,path: string = CATALOG_INCOMPATIBLE_PATH): void {const record: CatalogIncompatibility = {detectedAt: new Date().toISOString(),serverContractVersion: info.serverContractVersion,+ clientContractVersion: SUPPORTED_CONTRACT_VERSION,...(info.minimumContractVersion !== undefined? { minimumContractVersion: info.minimumContractVersion }: {}),@@ -217,6 +255,12 @@ export function markCatalogIncompatible(* "compatible" would put the user back on the silent-mis-billing path, which is* the one outcome the whole mechanism exists to rule out.*+ * Presence is not the whole answer, though: a record this build has outgrown is+ * dropped and deleted here, before any caller sees it ({@link isSentinelStale}).+ * That judgement applies to the FILE only. `_memFlag` was set by a response this+ * very process read off the wire — a live observation, not persisted state — and+ * a 426 outranks any version arithmetic we could do against it.+ ** @param path Override the sentinel path. Only tests should pass this.*/export function readCatalogIncompatibility(@@ -233,10 +277,75 @@ export function readCatalogIncompatibility(// process can act on beyond what the next fetch rediscovers.}+ if (value !== null && isSentinelStale(value)) {+ // Delete as well as ignore, so the next process does no work at all and the+ // user never trips over a file describing a problem they no longer have.+ // Best-effort, like every other fs call here; the read-time test is what+ // actually protects them, the removal is housekeeping. This also parks the+ // `null` in `_fileMemo`, so the whole check runs at most once per process.+ clearCatalogIncompatibility(path);+ return null;+ }+_fileMemo = { path, value };return value;}+/**+ * Has this build caught up with what the record describes?+ *+ * The trap, stated once: persisted state that describes a RELATIONSHIP between+ * two versions must be re-evaluated against the current version, never merely+ * read back. Only the server's half of this record is frozen on disk; ours moves+ * every time the user updates. See the header section on re-judging.+ *+ * Three questions, ordered by how much each one actually knows:+ *+ * 1. **Did the server name a floor we are still below?** Then no amount of+ * other evidence matters — the server has said in as many words that it will+ * not serve this build. Decisive, and it cannot brick: a build at or above+ * the floor never reaches this branch.+ *+ * 2. **Did the server name the version it was serving?** Then judge by that+ * alone: `<=` ours means we now read what it was serving, so the finding is+ * spent. `>` ours means we still cannot, and the message stays true and+ * actionable ("publishes 4, this build reads 3"). Note this deliberately+ * answers the question WITHOUT consulting the writer's version — a record+ * saying "server 4" written by a v2 build still applies to this v3 build,+ * and clearing it on the writer's age alone would hand a stale v2 cache to+ * bare-name routing, which is the mis-billing this module exists to stop.+ *+ * 3. **Nothing on the wire to judge** (a body-less 426 records `null` for both+ * server fields). Then judge the WRITER: a record from a build that read an+ * OLDER contract than we do describes a client that no longer exists, and+ * nothing else will ever clear it — the updated user who is offline, or whom+ * the server has since started answering, would carry it forever. Strictly+ * less than, so the ordinary "same build, still too old" record keeps firing.+ *+ * An absent `clientContractVersion` (a record from before that field existed)+ * falls out of question 3 as "not stale": unknown, so assume nothing. Question 2+ * is then the only thing that can clear it, which is exactly the pre-existing+ * behaviour for those records.+ */+function isSentinelStale(record: CatalogIncompatibility): boolean {+ if (+ typeof record.minimumContractVersion === "number" &&+ record.minimumContractVersion > SUPPORTED_CONTRACT_VERSION+ ) {+ return false;+ }++ if (record.serverContractVersion !== null) {+ return record.serverContractVersion <= SUPPORTED_CONTRACT_VERSION;+ }++ if (typeof record.clientContractVersion === "number") {+ return record.clientContractVersion < SUPPORTED_CONTRACT_VERSION;+ }++ return false;+}+/** Coerce whatever is on disk into a finding. Never throws. */function parseSentinelFile(raw: string): CatalogIncompatibility {const unspecific: CatalogIncompatibility = {@@ -260,16 +369,25 @@ function parseSentinelFile(raw: string): CatalogIncompatibility {...(typeof data.minimumContractVersion === "number"? { minimumContractVersion: data.minimumContractVersion }: {}),+ // Carried through only when the file really has it. Defaulting it to+ // anything would be a lie about which build wrote the record, and+ // `isSentinelStale` reads a missing field as "unknown" on purpose.+ ...(typeof data.clientContractVersion === "number"+ ? { clientContractVersion: data.clientContractVersion }+ : {}),};}/*** Forget the finding — the server answered in a contract this build reads.*- * Called on every fully successful refresh, which is what makes the sentinel- * self-healing: `claudish update` installs a build with a higher+ * Called on every fully successful refresh, which is one of the two ways the+ * sentinel heals: `claudish update` installs a build with a higher* {@link SUPPORTED_CONTRACT_VERSION}, its first refresh parses cleanly, and the- * file is gone before the user notices it existed. Never throws.+ * file is gone before the user notices it existed. That route needs a network+ * round trip, which is why it is not the only one — {@link readCatalogIncompatibility}+ * also clears through here the moment the RECORD shows this build has caught up,+ * offline or not. Never throws.** @param path Override the sentinel path. Only tests should pass this.*/