Skip to content

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

audit reviewer and task-template model pins for retired models (#7339)

[._.]/ Adam Eivy9dff6b9fd5ab
diff --git a/client/src/components/providers/RetiredModelPinsPanel.jsx b/client/src/components/providers/RetiredModelPinsPanel.jsx
index 80c5cf50ae..b2225884a2 100644
--- a/client/src/components/providers/RetiredModelPinsPanel.jsx
+++ b/client/src/components/providers/RetiredModelPinsPanel.jsx
@@ -91,8 +91,16 @@ export default function RetiredModelPinsPanel({ reloadKey = 0 }) {
</p>
<ul className="mt-3 space-y-2">
{pins.map((pin) => {
- const provider = providers[pin.providerId];
- const offered = Array.isArray(provider?.available) ? provider.available : [];
+ // 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];
+ const offered = Array.from(new Set(
+ judged.flatMap((id) => (Array.isArray(providers[id]?.available) ? providers[id].available : []))
+ ));
return (
<li
key={pin.id}
@@ -103,7 +111,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} · {provider?.name || pin.providerId}
+ {pin.location} · {judged.map((id) => providers[id]?.name || id).join(' · ')}
</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.jsx
index dcc707fae2..d606b94e9d 100644
--- a/client/src/components/providers/RetiredModelPinsPanel.test.jsx
+++ b/client/src/components/providers/RetiredModelPinsPanel.test.jsx
@@ -149,3 +149,46 @@ describe('RetiredModelPinsPanel', () => {
expect(await screen.findByText('Agy image model:')).toBeTruthy();
});
});
+
+describe('a reviewer pin judged against several provider records (#7339)', () => {
+ const REVIEWER_PIN = {
+ pins: [{
+ id: 'codeReview:claudeModel',
+ kind: 'reviewerModel',
+ reviewer: 'claude',
+ providerId: 'claude-code',
+ providerIds: ['claude-code', 'claude-code-tui'],
+ model: 'claude-3-opus',
+ label: 'claude reviewer model',
+ location: 'Code Review Defaults',
+ href: '/models/code-reviewers',
+ }],
+ providers: {
+ 'claude-code': { id: 'claude-code', name: 'Claude Code', available: ['claude-sonnet-4-6'] },
+ 'claude-code-tui': { id: 'claude-code-tui', name: 'Claude Code TUI', available: ['claude-sonnet-5'] },
+ },
+ };
+
+ it('offers the union of every judged record, not just the preferred one', async () => {
+ // Showing one record's catalog would hide tiers the reviewer's binary can
+ // still be handed — the same staleness the union exists to route around.
+ api.getModelPinWarnings.mockResolvedValue(REVIEWER_PIN);
+ renderPanel();
+
+ const offered = await screen.findByText(/Now offered:/);
+ expect(offered.textContent).toContain('claude-sonnet-4-6');
+ 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.js
index 66d0f43c24..dc7f2c9176 100644
--- a/client/src/hooks/useReviewerModelOptions.js
+++ b/client/src/hooks/useReviewerModelOptions.js
@@ -1,6 +1,11 @@
import { useEffect, useMemo, useState } from 'react';
import * as api from '../services/api';
-import { filterSelectableModels, selectableModelsForProvider, commandBasename, isAntigravityProvider, isCursorProvider, isGrokBuildCli, isKimiProvider, antigravityModelEffortLevels } from '../utils/providers';
+import { filterSelectableModels, selectableModelsForProvider, antigravityModelEffortLevels } from '../utils/providers';
+// THE reviewer -> provider-record table, shared with the retired-pin audit
+// (#7339). Taken from the server leaf rather than mirrored: the picker offering
+// a tier the audit calls retired — or the audit flagging a pin the picker just
+// handed the user — is exactly the drift a second copy would reintroduce.
+import { REVIEWER_PROVIDER_MATCHERS, providersForReviewer } from '../../../server/lib/reviewerProviderMatchers.js';
import { MODEL_SELECTABLE_REVIEWERS } from '../components/cos/constants';
import { reviewerEffortLevels, normalizeReviewerSlug } from '../lib/reviewerPins';
import { LOCAL_LLM_BACKENDS } from '../lib/localLlmBackends';
@@ -11,56 +16,6 @@ import { LOCAL_LLM_BACKENDS } from '../lib/localLlmBackends';
// listing runs the `mtplx` wrapper, so it stays catalog-sourced and free-text.
const PROBED_LOCAL_BACKENDS = LOCAL_LLM_BACKENDS.map((b) => b.id);
-/**
- * Every provider record that fronts a reviewer's binary, as predicates in
- * PREFERENCE ORDER. Two reductions run over each list and they answer different
- * questions:
- *
- * - the **option list** unions every matching record's catalog, because a
- * reviewer runs one binary and any record fronting that binary lists ids that
- * binary accepts. Sourcing from a single record made the picker hostage to
- * that record's staleness — `claude-code` (CLI) listing `claude-sonnet-4-6`
- * while `claude-code-tui` already listed `claude-sonnet-5` showed the reviewer
- * the retired tier and hid the current one.
- * - the **shown default** takes the FIRST match, so a reviewer spawned
- * non-interactively reports the CLI record's default rather than the TUI's.
- *
- * A predicate rather than a bare id wherever the app already recognizes a
- * provider by more than its shipped id (an `agy` configured by path), so this
- * classifies the same records the rest of the UI does.
- *
- * What is deliberately NOT matched matters as much as what is:
- * - **No Bedrock/Vertex record.** `claude-code-bedrock` lists
- * `us.anthropic.*` ids that resolve only under that record's own environment.
- * - **No `opencode-<local-backend>` preset.** Those enumerate ids that resolve
- * only under the `OPENCODE_CONFIG_CONTENT` a PortOS-spawned provider injects,
- * and the reviewer runs a bare `opencode` against the user's OWN config. The
- * Zen CLI/TUI records are the exception and ARE matched: their ids are the
- * namespaced `opencode/*` spellings that bare `opencode models` prints, and
- * the Harnesses page's model refresh fills them from exactly that probe (see
- * `server/services/harnesses.js#usesHarnessCatalog`), so they are the live
- * catalog for the account the reviewer will bill.
- * - **Not `opencode-zen` itself.** That is the HTTP-API record; its bare ids
- * (`claude-opus-5`) are Zen's API model names, which `opencode -m` cannot
- * resolve.
- */
-const REVIEWER_PROVIDER_MATCHERS = Object.freeze({
- claude: [(p) => p.id === 'claude-code', (p) => p.id === 'claude-code-tui'],
- codex: [(p) => p.id === 'codex', (p) => p.id === 'codex-tui'],
- antigravity: [isAntigravityProvider],
- // `grok` names one binary that ships as BOTH a `cli` and a `tui` provider, and
- // the reviewer is spawned non-interactively, so the CLI's record wins the
- // default — the broad predicate follows it for an install that only kept the TUI.
- grok: [(p) => p.id === 'grok-cli', isGrokBuildCli],
- cursor: [(p) => p.id === 'cursor-cli', isCursorProvider],
- pi: [(p) => p.id === 'pi-cli', (p) => ['cli', 'tui'].includes(p.type) && commandBasename(p.command) === 'pi'],
- kimi: [(p) => p.id === 'kimi-cli', isKimiProvider],
- opencode: [(p) => p.id === 'opencode-zen-cli', (p) => p.id === 'opencode-zen-tui'],
- mtplx: [(p) => p.id === 'mtplx'],
- lmstudio: [(p) => p.id === 'lmstudio'],
- ollama: [(p) => p.id === 'ollama'],
-});
-
/**
* Selectable model ids per model-taking reviewer, for `ReviewerPicker`'s Model
* column. One hook so all four picker surfaces (Code Review Defaults, TaskAddForm,
@@ -148,15 +103,7 @@ export default function useReviewerModelOptions() {
// ask the same question, and a per-call helper re-walked the provider array
// for every one of them.
const providersByReviewer = Object.fromEntries(
- Object.entries(REVIEWER_PROVIDER_MATCHERS).map(([reviewer, matchers]) => {
- const matched = [];
- for (const match of matchers) {
- for (const provider of providers || []) {
- if (match(provider) && !matched.includes(provider)) matched.push(provider);
- }
- }
- return [reviewer, matched];
- })
+ Object.keys(REVIEWER_PROVIDER_MATCHERS).map((reviewer) => [reviewer, providersForReviewer(reviewer, providers)])
);
for (const provider of providers || []) providersByReviewer[`provider:${provider.id}`] = [provider];
const providerReviewers = (providers || []).map(provider => `provider:${provider.id}`);
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 2c52697d25..ecbfe45739 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -54,7 +54,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| Module | Purpose |
|---|---|
| `providers` | Compatibility facade re-exporting every helper from the nine modules below, so existing `../utils/providers` imports keep working. New code imports the declaring module. |
-| `providerTypes` | What KIND of provider a record is: `PROVIDER_TYPES` (re-exported from `server/lib/aiToolkit/constants.js`) with `isCliProvider` / `isTuiProvider` / `isApiProvider` / `isProcessProvider` and `isClaudeHarnessProvider` (re-exported from `server/lib/providerTypes.js`, with legacy alias `isClaudeCommandProvider`), `isLaunchableTuiProvider` (a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt — shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree), `enabledApiProviderFilter`, `enabledProcessProviderFilter` (the coding/CLI-TUI-only counterpart, for a manual Claim/Replan/Resolve/Review "Run with" picker), `providerTypeClass`; the vendor-harness predicates keyed on the shipped ids plus `commandBasename` so a path-configured or renamed binary still qualifies (`isCodexProvider`, `isCodexSubscriptionProvider` — subscription readiness is keyed on the `codex` command, never an editable id — `isAntigravityProvider`, `isCursorProvider`, `isKimiProvider`, `isGrokProvider`, `isGrokBuildCli`, `isClaudeCommandProvider`, `isOpencodeLocalProvider`); and the structural backend markers a wrapper carries (`localRuntimeNamespace`, `isOllamaBackedProvider`). Everything with a server twin is re-exported from the pure leaves `server/lib/providerModels.js`, `server/lib/aiToolkit/constants.js` and `server/lib/aiToolkit/internal/ollamaBacked.js`, never copied. |
+| `providerTypes` | What KIND of provider a record is: `PROVIDER_TYPES` (re-exported from `server/lib/aiToolkit/constants.js`) with `isCliProvider` / `isTuiProvider` / `isApiProvider` / `isProcessProvider` and `isClaudeHarnessProvider` (re-exported from `server/lib/providerTypes.js`, with legacy alias `isClaudeCommandProvider`), `isLaunchableTuiProvider` (a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt — shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree), `enabledApiProviderFilter`, `enabledProcessProviderFilter` (the coding/CLI-TUI-only counterpart, for a manual Claim/Replan/Resolve/Review "Run with" picker), `providerTypeClass`; the vendor-harness predicates keyed on the shipped ids plus `commandBasename` so a path-configured or renamed binary still qualifies (`isCodexProvider`, `isCodexSubscriptionProvider` — subscription readiness is keyed on the `codex` command, never an editable id — `isAntigravityProvider`, `isCursorProvider`, `isKimiProvider`, `isGrokProvider`, `isGrokBuildCli`, `isClaudeCommandProvider`, `isOpencodeLocalProvider`); and the structural backend markers a wrapper carries (`localRuntimeNamespace`, `isOllamaBackedProvider`). Everything with a server twin is re-exported from the pure leaves `server/lib/providerTypes.js`, `server/lib/providerModels.js`, `server/lib/aiToolkit/constants.js` and `server/lib/aiToolkit/internal/ollamaBacked.js`, never copied — `isGrokBuildCli` moved there in #7339 so the shared reviewer→provider matcher table keys on the same predicate the browser does. |
| `providerGateways` | `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` — the hosted OpenAI-compatible gateways (`orcarouter`, `openrouter`) an OpenCode CLI/TUI wrapper can front-end, inheriting its API key at spawn time from the sibling API provider whose id equals the gateway id. Reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. All three are re-exported from the pure leaf `server/lib/providerGateways.js`. |
| `providerHarnesses` | `harnessLabel(harnessId)` — the display name for an agent program PortOS drives (Claude Code, OpenCode, Codex, …), used by the connection-management UI, where `null` means Direct API and an unknown id renders verbatim rather than disappearing. Read through `harnessById` from the pure leaf `server/lib/providerHarnesses.js`, so a harness added to the registry is named here without a second edit. |
| `providerEndpoints` | WHERE a provider's endpoint points. `isLocalEndpoint` (loopback), `isPrivateNetworkEndpoint` (RFC1918 / tailnet address, or a `.local` / `.ts.net` / single-label host — somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key), `isLocalInstanceProvider` (talks to a daemon on THIS machine; mirror of `server/lib/localProviderRuntime.js#isLocalInstanceEndpoint` — gate anything that explains a provider by inspecting the host PortOS runs on), `isFleetProvider` / `isFleetHostConfigured` (another machine inside the private network), and `localBackendForProvider` (`'ollama'` / `'lmstudio'` / `null` by id, endpoint or name — it matches by NAME, so pair it with `isLocalInstanceProvider` before claiming this machine's install state). |
diff --git a/client/src/utils/providerTypes.js b/client/src/utils/providerTypes.js
index 5de90c46a4..c0e67d9e50 100644
--- a/client/src/utils/providerTypes.js
+++ b/client/src/utils/providerTypes.js
@@ -17,7 +17,6 @@
import { isTuiProvider, isApiProvider, isProcessProvider } from '../../../server/lib/providerTypes.js';
import { PROVIDER_TYPES } from '../../../server/lib/aiToolkit/constants.js';
-import { isGrokProvider } from '../../../server/lib/providerModels.js';
export { PROVIDER_TYPES } from '../../../server/lib/aiToolkit/constants.js';
// The public `aiToolkit/providers.js` barrel reaches `fs` and `child_process`,
@@ -42,6 +41,10 @@ export {
isProcessProvider,
isClaudeHarnessProvider,
isClaudeHarnessProvider as isClaudeCommandProvider,
+ // The Grok Build CLI/TUI predicate moved to the server leaf in #7339: the
+ // shared reviewer -> provider matcher table keys on it, and a browser-only
+ // copy is exactly the drift that table exists to remove.
+ isGrokBuildCli,
} from '../../../server/lib/providerTypes.js';
/**
@@ -75,14 +78,6 @@ export const enabledApiProviderFilter = (provider) => Boolean(provider?.enabled)
*/
export const enabledProcessProviderFilter = (provider) => Boolean(provider?.enabled) && isProcessProvider(provider);
-/**
- * Check if a provider is the Grok Build CLI/TUI (the `grok` command harness):
- * a PROCESS provider `isGrokProvider` recognizes — the shipped `grok-cli` /
- * `grok-tui` samples or any process provider whose command basename is `grok`.
- * The plain Grok API provider is excluded on both counts. Reviewer-model
- * discovery uses this for custom Grok process providers too.
- */
-export const isGrokBuildCli = (provider) => isProcessProvider(provider) && isGrokProvider(provider);
/**
* Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index aac5eea847..d8886cece5 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -650,6 +650,7 @@ describe('providerTypes re-exports the server predicates', () => {
'isCodexProvider',
'isCodexSubscriptionProvider',
'isCursorProvider',
+ 'isGrokBuildCli',
'isGrokProvider',
'isKimiProvider',
'isOllamaBackedProvider',
diff --git a/docs/API.md b/docs/API.md
index eb14b02b93..d48231154b 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 plus global and per-app scheduled-task pins. 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 `<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. |
| 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.md
index a832a6a841..5955a329c0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -210,6 +210,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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`. |
+| `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). |
| `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 8c53177ff4..6e9662a5ca 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -589,7 +589,18 @@ 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.
-const MAX_STATIC_INSTANTIATIONS = 104627;
+// Auditing reviewer and task-template model pins (#7339) measures +19, 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;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index cb3e2cea5b..bf5dad4abb 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -451,6 +451,7 @@ 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.js
index da91adbd72..138dae9662 100644
--- a/server/lib/modelPinReconcile.js
+++ b/server/lib/modelPinReconcile.js
@@ -12,7 +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 that serves it, is the id still listed?
+ * 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?
*
* 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
@@ -103,19 +104,59 @@ export function providerCatalogListsModel(provider, modelId) {
return modelPinIsOffered(provider, id);
}
+/**
+ * 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.
+ */
+const pinProviderIds = (pin) =>
+ (Array.isArray(pin?.providerIds) ? pin.providerIds : [pin?.providerId])
+ .filter((id) => typeof id === 'string' && id.trim() !== '');
+
+/**
+ * Is `modelId` still served by ANY of `providerIds`?
+ *
+ * Deliberately `some`, not `every`: a pin is stale only when every named
+ * provider fails to list it. One record that still offers the id means the
+ * reviewer's binary can still be handed it, so there is nothing to warn about.
+ *
+ * An EMPTY list answers `true`, matching `providerCatalogListsModel`'s
+ * no-provider arm — a pin nobody could resolve a catalog for is unjudgeable,
+ * and `[].some()` would otherwise report every one of them as retired. An id
+ * that resolves to no record is likewise `true` (that arm again), so an
+ * unknown provider among several still answers "still served".
+ *
+ * @param {string[]} providerIds
+ * @param {Record<string, object>} byId
+ * @param {string|null|undefined} modelId
+ * @returns {boolean}
+ */
+const anyProviderListsModel = (providerIds, byId, modelId) =>
+ providerIds.length === 0 || providerIds.some((id) => providerCatalogListsModel(byId[id], modelId));
+
/**
* Which of `pins` name a model their provider no longer lists.
*
- * A pin descriptor is `{ id, providerId, model, label, location, ... }`; every
- * field rides through onto the warning untouched so a collector can carry
+ * A pin descriptor is `{ id, providerId | providerIds, model, label, location, ... }`;
+ * every field rides through onto the warning untouched so a collector can carry
* whatever the UI needs (a deep link, a clearability flag) without this leaf
* 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.
+ *
* `providers` is the provider records keyed by id. A pin naming a provider that
* is not in the map is left alone — see `providerCatalogListsModel`.
*
- * @param {Array<{id:string, providerId:string, model:string}>} pins
+ * @param {Array<{id:string, providerId?:string, providerIds?:string[], model:string}>} pins
* @param {Record<string, {id?:string, name?:string, models?:unknown[]}>} providers
* @returns {Array<object>}
*/
@@ -123,6 +164,6 @@ 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() !== '')
- .filter((pin) => !providerCatalogListsModel(byId[pin.providerId], pin.model))
- .map((pin) => ({ ...pin, model: pin.model.trim() }));
+ .map((pin) => ({ ...pin, model: pin.model.trim(), providerIds: pinProviderIds(pin) }))
+ .filter((pin) => !anyProviderListsModel(pin.providerIds, byId, pin.model));
}
diff --git a/server/lib/modelPinReconcile.test.js b/server/lib/modelPinReconcile.test.js
index 6ec0f2b2b4..3078b9be75 100644
--- a/server/lib/modelPinReconcile.test.js
+++ b/server/lib/modelPinReconcile.test.js
@@ -110,7 +110,10 @@ describe('reconcileModelPins', () => {
const pin = {
id: 'a', providerId: 'codex', model: ' gpt-4o ', label: 'L', location: 'Loc', href: '/x',
};
- expect(reconcileModelPins([pin], providers)).toEqual([{ ...pin, model: 'gpt-4o' }]);
+ // `providerIds` is normalized ON — the panel unions the catalogs it names,
+ // so a single-provider source must answer in the same shape as a reviewer.
+ expect(reconcileModelPins([pin], providers))
+ .toEqual([{ ...pin, model: 'gpt-4o', providerIds: ['codex'] }]);
});
it('leaves a pin alone when its provider is not in the map', () => {
@@ -120,6 +123,36 @@ describe('reconcileModelPins', () => {
expect(reconcileModelPins(pins, providers)).toEqual([]);
});
+ describe('a pin judged against SEVERAL providers (#7339)', () => {
+ // A reviewer slug names a BINARY, and PortOS ships more than one record per
+ // binary. The rule is "stale only when EVERY named record fails to list it".
+ it('stays silent while any one of them still lists the model', () => {
+ const pin = { id: 'r', providerIds: ['antigravity-cli', 'codex'], model: 'gpt-5-codex' };
+ expect(reconcileModelPins([pin], providers)).toEqual([]);
+ });
+
+ 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'] },
+ ]);
+ });
+
+ it('answers "still served" when one of the named records is unresolvable', () => {
+ // An unknown record could be the one that lists it — warning here would be
+ // a false retirement on a pin that works.
+ const pin = { id: 'r', providerIds: ['codex', 'deleted-provider'], model: 'gpt-4o' };
+ expect(reconcileModelPins([pin], providers)).toEqual([]);
+ });
+
+ 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.
+ const pin = { id: 'r', providerIds: [], model: 'gpt-4o' };
+ expect(reconcileModelPins([pin], providers)).toEqual([]);
+ });
+ });
+
it('tolerates absent/garbage inputs rather than throwing on a page load', () => {
expect(reconcileModelPins(null, providers)).toEqual([]);
expect(reconcileModelPins([null, { id: 'a' }, { id: 'b', model: ' ' }], providers)).toEqual([]);
diff --git a/server/lib/providerTypes.js b/server/lib/providerTypes.js
index 07efbffc6c..876795a9b2 100644
--- a/server/lib/providerTypes.js
+++ b/server/lib/providerTypes.js
@@ -1,5 +1,5 @@
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
-import { isClaudeCommand } from './providerModels.js';
+import { isClaudeCommand, isGrokProvider } from './providerModels.js';
/** Provider record types, shared by server dispatch and browser controls. */
export const isCliProvider = (provider) => provider?.type === PROVIDER_TYPES.CLI;
@@ -9,3 +9,16 @@ export const isProcessProvider = (provider) => isCliProvider(provider) || isTuiP
/** Blank process commands default to Claude; API records never launch a harness. */
export const isClaudeHarnessProvider = (provider) => isProcessProvider(provider) && isClaudeCommand(provider?.command);
+
+/**
+ * The Grok Build CLI/TUI (the `grok` command harness): a PROCESS provider
+ * `isGrokProvider` recognizes — the shipped `grok-cli` / `grok-tui` samples
+ * or any process provider whose command basename is `grok`. The plain Grok
+ * API provider is excluded on both counts.
+ *
+ * Lives here rather than in the browser mirror because the reviewer -> provider
+ * matcher table (`reviewerProviderMatchers.js`) keys on it, and that table is
+ * shared: a second definition is exactly the drift that table exists to remove.
+ * `client/src/utils/providerTypes.js` re-exports this one.
+ */
+export const isGrokBuildCli = (provider) => isProcessProvider(provider) && isGrokProvider(provider);
diff --git a/server/lib/reviewerProviderMatchers.js b/server/lib/reviewerProviderMatchers.js
new file mode 100644
index 0000000000..5fddef6cb4
--- /dev/null
+++ b/server/lib/reviewerProviderMatchers.js
@@ -0,0 +1,114 @@
+/**
+ * Which PROVIDER RECORDS front each model-taking reviewer's binary (#7339).
+ *
+ * A reviewer slug names a BINARY, not a provider record — `claude` is whatever
+ * `claude` on PATH resolves to, and PortOS ships more than one record per
+ * binary (`claude-code` for the headless CLI, `claude-code-tui` for the PTY;
+ * `grok-cli` beside the Grok TUI). Two questions need that mapping and used to
+ * have only a client-side answer (`useReviewerModelOptions.js`):
+ *
+ * - the PICKER, which offers the union of every matching record's catalog,
+ * because any record fronting that binary lists ids the binary accepts;
+ * - the RETIRED-PIN AUDIT, which asks whether a stored `<reviewer>Model` pin
+ * still appears in ANY of them.
+ *
+ * Both must classify the same records or they disagree about the same pin: the
+ * picker would offer a tier the audit calls retired, or the audit would flag a
+ * pin the picker just handed the user. So the table lives HERE, in a pure leaf
+ * the browser imports directly — one table, no mirror to drift.
+ *
+ * Matchers are listed in PREFERENCE ORDER, and the two reductions over each
+ * list answer different questions: the option list and the audit union EVERY
+ * match, while the picker's shown default takes the FIRST — so a reviewer
+ * spawned non-interactively reports the CLI record's default rather than the
+ * TUI's. A predicate rather than a bare id wherever the app already recognizes
+ * a provider by more than its shipped id (an `agy` configured by path), so this
+ * classifies the same records the rest of PortOS does.
+ *
+ * What is deliberately NOT matched matters as much as what is:
+ * - **No Bedrock/Vertex record.** `claude-code-bedrock` lists `us.anthropic.*`
+ * ids that resolve only under that record's own environment.
+ * - **No `opencode-<local-backend>` preset.** Those enumerate ids that resolve
+ * only under the `OPENCODE_CONFIG_CONTENT` a PortOS-spawned provider injects,
+ * and the reviewer runs a bare `opencode` against the user's OWN config. The
+ * Zen CLI/TUI records are the exception and ARE matched: their ids are the
+ * namespaced `opencode/*` spellings that bare `opencode models` prints, and
+ * the Harnesses page's model refresh fills them from exactly that probe (see
+ * `server/services/harnesses.js#usesHarnessCatalog`), so they are the live
+ * catalog for the account the reviewer will bill.
+ * - **Not `opencode-zen` itself.** That is the HTTP-API record; its bare ids
+ * (`claude-opus-5`) are Zen's API model names, which `opencode -m` cannot
+ * resolve.
+ *
+ * Pure leaf (`providerModels.js` + `providerTypes.js`, both already browser-
+ * imported) so `client/src/hooks/useReviewerModelOptions.js` takes it verbatim.
+ * Deliberately does NOT import `reviewerConfig.js`: the coverage rule — every
+ * MODEL_SELECTABLE_REVIEWERS slug has a row — is a test
+ * (`reviewerProviderMatchers.test.js`), not a runtime dependency, which keeps
+ * this leaf out of the reviewer-argv vocabulary's closure.
+ */
+
+import {
+ commandBasename,
+ isAntigravityProvider,
+ isCursorProvider,
+ isKimiProvider,
+} from './providerModels.js';
+import { isGrokBuildCli, isProcessProvider } from './providerTypes.js';
+
+/** Reviewer slug → the provider-record predicates that front its binary, in preference order. */
+export const REVIEWER_PROVIDER_MATCHERS = Object.freeze({
+ claude: [(p) => p.id === 'claude-code', (p) => p.id === 'claude-code-tui'],
+ codex: [(p) => p.id === 'codex', (p) => p.id === 'codex-tui'],
+ antigravity: [isAntigravityProvider],
+ // `grok` names one binary that ships as BOTH a `cli` and a `tui` provider, and
+ // the reviewer is spawned non-interactively, so the CLI's record wins the
+ // default — the broad predicate follows it for an install that only kept the TUI.
+ grok: [(p) => p.id === 'grok-cli', isGrokBuildCli],
+ cursor: [(p) => p.id === 'cursor-cli', isCursorProvider],
+ pi: [(p) => p.id === 'pi-cli', (p) => isProcessProvider(p) && commandBasename(p.command) === 'pi'],
+ kimi: [(p) => p.id === 'kimi-cli', isKimiProvider],
+ opencode: [(p) => p.id === 'opencode-zen-cli', (p) => p.id === 'opencode-zen-tui'],
+ mtplx: [(p) => p.id === 'mtplx'],
+ lmstudio: [(p) => p.id === 'lmstudio'],
+ ollama: [(p) => p.id === 'ollama'],
+});
+
+/**
+ * Every provider record fronting `reviewer`'s binary, in matcher-preference
+ * order (NOT the order they appear in `providers`) so `[0]` is the record whose
+ * default a picker shows. De-duped by identity: two matchers commonly overlap —
+ * `grok-cli` is also an `isGrokBuildCli`.
+ *
+ * A reviewer with no row, or one no record matches, yields `[]` — which every
+ * caller must read as "nothing is known", never as "nothing is offered".
+ *
+ * @param {string} reviewer
+ * @param {Array<object>|null|undefined} providers
+ * @returns {Array<object>}
+ */
+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;
+}
+
+/**
+ * The ids of those records — the audit's side of the question, where a pin is
+ * judged against SEVERAL candidate catalogs and is stale only when every one of
+ * them fails to list it.
+ *
+ * @param {string} reviewer
+ * @param {Array<object>|null|undefined} providers
+ * @returns {string[]}
+ */
+export const reviewerProviderIds = (reviewer, providers) =>
+ providersForReviewer(reviewer, providers)
+ .map((provider) => provider?.id)
+ .filter((id) => typeof id === 'string' && id !== '');
diff --git a/server/lib/reviewerProviderMatchers.test.js b/server/lib/reviewerProviderMatchers.test.js
new file mode 100644
index 0000000000..bd81f4c9a1
--- /dev/null
+++ b/server/lib/reviewerProviderMatchers.test.js
@@ -0,0 +1,60 @@
+import { describe, it, expect } from 'vitest';
+import { MODEL_SELECTABLE_REVIEWERS } from './reviewerConfig.js';
+import {
+ REVIEWER_PROVIDER_MATCHERS,
+ providersForReviewer,
+ reviewerProviderIds,
+} from './reviewerProviderMatchers.js';
+
+const cli = (id, command = id) => ({ id, type: 'cli', command });
+const tui = (id, command) => ({ id, type: 'tui', command });
+
+describe('reviewer roster coverage', () => {
+ it('classifies every reviewer whose model the user can pin', () => {
+ // A reviewer that gains model selection with no row here has its pin judged
+ // against NO catalog — the audit silently stops covering it, and the picker
+ // offers it nothing. Both failures are invisible without this.
+ expect(Object.keys(REVIEWER_PROVIDER_MATCHERS).sort())
+ .toEqual([...MODEL_SELECTABLE_REVIEWERS].sort());
+ });
+});
+
+describe('providersForReviewer', () => {
+ it('returns every record fronting the binary, in matcher order not catalog order', () => {
+ // The TUI record is listed FIRST in the catalog; preference order still puts
+ // the headless CLI at [0], because that is the one a reviewer spawns.
+ const records = [cli('claude-code-tui'), cli('claude-code'), cli('codex')];
+ expect(providersForReviewer('claude', records).map((p) => p.id))
+ .toEqual(['claude-code', 'claude-code-tui']);
+ });
+
+ it('de-dupes a record two matchers both claim', () => {
+ // `grok-cli` satisfies the id matcher AND `isGrokBuildCli`.
+ const records = [cli('grok-cli', 'grok'), tui('grok-tui', 'grok')];
+ expect(providersForReviewer('grok', records).map((p) => p.id))
+ .toEqual(['grok-cli', 'grok-tui']);
+ });
+
+ it('recognizes a path-configured binary the shipped ids do not name', () => {
+ const records = [cli('my-grok', '/opt/homebrew/bin/grok')];
+ expect(providersForReviewer('grok', records).map((p) => p.id)).toEqual(['my-grok']);
+ });
+
+ it('leaves a plain Grok API record out — it launches no binary', () => {
+ expect(providersForReviewer('grok', [{ id: 'grok', type: 'api', command: '' }])).toEqual([]);
+ });
+
+ it('answers empty for an unknown reviewer and for a missing catalog', () => {
+ // Both must read as "nothing is KNOWN" at every caller, never as
+ // "nothing is offered" — the audit turns the second into a false retirement.
+ expect(providersForReviewer('copilot', [cli('codex')])).toEqual([]);
+ expect(providersForReviewer('codex', null)).toEqual([]);
+ });
+});
+
+describe('reviewerProviderIds', () => {
+ it('drops a record carrying no usable id', () => {
+ expect(reviewerProviderIds('codex', [{ type: 'cli', command: 'codex' }, cli('codex')]))
+ .toEqual(['codex']);
+ });
+});
diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.js
index 19b80268d5..d05bf6add5 100644
--- a/server/services/modelPinAudit.js
+++ b/server/services/modelPinAudit.js
@@ -31,6 +31,8 @@ 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 { reviewerProviderIds } from '../lib/reviewerProviderMatchers.js';
import { normalizeRenderPinValue, RENDER_TARGETS } from '../lib/renderTargets.js';
import { getSettings, updateSettingsWith } from './settings.js';
@@ -54,11 +56,13 @@ let notificationsModule = null;
let providersModule = null;
let taskScheduleModule = null;
let recordPinsModule = null;
+let taskTemplatesModule = null;
const loadAppsModule = () => (appsModule ||= import('./apps.js'));
const loadNotificationsModule = () => (notificationsModule ||= import('./notifications.js'));
const loadProvidersModule = () => (providersModule ||= import('./providers.js'));
const loadTaskScheduleModule = () => (taskScheduleModule ||= import('./taskSchedule.js'));
const loadRecordPinsModule = () => (recordPinsModule ||= import('./modelPinRecords.js'));
+const loadTaskTemplatesModule = () => (taskTemplatesModule ||= import('./taskTemplates.js'));
/**
* Which provider record serves each cloud image-gen mode that can carry a pin.
@@ -105,10 +109,14 @@ const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');
* compare it against, and a wrong guess is a false retirement. Returns an array
* so every collector can stay a single `flatMap`.
*/
-const pinIf = ({ model, providerId, ...rest }) => {
+const pinIf = ({ model, providerId, providerIds, ...rest }) => {
const id = trimmed(model);
- const provider = trimmed(providerId);
- return id && provider ? [{ ...rest, model: id, providerId: provider }] : [];
+ // 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 }] : [];
};
/** `settings.imageGen.<mode>.model` — the install-wide Image Gen pins. */
@@ -194,6 +202,93 @@ async function collectAppOverridePins({ schedule }) {
);
}
+/**
+ * `settings.codeReview.<reviewer>Model` and `settings.codeReview.goalFidelity.model`
+ * — the Code Review Defaults pins (#7339).
+ *
+ * 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
+ * review loop spawns `codex --model gpt-4o` and dies on a vendor error — inside
+ * 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
+ * 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.
+ */
+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',
+ href: '/models/code-reviewers',
+ }));
+ const backend = trimmed(codeReview?.goalFidelity?.backend);
+ return [...scalarPins, ...pinIf({
+ id: 'codeReview:goalFidelity.model',
+ model: normalizeReviewerModel(codeReview?.goalFidelity?.model, backend),
+ providerIds: reviewerProviderIds(backend, providers),
+ 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.
+ *
+ * A template is a durable "run it this way" the user saved once and picks from
+ * a menu for months, so its pin is among the likeliest to outlive the model it
+ * names — and unlike a scheduled task it fails at the moment the user is
+ * standing there launching work, with a vendor error for a model they picked so
+ * long ago they no longer remember it.
+ *
+ * `provider` is a provider RECORD id (the Quick Templates menu seeds it from
+ * `/api/providers`, and `applyTemplate` looks the record up by it), so one id —
+ * no reviewer-style union. A template pinning a model but no provider would run
+ * on whatever the form resolves at launch, which is not knowable here; `pinIf`
+ * drops it rather than guessing. Built-ins carry neither field, so they can
+ * never yield a pin.
+ */
+async function collectTaskTemplatePins() {
+ const { getAllTemplates } = await loadTaskTemplatesModule();
+ const templates = await getAllTemplates();
+ return (templates || []).flatMap((template) => pinIf({
+ id: `template:${template?.id}`,
+ templateId: template?.id,
+ providerId: template?.provider,
+ model: template?.model,
+ label: `${trimmed(template?.name) || template?.id} · template model`,
+ location: 'Chief of Staff → Tasks → Quick Templates',
+ // No per-template route exists — a template is edited from the Quick
+ // Templates row on the task form, so that page IS the destination.
+ href: '/cos/tasks',
+ }));
+}
+
/**
* The pin sources, in the order the panel reads them (install-wide first).
*
@@ -244,6 +339,39 @@ const PIN_SOURCES = Object.freeze([
return updateAppTaskTypeOverride(pin.appId, pin.taskType, { model: null });
},
},
+ // Reviewer model pins (#7339). Install-wide, so above the per-record row, and
+ // after the task/app rows because a reviewer pin only ever breaks the REVIEW
+ // half of a run — a broken task pin breaks the run itself.
+ {
+ 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'),
+ },
+ })),
+ },
+ // User-saved CoS task-template pins (#7339).
+ {
+ kind: 'taskTemplate',
+ collect: collectTaskTemplatePins,
+ // `''` rather than a deleted key: that is this store's OWN encoding for an
+ // unpinned template (`createTemplate` writes `model: ''`), and
+ // `updateTemplate` merges rather than replaces, so an absent key would leave
+ // the stale id in place. `provider` and `effort` are untouched.
+ clear: async (pin) => {
+ const { updateTemplate } = await loadTaskTemplatesModule();
+ return updateTemplate(pin.templateId, { model: '' });
+ },
+ },
// Per-record `imageModelId` pins (#7326) — universes, series, sprite records,
// decks and music-video projects. ONE row rather than five: they share a
// storage shape, so `modelPinRecords.js` handles them with one query per
@@ -284,15 +412,23 @@ 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() {
+async function collectModelPins(providerListPromise) {
const { loadSchedule } = await loadTaskScheduleModule();
- const [settings, schedule] = await Promise.all([
+ 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(() => []),
]);
- const context = { settings, schedule };
+ const context = { settings, schedule, providers };
const collected = await Promise.all(PIN_SOURCES.map(async ({ kind, collect }) => {
const pins = await Promise.resolve(collect(context)).catch((error) => {
console.error(`❌ Model pin collector ${kind} failed: ${error.message}`);
@@ -306,20 +442,25 @@ async function collectModelPins() {
/**
* The stale pins, plus the catalog each one's provider now offers.
*
- * `providers` is keyed by provider id and carries only the providers a stale
- * pin actually names, so a 200-model Ollama catalog is not shipped to a page
- * with no Ollama pin on it.
+ * `providers` is keyed by provider id and carries only the records a stale pin
+ * actually names — every id in its `providerIds`, so a reviewer pin ships the
+ * catalog of each record fronting its binary and the panel can union them. A
+ * 200-model Ollama catalog is still not shipped to a page with no Ollama pin.
*
* @returns {Promise<{pins: Array<object>, providers: Record<string, object>}>}
*/
export async function auditModelPins() {
const { listProviders } = await loadProvidersModule();
- // The pin stores and the provider catalog are independent reads.
- const [providerList, pins] = await Promise.all([listProviders(), collectModelPins()]);
+ // 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)]);
const byId = Object.fromEntries(providerList.map((provider) => [provider.id, provider]));
const stale = reconcileModelPins(pins, byId);
const providers = Object.fromEntries(
- [...new Set(stale.map((pin) => pin.providerId))].map((id) => [id, {
+ [...new Set(stale.flatMap((pin) => pin.providerIds))].map((id) => [id, {
id,
name: byId[id]?.name || id,
available: catalogOfferings(byId[id]),
@@ -358,7 +499,12 @@ const withoutKey = (parent, key) => {
* @returns {Promise<{cleared: boolean, id: string}>}
*/
export async function clearModelPin(pinId) {
- const pins = await collectModelPins();
+ // 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 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.js
index 5be6d587a0..65ef828f3d 100644
--- a/server/services/modelPinAudit.test.js
+++ b/server/services/modelPinAudit.test.js
@@ -13,6 +13,7 @@ vi.mock('./apps.js', () => ({
// so the registry wiring — reconciliation, ordering, clear dispatch — is what
// these assertions are about.
vi.mock('./modelPinRecords.js', () => ({ collectRecordPins: vi.fn(), clearRecordPin: vi.fn() }));
+vi.mock('./taskTemplates.js', () => ({ getAllTemplates: vi.fn(), updateTemplate: vi.fn() }));
const { listProviders } = await import('./providers.js');
const { removeByMetadata } = await import('./notifications.js');
@@ -20,6 +21,7 @@ const { getSettings, updateSettingsWith } = await import('./settings.js');
const { loadSchedule, updateTaskInterval } = await import('./taskSchedule.js');
const { getActiveApps, updateAppTaskTypeOverride } = await import('./apps.js');
const { collectRecordPins, clearRecordPin } = await import('./modelPinRecords.js');
+const { getAllTemplates, updateTemplate } = await import('./taskTemplates.js');
const {
auditModelPins, clearModelPin, MODEL_OVERRIDE_CAPABLE_MODES, PINNED_IMAGE_MODE_IDS,
} = await import('./modelPinAudit.js');
@@ -33,6 +35,11 @@ const AGY = {
models: ['gemini-3.6-flash-low', 'gemini-3.6-flash-high'],
};
const CODEX = { id: 'codex', name: 'Codex', command: 'codex', models: ['gpt-5-codex'] };
+// The reviewer union's reason to exist (#7339): one record lags the other, so a
+// tier only the TUI lists is still a model the `claude` binary accepts.
+const CLAUDE_CLI = { id: 'claude-code', name: 'Claude Code', command: 'claude', models: ['claude-sonnet-4-6'] };
+const CLAUDE_TUI = { id: 'claude-code-tui', name: 'Claude Code TUI', command: 'claude', models: ['claude-sonnet-5'] };
+const OLLAMA = { id: 'ollama', name: 'Ollama', endpoint: 'http://localhost:11434', models: ['qwen2.5:7b'] };
const settingsWith = (overrides) => ({ imageGen: {}, renderDefaults: {}, ...overrides });
@@ -44,6 +51,7 @@ beforeEach(() => {
getActiveApps.mockResolvedValue([]);
removeByMetadata.mockResolvedValue({ success: true, removed: 0 });
collectRecordPins.mockResolvedValue([]);
+ getAllTemplates.mockResolvedValue([]);
});
// One record's stored render pin, as the record source reports it.
@@ -254,6 +262,7 @@ describe('clearModelPin', () => {
expect(updateTaskInterval).not.toHaveBeenCalled();
expect(updateAppTaskTypeOverride).not.toHaveBeenCalled();
expect(clearRecordPin).not.toHaveBeenCalled();
+ expect(updateTemplate).not.toHaveBeenCalled();
});
});
@@ -326,3 +335,185 @@ describe('per-record pins (#7326)', () => {
expect(updateSettingsWith).not.toHaveBeenCalled();
});
});
+
+describe('reviewer model pins (#7339)', () => {
+ const codeReview = (overrides) => settingsWith({ codeReview: overrides });
+
+ it('reports a retired reviewer pin with its deep link and what the provider now offers', async () => {
+ getSettings.mockResolvedValue(codeReview({ codexModel: 'gpt-4o' }));
+
+ const { pins, providers } = await auditModelPins();
+
+ expect(pins).toHaveLength(1);
+ expect(pins[0]).toMatchObject({
+ id: 'codeReview:codexModel',
+ kind: 'reviewerModel',
+ reviewer: 'codex',
+ model: 'gpt-4o',
+ providerId: 'codex',
+ providerIds: ['codex'],
+ location: 'Code Review Defaults',
+ href: '/models/code-reviewers',
+ });
+ expect(providers.codex.available).toEqual(['gpt-5-codex']);
+ });
+
+ it('leaves a claude pin alone when only the TUI record lists it', async () => {
+ // THE regression the union exists for. `claude` names a BINARY; judging its
+ // pin against `claude-code` alone would call a tier retired that the TUI
+ // record still lists — and the picker would go on offering it.
+ listProviders.mockResolvedValue([CLAUDE_CLI, CLAUDE_TUI]);
+ getSettings.mockResolvedValue(codeReview({ claudeModel: 'claude-sonnet-5' }));
+
+ expect((await auditModelPins()).pins).toEqual([]);
+ });
+
+ it('reports a claude pin no record fronting the binary lists, naming both catalogs', async () => {
+ listProviders.mockResolvedValue([CLAUDE_CLI, CLAUDE_TUI]);
+ getSettings.mockResolvedValue(codeReview({ claudeModel: 'claude-3-opus' }));
+
+ const { pins, providers } = await auditModelPins();
+
+ expect(pins[0]).toMatchObject({
+ id: 'codeReview:claudeModel',
+ providerId: 'claude-code',
+ providerIds: ['claude-code', 'claude-code-tui'],
+ });
+ // Both catalogs ride along so the panel can union them — one record's list
+ // would hide half of what the reviewer can actually be handed.
+ expect(Object.keys(providers).sort()).toEqual(['claude-code', 'claude-code-tui']);
+ });
+
+ it('leaves a local-daemon reviewer pin alone — the daemon is the authority', async () => {
+ // `lmstudio`/`ollama` records carry a cached snapshot, not a catalog. The
+ // carve-out in modelPinMembership.js is what keeps a freshly pulled model
+ // from being reported as retired.
+ listProviders.mockResolvedValue([OLLAMA]);
+ getSettings.mockResolvedValue(codeReview({ ollamaModel: 'llama3.3:70b' }));
+
+ expect((await auditModelPins()).pins).toEqual([]);
+ });
+
+ it('leaves a reviewer pin alone when no record on this install fronts its binary', async () => {
+ // Nothing to judge it against — guessing a catalog is how a false
+ // retirement gets in front of the user.
+ listProviders.mockResolvedValue([CODEX]);
+ getSettings.mockResolvedValue(codeReview({ cursorModel: 'gpt-5-retired' }));
+
+ expect((await auditModelPins()).pins).toEqual([]);
+ });
+
+ it('ignores a hand-edited pin the token builders would drop anyway', async () => {
+ // `settings.json` is hand-editable; a `[`-bearing id never reaches a
+ // reviewer, so warning that it is retired points at the wrong problem.
+ getSettings.mockResolvedValue(codeReview({ codexModel: 'gpt-4o[bogus]' }));
+
+ expect((await auditModelPins()).pins).toEqual([]);
+ });
+
+ it('judges the goal-fidelity pin against the backend it names', async () => {
+ listProviders.mockResolvedValue([CODEX, OLLAMA]);
+ getSettings.mockResolvedValue(codeReview({
+ goalFidelity: { enabled: true, backend: 'ollama', model: 'llama3.3:70b' },
+ }));
+ // 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([]);
+ });
+
+ it('clears the reviewer scalar and nothing beside it', async () => {
+ const stored = codeReview({
+ codexModel: 'gpt-4o',
+ codexEffort: 'high',
+ claudeModel: 'claude-sonnet-4-6',
+ reviewers: ['codex', 'claude'],
+ });
+ getSettings.mockResolvedValue(stored);
+
+ await expect(clearModelPin('codeReview:codexModel')).resolves.toEqual({
+ cleared: true, id: 'codeReview:codexModel',
+ });
+
+ const next = updateSettingsWith.mock.calls[0][0](stored);
+ expect('codexModel' in next.codeReview).toBe(false);
+ // Dropping the reviewer's effort, or the reviewer itself, would silently
+ // weaken the review loop over a model id the user asked to forget.
+ expect(next.codeReview.codexEffort).toBe('high');
+ expect(next.codeReview.claudeModel).toBe('claude-sonnet-4-6');
+ expect(next.codeReview.reviewers).toEqual(['codex', 'claude']);
+ });
+
+ it('clears the goal-fidelity model without disturbing its backend or effort', async () => {
+ listProviders.mockResolvedValue([{ ...CODEX, 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');
+
+ const next = updateSettingsWith.mock.calls[0][0](stored);
+ expect(next.codeReview.goalFidelity).toEqual({ enabled: true, backend: 'lmstudio', effort: 'high' });
+ });
+});
+
+describe('task template pins (#7339)', () => {
+ const template = (overrides = {}) => ({
+ id: 'user-abc',
+ name: 'Nightly sweep',
+ provider: 'codex',
+ model: 'gpt-4o',
+ ...overrides,
+ });
+
+ it('reports a retired template pin with its name and where it is picked', async () => {
+ getAllTemplates.mockResolvedValue([template()]);
+
+ const { pins } = await auditModelPins();
+
+ expect(pins).toHaveLength(1);
+ expect(pins[0]).toMatchObject({
+ id: 'template:user-abc',
+ kind: 'taskTemplate',
+ templateId: 'user-abc',
+ providerId: 'codex',
+ model: 'gpt-4o',
+ label: 'Nightly sweep · template model',
+ location: 'Chief of Staff → Tasks → Quick Templates',
+ href: '/cos/tasks',
+ });
+ });
+
+ it.each([
+ ['a template that pins no provider', { provider: '' }],
+ ['a built-in, which pins neither field', { provider: undefined, model: undefined }],
+ ['a template still on a listed model', { model: 'gpt-5-codex' }],
+ ])('leaves %s alone', async (_case, overrides) => {
+ getAllTemplates.mockResolvedValue([template(overrides)]);
+
+ expect((await auditModelPins()).pins).toEqual([]);
+ });
+
+ it('clears the template model through the templates writer, leaving its provider pinned', async () => {
+ getAllTemplates.mockResolvedValue([template()]);
+
+ await expect(clearModelPin('template:user-abc')).resolves.toEqual({
+ cleared: true, id: 'template:user-abc',
+ });
+ // `''` is this store's own unpinned encoding, and `updateTemplate` MERGES —
+ // an absent key would leave the retired id exactly where it was.
+ expect(updateTemplate).toHaveBeenCalledWith('user-abc', { model: '' });
+ });
+
+ it('keeps the rest of the audit when the templates store cannot be read', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ getSettings.mockResolvedValue(settingsWith({
+ imageGen: { agy: { model: 'gemini-3.5-flash-low' } },
+ }));
+ getAllTemplates.mockRejectedValue(new Error('task-templates.json unreadable'));
+
+ expect((await auditModelPins()).pins.map((pin) => pin.id)).toEqual(['settings:imageGen.agy.model']);
+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('taskTemplate'));
+ logged.mockRestore();
+ });
+});