Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
simplify: one settings-path writer, one provider-id coercion, one provider name
[._.]/ Adam Eivy1cc78800de21
diff --git a/client/src/components/providers/RetiredModelPinsPanel.jsx b/client/src/components/providers/RetiredModelPinsPanel.jsxindex b2225884a2..7b50aad33d 100644--- a/client/src/components/providers/RetiredModelPinsPanel.jsx+++ b/client/src/components/providers/RetiredModelPinsPanel.jsx@@ -6,6 +6,9 @@ import * as api from '../../services/api';import Banner from '../ui/Banner';import { modeLabel, RENDER_TARGET_OPTIONS } from '../../lib/imageGenModes';import { pluralize } from '../../lib/textUtils';+// The retired-pin notification card names a pin's provider records with this+// too, so the two surfaces cannot describe the same pin differently.+import { pinProviderNames } from '../../../../server/lib/modelPinReconcile.js';/*** The user-facing name for a pin, composed HERE rather than on the server.@@ -93,13 +96,9 @@ export default function RetiredModelPinsPanel({ reloadKey = 0 }) {{pins.map((pin) => {// A reviewer pin is judged against EVERY record fronting its binary// (#7339), so "now offered" is their union — showing one record's- // catalog would hide tiers the reviewer can still be handed. Falls- // back to the single `providerId` for a payload predating the field.- const judged = Array.isArray(pin.providerIds) && pin.providerIds.length- ? pin.providerIds- : [pin.providerId];+ // catalog would hide tiers the reviewer can still be handed.const offered = Array.from(new Set(- judged.flatMap((id) => (Array.isArray(providers[id]?.available) ? providers[id].available : []))+ pin.providerIds.flatMap((id) => (Array.isArray(providers[id]?.available) ? providers[id].available : []))));return (<li@@ -111,7 +110,7 @@ export default function RetiredModelPinsPanel({ reloadKey = 0 }) {{pinLabel(pin)}: <code className="text-port-warning">{pin.model}</code></div><div className="mt-0.5 text-xs text-gray-400">- {pin.location} · {judged.map((id) => providers[id]?.name || id).join(' · ')}+ {pin.location} · {pinProviderNames(pin, providers)}</div>{offered.length > 0 && (<div className="mt-1 break-words text-xs text-gray-500">diff --git a/client/src/components/providers/RetiredModelPinsPanel.test.jsx b/client/src/components/providers/RetiredModelPinsPanel.test.jsxindex d606b94e9d..47f0870e1c 100644--- a/client/src/components/providers/RetiredModelPinsPanel.test.jsx+++ b/client/src/components/providers/RetiredModelPinsPanel.test.jsx@@ -18,7 +18,7 @@ const STALE = {id: 'settings:imageGen.agy.model',kind: 'imageGen',mode: 'agy',- providerId: 'antigravity-cli',+ providerIds: ['antigravity-cli'],model: 'gemini-3.5-flash-low',label: 'Agy CLI image model',location: 'Settings → Media Gen → Image Gen',@@ -56,7 +56,7 @@ describe('RetiredModelPinsPanel', () => {id: 'settings:renderDefaults.universe-bible.imageModel',kind: 'renderDefault',target: 'universe-bible',- providerId: 'antigravity-cli',+ providerIds: ['antigravity-cli'],model: 'gemini-3.5-flash-low',label: 'universe-bible render model',location: 'Settings → Media Gen → Render Defaults',@@ -79,7 +79,7 @@ describe('RetiredModelPinsPanel', () => {family: 'universe',recordId: 'u-1',mode: 'agy',- providerId: 'antigravity-cli',+ providerIds: ['antigravity-cli'],model: 'gemini-3.5-flash-low',label: 'Example Universe · universe render model',location: 'Universes → Render',@@ -156,7 +156,6 @@ describe('a reviewer pin judged against several provider records (#7339)', () =>id: 'codeReview:claudeModel',kind: 'reviewerModel',reviewer: 'claude',- providerId: 'claude-code',providerIds: ['claude-code', 'claude-code-tui'],model: 'claude-3-opus',label: 'claude reviewer model',@@ -180,15 +179,4 @@ describe('a reviewer pin judged against several provider records (#7339)', () =>expect(offered.textContent).toContain('claude-sonnet-5');expect(screen.getByText(/Claude Code · Claude Code TUI/)).toBeTruthy();});-- it('falls back to the single providerId for a payload predating providerIds', async () => {- const { providerIds, ...legacyPin } = REVIEWER_PIN.pins[0];- expect(providerIds).toHaveLength(2);- api.getModelPinWarnings.mockResolvedValue({ ...REVIEWER_PIN, pins: [legacyPin] });- renderPanel();-- const offered = await screen.findByText(/Now offered:/);- expect(offered.textContent).toContain('claude-sonnet-4-6');- expect(offered.textContent).not.toContain('claude-sonnet-5');- });});diff --git a/client/src/hooks/useReviewerModelOptions.js b/client/src/hooks/useReviewerModelOptions.jsindex dc7f2c9176..cf1ddeef7c 100644--- a/client/src/hooks/useReviewerModelOptions.js+++ b/client/src/hooks/useReviewerModelOptions.js@@ -93,15 +93,11 @@ export default function useReviewerModelOptions() {.map((m) => m.id || m.name).filter(Boolean);- // Every record fronting each reviewer's binary, in matcher-preference order- // (not `providers` array order) so `[0]` is the record whose default the- // picker shows. De-duped by identity: two matchers commonly overlap- // (`grok-cli` is also an `isGrokBuildCli`).- //// Resolved ONCE for the whole roster rather than per lookup — the option// list, the shown default, the agy raw catalog and `providerDisabled` all// ask the same question, and a per-call helper re-walked the provider array- // for every one of them.+ // for every one of them. Ordering and de-duping are `providersForReviewer`'s+ // own contract; see its JSDoc.const providersByReviewer = Object.fromEntries(Object.keys(REVIEWER_PROVIDER_MATCHERS).map((reviewer) => [reviewer, providersForReviewer(reviewer, providers)]));diff --git a/client/src/utils/providerTypes.js b/client/src/utils/providerTypes.jsindex c0e67d9e50..95c7b8d4d2 100644--- a/client/src/utils/providerTypes.js+++ b/client/src/utils/providerTypes.js@@ -78,7 +78,6 @@ export const enabledApiProviderFilter = (provider) => Boolean(provider?.enabled)*/export const enabledProcessProviderFilter = (provider) => Boolean(provider?.enabled) && isProcessProvider(provider);-/*** Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').* Lifted out of AIProviders.jsx so other components can render the samediff --git a/docs/API.md b/docs/API.mdindex d48231154b..f9c3d743c7 100644--- a/docs/API.md+++ b/docs/API.md@@ -125,7 +125,7 @@ legacy list for local Apps/Dashboard views.| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. || POST | `/providers/readiness/setup?provider=<id>` | Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of `/providers/readiness`, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional `runtime=` is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight. || POST | `/providers/readiness/serve-model?provider=<id>` | Relaunch the local daemon so it answers under the model id THIS provider sends — the other half of the readiness model mismatch. `llama-server` serves one model per process under the `--alias` on its launch line, so the fix keeps the loaded weights and changes only the name; the whole launch line is carried forward and the previous one restored if the relaunch is rejected or never answers. The model id is re-derived server-side from the stored record. 400s for a runtime that has no such label (Ollama / LM Studio / MTPLX name a model after its weights), 409s when PortOS did not start the daemon. |-| GET | `/providers/model-pins` | Stored model pins naming a model their provider no longer lists. A vendor retires an id, the install's catalog refresh picks that up, and every pin still naming it rots silently until a render or a scheduled run dies with a raw vendor error. Answers `{ pins, providers }` — each pin carries where it lives and a deep link, and `providers` carries only the catalogs a stale pin actually names. Covers the Image Gen and render-default settings pins, global and per-app scheduled-task pins, per-record render pins, the Code Review Defaults reviewer `<reviewer>Model` scalars (plus `goalFidelity.model`), and user-saved CoS task-template pins. A reviewer pin names a BINARY that several provider records front, so it carries `providerIds` and is reported only when EVERY one of them stops listing the model — judging it against one record would call a tier retired that the other still serves. Derived on read, never persisted, so a pin cleared a moment ago is already gone from the answer and one that rotted before this shipped is reported on the first read. Every UNKNOWN case (no pin, empty catalog, unresolved provider) reads as "still listed" — a false "your pin is gone" tells the user to change a setting that works. |+| GET | `/providers/model-pins` | Stored model pins naming a model their provider no longer lists. A vendor retires an id, the install's catalog refresh picks that up, and every pin still naming it rots silently until a render or a scheduled run dies with a raw vendor error. Answers `{ pins, providers }` — each pin carries where it lives and a deep link, and `providers` carries only the catalogs a stale pin actually names. Covers the Image Gen and render-default settings pins, global and per-app scheduled-task pins, per-record render pins, the Code Review Defaults reviewer pins (the `<reviewer>Model` scalars, the `provider:<id>` entries in `providerModels`, and `goalFidelity.model`), and user-saved CoS task-template pins. A reviewer pin names a BINARY that several provider records front, so it carries `providerIds` and is reported only when EVERY one of them stops listing the model — judging it against one record would call a tier retired that the other still serves. Derived on read, never persisted, so a pin cleared a moment ago is already gone from the answer and one that rotted before this shipped is reported on the first read. Every UNKNOWN case (no pin, empty catalog, unresolved provider) reads as "still listed" — a false "your pin is gone" tells the user to change a setting that works. || POST | `/providers/model-pins/clear` | Clear ONE stale pin back to "inherit", named by the `pinId` the endpoint above reported. PortOS re-points only the shipped default it owns; a pin the USER chose is surfaced and never rewritten, because substituting it would render under the chosen model's name and bury the vendor's own "unknown model" error. Clears the model field only, never the sibling mode/provider/enabled choices. An id naming a pin that is already gone answers `{ cleared: false }` rather than 404ing, and an id matching no collected pin reaches no writer. || GET | `/providers/codex/account?fresh=1` | Is a ChatGPT subscription signed in, and usable right now? Answers `{ readiness }` with a `status` of `runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`, plus the plan name and quota percentages. Read from the Codex app-server's own `account/read` — PortOS never opens Codex's credential file and the payload carries no token, account id, or credential path. This is the ONLY call that may spawn `codex app-server`, and it runs from an explicit page fetch: nothing on the boot path calls it, and `GET /providers` decorates its Codex cards from the cached snapshot only. `fresh=1` skips the 15s TTL for the poll after a sign-in. || POST | `/providers/codex/account/login` | Start an explicit ChatGPT sign-in. Returns `{ login }` — a bounded `loginId` plus `authUrl` (browser flow) or `verificationUrl` + `userCode` (device-code flow, via `{ "deviceCode": true }`). A POST because it begins an OAuth flow; never a side effect of a read. 409s while another sign-in is already pending. |diff --git a/server/lib/README.md b/server/lib/README.mdindex 5955a329c0..887ef1d235 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. || `modelPinMembership.js` | THE model-pin membership rule, and the local-daemon classification it rests on — `modelPinIsOffered(provider, model)` (may this provider be handed this model? a configured-default sentinel, an empty catalog and a local daemon's cached snapshot are all pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"; beyond those the match is exact, with two same-model-spelled-differently tolerances: agy compares on BASE ids, since `--effort` carries the tier and the spawner splits a suffixed pin into exactly that, and OpenCode's `namespace/model` form matches a bare pin, since pins are stored bare and namespaced at spawn), plus `localRuntimeKind(provider)` (the `*Backed` markers first, then the endpoint/name classifier; `orcarouter` excluded as a remote API) and `localBackendForProvider`. Split out of `localProviderRuntime.js` — which re-exports all three, so existing importers are untouched — because the browser needs this rule for a picker and must not pull that module's endpoint graph (`opencodeConfig.js` → `zod`, not a client dependency) to get it. Consumed by `cliProviderRun.js`, `routes/brainSettings.js`, `services/agentProviderResolution.js`, `modelPinReconcile.js` and `client/src/utils/providerModels.js` — one answer for all five (#7327). |-| `modelPinReconcile.js` | Retired-model-pin AUDIT over the shared membership rule (#7315) — `providerCatalogListsModel(provider, modelId)` (is a stored pin still served? `modelPinIsOffered` from `modelPinMembership.js` verbatim, plus the one case a retirement check answers differently from a spawn-time one: nothing is pinned at all. The agy base-id and OpenCode namespace tolerances used to be layered HERE above a stricter rule, which made the audit and the three spawn-time callers disagree about the same pin; they moved down into the rule in #7327), `catalogOfferings` (the listed ids with sentinels dropped, agy collapsed to base ids for a picker), and `reconcileModelPins(pins, providers)` — which pin descriptors name a model their provider no longer lists. Every UNKNOWN case (no pin, empty catalog, unresolved provider) answers "still listed": a false "your pin is gone" tells the user to change a setting that works. Derived on read, never persisted — see `services/modelPinAudit.js`. |+| `modelPinReconcile.js` | Retired-model-pin AUDIT over the shared membership rule (#7315) — `providerCatalogListsModel(provider, modelId)` (is a stored pin still served? `modelPinIsOffered` from `modelPinMembership.js` verbatim, plus the one case a retirement check answers differently from a spawn-time one: nothing is pinned at all. The agy base-id and OpenCode namespace tolerances used to be layered HERE above a stricter rule, which made the audit and the three spawn-time callers disagree about the same pin; they moved down into the rule in #7327), `catalogOfferings` (the listed ids with sentinels dropped, agy collapsed to base ids for a picker), `reconcileModelPins(pins, providers)` — which pin descriptors name a model their provider no longer lists — and, since #7339, the two helpers that make a pin's provider field singular-or-plural-agnostic: `pinProviderIds(pin)` (THE coercion from `providerId` / `providerIds` to a trimmed id list, called by the audit's descriptor builder too so the two layers cannot drift) and `pinProviderNames(pin, providers)` (how a surface names those records — shared by the warnings panel and the notification card so they cannot describe one pin differently). A reviewer pin names a BINARY several records front, so it is stale only when EVERY named record stops listing the model. Every UNKNOWN case (no pin, empty catalog, unresolved provider) answers "still listed": a false "your pin is gone" tells the user to change a setting that works. Derived on read, never persisted — see `services/modelPinAudit.js`. || `reviewerProviderMatchers.js` | Which PROVIDER RECORDS front each model-taking reviewer's binary — `REVIEWER_PROVIDER_MATCHERS` (slug → record predicates, in preference order), `providersForReviewer(reviewer, providers)` (every match, de-duped, preference-ordered so `[0]` is the record whose default a picker shows) and `reviewerProviderIds`. A reviewer slug names a BINARY and PortOS ships more than one record per binary (`claude` spans `claude-code` + `claude-code-tui`, `grok` spans `grok-cli` + its TUI), so both the picker's option list and the retired-pin audit union every match: sourcing from one record makes the answer hostage to that record's staleness, and judging a pin against one produces a false retirement for a model the other still lists. Deliberately excludes Bedrock/Vertex and the `opencode-<backend>` presets (ids that resolve only under another record's environment). Imported directly by `client/src/hooks/useReviewerModelOptions.js` — one table, no mirror to drift (#7339). || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 6e9662a5ca..fcdf1706ca 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -589,18 +589,24 @@ describe('deferred imports stay deferred (#6156)', () => {// `lib/index.test.js` fails without it. The module is deliberately// dependency-free (a few regexes over a string), so it adds no edge into any// subtree — its only consumer, `services/shell.js`, deep-imports it directly.-// Auditing reviewer and task-template model pins (#7339) measures +19, and none+// Auditing reviewer and task-template model pins (#7339) measures +41, and none// of it is a new edge into a heavy subtree. The shared reviewer -> provider-record// table is a pure leaf (`lib/reviewerProviderMatchers.js`) importing only-// `providerModels.js` and `providerTypes.js`, which every module that can reach-// it already instantiates; registering it in the `lib/` barrel is mandatory-// (`lib/index.test.js`) and costs one node in each barrel reacher's closure,-// and its own suite pulls the same two leaves plus `reviewerConfig.js`. The two-// stores the new collectors read stay behind the audit's memoized call-site-// `await import()` — `services/taskTemplates.js` is never in a static closure —-// and `modelPinAudit.js` gaining `reviewerConfig.js` cost nothing, because-// `routes/providers.js` already reaches it through `lib/validation.js`.-const MAX_STATIC_INSTANTIATIONS = 104646;+// `providerModels.js`, `providerTypes.js` and `arrayUtils.js`, which every module+// that can reach it already instantiates; registering it in the `lib/` barrel is+// mandatory (`lib/index.test.js`) and costs one node in each barrel reacher's+// closure, and its own suite pulls those leaves plus `reviewerConfig.js`. The+// remaining ~22 is `services/modelPinAuditNotifier.js` taking its ONE static+// import — `lib/modelPinReconcile.js`, so the card and the panel name a pin's+// provider records with the same function — which lands in that module's own+// suite and in `bootstrap.js`'s closure; no server test file statically reaches+// `bootstrap.js`, so the production edge costs nothing. The two stores the new+// collectors read stay behind the audit's memoized call-site `await import()`+// (`services/taskTemplates.js` is never in a static closure), and+// `modelPinAudit.js` gaining `reviewerConfig.js` / `goalFidelity.js` cost+// nothing — `routes/providers.js` already reaches both through+// `lib/validation.js`.+const MAX_STATIC_INSTANTIATIONS = 104668;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex bf5dad4abb..6f0c7031d0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -218,6 +218,7 @@ export * from './publicReviewSpawnGate.js';// by validation.js), so a flat `export *` here would trip the barrel's// duplicate-identifier collision check.export * as reviewerConfig from './reviewerConfig.js';+export * from './reviewerProviderMatchers.js';export * from './quotaBurnConfig.js';export * from './quotaBurnLegacyConversion.js';export * from './quotaBurnOrigin.js';@@ -451,7 +452,6 @@ export * from './assetProvenance.js';export * from './migrationMarker.js';export * from './modelPinMembership.js';export * from './modelPinReconcile.js';-export * from './reviewerProviderMatchers.js';export * from './modelPricing.js';export * from './navManifest.js';export * from './noReplaceMove.js';diff --git a/server/lib/modelPinReconcile.js b/server/lib/modelPinReconcile.jsindex 138dae9662..76e217ab7c 100644--- a/server/lib/modelPinReconcile.js+++ b/server/lib/modelPinReconcile.js@@ -12,8 +12,8 @@* user's pin would render something different under their chosen model's name* and bury the vendor's own "unknown model" error, so such a pin can only be* SURFACED. This leaf is the membership half of that: given a pin and the- * provider record — or records, for a reviewer pin whose binary several records- * front (#7339) — that serve it, is the id still listed by ANY of them?+ * provider record — or records, for a reviewer pin (#7339) — that serve it, is+ * the id still listed by ANY of them?** The comparison is deliberately STATE-BASED ("is this pin in today's* catalog?") rather than a diff of one refresh against the previous one. The@@ -105,18 +105,25 @@ export function providerCatalogListsModel(provider, modelId) {}/**- * The provider ids a pin is judged against, ALWAYS as a list.- *- * Most pins name exactly one record. A REVIEWER pin (#7339) names a binary, and- * PortOS ships more than one record per binary — `claude` spans `claude-code`- * and `claude-code-tui`, `grok` spans `grok-cli` and its TUI — so it carries- * `providerIds`. Collapsing those to one record would produce a false- * retirement for a model the OTHER record still lists, which is exactly the- * failure this whole audit's posture exists to avoid.+ * THE coercion from a pin's provider field(s) to the id list it is judged+ * against — trimmed, blanks dropped.+ *+ * Most pins name exactly one record. A REVIEWER pin (#7339) names a binary that+ * several records front, so it carries `providerIds` — see+ * `reviewerProviderMatchers.js` for which records, and why collapsing them to+ * one would produce a false retirement for a model another still lists.+ *+ * Exported because the audit's own descriptor builder normalizes with it too:+ * one definition, applied at both layers, rather than two spellings that drift+ * on whitespace the first time somebody touches one of them.+ *+ * @param {{providerId?: unknown, providerIds?: unknown}} pin+ * @returns {string[]}*/-const pinProviderIds = (pin) =>+export const pinProviderIds = (pin) =>(Array.isArray(pin?.providerIds) ? pin.providerIds : [pin?.providerId])- .filter((id) => typeof id === 'string' && id.trim() !== '');+ .map((id) => (typeof id === 'string' ? id.trim() : ''))+ .filter(Boolean);/*** Is `modelId` still served by ANY of `providerIds`?@@ -139,6 +146,22 @@ const pinProviderIds = (pin) =>const anyProviderListsModel = (providerIds, byId, modelId) =>providerIds.length === 0 || providerIds.some((id) => providerCatalogListsModel(byId[id], modelId));+/**+ * How a surface NAMES the records a pin was judged against.+ *+ * Shared so the panel and the notification card cannot describe one pin+ * differently — naming only the first record would have the panel say+ * "Claude Code · Claude Code TUI" while the card said "Claude Code", from the+ * same descriptor. Falls back to the raw id for a record the catalog no longer+ * carries, which is itself a thing the user needs to see.+ *+ * @param {{providerIds?: string[]}} pin+ * @param {Record<string, {name?: string}>} providers+ * @returns {string}+ */+export const pinProviderNames = (pin, providers) =>+ pinProviderIds(pin).map((id) => providers?.[id]?.name || id).join(' · ');+/*** Which of `pins` name a model their provider no longer lists.*@@ -148,10 +171,9 @@ const anyProviderListsModel = (providerIds, byId, modelId) =>* knowing about it. Warnings are returned in the order the pins were given, so* a stable collector order yields a stable panel.*- * Each warning is normalized to carry `providerIds` — the full judged list —- * so the panel can union the catalogs it should offer instead of showing one- * record's. `providerId` (the first, preferred record) rides through untouched- * for the single-provider sources and is what a UI names the pin's provider by.+ * Each warning carries `providerIds` — the full judged list, and the ONE field+ * a surface reads — so the panel can union the catalogs it should offer instead+ * of showing one record's, and `pinProviderNames` can name them all.** `providers` is the provider records keyed by id. A pin naming a provider that* is not in the map is left alone — see `providerCatalogListsModel`.@@ -162,8 +184,15 @@ const anyProviderListsModel = (providerIds, byId, modelId) =>*/export function reconcileModelPins(pins, providers) {const byId = providers && typeof providers === 'object' ? providers : {};- return (Array.isArray(pins) ? pins : [])- .filter((pin) => pin && typeof pin.model === 'string' && pin.model.trim() !== '')- .map((pin) => ({ ...pin, model: pin.model.trim(), providerIds: pinProviderIds(pin) }))- .filter((pin) => !anyProviderListsModel(pin.providerIds, byId, pin.model));+ // One pass, and the descriptor is built only for a pin that is actually+ // stale. The healthy pins are the overwhelming majority — an install with a+ // render pin on every universe, series, sprite, deck and music video reaches+ // here with hundreds of them for a result that is normally empty — so a+ // map-then-filter would spread every one of them just to drop it.+ return (Array.isArray(pins) ? pins : []).flatMap((pin) => {+ const model = typeof pin?.model === 'string' ? pin.model.trim() : '';+ if (model === '') return [];+ const providerIds = pinProviderIds(pin);+ return anyProviderListsModel(providerIds, byId, model) ? [] : [{ ...pin, model, providerIds }];+ });}diff --git a/server/lib/modelPinReconcile.test.js b/server/lib/modelPinReconcile.test.jsindex 3078b9be75..21b9c7a576 100644--- a/server/lib/modelPinReconcile.test.js+++ b/server/lib/modelPinReconcile.test.js@@ -133,9 +133,7 @@ describe('reconcileModelPins', () => {it('reports it once no named record lists it, keeping the full judged list', () => {const pin = { id: 'r', providerIds: ['antigravity-cli', 'codex'], model: 'gpt-4o' };- expect(reconcileModelPins([pin], providers)).toEqual([- { ...pin, providerIds: ['antigravity-cli', 'codex'] },- ]);+ expect(reconcileModelPins([pin], providers)).toEqual([pin]);});it('answers "still served" when one of the named records is unresolvable', () => {@@ -145,6 +143,13 @@ describe('reconcileModelPins', () => {expect(reconcileModelPins([pin], providers)).toEqual([]);});+ it('normalizes a scalar providerId onto the same list shape, trimmed', () => {+ // ONE coercion for both input shapes — `pinProviderIds` — so the audit's+ // descriptor builder and this leaf cannot disagree about whitespace.+ const pin = { id: 'a', providerId: ' codex ', model: 'gpt-4o' };+ expect(reconcileModelPins([pin], providers)).toEqual([{ ...pin, providerIds: ['codex'] }]);+ });+it('leaves a pin with an EMPTY provider list alone rather than reporting all of them', () => {// `[].some()` is false, so without the explicit empty-list arm every// unjudgeable pin would surface as retired.diff --git a/server/lib/reviewerProviderMatchers.js b/server/lib/reviewerProviderMatchers.jsindex 5fddef6cb4..bedc6e3341 100644--- a/server/lib/reviewerProviderMatchers.js+++ b/server/lib/reviewerProviderMatchers.js@@ -55,6 +55,7 @@ import {isKimiProvider,} from './providerModels.js';import { isGrokBuildCli, isProcessProvider } from './providerTypes.js';+import { dedupeByKey } from './arrayUtils.js';/** Reviewer slug → the provider-record predicates that front its binary, in preference order. */export const REVIEWER_PROVIDER_MATCHERS = Object.freeze({@@ -90,13 +91,11 @@ export const REVIEWER_PROVIDER_MATCHERS = Object.freeze({export function providersForReviewer(reviewer, providers) {const matchers = REVIEWER_PROVIDER_MATCHERS[reviewer];if (!matchers) return [];- const matched = [];- for (const match of matchers) {- for (const provider of providers || []) {- if (provider && match(provider) && !matched.includes(provider)) matched.push(provider);- }- }- return matched;+ const matched = matchers.flatMap((match) => (providers || []).filter((p) => p && match(p)));+ // Keyed on the record itself, so identity is what de-dupes — two matchers+ // commonly overlap (`grok-cli` is also an `isGrokBuildCli`) and the FIRST+ // match is the one whose order a picker reads as the preference.+ return dedupeByKey(matched, (provider) => provider, (held) => held);}/**diff --git a/server/lib/reviewerProviderMatchers.test.js b/server/lib/reviewerProviderMatchers.test.jsindex bd81f4c9a1..f5d1d7c2ea 100644--- a/server/lib/reviewerProviderMatchers.test.js+++ b/server/lib/reviewerProviderMatchers.test.js@@ -53,8 +53,11 @@ describe('providersForReviewer', () => {});describe('reviewerProviderIds', () => {- it('drops a record carrying no usable id', () => {- expect(reviewerProviderIds('codex', [{ type: 'cli', command: 'codex' }, cli('codex')]))- .toEqual(['codex']);+ it('drops a record a predicate matched but that carries no usable id', () => {+ // A COMMAND-matched reviewer is the one that can reach an id-less record —+ // an id-equality matcher never does — so without the filter this yields+ // `[undefined]`, and the pin gets judged against a catalog of nothing.+ expect(reviewerProviderIds('grok', [{ type: 'cli', command: 'grok' }, cli('grok-cli', 'grok')]))+ .toEqual(['grok-cli']);});});diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.jsindex d05bf6add5..bc4233410c 100644--- a/server/services/modelPinAudit.js+++ b/server/services/modelPinAudit.js@@ -30,8 +30,9 @@ import { ANTIGRAVITY_CLI_ID } from '../lib/antigravity.js';import { CODEX_CLI_ID } from '../lib/codex.js';import { IMAGE_GEN_MODE } from '../lib/generationModes.js';import { MODEL_OVERRIDE_CAPABLE_MODES } from '../lib/imageGenCapabilities.js';-import { catalogOfferings, reconcileModelPins } from '../lib/modelPinReconcile.js';-import { MODEL_SELECTABLE_REVIEWERS, normalizeReviewerModel } from '../lib/reviewerConfig.js';+import { resolveGoalFidelityConfig } from '../lib/goalFidelity.js';+import { catalogOfferings, pinProviderIds, reconcileModelPins } from '../lib/modelPinReconcile.js';+import { isProviderReviewer, normalizeReviewerModel, reviewerModelsFromDefaults } from '../lib/reviewerConfig.js';import { reviewerProviderIds } from '../lib/reviewerProviderMatchers.js';import { normalizeRenderPinValue, RENDER_TARGETS } from '../lib/renderTargets.js';import { getSettings, updateSettingsWith } from './settings.js';@@ -112,11 +113,12 @@ const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');const pinIf = ({ model, providerId, providerIds, ...rest }) => {const id = trimmed(model);// A reviewer pin names a BINARY that several records front, so it hands in a- // LIST (#7339); every other source names exactly one record. Both normalize to- // the same descriptor — `providerIds` is what the membership rule judges, and- // `providerId` (the preferred record) is what the panel names the pin by.- const resolved = (providerIds ? [...providerIds] : [providerId]).map(trimmed).filter(Boolean);- return id && resolved.length ? [{ ...rest, model: id, providerId: resolved[0], providerIds: resolved }] : [];+ // LIST (#7339); every other source names exactly one record. Both collapse to+ // ONE output field, `providerIds` — what the membership rule judges and what+ // every surface names the pin by, through `pinProviderNames`. Normalized by+ // the leaf's own `pinProviderIds` rather than a second spelling of it here.+ const resolved = pinProviderIds({ providerId, providerIds });+ return id && resolved.length ? [{ ...rest, model: id, providerIds: resolved }] : [];};/** `settings.imageGen.<mode>.model` — the install-wide Image Gen pins. */@@ -124,6 +126,7 @@ function collectImageGenPins({ settings }) {return Object.entries(PINNED_IMAGE_MODES).flatMap(([mode, { providerId, label }]) => pinIf({id: `settings:imageGen.${mode}.model`,mode,+ settingsPath: ['imageGen', mode, 'model'],providerId,model: settings?.imageGen?.[mode]?.model,label: `${label} image model`,@@ -148,6 +151,7 @@ function collectRenderDefaultPins({ settings }) {return pinIf({id: `settings:renderDefaults.${target}.imageModel`,target,+ settingsPath: ['renderDefaults', target, 'imageModel'],providerId: pinnedModeProviderId(mode),model: normalizeRenderPinValue(entry?.imageModel),label: `${target} render model`,@@ -203,8 +207,9 @@ async function collectAppOverridePins({ schedule }) {}/**- * `settings.codeReview.<reviewer>Model` and `settings.codeReview.goalFidelity.model`- * — the Code Review Defaults pins (#7339).+ * `settings.codeReview`'s reviewer model pins (#7339) — the `<reviewer>Model`+ * scalars, the `provider:<id>` entries in `providerModels`, and the+ * goal-fidelity gate's own model.** These rot exactly like every other pin, with a worse failure: the user pins* `codexModel: 'gpt-4o'`, the vendor retires it, and nobody learns until a@@ -212,51 +217,66 @@ async function collectAppOverridePins({ schedule }) {* an unattended run, with the reviewer's verdict silently missing.** **A reviewer is judged against SEVERAL provider records, not one.** The slug- * names a BINARY, and PortOS ships more than one record per binary — `claude`- * spans `claude-code` and `claude-code-tui`, `grok` spans `grok-cli` and its- * TUI. The picker already unions their catalogs for exactly this reason- * (sourcing from one record made it hostage to that record's staleness), so- * judging a pin against a single record would report a model the OTHER record- * still lists as retired. `reviewerProviderIds` resolves the whole set from the- * shared matcher table the picker uses, and `reconcileModelPins` flags the pin- * only when EVERY one of them fails to list it.- *- * A reviewer no record matches yields no ids, so `pinIf` drops the pin rather- * than guessing — the same posture as an app override with no resolvable- * provider. The `lmstudio`/`ollama`/`mtplx` reviewers DO match a record, whose+ * names a BINARY that more than one record fronts — see+ * `lib/reviewerProviderMatchers.js` for the table and why the union is the only+ * safe answer. A reviewer no record matches yields no ids, so `pinIf` drops the+ * pin rather than guessing, the same posture as an app override with no+ * resolvable provider. A `provider:<id>` reviewer IS one record by construction.+ * The `lmstudio`/`ollama`/`mtplx` reviewers DO match a record, whose* local-daemon carve-out in `modelPinMembership.js` passes any id through: the* daemon on this machine is the authority, not the record's cached snapshot.*- * `goalFidelity` rides the same collector because it is the same kind of pin on- * the same settings object — its `backend` names the record to judge against.- * Today that backend is restricted to the local-LLM set, so it is silent by- * construction; the row costs one settings read that already happened and keeps- * the pin vocabulary complete if that restriction ever widens.+ * The stored scalars are read through `reviewerModelsFromDefaults`, the one+ * adapter between the persisted scalar encoding and the token-keyed map the+ * resolvers speak — so a pin this audit judges is exactly a pin the token+ * builders would emit, and the `provider:<id>` family cannot be missed.+ * Resolving a reviewer's records is deferred until a token is known to carry a+ * pin: `providersForReviewer` walks the catalog once per matcher, and a typical+ * install pins one or two reviewers out of eleven.*/function collectReviewerModelPins({ settings, providers }) {const codeReview = settings?.codeReview;- const scalarPins = MODEL_SELECTABLE_REVIEWERS.flatMap((reviewer) => pinIf({- id: `codeReview:${reviewer}Model`,- reviewer,- // Re-checked rather than trusted: settings.json is hand-editable, and a- // value the token builders would silently drop is not a pin the user has.- model: normalizeReviewerModel(codeReview?.[`${reviewer}Model`], reviewer),- providerIds: reviewerProviderIds(reviewer, providers),- label: `${reviewer} reviewer model`,- location: 'Code Review Defaults',+ // `settingsPath` is how a pin says where it lives, so all three shapes — a+ // scalar, a map entry, and the nested goal-fidelity key — share ONE writer+ // instead of branching a clear on which kind of pin arrived.+ const reviewerPin = ({ judgeAs, settingsPath, ...rest }) => pinIf({+ ...rest,+ settingsPath,+ // Same `settings:<dotted path>` spelling the image-gen and render-default+ // pins already use, so a pin id still says where it lives.+ id: `settings:${settingsPath.join('.')}`,+ providerIds: isProviderReviewer(judgeAs)+ ? [judgeAs.slice('provider:'.length)]+ : reviewerProviderIds(judgeAs, providers),href: '/models/code-reviewers',+ });++ const scalarPins = Object.entries(reviewerModelsFromDefaults(codeReview)).flatMap(([token, model]) => reviewerPin({+ judgeAs: token,+ model,+ settingsPath: isProviderReviewer(token)+ ? ['codeReview', 'providerModels', token]+ : ['codeReview', `${token}Model`],+ label: `${token} reviewer model`,+ location: 'Code Review Defaults',}));- const backend = trimmed(codeReview?.goalFidelity?.backend);- return [...scalarPins, ...pinIf({- id: 'codeReview:goalFidelity.model',- model: normalizeReviewerModel(codeReview?.goalFidelity?.model, backend),- providerIds: reviewerProviderIds(backend, providers),++ // The gate's BACKEND comes from `resolveGoalFidelityConfig`, which owns the+ // rules for when the gate runs at all (disabled, or a hand-edited backend+ // outside the local-LLM set it can actually call) — a pin no run would ever+ // carry is not one to warn about. Its MODEL deliberately does not: that+ // resolver falls back to `<backend>Model`, and auditing the fallback would+ // report that scalar a second time, under a second id, with a clear that+ // wrote somewhere else.+ const gate = resolveGoalFidelityConfig(codeReview);+ return [...scalarPins, ...reviewerPin({+ judgeAs: gate?.backend,+ model: normalizeReviewerModel(codeReview?.goalFidelity?.model, gate?.backend),+ settingsPath: ['codeReview', 'goalFidelity', 'model'],label: 'goal-fidelity review model',location: 'Code Review Defaults → Goal fidelity',- href: '/models/code-reviewers',})];}-/*** The `provider` + `model` pair a user-saved CoS task template pins.*@@ -289,6 +309,44 @@ async function collectTaskTemplatePins() {}));}+/**+ * One parent object with `key` REMOVED — "back to inherit" is the absence of+ * the field, not a blank string sitting where a model id used to be. `''` would+ * also read as no-pin at every resolver, but it survives a settings round-trip+ * and shows up in the file as a value the user never typed.+ */+const withoutKey = (parent, key) => {+ const next = { ...(parent || {}) };+ delete next[key];+ return next;+};++/**+ * `root` with the key at `path` removed, every level above it copied.+ *+ * Three pin sources are a model id stored somewhere under `settings`, at three+ * different depths (`imageGen.<mode>.model`, `codeReview.<reviewer>Model`,+ * `codeReview.goalFidelity.model`). Each used to hand-spread its own nesting,+ * which is how the reviewer row ended up branching its clear on which SHAPE of+ * reviewer pin had arrived. A pin carries its own `settingsPath` instead, and+ * they share this one writer — so a new settings-backed pin source is a+ * collector-only edit.+ *+ * A path whose parent holds no object is returned unchanged rather than having+ * one built for it: there is nothing there to clear, and writing `{}` into+ * settings for a pin that is already gone is a change the user did not ask for.+ */+const withoutSettingsPath = (root, [head, ...rest]) => {+ if (!root || typeof root !== 'object') return root;+ if (rest.length === 0) return withoutKey(root, head);+ if (!root[head] || typeof root[head] !== 'object') return root;+ return { ...root, [head]: withoutSettingsPath(root[head], rest) };+};++/** The `clear` every settings-backed pin source shares. */+const clearSettingsPath = (pin) =>+ updateSettingsWith((current) => withoutSettingsPath(current, pin.settingsPath));+/*** The pin sources, in the order the panel reads them (install-wide first).*@@ -304,24 +362,12 @@ const PIN_SOURCES = Object.freeze([{kind: 'imageGen',collect: collectImageGenPins,- clear: (pin) => updateSettingsWith((current) => ({- ...current,- imageGen: {- ...(current.imageGen || {}),- [pin.mode]: withoutKey(current.imageGen?.[pin.mode], 'model'),- },- })),+ clear: clearSettingsPath,},{kind: 'renderDefault',collect: collectRenderDefaultPins,- clear: (pin) => updateSettingsWith((current) => ({- ...current,- renderDefaults: {- ...(current.renderDefaults || {}),- [pin.target]: withoutKey(current.renderDefaults?.[pin.target], 'imageModel'),- },- })),+ clear: clearSettingsPath,},{kind: 'task',@@ -345,19 +391,12 @@ const PIN_SOURCES = Object.freeze([{kind: 'reviewerModel',collect: collectReviewerModelPins,- // The reviewer's own scalar ONLY — never the sibling `<reviewer>Effort`, the- // `reviewers` list, or `goalFidelity`'s `backend`/`effort`. Each of those is- // a separate choice the user did not ask to undo, and dropping a reviewer- // out of the chain because its MODEL rotted would silently weaken the loop.- clear: (pin) => updateSettingsWith((current) => ({- ...current,- codeReview: pin.reviewer- ? withoutKey(current.codeReview, `${pin.reviewer}Model`)- : {- ...(current.codeReview || {}),- goalFidelity: withoutKey(current.codeReview?.goalFidelity, 'model'),- },- })),+ // The pin's own `settingsPath` and nothing beside it — never the sibling+ // `<reviewer>Effort`, the `reviewers` list, or `goalFidelity`'s+ // `backend`/`effort`. Each is a separate choice the user did not ask to+ // undo, and dropping a reviewer out of the chain because its MODEL rotted+ // would silently weaken the loop.+ clear: clearSettingsPath,},// User-saved CoS task-template pins (#7339).{@@ -412,21 +451,20 @@ const PIN_SOURCES = Object.freeze([* A collector that throws must not take the whole audit down with it: one* unreadable store is a missing section, not a failed page.*- * @param {Promise<Array<object>>|Array<object>} providerListPromise the caller's- * in-flight provider catalog read, shared rather than re-issued.* @returns {Promise<Array<object>>}*/-async function collectModelPins(providerListPromise) {+async function collectModelPins() {const { loadSchedule } = await loadTaskScheduleModule();+ const { listProviders } = await loadProvidersModule();const [settings, schedule, providers] = await Promise.all([getSettings().catch(() => ({})),loadSchedule().catch(() => null),- // The reviewer collector classifies provider RECORDS, so it needs the same- // catalog the reconciliation does. It takes the caller's in-flight promise- // rather than a second `listProviders()`: awaiting it here keeps the two- // reads independent for every other collector, while making one store read- // serve both halves.- Promise.resolve(providerListPromise).catch(() => []),+ // The reviewer collector classifies provider RECORDS, so the catalog is one+ // of this function's own inputs — read here, beside the others, rather than+ // threaded in from both callers. `loadProviders` fronts a short TTL cache+ // that coalesces in-flight reads, so the reconciliation's own read of the+ // same catalog costs nothing extra.+ listProviders().catch(() => []),]);const context = { settings, schedule, providers };const collected = await Promise.all(PIN_SOURCES.map(async ({ kind, collect }) => {@@ -451,12 +489,8 @@ async function collectModelPins(providerListPromise) {*/export async function auditModelPins() {const { listProviders } = await loadProvidersModule();- // The pin stores and the provider catalog are independent reads. The catalog- // promise is handed to the collectors as well — a reviewer pin needs it to- // resolve WHICH records front its binary — so both halves share one read- // without either waiting on the other.- const providerListPromise = listProviders();- const [providerList, pins] = await Promise.all([providerListPromise, collectModelPins(providerListPromise)]);+ // The pin stores and the provider catalog are independent reads.+ const [providerList, pins] = await Promise.all([listProviders(), collectModelPins()]);const byId = Object.fromEntries(providerList.map((provider) => [provider.id, provider]));const stale = reconcileModelPins(pins, byId);const providers = Object.fromEntries(@@ -469,18 +503,6 @@ export async function auditModelPins() {return { pins: stale, providers };}-/**- * One parent object with `key` REMOVED — "back to inherit" is the absence of- * the field, not a blank string sitting where a model id used to be. `''` would- * also read as no-pin at every resolver, but it survives a settings round-trip- * and shows up in the file as a value the user never typed.- */-const withoutKey = (parent, key) => {- const next = { ...(parent || {}) };- delete next[key];- return next;-};-/*** Clear ONE pin back to "inherit", by the `id` the audit reported.*@@ -499,12 +521,7 @@ const withoutKey = (parent, key) => {* @returns {Promise<{cleared: boolean, id: string}>}*/export async function clearModelPin(pinId) {- // The SAME catalog read the audit makes, for the same reason: a reviewer pin- // resolves its provider records from it, and a collection that skipped it- // would silently drop every reviewer pin from the write-target allowlist —- // turning the Clear button on a reported pin into a no-op `cleared: false`.- const { listProviders } = await loadProvidersModule();- const pins = await collectModelPins(listProviders());+ const pins = await collectModelPins();const pin = pins.find((candidate) => candidate.id === pinId);if (pin) await PIN_SOURCES.find((source) => source.kind === pin.kind).clear(pin);const { removeByMetadata } = await loadNotificationsModule();diff --git a/server/services/modelPinAudit.test.js b/server/services/modelPinAudit.test.jsindex 65ef828f3d..079ac44c5a 100644--- a/server/services/modelPinAudit.test.js+++ b/server/services/modelPinAudit.test.js@@ -86,7 +86,7 @@ describe('auditModelPins', () => {expect(pins).toHaveLength(1);expect(pins[0]).toMatchObject({id: 'settings:imageGen.agy.model',- providerId: 'antigravity-cli',+ providerIds: ['antigravity-cli'],model: 'gemini-3.5-flash-low',location: 'Settings → Media Gen → Image Gen',});@@ -149,7 +149,7 @@ describe('auditModelPins', () => {const { pins } = await auditModelPins();expect(pins).toHaveLength(1);- expect(pins[0]).toMatchObject({ id: 'app:app-1:code-review', providerId: 'antigravity-cli' });+ expect(pins[0]).toMatchObject({ id: 'app:app-1:code-review', providerIds: ['antigravity-cli'] });});it('leaves an app override alone when no provider can be resolved for it', async () => {@@ -193,6 +193,17 @@ describe('clearModelPin', () => {expect(next.other).toBe('kept');});+ it('writes nothing into settings for a path whose parent is not there', async () => {+ // The shared settings writer copies every level above the key it removes —+ // it must not MINT one. Building `{ codeReview: {} }` for a pin that is+ // already gone is a settings change the user never asked for.+ getSettings.mockResolvedValue(settingsWith({ codeReview: { codexModel: 'gpt-4o' } }));+ await clearModelPin('settings:codeReview.codexModel');+ const next = updateSettingsWith.mock.calls[0][0](settingsWith({}));+ expect(next.imageGen).toEqual({});+ expect('codeReview' in next).toBe(false);+ });+it('clears a renderDefaults pin without disturbing its mode', async () => {getSettings.mockResolvedValue(settingsWith({renderDefaults: { deck: { imageMode: 'agy', imageModel: 'gemini-3.5-flash-low' } },@@ -346,11 +357,9 @@ describe('reviewer model pins (#7339)', () => {expect(pins).toHaveLength(1);expect(pins[0]).toMatchObject({- id: 'codeReview:codexModel',+ id: 'settings:codeReview.codexModel',kind: 'reviewerModel',- reviewer: 'codex',model: 'gpt-4o',- providerId: 'codex',providerIds: ['codex'],location: 'Code Review Defaults',href: '/models/code-reviewers',@@ -375,8 +384,7 @@ describe('reviewer model pins (#7339)', () => {const { pins, providers } = await auditModelPins();expect(pins[0]).toMatchObject({- id: 'codeReview:claudeModel',- providerId: 'claude-code',+ id: 'settings:codeReview.claudeModel',providerIds: ['claude-code', 'claude-code-tui'],});// Both catalogs ride along so the panel can union them — one record's list@@ -411,14 +419,42 @@ describe('reviewer model pins (#7339)', () => {expect((await auditModelPins()).pins).toEqual([]);});- it('judges the goal-fidelity pin against the backend it names', async () => {- listProviders.mockResolvedValue([CODEX, OLLAMA]);+ it('audits a provider:<id> reviewer pin against that record', async () => {+ // `providerModels` is the other half of the pin vocabulary+ // (`reviewerModelsFromDefaults` folds both), and a `provider:<id>` token+ // names its record outright — no matcher union needed.+ getSettings.mockResolvedValue(codeReview({ providerModels: { 'provider:codex': 'gpt-4o' } }));++ const { pins } = await auditModelPins();++ expect(pins[0]).toMatchObject({+ id: 'settings:codeReview.providerModels.provider:codex',+ providerIds: ['codex'],+ model: 'gpt-4o',+ });+ });++ it('clears a provider:<id> pin out of the providerModels map, leaving its siblings', async () => {+ const stored = codeReview({ providerModels: { 'provider:codex': 'gpt-4o', 'provider:other': 'keep-me' } });+ getSettings.mockResolvedValue(stored);++ await clearModelPin('settings:codeReview.providerModels.provider:codex');++ const next = updateSettingsWith.mock.calls[0][0](stored);+ expect(next.codeReview.providerModels).toEqual({ 'provider:other': 'keep-me' });+ });++ it('ignores the goal-fidelity model while the gate is switched off', async () => {+ // `resolveGoalFidelityConfig` owns when the gate runs at all; a pin no run+ // would carry is not one to warn about — and its id must reach no writer.+ listProviders.mockResolvedValue([CODEX]);getSettings.mockResolvedValue(codeReview({- goalFidelity: { enabled: true, backend: 'ollama', model: 'llama3.3:70b' },+ goalFidelity: { enabled: false, backend: 'ollama', model: 'gpt-4o' },}));- // The local-daemon carve-out again: a backend PortOS probes live is never- // judged against the record's cached snapshot.+expect((await auditModelPins()).pins).toEqual([]);+ await expect(clearModelPin('settings:codeReview.goalFidelity.model'))+ .resolves.toMatchObject({ cleared: false });});it('clears the reviewer scalar and nothing beside it', async () => {@@ -430,8 +466,8 @@ describe('reviewer model pins (#7339)', () => {});getSettings.mockResolvedValue(stored);- await expect(clearModelPin('codeReview:codexModel')).resolves.toEqual({- cleared: true, id: 'codeReview:codexModel',+ await expect(clearModelPin('settings:codeReview.codexModel')).resolves.toEqual({+ cleared: true, id: 'settings:codeReview.codexModel',});const next = updateSettingsWith.mock.calls[0][0](stored);@@ -444,13 +480,13 @@ describe('reviewer model pins (#7339)', () => {});it('clears the goal-fidelity model without disturbing its backend or effort', async () => {- listProviders.mockResolvedValue([{ ...CODEX, id: 'lmstudio', name: 'LM Studio' }]);+ listProviders.mockResolvedValue([{ id: 'lmstudio', name: 'LM Studio' }]);const stored = codeReview({goalFidelity: { enabled: true, backend: 'lmstudio', model: 'gpt-4o', effort: 'high' },});getSettings.mockResolvedValue(stored);- await clearModelPin('codeReview:goalFidelity.model');+ await clearModelPin('settings:codeReview.goalFidelity.model');const next = updateSettingsWith.mock.calls[0][0](stored);expect(next.codeReview.goalFidelity).toEqual({ enabled: true, backend: 'lmstudio', effort: 'high' });@@ -476,7 +512,7 @@ describe('task template pins (#7339)', () => {id: 'template:user-abc',kind: 'taskTemplate',templateId: 'user-abc',- providerId: 'codex',+ providerIds: ['codex'],model: 'gpt-4o',label: 'Nightly sweep · template model',location: 'Chief of Staff → Tasks → Quick Templates',diff --git a/server/services/modelPinAuditNotifier.js b/server/services/modelPinAuditNotifier.jsindex 6de8730c89..c3496a47f7 100644--- a/server/services/modelPinAuditNotifier.js+++ b/server/services/modelPinAuditNotifier.js@@ -58,6 +58,12 @@ export function resetModelPinReportState() {queued = false;}+// The one exception to this module's no-static-imports posture: naming a pin's+// provider records is a pure leaf (`modelPinReconcile.js`), and the panel calls+// the same function — a private spelling here is how the card and the panel end+// up describing one pin differently.+import { pinProviderNames } from '../lib/modelPinReconcile.js';+/*** Deferred so the audit's own import closure — and the pin stores behind it —* stays out of the boot closure `bootstrap.js` pays for. Memoizes the PROMISE@@ -75,12 +81,15 @@ const loadNotificationsModule = () => (notificationsModule ||= import('./notific* retracted independently when that one pin is cleared. A single rolled-up card* could do neither.*/-async function announce(pin, provider) {+async function announce(pin, providers) {const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } =await loadNotificationsModule();// The persisted card is the dedupe record: already announced, still true.if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'pinId', pin.id)) return false;- const providerName = provider?.name || pin.providerId;+ // Every record the pin was judged against, not just the first: a reviewer pin+ // spans several (#7339), and naming one would have this card disagree with the+ // panel about the same pin. `pinProviderNames` is what both call.+ const providerName = pinProviderNames(pin, providers);await addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,title: 'Pinned model retired',@@ -88,7 +97,7 @@ async function announce(pin, provider) {+ ` — clear it in ${pin.location}.`,priority: PRIORITY_LEVELS.MEDIUM,link: pin.href || null,- metadata: { pinId: pin.id, kind: pin.kind, providerId: pin.providerId, model: pin.model },+ metadata: { pinId: pin.id, kind: pin.kind, providerIds: pin.providerIds, model: pin.model },});return true;}@@ -107,7 +116,7 @@ async function reportOnce() {// the next audit may be a whole burst away.let announced = 0;for (const pin of pins) {- const raised = await announce(pin, providers?.[pin.providerId]).catch((error) => {+ const raised = await announce(pin, providers).catch((error) => {console.error(`❌ Announcing retired model pin ${pin.id} failed: ${error.message}`);return false;});diff --git a/server/services/modelPinAuditNotifier.test.js b/server/services/modelPinAuditNotifier.test.jsindex 21cf3b8d65..17e61c8192 100644--- a/server/services/modelPinAuditNotifier.test.js+++ b/server/services/modelPinAuditNotifier.test.js@@ -32,7 +32,7 @@ const {const pin = (id, overrides = {}) => ({id,kind: 'imageGen',- providerId: 'antigravity-cli',+ providerIds: ['antigravity-cli'],model: 'retired-model-1',label: 'Agy CLI image model',location: 'Settings → Media Gen → Image Gen',@@ -42,7 +42,7 @@ const pin = (id, overrides = {}) => ({const audited = (...pins) => ({pins,- providers: Object.fromEntries(pins.map((p) => [p.providerId, { id: p.providerId, name: 'Agy CLI' }])),+ providers: Object.fromEntries(pins.flatMap((p) => p.providerIds.map((id) => [id, { id, name: 'Agy CLI' }]))),});/**