Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(catalog): keep the route registry in a sidecar older releases leave alone
Jack Rudenko2ebb20ae9ff4
diff --git a/packages/cli/src/providers/all-models-cache.test.ts b/packages/cli/src/providers/all-models-cache.test.tsindex 821dcf1c..f5a88862 100644--- a/packages/cli/src/providers/all-models-cache.test.ts+++ b/packages/cli/src/providers/all-models-cache.test.ts@@ -8,7 +8,9 @@ import {_clearAllModelsCacheMemo,readAllModelsCache,reasoningStatusOf,+ routeRegistryPathFor,writeAllModelsCache,+ writeRouteRegistry,} from "./all-models-cache.js";const dirs: string[] = [];@@ -212,3 +214,87 @@ describe("wire registry cache validation", () => {expect(readAllModelsCache(path)).toBeNull();});});++describe("route registry sidecar", () => {+ function withoutRegistry() {+ const cache = structuredClone(wireFixture);+ delete cache.routeRegistry;+ return cache;+ }+ test("attaches a matching sidecar without embedding it in the models file", () => {+ const path = cachePath();+ writeAllModelsCache(withoutRegistry(), path);+ writeFileSync(routeRegistryPathFor(path), JSON.stringify(wireFixture.routeRegistry));+ expect(readAllModelsCache(path)?.routeRegistry).toEqual(wireFixture.routeRegistry);+ expect(JSON.parse(readFileSync(path, "utf8")).routeRegistry).toBeUndefined();+ });+ test.each(["generation", "profile"])("ignores a sidecar with mismatched %s", (mismatch) => {+ const path = cachePath();+ const cache = withoutRegistry();+ const registry = structuredClone(wireFixture.routeRegistry!);+ if (mismatch === "generation") registry.generationId = "different-generation";+ else {+ const route = knownConnection(cache).route!;+ delete registry.registry.routes[route.routeId]!.profiles[route.routeProfileId];+ }+ writeAllModelsCache(cache, path);+ writeRouteRegistry(registry, path);+ expect(readAllModelsCache(path)).toEqual(cache);+ });+ test("both writers persist the sidecar and the registry writer invalidates a memoized read", () => {+ const path = cachePath();+ expect(routeRegistryPathFor(path)).toBe(path.replace(/\.json$/, ".routes.json"));+ writeAllModelsCache(wireFixture, path);+ expect(JSON.parse(readFileSync(routeRegistryPathFor(path), "utf8"))).toEqual(+ wireFixture.routeRegistry+ );+ rmSync(routeRegistryPathFor(path));+ writeAllModelsCache(withoutRegistry(), path);+ expect(readAllModelsCache(path)?.routeRegistry).toBeUndefined();+ writeRouteRegistry(wireFixture.routeRegistry!, path);+ expect(readAllModelsCache(path)?.routeRegistry).toEqual(wireFixture.routeRegistry);+ });+ test("memo observes out-of-band sidecar creation, size, mtime and removal", () => {+ const path = cachePath();+ const side = routeRegistryPathFor(path);+ writeAllModelsCache(withoutRegistry(), path);+ expect(readAllModelsCache(path)?.routeRegistry).toBeUndefined();+ const bytes = JSON.stringify(wireFixture.routeRegistry);+ const stamp = new Date("2026-10-12T00:00:00Z");+ writeFileSync(side, bytes);+ utimesSync(side, stamp, stamp);+ expect(readAllModelsCache(path)?.routeRegistry).toEqual(wireFixture.routeRegistry);+ const invalid = JSON.stringify({ ...wireFixture.routeRegistry, generationId: "wrong" });+ writeFileSync(side, invalid);+ utimesSync(side, stamp, stamp);+ expect(readAllModelsCache(path)?.routeRegistry).toBeUndefined();+ writeFileSync(side, bytes);+ utimesSync(side, stamp, stamp);+ expect(readAllModelsCache(path)?.routeRegistry).toEqual(wireFixture.routeRegistry);+ // Same byte count: only the sidecar mtime reveals this invalid generation.+ writeFileSync(+ side,+ bytes.replace(+ wireFixture.catalogGenerationId,+ "x".repeat(wireFixture.catalogGenerationId.length)+ )+ );+ utimesSync(side, new Date(stamp.getTime() + 2000), new Date(stamp.getTime() + 2000));+ expect(readAllModelsCache(path)?.routeRegistry).toBeUndefined();+ writeFileSync(side, bytes);+ expect(readAllModelsCache(path)?.routeRegistry).toBeDefined();+ rmSync(side);+ expect(readAllModelsCache(path)?.routeRegistry).toBeUndefined();+ });+ test("an older claudish rewrite cannot attach the previous generation's sidecar", () => {+ const path = cachePath();+ writeAllModelsCache(wireFixture, path);+ expect(readAllModelsCache(path)?.routeRegistry).toBeDefined();+ const newer = { ...withoutRegistry(), catalogGenerationId: "new-generation" };+ writeFileSync(path, JSON.stringify(newer));+ expect(readAllModelsCache(path)).toEqual(newer);+ expect(JSON.parse(readFileSync(routeRegistryPathFor(path), "utf8"))).toEqual(+ wireFixture.routeRegistry+ );+ });+});diff --git a/packages/cli/src/providers/all-models-cache.ts b/packages/cli/src/providers/all-models-cache.tsindex 6dfadbb9..ec9bbc67 100644--- a/packages/cli/src/providers/all-models-cache.ts+++ b/packages/cli/src/providers/all-models-cache.ts@@ -227,10 +227,49 @@ function parseAllModelsCache(raw: unknown): DiskCacheV3 | null {return data as unknown as DiskCacheV3;}+/**+ * Where the route registry for the cache at `path` is kept: a SIDECAR file+ * next to it (`cloud-models-catalog-v3.routes.json`).+ *+ * Its own file because claudish releases before 10.5.0 rewrite the models+ * cache on every refresh and know nothing of the registry: measured+ * 2026-10-14, an installed 10.4.1 in another session replaced the cache with+ * a newer generation and no `routeRegistry`, so the new reader refreshed+ * everything (9.3 s) and the old one erased it again. A sidecar survives them;+ * when its generation no longer matches, only the routes of the cache's+ * generation are fetched (`ensureRouteRegistryReady`).+ */+export function routeRegistryPathFor(path: string): string {+ return path.endsWith(".json") ? `${path.slice(0, -5)}.routes.json` : `${path}.routes.json`;+}++function readSidecarRegistry(path: string): CachedRouteRegistry | null {+ try {+ const raw = JSON.parse(readFileSync(routeRegistryPathFor(path), "utf-8")) as Record<+ string,+ unknown+ >;+ return typeof raw.generationId === "string" && isRouteRegistry(raw.registry)+ ? (raw as unknown as CachedRouteRegistry)+ : null;+ } catch {+ return null;+ }+}++function statOrNull(path: string): { mtimeMs: number; size: number } | null {+ try {+ const { mtimeMs, size } = statSync(path);+ return { mtimeMs, size };+ } catch {+ return null;+ }+}+// The request path reads the cache on every request, and the file is several-// MB. Parsed results are memoized per path, keyed by mtime and size, so a write-// by `refreshCatalog` or an out-of-band edit is seen on the next read.-const _readMemo = new Map<string, { mtimeMs: number; size: number; cache: DiskCacheV3 | null }>();+// MB. Parsed results are memoized per path, keyed by the mtime and size of the+// cache AND its registry sidecar, so a write to either is seen on the next read.+const _readMemo = new Map<string, { key: string; cache: DiskCacheV3 | null }>();export function _clearAllModelsCacheMemo(): void {_readMemo.clear();@@ -238,15 +277,12 @@ export function _clearAllModelsCacheMemo(): void {export function readAllModelsCache(path: string = ALL_MODELS_CACHE_PATH): DiskCacheV3 | null {if (!existsSync(path)) return null;-- let stat: { mtimeMs: number; size: number };- try {- stat = statSync(path);- } catch {- return null;- }+ const main = statOrNull(path);+ if (!main) return null;+ const side = statOrNull(routeRegistryPathFor(path));+ const key = `${main.mtimeMs}:${main.size}|${side ? `${side.mtimeMs}:${side.size}` : "-"}`;const memo = _readMemo.get(path);- if (memo && memo.mtimeMs === stat.mtimeMs && memo.size === stat.size) return memo.cache;+ if (memo && memo.key === key) return memo.cache;let cache: DiskCacheV3 | null;try {@@ -254,12 +290,31 @@ export function readAllModelsCache(path: string = ALL_MODELS_CACHE_PATH): DiskCa} catch {cache = null;}- _readMemo.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, cache });+ if (cache && !cache.routeRegistry && side) {+ const registry = readSidecarRegistry(path);+ if (registry && wiresMatchRegistry(cache.entries, registry, cache.catalogGenerationId)) {+ cache = { ...cache, routeRegistry: registry };+ }+ }+ _readMemo.set(path, { key, cache });return cache;}+/** Write the registry sidecar for the cache at `path`. */+export function writeRouteRegistry(+ routeRegistry: CachedRouteRegistry,+ path: string = ALL_MODELS_CACHE_PATH+): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(routeRegistryPathFor(path), JSON.stringify(routeRegistry), "utf-8");+ _readMemo.delete(path);+}+export function writeAllModelsCache(data: DiskCacheV3, path: string = ALL_MODELS_CACHE_PATH): void {mkdirSync(dirname(path), { recursive: true });writeFileSync(path, JSON.stringify(data), "utf-8");+ if (data.routeRegistry) {+ writeFileSync(routeRegistryPathFor(path), JSON.stringify(data.routeRegistry), "utf-8");+ }_readMemo.delete(path);}diff --git a/packages/cli/src/providers/catalog-client.test.ts b/packages/cli/src/providers/catalog-client.test.tsindex 224bd2b7..95f48793 100644--- a/packages/cli/src/providers/catalog-client.test.ts+++ b/packages/cli/src/providers/catalog-client.test.ts@@ -531,3 +531,73 @@ describe("route registry refresh", () => {});});});++test.each(["routes-only", "routes-fail", "disabled"])(+ "registry readiness in isolated HOME: %s",+ (scenario) => {+ const home = mkdtempSync(join(tmpdir(), "registry-ready-"));+ dirs.push(home);+ const source = (name: string) => JSON.stringify(new URL(name, import.meta.url).pathname);+ const child = Bun.spawnSync(+ [+ process.execPath,+ "--eval",+ `+ import assert from "node:assert/strict";+ import { readFileSync, existsSync } from "node:fs";+ import { ALL_MODELS_CACHE_PATH, writeAllModelsCache, readAllModelsCache, routeRegistryPathFor } from ${source("./all-models-cache.ts")};+ import { ensureRouteRegistryReady } from ${source("./catalog-client.ts")};+ const fixture = JSON.parse(readFileSync(${source("../test-fixtures/catalog-v3/wire-g-20261012101007285-7770c36e.json")}, "utf8"));+ const registry = fixture.routeRegistry;+ delete fixture.routeRegistry;+ assert.ok(ALL_MODELS_CACHE_PATH.startsWith(process.env.HOME + "/"));+ writeAllModelsCache(fixture);+ const calls = [];+ const original = globalThis.fetch;+ const envelope = data => Response.json({contractVersion: 3, generationId: fixture.catalogGenerationId, generatedAt: fixture.lastUpdated, data});+ globalThis.fetch = async input => {+ const url = new URL(String(input));+ assert.equal(url.hostname, "catalog.test");+ calls.push(url);+ if (url.searchParams.get("catalog") === "routes") {+ if (process.env.SCENARIO === "routes-fail" && calls.length === 1) return new Response("unavailable", {status: 503});+ return envelope({mode: "routes", registry: registry.registry});+ }+ if (url.pathname === "/queryPlans") return envelope({plans: fixture.plans, total: fixture.plans.length});+ const second = url.searchParams.has("cursor");+ return envelope({mode: "slim", models: second ? fixture.entries.slice(8) : fixture.entries.slice(0,8), total: fixture.entries.length, ...(second ? {} : {nextCursor: "next"})});+ };+ try {+ await ensureRouteRegistryReady(2000);+ if (process.env.SCENARIO === "disabled") {+ assert.equal(calls.length, 0);+ assert.equal(existsSync(routeRegistryPathFor(ALL_MODELS_CACHE_PATH)), false);+ } else {+ assert.equal(calls[0].pathname, "/queryModels");+ assert.deepEqual(Object.fromEntries(calls[0].searchParams), {catalog: "routes", generationId: fixture.catalogGenerationId});+ if (process.env.SCENARIO === "routes-only") assert.equal(calls.length, 1);+ else assert.deepEqual(calls.filter(u => u.searchParams.get("catalog") === "slim").map(u => u.searchParams.get("cursor")), [null, "next"]);+ assert.deepEqual(readAllModelsCache().routeRegistry, registry);+ assert.deepEqual(JSON.parse(readFileSync(routeRegistryPathFor(ALL_MODELS_CACHE_PATH), "utf8")), registry);+ }+ } finally { globalThis.fetch = original; }+ `,+ ],+ {+ env: {+ PATH: process.env.PATH,+ HOME: home,+ SCENARIO: scenario,+ CLAUDISH_DISABLE_KEYCHAIN: "1",+ CLAUDISH_DISABLE_OP: "1",+ CLAUDISH_DISABLE_CATALOG_WARM: scenario === "disabled" ? "1" : "0",+ CLAUDISH_CATALOG_URL: "https://catalog.test/queryModels?catalog=slim",+ CLAUDISH_PLANS_URL: "https://catalog.test/queryPlans",+ },+ stdout: "pipe",+ stderr: "pipe",+ }+ );+ expect(child.exitCode, child.stderr.toString()).toBe(0);+ }+);diff --git a/packages/cli/src/providers/catalog-client.ts b/packages/cli/src/providers/catalog-client.tsindex d2ebdf4f..5ca96236 100644--- a/packages/cli/src/providers/catalog-client.ts+++ b/packages/cli/src/providers/catalog-client.ts@@ -7,6 +7,7 @@ import {readAllModelsCache,wiresMatchRegistry,writeAllModelsCache,+ writeRouteRegistry,} from "./all-models-cache.js";import { catalogRouteMatchesProvider } from "./catalog-route-bindings.js";import { CATALOG_V3_ACCEPT, type CatalogV3Envelope, parseCatalogV3Envelope } from "./catalog-v3.js";@@ -582,7 +583,21 @@ export async function ensureCatalogReady(timeoutMs = 5000): Promise<void> {* built from it. Such a cache is refreshed rather than accepted.*/export async function ensureRouteRegistryReady(timeoutMs = 5000): Promise<void> {- if (readAllModelsCache()?.routeRegistry) return;+ const cache = readAllModelsCache();+ if (cache?.routeRegistry) return;+ // Models cached, registry missing or of another generation (an older claudish+ // rewrote the models): fetch only the routes of THIS generation — one small+ // request instead of the whole refresh.+ if (cache && !catalogWarmDisabled()) {+ const result = await fetchRouteRegistry(timeoutMs, cache.catalogGenerationId);+ if (result.ok) {+ const routeRegistry = { generationId: cache.catalogGenerationId, registry: result.registry };+ if (wiresMatchRegistry(cache.entries, routeRegistry, cache.catalogGenerationId)) {+ writeRouteRegistry(routeRegistry);+ return;+ }+ }+ }await waitForCatalogWarm(timeoutMs);}diff --git a/packages/cli/src/providers/connection-resolver.test.ts b/packages/cli/src/providers/connection-resolver.test.tsindex 1baca2de..e78ef2ad 100644--- a/packages/cli/src/providers/connection-resolver.test.ts+++ b/packages/cli/src/providers/connection-resolver.test.ts@@ -264,12 +264,25 @@ describe("production connection resolution", () => {test("legacy cache reports no-registry", () => {const cache = structuredClone(fixture);delete cache.routeRegistry;- writeAllModelsCache(cache, cachePath);- expect(resolveConnection("openai", "gpt-6.1-sol", cachePath)).toEqual({+ const legacyPath = join(dir, "legacy.json");+ writeAllModelsCache(cache, legacyPath);+ _clearAllModelsCacheMemo();+ expect(resolveConnection("openai", "gpt-6.1-sol", legacyPath)).toEqual({ok: false,reason: "no-registry",});});+ test("legacy cache resolves with a matching route registry sidecar", () => {+ const expected = resolveConnection("openai", "gpt-6.1-sol", cachePath);+ expect(expected.ok).toBe(true);+ const cache = structuredClone(fixture);+ delete cache.routeRegistry;+ // Keep the matching-generation sidecar written by beforeEach.+ writeAllModelsCache(cache, cachePath);+ _clearAllModelsCacheMemo();+ expect(JSON.parse(readFileSync(cachePath, "utf8")).routeRegistry).toBeUndefined();+ expect(resolveConnection("openai", "gpt-6.1-sol", cachePath)).toEqual(expected);+ });test.each(["GPT-6.1-SOL", "vendor/GPT-6.1-SOL", "OPENAI/GPT-6.1-SOL:BATCH"])("resolves canonical ids and aliases case-insensitively: %s",(name) => {diff --git a/scripts/guard-real-config.ts b/scripts/guard-real-config.tsindex fdeeda1b..2c8410a2 100644--- a/scripts/guard-real-config.ts+++ b/scripts/guard-real-config.ts@@ -73,6 +73,15 @@ const GUARDED = ["pass a temp path to readAllModelsCache/writeAllModelsCache, or seed in memory the way " +"catalog-client.ts's _setCatalogEntriesForTest does, instead of writing the real cache",},+ {+ // The route registry sidecar (`routeRegistryPathFor`): a test that writes it+ // hands the real request path another generation's base URLs.+ path: join(homedir(), ".claudish", "cloud-models-catalog-v3.routes.json"),+ label: "REAL ROUTE REGISTRY SIDECAR",+ remedy:+ "pass a temp cache path to writeAllModelsCache/writeRouteRegistry, or run the refresh in a " ++ "child process with its own HOME, instead of writing the real sidecar",+ },{// The pre-v3 cache file. This build no longer writes it, but older builds on the// same machine still read it, so a test that touches it breaks them.