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

feat: select configured providers and models for code review

[._.]/ Adam Eivycbf7d24aacdf
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsx
index 679f301845..5efa437cd6 100644
--- a/client/src/components/cos/ReviewerPicker.jsx
+++ b/client/src/components/cos/ReviewerPicker.jsx
@@ -15,7 +15,9 @@ import {
reviewerLabel,
sanitizeReviewerModelInput
} from './constants';
-import { normalizeReviewerSlug } from '../../lib/reviewerPins';
+import ProviderModelSelector from '../ProviderModelSelector';
+import { selectableModelsForProvider } from '../../utils/providers';
+import { isProviderReviewer, normalizeReviewerSlug } from '../../lib/reviewerPins';
const normalizeReviewerValue = (value) => normalizeReviewerSlug(value);
@@ -145,6 +147,13 @@ export default function ReviewerPicker({
showRunFlags = true
}) {
const id = useId();
+ const [addProviderId, setAddProviderId] = useState('');
+ const [addProviderModel, setAddProviderModel] = useState('');
+ const providerRecords = modelOptions?.providers || [];
+ const addProvider = providerRecords.find(provider => provider.id === addProviderId);
+ const labelFor = (token) => isProviderReviewer(token)
+ ? providerRecords.find(provider => `provider:${provider.id}` === token)?.name || token.slice(9)
+ : reviewerLabel(token);
const [usernameInput, setUsernameInput] = useState('');
const [usernameError, setUsernameError] = useState('');
// Reviewers whose Model cell the user switched to free text by picking the
@@ -226,16 +235,22 @@ export default function ReviewerPicker({
// `/api/providers` that failed or hasn't landed reports nothing (see the
// hook), so this never fires on a slow page.
const unavailability = (token) => {
+ if (isProviderReviewer(token)) {
+ const provider = providerRecords.find(record => `provider:${record.id}` === token);
+ if (modelOptions?.loaded && !provider) return { label: 'missing', title: 'This reviewer provider is no longer configured on this machine.' };
+ if (provider?.enabled === false) return { label: 'disabled', title: 'Enable this provider in AI Providers before running its review.' };
+ return null;
+ }
if (installed?.[token] === false) {
return {
label: 'not installed',
- title: `${reviewerLabel(token)}'s CLI binary wasn't found on this machine. It still runs (federation-wide config), but the review loop here will report it unsatisfied until it's installed.`
+ title: `${labelFor(token)}'s CLI binary wasn't found on this machine. It still runs (federation-wide config), but the review loop here will report it unsatisfied until it's installed.`
};
}
if (modelOptions?.providerDisabled?.[token]) {
return {
label: 'disabled',
- title: `${reviewerLabel(token)}'s provider records are all switched off in Settings → AI Providers, so this machine isn't set up to use it. Adding it still works — the review loop spawns its CLI directly, and a federated peer may have it enabled.`
+ title: `${labelFor(token)}'s provider records are all switched off in Settings → AI Providers, so this machine isn't set up to use it. Adding it still works — the review loop spawns its CLI directly, and a federated peer may have it enabled.`
};
}
return null;
@@ -422,7 +437,7 @@ export default function ReviewerPicker({
// the static ladder when it didn't, so a caller that passes no `modelOptions`
// keeps a working (just unnarrowed) select rather than losing the cell.
const renderEffortCell = (token) => {
- const subject = reviewerLabel(token);
+ const subject = labelFor(token);
const stored = efforts.get(token) ?? '';
const ladder = reviewerEffortLevels(token);
if (!ladder?.length) return renderNoPinCell(`${subject} has no reasoning-effort control`);
@@ -526,8 +541,8 @@ export default function ReviewerPicker({
// `loaded` gates the "nothing installed" messaging so a pre-fetch render
// doesn't accuse a healthy backend of being empty.
const renderModelCell = (token) => {
- if (!MODEL_SELECTABLE_REVIEWERS.includes(token)) return renderNoPinCell(`${reviewerLabel(token)} takes no model`);
- const subject = reviewerLabel(token);
+ if (!MODEL_SELECTABLE_REVIEWERS.includes(token) && !isProviderReviewer(token)) return renderNoPinCell(`${labelFor(token)} takes no model`);
+ const subject = labelFor(token);
const pinnedValue = models.get(token);
const value = pinnedValue ?? '';
const defaultModel = modelOptions?.defaultModels?.[token] || '';
@@ -663,6 +678,30 @@ export default function ReviewerPicker({
return (
<div className="@container flex flex-col gap-2 w-full">
+ {providerRecords.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <ProviderModelSelector
+ providers={providerRecords}
+ selectedProviderId={addProviderId}
+ selectedModel={addProviderModel}
+ availableModels={addProvider ? selectableModelsForProvider(addProvider, addProvider.models || []) : []}
+ onProviderChange={value => { setAddProviderId(value); setAddProviderModel(''); }}
+ onModelChange={setAddProviderModel}
+ emptyProviderOption="Choose a reviewer provider"
+ emptyModelOption="Provider default"
+ alwaysShowModel
+ disabled={disabled}
+ />
+ <button type="button" disabled={disabled || !addProviderId || selected.includes(`provider:${addProviderId}`)}
+ className="text-sm text-port-accent disabled:opacity-50 self-start"
+ onClick={() => {
+ const token = `provider:${addProviderId}`;
+ emit({ reviewers: [...selected, token], reviewerModels: { ...modelsMap, ...(addProviderModel ? { [token]: addProviderModel } : {}) } });
+ setAddProviderId(''); setAddProviderModel('');
+ }}>Add provider reviewer</button>
+ <p className="text-xs text-gray-500">Choose from your enabled AI providers. Providers need an API text transport or an enforced tool-free harness to run reviews.</p>
+ </div>
+ )}
<div className="flex flex-col gap-1">
<span className="text-xs text-gray-500">Reviewers (in order):</span>
{selected.length > 0 && (
@@ -690,7 +729,7 @@ export default function ReviewerPicker({
disabled={disabled || index === 0}
onClick={() => move(index, -1)}
className="text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
- aria-label={`Move ${reviewerLabel(value)} earlier`}
+ aria-label={`Move ${labelFor(value)} earlier`}
>
<ChevronUp size={12} />
</button>
@@ -699,13 +738,13 @@ export default function ReviewerPicker({
disabled={disabled || index === selected.length - 1}
onClick={() => move(index, 1)}
className="text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
- aria-label={`Move ${reviewerLabel(value)} later`}
+ aria-label={`Move ${labelFor(value)} later`}
>
<ChevronDown size={12} />
</button>
</div>
<span className="flex items-center gap-1 min-w-0 col-span-2 @xl:col-span-1">
- <span className="text-xs text-gray-300 truncate">{reviewerLabel(value)}</span>
+ <span className="text-xs text-gray-300 truncate">{labelFor(value)}</span>
{renderUnavailableBadge(value)}
</span>
<span className={CELL_LABEL_CLASS}>Model</span>
@@ -714,19 +753,19 @@ export default function ReviewerPicker({
<div className="min-w-0">{renderEffortCell(value)}</div>
<span className={CELL_LABEL_CLASS}>Optional</span>
<div>
- {renderOptToggle(value, reviewerLabel(value), isOptional(value)
- ? `${reviewerLabel(value)} is non-blocking (~opt): an inconclusive verdict from it won't block the merge. Click to make it blocking.`
- : `${reviewerLabel(value)} gates the merge. Click to make it non-blocking (~opt) — its inconclusive verdicts won't block the merge (a hard failure still does).`)}
+ {renderOptToggle(value, labelFor(value), isOptional(value)
+ ? `${labelFor(value)} is non-blocking (~opt): an inconclusive verdict from it won't block the merge. Click to make it blocking.`
+ : `${labelFor(value)} gates the merge. Click to make it non-blocking (~opt) — its inconclusive verdicts won't block the merge (a hard failure still does).`)}
</div>
<span className={CELL_LABEL_CLASS}>Max iterations</span>
- <div>{renderMaxRounds(value, reviewerLabel(value))}</div>
+ <div>{renderMaxRounds(value, labelFor(value))}</div>
<div className="col-span-2 @xl:col-span-1 justify-self-end">
<button
type="button"
disabled={disabled}
onClick={() => remove(value)}
className="text-gray-500 hover:text-port-error"
- aria-label={`Remove ${reviewerLabel(value)}`}
+ aria-label={`Remove ${labelFor(value)}`}
>
<X size={12} />
</button>
diff --git a/client/src/components/settings/CodeReviewersTab.jsx b/client/src/components/settings/CodeReviewersTab.jsx
index f44d9d84da..6d6a05046b 100644
--- a/client/src/components/settings/CodeReviewersTab.jsx
+++ b/client/src/components/settings/CodeReviewersTab.jsx
@@ -10,17 +10,8 @@ import { reviewerModelsFromDefaults, reviewerModelsToDefaults, reviewerEffortsFr
import {
DEFAULT_REVIEWERS,
DEFAULT_REVIEW_STOP_MODE,
- MODEL_CAPABLE_CLI_REVIEWERS,
- reviewerLabel,
} from '../cos/constants';
-// The CLI reviewers named in the help text below, derived from the roster the
-// schema and `pickCodeReviewDefaults` generate from rather than spelled out — the
-// literal sentence drifted twice as reviewers shipped (#3839). Adding a reviewer
-// to MODEL_CAPABLE_CLI_REVIEWERS now updates this copy with no edit here.
-const CLI_REVIEWER_LIST = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' })
- .format(MODEL_CAPABLE_CLI_REVIEWERS.map(reviewerLabel));
-
// Global Code Review Defaults — the chain the Review Loop uses when a task or
// task-type config didn't pin its own reviewers. Owns the Settings › Code
// Reviewers tab (it used to sit at the top of the AI Providers page, where it
@@ -124,7 +115,7 @@ export default function CodeReviewersTab() {
<h2 className="text-base font-semibold text-white">Code Review Defaults</h2>
</div>
<p className="text-xs text-gray-500">
- Default Review Loop reviewer chain — used by ad-hoc CoS tasks and task-type schedules that haven't pinned their own. Leave it empty to keep code review disabled by default. Local-LLM reviewers route the diff through PortOS's local code-review endpoint; the {CLI_REVIEWER_LIST} reviewers invoke their CLI directly. Each runs the model picked on its row — choose <span className="font-mono">Custom…</span> to type an id its catalog doesn't list, such as an installed Ollama model for an Ollama-backed Claude.
+ Choose providers and models for the default review chain used by CoS tasks and schedules without their own override. Leave the chain empty to disable code review by default. Provider reviews retain the selected provider's configuration; existing harness and GitHub reviewer choices remain available below. Choose <span className="font-mono">Custom…</span> on a reviewer row to enter a model absent from its catalog.
</p>
{loadError && (
diff --git a/client/src/components/settings/CodeReviewersTab.test.jsx b/client/src/components/settings/CodeReviewersTab.test.jsx
index 9c2e5cdc53..f427a70da2 100644
--- a/client/src/components/settings/CodeReviewersTab.test.jsx
+++ b/client/src/components/settings/CodeReviewersTab.test.jsx
@@ -8,9 +8,8 @@ vi.mock('../../services/api', () => ({
updateSettings: vi.fn(),
}));
-vi.mock('../../hooks/useReviewerModelOptions', () => ({
- default: () => ({ ctxById: {} }),
-}));
+const pickerData = vi.hoisted(() => ({ current: { ctxById: {} } }));
+vi.mock('../../hooks/useReviewerModelOptions', () => ({ default: () => pickerData.current }));
vi.mock('../ui/Toast', () => ({
default: {
@@ -22,12 +21,45 @@ vi.mock('../ui/Toast', () => ({
describe('CodeReviewersTab', () => {
beforeEach(() => {
vi.clearAllMocks();
+ pickerData.current = { ctxById: {} };
});
afterEach(() => {
cleanup();
});
+ it('adds an arbitrary enabled provider, saves its model, reloads it and clears the pin on removal', async () => {
+ pickerData.current = {
+ loaded: true,
+ providers: [
+ { id: 'example-gpu', name: 'Example GPU', type: 'api', enabled: true, models: ['coder-a', 'coder-b'] },
+ { id: 'disabled-api', name: 'Disabled API', type: 'api', enabled: false, models: ['other'] },
+ ],
+ optionsByReviewer: { 'provider:example-gpu': ['coder-a', 'coder-b'] },
+ freeText: { 'provider:example-gpu': true },
+ };
+ api.getCodeReviewDefaults.mockResolvedValue({ reviewers: ['copilot'], codexModel: 'legacy-model' });
+ api.updateSettings.mockResolvedValue({});
+ const view = render(<CodeReviewersTab />);
+ const provider = await screen.findByLabelText('Provider');
+ expect(screen.queryByRole('option', { name: 'Disabled API' })).not.toBeInTheDocument();
+ fireEvent.change(provider, { target: { value: 'example-gpu' } });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Model', exact: true }), { target: { value: 'coder-b' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add provider reviewer' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Save defaults' }));
+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledTimes(1));
+ const saved = api.updateSettings.mock.calls[0][0].codeReview;
+ expect(saved).toMatchObject({ reviewers: ['copilot', 'provider:example-gpu'], providerModels: { 'provider:example-gpu': 'coder-b' }, codexModel: 'legacy-model' });
+ view.unmount();
+ api.getCodeReviewDefaults.mockResolvedValue(saved);
+ render(<CodeReviewersTab />);
+ expect(await screen.findByLabelText('Model for Example GPU')).toHaveValue('coder-b');
+ fireEvent.click(screen.getByLabelText('Remove Example GPU'));
+ fireEvent.click(screen.getByRole('button', { name: 'Save defaults' }));
+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledTimes(2));
+ expect(api.updateSettings.mock.calls[1][0].codeReview).toMatchObject({ reviewers: ['copilot'], providerModels: {} });
+ });
+
it('renders loading state initially and populates panel when fetch succeeds', async () => {
api.getCodeReviewDefaults.mockResolvedValue({
reviewers: ['codex'],
diff --git a/client/src/hooks/useReviewerModelOptions.js b/client/src/hooks/useReviewerModelOptions.js
index 4358005ef1..66d0f43c24 100644
--- a/client/src/hooks/useReviewerModelOptions.js
+++ b/client/src/hooks/useReviewerModelOptions.js
@@ -158,6 +158,8 @@ export default function useReviewerModelOptions() {
return [reviewer, matched];
})
);
+ for (const provider of providers || []) providersByReviewer[`provider:${provider.id}`] = [provider];
+ const providerReviewers = (providers || []).map(provider => `provider:${provider.id}`);
const providersFor = (reviewer) => providersByReviewer[reviewer] || [];
// `selectableModelsForProvider` owns the per-provider normalization (today:
@@ -195,6 +197,7 @@ export default function useReviewerModelOptions() {
const ollama = localIds('ollama');
const optionsByReviewer = {
+ ...Object.fromEntries(providerReviewers.map(reviewer => [reviewer, providerTiers(reviewer)])),
lmstudio: localIds('lmstudio'),
ollama,
codex: providerTiers('codex'),
@@ -223,6 +226,7 @@ export default function useReviewerModelOptions() {
};
const defaultModels = {
+ ...Object.fromEntries(providerReviewers.map(reviewer => [reviewer, providerDefault(reviewer)])),
lmstudio: localDefault('lmstudio'),
ollama: localDefault('ollama'),
codex: providerDefault('codex'),
@@ -264,6 +268,7 @@ export default function useReviewerModelOptions() {
};
return {
+ providers: providers || [],
optionsByReviewer,
defaultModels,
modelEffortLevels,
@@ -280,7 +285,7 @@ export default function useReviewerModelOptions() {
// namespaces the Zen catalog never lists. Derived from the rosters so a
// reviewer added to either one can't silently default to the wrong control.
freeText: Object.fromEntries(
- MODEL_SELECTABLE_REVIEWERS.map((r) => [r, !PROBED_LOCAL_BACKENDS.includes(r)])
+ [...MODEL_SELECTABLE_REVIEWERS, ...providerReviewers].map((r) => [r, !PROBED_LOCAL_BACKENDS.includes(r)])
),
unavailable: {
lmstudio: localStatus?.lmstudio?.available === false,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 12c3c628fc..9d015f867d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -66,8 +66,8 @@ grep -i "what you want to do" client/src/lib/README.md
| `grokVideoClip.js` | Re-export of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
| `reactorVideoClip.js` | Re-export of `server/lib/reactorVideoClip.js` — `REACTOR_MAX_PROMPT_LENGTH` (800, counted in the VideoGen prompt field before submit), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS`, the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()`, and the canvas contract `REACTOR_CANVASES` / `REACTOR_ASPECTS` / `REACTOR_DEFAULT_ASPECT` / `reactorCanvas()` / `nearestReactorAspect()`. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
-| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. |
-| `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. |
+| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. Also preserves provider-backed model pins in the additive `providerModels` map. |
+| `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. `isProviderReviewer` recognizes the shared `provider:<id>` identity alongside legacy harness slugs. |
| `loraEffect.js` | How the LoRA manager card renders an adapter-effect measurement (#4872). `LORA_EFFECT_STATUSES` is re-exported from `server/lib/loraEffect.js`; `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (only `zero` is styled as an error, because only `zero` refuses a render server-side) and `loraEffectDetail(report)` are client-only — the detail line returns `null` when the badge already says everything, where the server's `formatLoraEffect` always returns a sentence for its log. |
| `loraTriggers.js` | The picker's `+ trigger` append (#4665). `firstTriggerWord` / `promptHasTriggerWord` / `separatorFor` are re-exported from `server/lib/loraTriggers.js`, so the hint reads the rule the render enforces. `appendTriggerWords(prompt, words, effectivePrompt?)` is client-only: it adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`, including the shared LTX + MiniMax H3 Ref2VA audio-to-video runtime predicate. |
diff --git a/client/src/lib/reviewerModels.js b/client/src/lib/reviewerModels.js
index 3cd9641ef6..45f389a4c0 100644
--- a/client/src/lib/reviewerModels.js
+++ b/client/src/lib/reviewerModels.js
@@ -1,3 +1,4 @@
+import { isProviderReviewer } from './reviewerPins';
import {
MODEL_SELECTABLE_REVIEWERS,
MAX_REVIEWER_MODEL_LENGTH,
@@ -13,7 +14,8 @@ import {
* The Code Review Defaults settings slice persists ONE SCALAR PER REVIEWER
* (`codexModel`, `claudeModel`, `lmstudioModel`, `ollamaModel`, and the matching
* `<reviewer>Effort` scalars) and stays that way — the encoding crosses installs,
- * so changing it would need a migration for zero gain. Everything else (the
+ * so legacy scalars remain readable. Provider-backed model pins are additive in
+ * `providerModels`, keyed by `provider:<id>`. Everything else (the
* ReviewerPicker table, per-task metadata, the slashdo token builders) speaks the
* token-keyed MAP shape the `~opt` / `~max` controls already use, so the two need
* one documented conversion point rather than a hand-rolled loop in each consumer.
@@ -47,6 +49,13 @@ function pinScalarAdapters(roster, suffix, validateOne) {
return {
fromDefaults: (defaults) => {
const out = {};
+ if (suffix === 'Model') {
+ for (const [key, raw] of Object.entries(defaults?.providerModels || {})) {
+ if (!isProviderReviewer(key) || typeof raw !== 'string') continue;
+ const value = validateOne(raw, key);
+ if (value) out[key] = value;
+ }
+ }
for (const reviewer of roster) {
const raw = defaults?.[`${reviewer}${suffix}`];
if (typeof raw !== 'string') continue;
@@ -55,9 +64,10 @@ function pinScalarAdapters(roster, suffix, validateOne) {
}
return out;
},
- toDefaults: (pins) => Object.fromEntries(
- roster.map((reviewer) => [`${reviewer}${suffix}`, pins?.[reviewer] || undefined])
- )
+ toDefaults: (pins) => ({
+ ...Object.fromEntries(roster.map((reviewer) => [`${reviewer}${suffix}`, pins?.[reviewer] || undefined])),
+ ...(suffix === 'Model' ? { providerModels: Object.fromEntries(Object.entries(pins || {}).filter(([key]) => isProviderReviewer(key))) } : {})
+ })
};
}
diff --git a/client/src/lib/reviewerPins.js b/client/src/lib/reviewerPins.js
index 42d10d863a..cf5f88328e 100644
--- a/client/src/lib/reviewerPins.js
+++ b/client/src/lib/reviewerPins.js
@@ -264,3 +264,6 @@ export function normalizeReviewers(meta) {
}
return out.length ? out : [...DEFAULT_REVIEWERS];
}
+
+// Stable provider-backed reviewer identity; mirror of the server vocabulary.
+export const isProviderReviewer = (value) => typeof value === 'string' && /^provider:[a-z0-9][a-z0-9-]{0,79}$/.test(value);
diff --git a/server/lib/README.md b/server/lib/README.md
index ecf5bcdf15..d583b6d77c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -165,7 +165,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. `parseAntigravityModelList(stdout)` parses `agy models` rows — accepts both the modern `<id>\t<Label>` shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's `internal/antigravity.js`; used by both the provider-catalog refresh and Image Gen's agy model picker). `isAntigravityModelId(id)` is the same id shape as a bare predicate, for spawn sites building an `agy --model` argv from a value no route schema bounded. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. |
| `llmText.js` | Pure LLM-output text helpers — `stripCodeFences` (unfence a model reply) and `parseLLMJSON` (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration. |
| `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `services/promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |
-| `reviewerConfig.js` | Review-Loop reviewer vocabulary (split out of `cosValidation.js`, #5702; Zod-free): the reviewer roster + aliases (`REVIEWER_VALUES` / `REVIEWER_ALIASES` / `DEFAULT_REVIEWER`), the local-LLM / PortOS-only / model-capable / effort-selectable subsets, the slug→CLI-binary map (`REVIEWER_CLI_BINARIES`, `isCliReviewer`, `reviewerCliBinary`), the keyed model/effort/max-rounds pin normalizers + resolvers (`normalizeReviewers`, `normalizeReviewerModels`, `normalizeReviewerEfforts`, `resolveReviewerConfig`, `resolveClaimReviewerConfig`, `KEYED_REVIEWER_PINS`), the override-key rosters that say when a task has pinned its own reviewers (`REVIEWER_OVERRIDE_KEYS` — everything the picker writes and its reset clears; `REVIEWER_LIST_OVERRIDE_KEYS` / `hasReviewerOverride` — only the keys that can change the resolved LIST), and the emitters that render a reviewer set into slashdo argv (`buildReviewWithArgs`, `buildReviewersCsv`) and into agent-prompt notes (`buildReviewerPinNote`, `buildReviewerEffortNote`). Re-exported flat by `cosValidation.js`, so existing `validation.js` imports keep resolving. |
+| `reviewerConfig.js` | Review-Loop reviewer vocabulary (split out of `cosValidation.js`, #5702; Zod-free): the reviewer roster + aliases (`REVIEWER_VALUES` / `REVIEWER_ALIASES` / `DEFAULT_REVIEWER`), the local-LLM / PortOS-only / model-capable / effort-selectable subsets, the slug→CLI-binary map (`REVIEWER_CLI_BINARIES`, `isCliReviewer`, `reviewerCliBinary`), the keyed model/effort/max-rounds pin normalizers + resolvers (`normalizeReviewers`, `normalizeReviewerModels`, `normalizeReviewerEfforts`, `resolveReviewerConfig`, `resolveClaimReviewerConfig`, `KEYED_REVIEWER_PINS`), the override-key rosters that say when a task has pinned its own reviewers (`REVIEWER_OVERRIDE_KEYS` — everything the picker writes and its reset clears; `REVIEWER_LIST_OVERRIDE_KEYS` / `hasReviewerOverride` — only the keys that can change the resolved LIST), and the emitters that render a reviewer set into slashdo argv (`buildReviewWithArgs`, `buildReviewersCsv`) and into agent-prompt notes (`buildReviewerPinNote`, `buildReviewerEffortNote`). Re-exported flat by `cosValidation.js`, so existing `validation.js` imports keep resolving. Provider-backed identities use `provider:<id>` (`isProviderReviewer`, `isReviewer`, `isToolFreeReviewer`) and additive `providerModels` defaults; legacy scalar pins stay compatible. |
| `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, gatewayKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key a gateway-backed wrapper inherits from the API record of its own gateway id unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. |
| `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). |
| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. |
@@ -237,7 +237,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
-| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
+| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. |
| `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |
| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` predicate, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. Also owns `buildCodexOssArgs` — the `--oss --local-provider <ns>` pair emitted from a record's `ollamaBacked` marker, so the Codex harness runs on a local model without rewriting the user's `~/.codex/config.toml` (the record-classification half of that lives in `providerModels.js`, so `providerPrerequisites.js` can classify a codex record without importing a vendor argv module). |
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index c5606b6107..f5ffb15370 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -23,6 +23,9 @@ import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, gua
import { buildCliChildEnv } from './cliChildEnv.js';
import { modelPinIsOffered } from './localProviderRuntime.js';
import { filterCallerModeEligible } from './callerModePolicy.js';
+import { buildVendorSpawnConfig, supportsPublicReviewProvider } from './providerVendors.js';
+import { isPublicReviewNoToolProfile } from './agentExecutionProfiles.js';
+import { resolveCliModel } from './providerModels.js';
// How much stderr to hand back to callers. Enough to carry a rate-limit banner
// or a stack's first frames, short enough to embed in an error message or a
@@ -99,10 +102,11 @@ export function pickCliProvider(providers, config = {}) {
* @param {number} [args.timeoutMs] - SIGTERM after this many ms (default 300000)
* @param {(chunk: string, stream: 'stdout'|'stderr') => void} [args.onData] - live output callback
* @param {NodeJS.ProcessEnv} [args.baseEnv] - base env for the child (default process.env); the shared child-env composer filters inherited variables. Explicit provider.envVars still overlays it.
+ * @param {string} [args.safetyProfile] - Optional maintained no-tool profile. Refuses unsupported providers and extra argv; both argv and environment use the same profile.
* @returns {Promise<{ text: string, exitCode: number, stderr: string, partial: boolean, stderrTail: string } | { error: string, exitCode?: number, stderr?: string, stderrTail?: string }>}
*/
export function runCliProviderPrompt(args = {}) {
- const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData, baseEnv = process.env } = args;
+ const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData, baseEnv = process.env, safetyProfile = null } = args;
if (!provider?.command) {
return Promise.resolve({ error: 'Provider has no command configured' });
@@ -110,11 +114,17 @@ export function runCliProviderPrompt(args = {}) {
if (typeof prompt !== 'string' || prompt.length === 0) {
return Promise.resolve({ error: 'prompt must be a non-empty string' });
}
+ if (safetyProfile && (!isPublicReviewNoToolProfile(safetyProfile) || !supportsPublicReviewProvider(provider) || extraArgs.length)) {
+ return Promise.resolve({ error: 'Provider has no enforced tool-free review mode, or extra arguments would override it.' });
+ }
// Clone with the per-call model as defaultModel so buildCliArgs injects the
// right --model/-m flag for this provider's CLI convention.
- const effectiveProvider = { ...provider, defaultModel: model ?? provider.defaultModel };
- const builtArgs = [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];
+ const effectiveProvider = { ...provider, apiKey: provider.apiKey, defaultModel: model ?? provider.defaultModel };
+ const restrictedConfig = safetyProfile ? buildVendorSpawnConfig(effectiveProvider, {
+ safetyProfile, effectiveModel: resolveCliModel(effectiveProvider.defaultModel), effort: effectiveProvider.effort,
+ }) : null;
+ const builtArgs = restrictedConfig?.args || [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];
// Deliver the prompt per provider convention: antigravity gets it as the
// --print VALUE (no stdin); grok's `--prompt-file /dev/stdin` is fed via stdin
// on POSIX / a temp file on Windows (useStdin=false); everyone else via stdin.
@@ -140,6 +150,7 @@ export function runCliProviderPrompt(args = {}) {
baseEnv,
provider: effectiveProvider,
cwd: effectiveCwd,
+ safetyProfile,
});
// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap
@@ -204,7 +215,9 @@ export function runCliProviderPrompt(args = {}) {
if (code !== 0 && !text) {
return done({ error: (stderr.trim().slice(0, STDERR_TAIL_LIMIT) || `${provider.command} exited with code ${code}`), exitCode: code, stderr, stderrTail });
}
- done({ text, exitCode: code, stderr, partial: code !== 0, stderrTail });
+ done({ text, exitCode: code, stderr, partial: code !== 0, stderrTail,
+ ...(restrictedConfig?.streamFormat ? { streamFormat: restrictedConfig.streamFormat } : {}),
+ });
});
});
}
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index 494064dae9..4de2b01a28 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -97,6 +97,35 @@ describe('pickCliProvider', () => {
});
describe('runCliProviderPrompt', () => {
+ it('refuses unknown safety profiles, unsupported commands, and extra arguments before spawning', async () => {
+ for (const args of [
+ { provider: cli('claude'), safetyProfile: 'unknown-profile' },
+ { provider: cli('custom-agent'), safetyProfile: 'public-review-gate' },
+ { provider: cli('claude'), safetyProfile: 'public-review-gate', extraArgs: ['--dangerously-skip-permissions'] },
+ ]) {
+ expect(await runCliProviderPrompt({ ...args, prompt: 'untrusted diff' })).toMatchObject({ error: expect.stringContaining('no enforced tool-free') });
+ }
+ });
+
+ it.skipIf(process.platform === 'win32')('enforces the shared no-tool argv and environment on an actual child', async () => {
+ const { mkdtemp, writeFile, rm } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const dir = await mkdtemp(join(tmpdir(), 'review-cli-test-'));
+ const command = join(dir, 'claude');
+ await writeFile(command, '#!/usr/bin/env node\nprocess.stdin.resume(); process.stdin.on("end", () => process.stdout.write(JSON.stringify({ args: process.argv.slice(2), forgeToken: process.env.GH_TOKEN || null })));', { mode: 0o755 });
+ const result = await runCliProviderPrompt({
+ provider: { ...cli('example-claude'), command, args: ['--dangerously-skip-permissions', '--model', 'wrong-model'], envVars: { GH_TOKEN: 'example-secret' } },
+ model: 'pinned-model', prompt: 'untrusted diff', cwd: dir, safetyProfile: 'public-review-gate',
+ }).finally(() => rm(dir, { recursive: true, force: true }));
+ expect(result.partial).toBe(false);
+ const child = JSON.parse(result.text);
+ expect(child.args).toEqual(expect.arrayContaining(['--restricted', '--tools', '', '--model', 'pinned-model']));
+ expect(child.args).not.toContain('--dangerously-skip-permissions');
+ expect(child.args).not.toContain('wrong-model');
+ expect(child.forgeToken).toBeNull();
+ });
+
it('rejects a missing command without spawning', async () => {
const result = await runCliProviderPrompt({ provider: { id: 'x' }, prompt: 'hi' });
expect(result.error).toMatch(/no command/i);
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 4844702e3e..8ea47c4683 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -30,7 +30,8 @@ import {
MODEL_CAPABLE_CLI_REVIEWERS,
MODEL_SELECTABLE_REVIEWERS,
REVIEWER_ALIASES,
- REVIEWER_VALUES,
+ isReviewer,
+ isToolFreeReviewer,
REVIEW_STOP_MODES,
normalizeOptionalReviewers,
normalizeReviewUsernames,
@@ -157,6 +158,8 @@ export const orchestrationProfilesSettingsSchema = z.array(namedOrchestrationPro
const orchestrationModeInputSchema = z.preprocess(emptyToUndefined, z.enum(ORCHESTRATION_MODES).optional());
const orchestrationModeUpdateSchema = z.preprocess(emptyToNull, z.enum(ORCHESTRATION_MODES).nullable().optional());
+const reviewerSchema = z.string().refine(isReviewer, 'Unknown reviewer');
+
export const createCosTaskSchema = z.object({
description: z.string().min(1),
diagnostics: cosTaskDiagnosticsSchema.optional(),
@@ -238,11 +241,11 @@ export const createCosTaskSchema = z.object({
),
reviewer: z.preprocess(
v => v === '' ? undefined : (typeof v === 'string' ? (REVIEWER_ALIASES[v] ?? v) : v),
- z.enum(REVIEWER_VALUES).optional()
+ reviewerSchema.optional()
),
reviewers: z.preprocess(
v => Array.isArray(v) ? v.map(r => (typeof r === 'string' ? (REVIEWER_ALIASES[r] ?? r) : r)) : v,
- z.array(z.enum(REVIEWER_VALUES)).optional()
+ z.array(reviewerSchema).optional()
),
reviewStopMode: z.enum(REVIEW_STOP_MODES).optional(),
reviewerApplies: z.preprocess(
@@ -326,7 +329,7 @@ export const updateCosTaskSchema = z.object({
export const challengeTaskSchema = z.object({
reason: z.string().trim().min(1).max(5000),
evidence: z.string().trim().max(20_000).optional(),
- reviewer: z.enum(REVIEWER_VALUES).optional(),
+ reviewer: reviewerSchema.optional(),
});
// Automatic re-check request (#2471). Instead of a human `outcome`, the resolver
@@ -337,7 +340,7 @@ export const challengeTaskSchema = z.object({
// re-run by the follow-up agent itself, which then resolves with an explicit
// `outcome`.
export const challengeRecheckSchema = z.object({
- backend: z.enum(LOCAL_LLM_REVIEWERS),
+ backend: z.string().refine(isToolFreeReviewer),
model: z.string().trim().min(1).optional(),
diff: z.string().min(1).max(500_000),
});
@@ -582,9 +585,10 @@ export const taskTemplateFromTaskSchema = z.object({
// `claudeModel` doubles as the Ollama model id when the user runs an
// Ollama-backed `claude` (isOllamaClaudeProvider) as their reviewer.
export const codeReviewSettingsSchema = z.object({
+ providerModels: z.preprocess(normalizeReviewerModels, z.record(z.string()).optional()),
reviewers: z.preprocess(
v => Array.isArray(v) ? v.map(r => (typeof r === 'string' ? (REVIEWER_ALIASES[r] ?? r) : r)) : v,
- z.array(z.enum(REVIEWER_VALUES)).optional()
+ z.array(reviewerSchema).optional()
),
// Arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`) requested as PR
// reviewers to gate the merge, appended to `--review-with` after the keyed
@@ -1014,7 +1018,7 @@ export function sanitizeTaskMetadata(raw) {
}
// `reviewer` is a legacy single constrained string.
const normalizedReviewer = REVIEWER_ALIASES[raw.reviewer] || raw.reviewer;
- if (Object.prototype.hasOwnProperty.call(raw, 'reviewer') && REVIEWER_VALUES.includes(normalizedReviewer)) {
+ if (Object.prototype.hasOwnProperty.call(raw, 'reviewer') && isReviewer(normalizedReviewer)) {
clean.reviewer = normalizedReviewer;
hasKeys = true;
}
@@ -1024,7 +1028,7 @@ export function sanitizeTaskMetadata(raw) {
const list = [];
for (const r of raw.reviewers) {
const normalized = REVIEWER_ALIASES[r] || r;
- if (REVIEWER_VALUES.includes(normalized) && !seen.has(normalized)) { seen.add(normalized); list.push(normalized); }
+ if (isReviewer(normalized) && !seen.has(normalized)) { seen.add(normalized); list.push(normalized); }
}
if (list.length) { clean.reviewers = list; hasKeys = true; }
}
diff --git a/server/lib/reviewerConfig.js b/server/lib/reviewerConfig.js
index d0e51ed980..8604196151 100644
--- a/server/lib/reviewerConfig.js
+++ b/server/lib/reviewerConfig.js
@@ -31,6 +31,11 @@ import { CURSOR_COMMAND } from './cursor.js';
// they are PORTOS_ONLY_REVIEWERS.
// Mirrored in client/src/components/cos/constants.js → REVIEWER_OPTIONS.
export const REVIEWER_VALUES = ['copilot', 'claude', 'antigravity', 'codex', 'grok', 'cursor', 'pi', 'opencode', 'kimi', 'lmstudio', 'ollama', 'mtplx'];
+// Provider records retain their own identity instead of collapsing to a harness.
+export const isProviderReviewer = (value) => typeof value === 'string' && /^provider:[a-z0-9][a-z0-9-]{0,79}$/.test(value);
+export const isReviewer = (value) => REVIEWER_VALUES.includes(value) || isProviderReviewer(value);
+export const isToolFreeReviewer = (value) => LOCAL_LLM_REVIEWERS.includes(value) || isProviderReviewer(value);
+
export const REVIEWER_ALIASES = { gemini: 'antigravity', 'cursor-agent': 'cursor' };
export const DEFAULT_REVIEWER = 'copilot';
export const DEFAULT_REVIEWERS = [];
@@ -134,7 +139,7 @@ export function reviewerModelFlag(reviewer) {
* @returns {boolean}
*/
export function isCliReviewer(reviewer) {
- return reviewer !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(reviewer);
+ return reviewer !== DEFAULT_REVIEWER && !isToolFreeReviewer(reviewer);
}
/**
@@ -287,7 +292,7 @@ function normalizeReviewerToken(raw) {
return user ? `@${user}` : null;
}
const slug = REVIEWER_ALIASES[trimmed] ?? trimmed;
- return REVIEWER_VALUES.includes(slug) ? slug : null;
+ return isReviewer(slug) ? slug : null;
}
/**
@@ -459,7 +464,7 @@ const REVIEWER_MODEL_FORBIDDEN_RE = /[[\],\r\n\t]/;
* naming a reviewer that takes no model. Pass `reviewer` to apply that last check.
*/
export function normalizeReviewerModel(raw, reviewer = null) {
- if (reviewer !== null && !MODEL_SELECTABLE_REVIEWERS.includes(reviewer)) return undefined;
+ if (reviewer !== null && !MODEL_SELECTABLE_REVIEWERS.includes(reviewer) && !isProviderReviewer(reviewer)) return undefined;
if (typeof raw !== 'string') return undefined;
const model = raw.trim();
if (!model || model.length > MAX_REVIEWER_MODEL_LENGTH) return undefined;
@@ -520,7 +525,7 @@ export const resolveReviewerModels = keyedReviewerPinResolver(normalizeReviewerM
* map form.
*/
export function reviewerModelsFromDefaults(defaults) {
- const out = {};
+ const out = Object.fromEntries(Object.entries(normalizeReviewerModels(defaults?.providerModels) || {}).filter(([key]) => isProviderReviewer(key)));
for (const r of MODEL_SELECTABLE_REVIEWERS) {
// Re-checked here, not trusted: settings.json is hand-editable, and a value
// stored before the scalars were validated must not surface as a pin the token
@@ -710,8 +715,8 @@ export function claimSafeReviewers(reviewers) {
export function prioritizeToolFreeReviewers(reviewers) {
const normalized = Array.isArray(reviewers) ? reviewers : [];
return [
- ...normalized.filter((reviewer) => LOCAL_LLM_REVIEWERS.includes(reviewer)),
- ...normalized.filter((reviewer) => !LOCAL_LLM_REVIEWERS.includes(reviewer)),
+ ...normalized.filter((reviewer) => isToolFreeReviewer(reviewer)),
+ ...normalized.filter((reviewer) => !isToolFreeReviewer(reviewer)),
];
}
@@ -1012,7 +1017,7 @@ export const reviewerTokenSlug = (token) => String(token).split('[')[0].split('~
*/
export function splitSlashdoReviewerTokens(tokens) {
const trimmed = (Array.isArray(tokens) ? tokens : []).map(t => String(t).trim()).filter(Boolean);
- const isSlashdoToken = t => t.startsWith('@') || !PORTOS_ONLY_REVIEWERS.includes(reviewerTokenSlug(t));
+ const isSlashdoToken = t => t.startsWith('@') || (!PORTOS_ONLY_REVIEWERS.includes(reviewerTokenSlug(t)) && !isProviderReviewer(reviewerTokenSlug(t)));
return {
flagTokens: trimmed.filter(isSlashdoToken),
portosOnly: [...new Set(trimmed.filter(t => !isSlashdoToken(t)).map(reviewerTokenSlug))],
@@ -1147,14 +1152,14 @@ export function normalizeReviewers(meta, fallback = DEFAULT_REVIEWERS) {
const out = [];
for (const r of source) {
const normalized = REVIEWER_ALIASES[r] || r;
- if (REVIEWER_VALUES.includes(normalized) && !seen.has(normalized)) { seen.add(normalized); out.push(normalized); }
+ if (isReviewer(normalized) && !seen.has(normalized)) { seen.add(normalized); out.push(normalized); }
}
if (out.length) return out;
const fallbackList = [];
const fallbackSeen = new Set();
for (const r of Array.isArray(fallback) ? fallback : []) {
const normalized = REVIEWER_ALIASES[r] || r;
- if (REVIEWER_VALUES.includes(normalized) && !fallbackSeen.has(normalized)) {
+ if (isReviewer(normalized) && !fallbackSeen.has(normalized)) {
fallbackSeen.add(normalized);
fallbackList.push(normalized);
}
diff --git a/server/lib/reviewerConfig.test.js b/server/lib/reviewerConfig.test.js
index f74da732cb..3e006c2828 100644
--- a/server/lib/reviewerConfig.test.js
+++ b/server/lib/reviewerConfig.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
describeReviewerCli,
+ isProviderReviewer,
isCliReviewer,
reviewerCliBinary,
DEFAULT_REVIEWER,
@@ -420,6 +421,9 @@ describe('client mirror of the reviewer vocabulary', () => {
it('matches the server reviewer roster', async () => {
const client = await import('../../client/src/lib/reviewerPins.js');
expect([...client.REVIEWER_VALUES].sort()).toEqual([...REVIEWER_VALUES].sort());
+ for (const token of ['provider:example-gpu', 'provider:custom-1', 'provider:', 'provider:foo,claude', 'provider:foo~opt', 'provider:foo[model]', 'provider:UPPER', 'claude']) {
+ expect(client.isProviderReviewer(token)).toBe(isProviderReviewer(token));
+ }
});
// Aliases resolve slugs already stored on tasks (`gemini`, `cursor-agent`). One
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 8fc1e9ef74..858352f1e6 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -661,7 +661,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// and run the workflow without the description context needed to file the
// issue. Per-category gate -> only cos-tasks sync pauses until the peer
// upgrades.
- cosTasks: 7,
+ // v8 = provider:<id> reviewers. Older peers drop these identities and could
+ // execute a task without its required review. Gate only task synchronization.
+ cosTasks: 8,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/routes/codeReview.js b/server/routes/codeReview.js
index 7bd35f5c50..22de15e3fc 100644
--- a/server/routes/codeReview.js
+++ b/server/routes/codeReview.js
@@ -1,7 +1,7 @@
import { Router } from 'express'
import { z } from 'zod'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
-import { validateRequest, LOCAL_LLM_REVIEWERS, normalizeReviewerEffort, reviewerEffortLevels, reviewerEffortsFromDefaults } from '../lib/validation.js'
+import { validateRequest, isToolFreeReviewer, isProviderReviewer, reviewerModelsFromDefaults, normalizeReviewerEffort, reviewerEffortLevels, reviewerEffortsFromDefaults } from '../lib/validation.js'
import { getSettings } from '../services/settings.js'
import { runLocalCodeReview, getCodeReviewDefaults, getReviewerCliInstalled } from '../services/codeReview.js'
@@ -20,7 +20,7 @@ const router = Router()
// silently drop it — a 200 with the effort ignored instead of a 400. Same
// normalizer both places, so they can't disagree.
const localReviewRequestSchema = z.object({
- backend: z.enum(LOCAL_LLM_REVIEWERS),
+ backend: z.string().refine(isToolFreeReviewer),
model: z.string().optional(),
effort: z.string().optional(),
diff: z.string().min(1, 'diff must be non-empty'),
@@ -60,7 +60,9 @@ router.post('/local', asyncHandler(async (req, res) => {
// Keyed off the roster's `<reviewer>Model` scalar rather than a per-backend
// branch, so a backend added to LOCAL_LLM_REVIEWERS reads its own configured
// model instead of silently inheriting another backend's.
- const configured = settings.codeReview?.[`${body.backend}Model`]
+ const configured = isProviderReviewer(body.backend)
+ ? reviewerModelsFromDefaults(settings.codeReview)[body.backend]
+ : settings.codeReview?.[`${body.backend}Model`]
const model = body.model || configured
// Per-request effort wins over the panel default; absent in both = omit the
// field entirely so the model reasons however it normally would. The stored
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
index d125651b8c..298a4bca5e 100644
--- a/server/routes/codeReview.test.js
+++ b/server/routes/codeReview.test.js
@@ -49,6 +49,18 @@ describe('GET /api/code-review/defaults', () => {
})
describe('POST /api/code-review/local', () => {
+ it('resolves a provider-backed model default and rejects unsafe provider identities', async () => {
+ settingsSvc.getSettings.mockResolvedValue({ codeReview: { providerModels: { 'provider:example-gpu': 'pinned-coder' } } });
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({ ok: true, findings: 'NO FINDINGS' });
+ const res = await request(makeApp()).post('/api/code-review/local')
+ .send({ backend: 'provider:example-gpu', diff: 'example diff' });
+ expect(res.status).toBe(200);
+ expect(codeReviewSvc.runLocalCodeReview).toHaveBeenCalledWith(expect.objectContaining({ backend: 'provider:example-gpu', model: 'pinned-coder' }));
+ const invalid = await request(makeApp()).post('/api/code-review/local')
+ .send({ backend: 'provider:example-gpu~opt', diff: 'example diff' });
+ expect(invalid.status).toBe(400);
+ });
+
it('returns 400 when diff is empty (Zod min(1) rejection)', async () => {
const res = await request(makeApp())
.post('/api/code-review/local')
diff --git a/server/scripts/run-local-code-review.mjs b/server/scripts/run-local-code-review.mjs
index 757cfe0d18..dbd474354d 100644
--- a/server/scripts/run-local-code-review.mjs
+++ b/server/scripts/run-local-code-review.mjs
@@ -6,13 +6,19 @@
*/
import { getCodeReviewDefaults, runLocalClaimCommentReview, runLocalCodeReview } from '../services/codeReview.js';
+import { Console } from 'node:console';
+import { reviewerModelsFromDefaults } from '../lib/reviewerConfig.js';
+
+// Provider/runtime diagnostics belong on stderr; stdout is exactly one JSON
+// response for the claim procedure's jq gate.
+globalThis.console = new Console({ stdout: process.stderr, stderr: process.stderr });
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
try {
const request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
const defaults = await getCodeReviewDefaults().catch(() => null);
- const model = request.model || defaults?.[`${request.backend}Model`] || null;
+ const model = request.model || reviewerModelsFromDefaults(defaults)[request.backend] || null;
const effort = request.effort || defaults?.[`${request.backend}Effort`] || null;
const review = request.kind === 'claim-comments'
? runLocalClaimCommentReview
diff --git a/server/scripts/run-local-code-review.test.js b/server/scripts/run-local-code-review.test.js
new file mode 100644
index 0000000000..abdf59fba8
--- /dev/null
+++ b/server/scripts/run-local-code-review.test.js
@@ -0,0 +1,57 @@
+import { it, expect } from 'vitest';
+import { createServer } from 'node:http';
+import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawn } from '../lib/childProcess.js';
+
+it('runs a saved provider reviewer from the standalone claim bridge without bootstrapping PortOS', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'review-bridge-test-'));
+ const bodies = [];
+ const api = createServer((request, response) => {
+ let body = '';
+ request.on('data', chunk => { body += chunk; });
+ request.on('end', () => {
+ bodies.push(body);
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(JSON.stringify({ choices: [{ message: { content: 'NO FINDINGS' } }] }));
+ });
+ });
+ await new Promise(resolve => api.listen(0, '127.0.0.1', resolve));
+ // Run under a temporary install path: source in a CoS worktree intentionally
+ // ignores PORTOS_DATA_ROOT. Preserve this test-only junction's module paths
+ // rather than weakening that live-data protection.
+ await symlink(fileURLToPath(new URL('../', import.meta.url)), join(root, 'server'), 'junction');
+ const data = join(root, 'data');
+ await mkdir(data);
+ await writeFile(join(data, 'providers.json'), JSON.stringify({ activeProvider: 'example-gpu', providers: {
+ 'example-gpu': { id: 'example-gpu', name: 'Example GPU', type: 'api', enabled: true,
+ endpoint: `http://127.0.0.1:${api.address().port}/v1`, models: ['default-model', 'review-model'], defaultModel: 'default-model' },
+ } }));
+ await writeFile(join(data, 'settings.json'), JSON.stringify({ codeReview: {
+ reviewers: ['provider:example-gpu'], providerModels: { 'provider:example-gpu': 'review-model' },
+ } }));
+ const child = spawn(process.execPath, ['--preserve-symlinks', '--preserve-symlinks-main', join(root, 'server/scripts/run-local-code-review.mjs')], {
+ env: { ...process.env, NODE_ENV: 'test', MEMORY_BACKEND: 'file', PORTOS_DATA_ROOT: root },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ const result = await new Promise((resolve, reject) => {
+ let stdout = '';
+ let stderr = '';
+ const timeout = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('Review bridge timed out')); }, 10000);
+ child.stdout.on('data', chunk => { stdout += chunk; });
+ child.stderr.on('data', chunk => { stderr += chunk; });
+ child.on('error', error => { clearTimeout(timeout); reject(error); });
+ child.on('close', code => { clearTimeout(timeout); resolve({ code, stdout, stderr }); });
+ child.stdin.end(JSON.stringify({ backend: 'provider:example-gpu', diff: 'diff --git a/example.js b/example.js' }));
+ }).finally(async () => {
+ await new Promise(resolve => api.close(resolve));
+ await rm(root, { recursive: true, force: true });
+ });
+ expect(result.code, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({ ok: true, backend: 'provider:example-gpu', model: 'review-model', findings: 'NO FINDINGS' });
+ expect(bodies).toHaveLength(1);
+ expect(JSON.parse(bodies[0])).toMatchObject({ model: 'review-model' });
+ expect(JSON.parse(bodies[0])).not.toHaveProperty('tools');
+}, 15000);
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 272c0495fe..eac24ed4da 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -14,7 +14,7 @@ import { buildPrompt } from './promptService.js';
import { getToolsSummaryForPrompt } from './tools.js';
import { PATHS, tryReadFile } from '../lib/fileUtils.js';
import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';
-import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, isCliReviewer, resolveReviewerConfig } from '../lib/validation.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isToolFreeReviewer, isCliReviewer, resolveReviewerConfig } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { doneSentinelName } from '../lib/agentSentinel.js';
import { canTypeSlashCommands, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
@@ -942,7 +942,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// Slashdo already partitions reviewers. Plain-git completion prompts need the
// same split spelled out: local CLIs/local LLMs inspect the committed branch
// before it is public; Copilot and @login reviewers can only run after a PR.
- const isLocalReviewer = reviewer => isCliReviewer(reviewer) || LOCAL_LLM_REVIEWERS.includes(reviewer);
+ const isLocalReviewer = reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer);
const localReviewers = lightReviewers.filter(isLocalReviewer);
const localReviewRequired = localReviewers.some(reviewer => !lightOptionalReviewers.includes(reviewer));
const reviewerPositions = [
diff --git a/server/services/aiProvider.js b/server/services/aiProvider.js
index dcb99d215d..18839ee504 100644
--- a/server/services/aiProvider.js
+++ b/server/services/aiProvider.js
@@ -548,7 +548,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
return { error: retry.error };
};
- if (first.status === 400 && LM_STUDIO_NO_MODEL_RE.test(first.body || '')) {
+ if (options.allowModelRecovery !== false && first.status === 400 && LM_STUDIO_NO_MODEL_RE.test(first.body || '')) {
const loaded = await ensureLMStudioModelLoaded(provider, statusOp);
if (loaded) {
statusOp.update('start', `Calling ${provider.name || provider.id} (${loaded})…`, { model: loaded });
@@ -562,7 +562,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// "model not found". Only fires for Ollama / LM Studio providers; healing is
// a no-op (returns null) for remote/CLI providers, leaving the error as-is.
const { healMissingLocalModel, isModelNotFoundError } = await import('../services/localModelHealing.js');
- if (isModelNotFoundError(first.body || first.error)) {
+ if (options.allowModelRecovery !== false && isModelNotFoundError(first.body || first.error)) {
const healed = await healMissingLocalModel({ provider, requestedModel: model }).catch(() => null);
if (healed) {
statusOp.update('model:corrected', `"${model}" isn't installed — retrying with ${healed.model}…`, { model: healed.model });
diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.js
index 11a230b93e..ffa1d9d8e7 100644
--- a/server/services/aiProvider.test.js
+++ b/server/services/aiProvider.test.js
@@ -380,6 +380,14 @@ describe('callProviderAISimple — malformed / non-2xx responses', () => {
vi.unstubAllGlobals();
});
+ it('does not load or substitute another local model when model recovery is disabled', async () => {
+ respondWithText('No models loaded', { ok: false, status: 400 });
+ const result = await callProviderAISimple(provider, 'pinned-model', 'review this diff', { allowModelRecovery: false });
+ expect(result.error).toContain('No models loaded');
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(globalThis.fetch.mock.calls[0][1].body).model).toBe('pinned-model');
+ });
+
it('returns an error, not an empty success, on a non-JSON 200 body', async () => {
respondWithText('<html><body>502 Bad Gateway</body></html>');
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index ce6af2411e..90b0707cba 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -20,6 +20,10 @@ import { probeOpenAiModels } from '../lib/openAiModelsProbe.js'
import { normalizeOpenAiBaseUrl } from '../lib/localProviderRuntime.js'
import {
LOCAL_LLM_REVIEWERS,
+ isProviderReviewer,
+ isReviewer,
+ isToolFreeReviewer,
+ normalizeReviewerModels,
DEFAULT_REVIEWERS,
DEFAULT_REVIEW_STOP_MODE,
REVIEWER_ALIASES,
@@ -88,7 +92,7 @@ export function isLocalLlmReviewer(backend) {
function configuredReviewers(settings) {
const raw = settings && typeof settings === 'object' ? settings.codeReview : null
if (!Array.isArray(raw?.reviewers)) return []
- return Array.from(new Set(raw.reviewers.map((r) => REVIEWER_ALIASES[r] || r).filter((r) => REVIEWER_VALUES.includes(r))))
+ return Array.from(new Set(raw.reviewers.map((r) => REVIEWER_ALIASES[r] || r).filter(isReviewer)))
}
/**
@@ -119,6 +123,7 @@ export function pickCodeReviewDefaults(settings) {
// token. Normalized so a hand-edited settings.json can't smuggle in a
// non-integer or unbounded budget. Empty object = no caps configured; an
// absent key is NOT `0` (which slashdo reads as "loop until clean").
+ ...(raw?.providerModels ? { providerModels: normalizeReviewerModels(raw.providerModels) || {} } : {}),
reviewerMaxRounds: normalizeReviewerMaxRounds(raw?.reviewerMaxRounds) || {},
stopMode: REVIEW_STOP_MODES.includes(raw?.stopMode) ? raw.stopMode : DEFAULT_REVIEW_STOP_MODE,
reviewerApplies: raw?.reviewerApplies === true,
@@ -425,11 +430,62 @@ async function resolveServedModel(backend, baseUrl) {
return { model: probe.models[0], reason: null }
}
+// Resolve the exact record the user selected. Never fall back to the active
+// provider, another account, or a replacement model for a pinned reviewer.
+async function runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, timeoutMs }) {
+ const { getProviderById } = await import('./providers.js')
+ const { getAIToolkitInstance } = await import('../lib/aiToolkitState.js')
+ const providerId = backend.slice('provider:'.length)
+ // The auth-independent claim bridge has no server bootstrap. Use the same
+ // provider-store reader there without starting a server or creating runners.
+ const provider = getAIToolkitInstance()
+ ? await getProviderById(providerId)
+ : await import('../lib/aiToolkit/providers.js').then(async ({ createProviderService }) => {
+ const { PATHS } = await import('../lib/paths.js')
+ return createProviderService({ dataDir: PATHS.data }).getProviderById(providerId)
+ })
+ if (!provider || provider.enabled === false) return { ok: false, error: 'Reviewer provider is missing or disabled.' }
+ const model = pinnedModel || provider.defaultModel
+ const prompt = messages.map(message => message.content).join('\n\n')
+ const { isCodexTextTransportEnabled } = await import('../lib/codexTurn.js')
+ let result
+ if (provider.type === 'api' || isCodexTextTransportEnabled(provider)) {
+ if (!model) return { ok: false, code: 'NO_MODEL', error: 'Select a model for the reviewer provider.' }
+ const { callProviderAISimple } = await import('./aiProvider.js')
+ result = await callProviderAISimple({ ...provider, apiKey: provider.apiKey, timeout: timeoutMs, fallbackProvider: null }, model,
+ prompt, { max_tokens: 8192, allowModelRecovery: false })
+ } else {
+ const { supportsPublicReviewProvider } = await import('../lib/providerVendors.js')
+ if (!supportsPublicReviewProvider(provider)) return { ok: false, error: 'This provider has no enforced tool-free review transport. Select its API mode or a supported reviewer harness.' }
+ const { runCliProviderPrompt } = await import('../lib/cliProviderRun.js')
+ const { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE } = await import('../lib/agentExecutionProfiles.js')
+ const { mkdtemp, rm } = await import('node:fs/promises')
+ const { tmpdir } = await import('node:os')
+ const { join } = await import('node:path')
+ // No repository context or project-level CLI settings are exposed. The
+ // shared recipe and environment composer enforce the no-tool posture.
+ const cwd = await mkdtemp(join(tmpdir(), 'portos-review-'))
+ result = await Promise.resolve().then(() => runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs,
+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
+ })).finally(() => rm(cwd, { recursive: true, force: true }))
+ if (result.partial) return { ok: false, error: 'Reviewer exited before completing its response.' }
+ if (!result.error && result.streamFormat === 'stream-json') {
+ const { safeJSONLParse } = await import('../lib/jsonIo.js')
+ const final = safeJSONLParse(result.text).findLast(event => event.type === 'result')
+ result = final?.is_error || typeof final?.result !== 'string'
+ ? { error: 'Reviewer returned no successful final result.' }
+ : { text: final.result }
+ }
+ }
+ if (result.error || !result.text?.trim()) return { ok: false, error: result.error || 'Reviewer returned no content.' }
+ return { ok: true, backend, model, effort: null, content: result.text.trim() }
+}
+
async function runToolFreeLocalCompletion({ backend, model: pinnedModel, messages, effort, timeoutMs, baseUrl: requestedBaseUrl = null }) {
+ if (isProviderReviewer(backend)) return runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, timeoutMs })
if (!isLocalLlmReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
-
// Local runtime records are normalized to the OpenAI `/v1` root, while the
// legacy backend managers return the host root. Keep both forms compatible
// with the one endpoint suffix below.
@@ -518,7 +574,7 @@ async function runToolFreeLocalCompletion({ backend, model: pinnedModel, message
* defaults to the backend manager's current URL.
*/
export async function runLocalCodeReview({ backend, model, diff, effort = null, timeoutMs = 120000, baseUrl = null } = {}) {
- if (!isLocalLlmReviewer(backend)) {
+ if (!isToolFreeReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
// No model pre-check here: an unpinned model is resolved from what the backend
diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.js
new file mode 100644
index 0000000000..887563cf72
--- /dev/null
+++ b/server/services/codeReview.providers.test.js
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { access } from 'node:fs/promises';
+import { codeReviewSettingsSchema, sanitizeTaskMetadata } from '../lib/cosValidation.js';
+import { resolveReviewerConfig, buildReviewWithArgs } from '../lib/reviewerConfig.js';
+import { buildLocalReviewerInstructions } from './cosTaskPrompts.js';
+
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(), settingsEvents: { on: vi.fn() } }));
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
+vi.mock('../lib/aiToolkitState.js', () => ({ getAIToolkitInstance: () => ({}) }));
+vi.mock('./aiProvider.js', () => ({ callProviderAISimple: vi.fn() }));
+vi.mock('../lib/cliProviderRun.js', () => ({ runCliProviderPrompt: vi.fn() }));
+vi.mock('./lmStudioManager.js', () => ({ getBaseUrl: vi.fn() }));
+vi.mock('./ollamaManager.js', () => ({ getBaseUrl: vi.fn(), getModelCapabilities: vi.fn() }));
+
+const { getProviderById } = await import('./providers.js');
+const { callProviderAISimple } = await import('./aiProvider.js');
+const { runCliProviderPrompt } = await import('../lib/cliProviderRun.js');
+const { pickCodeReviewDefaults, runLocalCodeReview } = await import('./codeReview.js');
+
+const backend = 'provider:example-gpu';
+const provider = { id: 'example-gpu', name: 'Example GPU', type: 'api', enabled: true,
+ endpoint: 'https://gpu.example.com/v1', apiKey: 'example-key', defaultModel: 'default-coder',
+ fallbackProvider: 'other-provider', models: ['default-coder', 'pinned-coder'] };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getProviderById.mockResolvedValue(provider);
+ callProviderAISimple.mockResolvedValue({ text: 'NO FINDINGS' });
+});
+
+describe('configured provider reviewers', () => {
+ it('keeps a saved provider/model through settings, task metadata, prompt generation and execution', async () => {
+ const settings = codeReviewSettingsSchema.parse({ reviewers: ['codex', backend],
+ providerModels: { [backend]: 'pinned-coder' }, codexModel: 'example-cloud-model',
+ optionalReviewers: [backend], reviewerMaxRounds: { [backend]: 1 } });
+ const defaults = pickCodeReviewDefaults({ codeReview: settings });
+ const config = resolveReviewerConfig({}, defaults, defaults.reviewers);
+ const task = sanitizeTaskMetadata(config);
+ expect(task.reviewers).toEqual([backend, 'codex']);
+ expect(task.reviewerModels).toEqual({ [backend]: 'pinned-coder', codex: 'example-cloud-model' });
+ expect(task.optionalReviewers).toEqual([backend]);
+ expect(task.reviewerMaxRounds).toEqual({ [backend]: 1 });
+ const instructions = buildLocalReviewerInstructions(task.reviewers, task.reviewerModels);
+ expect(instructions).toContain(backend);
+ expect(instructions).toContain('pinned-coder');
+ expect(buildReviewWithArgs(task.reviewers)).not.toContain(backend);
+ const result = await runLocalCodeReview({ backend, model: task.reviewerModels[backend], diff: 'diff --git a/example.js b/example.js' });
+ expect(result).toMatchObject({ ok: true, backend, model: 'pinned-coder', findings: 'NO FINDINGS' });
+ expect(getProviderById).toHaveBeenCalledWith('example-gpu');
+ expect(callProviderAISimple).toHaveBeenCalledWith(
+ expect.objectContaining({ id: provider.id, endpoint: provider.endpoint, apiKey: provider.apiKey, fallbackProvider: null }),
+ 'pinned-coder', expect.stringContaining('untrusted contributor-controlled data'),
+ expect.objectContaining({ allowModelRecovery: false }),
+ );
+ expect(runCliProviderPrompt).not.toHaveBeenCalled();
+ expect(resolveReviewerConfig({ reviewerModels: {} }, defaults, defaults.reviewers).reviewerModels).toEqual({});
+ });
+
+ it('uses only this provider default when unpinned and returns provider failure without substitution', async () => {
+ callProviderAISimple.mockResolvedValue({ error: 'Selected model is unavailable' });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false, error: 'Selected model is unavailable' });
+ expect(callProviderAISimple).toHaveBeenCalledTimes(1);
+ expect(callProviderAISimple.mock.calls[0][1]).toBe('default-coder');
+ });
+
+ it.each([null, { ...provider, enabled: false }])('refuses a missing or disabled provider before inference', async record => {
+ getProviderById.mockResolvedValue(record);
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false });
+ expect(callProviderAISimple).not.toHaveBeenCalled();
+ expect(runCliProviderPrompt).not.toHaveBeenCalled();
+ });
+
+ it('uses the maintained no-tool CLI recipe in disposable scratch and accepts only a final result', async () => {
+ const cli = { ...provider, type: 'tui', command: 'claude' };
+ getProviderById.mockResolvedValue(cli);
+ runCliProviderPrompt.mockResolvedValue({ text: '{"type":"result","result":"NO FINDINGS"}', partial: false, streamFormat: 'stream-json' });
+ const result = await runLocalCodeReview({ backend, model: 'pinned-coder', diff: 'example diff' });
+ expect(result).toMatchObject({ ok: true, findings: 'NO FINDINGS' });
+ const args = runCliProviderPrompt.mock.calls[0][0];
+ expect(args).toMatchObject({ provider: cli, model: 'pinned-coder', safetyProfile: 'public-review-gate' });
+ await expect(access(args.cwd)).rejects.toThrow();
+ expect(callProviderAISimple).not.toHaveBeenCalled();
+
+ runCliProviderPrompt.mockResolvedValue({ text: '{"type":"result","is_error":true,"result":"incomplete"}', partial: false, streamFormat: 'stream-json' });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false });
+ runCliProviderPrompt.mockResolvedValue({ text: 'NO FINDINGS', partial: true });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false });
+ });
+
+ it('refuses an unsupported harness instead of spawning it with ordinary agent permissions', async () => {
+ getProviderById.mockResolvedValue({ ...provider, type: 'cli', command: 'custom-agent' });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false, error: expect.stringContaining('no enforced tool-free') });
+ expect(runCliProviderPrompt).not.toHaveBeenCalled();
+ expect(callProviderAISimple).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/cosTaskPrompts.js b/server/services/cosTaskPrompts.js
index 11e2d20563..c629edaf58 100644
--- a/server/services/cosTaskPrompts.js
+++ b/server/services/cosTaskPrompts.js
@@ -6,7 +6,7 @@
*/
import { join } from 'path';
-import { CLAIM_OVERRIDE_CONTEXT_MAX_CHARS, buildReviewerEffortNote, LOCAL_LLM_REVIEWERS } from '../lib/validation.js';
+import { CLAIM_OVERRIDE_CONTEXT_MAX_CHARS, buildReviewerEffortNote, isToolFreeReviewer } from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
import { shellQuote } from '../lib/shellQuote.js';
@@ -106,7 +106,7 @@ export const appendReviewerEffortBlock = (reviewers, reviewerEfforts, reviewerMo
appendBlock(buildReviewerEffortNote(reviewers, reviewerEfforts, { reviewerModels }));
export function buildLocalReviewerInstructions(reviewers, reviewerModels = {}, reviewerEfforts = {}, { claimCommentGate = false } = {}) {
- const localReviewers = (reviewers || []).filter((reviewer) => LOCAL_LLM_REVIEWERS.includes(reviewer));
+ const localReviewers = (reviewers || []).filter((reviewer) => isToolFreeReviewer(reviewer));
if (!localReviewers.length) return '';
const diffCommand = [
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 27bcaeb82e..398fdc69a8 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -12,6 +12,7 @@
* logic stays in cos.js while persistence lives here.
*/
+import { reviewerModelsFromDefaults } from '../lib/reviewerConfig.js';
import { readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -1392,7 +1393,7 @@ export async function resolveTaskChallengeWithRecheck(taskId, { recheck, resolve
// single-model daemon re-checks without one. It reports `code: 'NO_MODEL'` when it
// could not resolve one either, which stays a config problem (4xx) rather than the
// 502 bucket reserved for a reviewer that's actually unreachable.
- const model = recheck?.model || recheckDefaults?.[`${backend}Model`] || null;
+ const model = recheck?.model || reviewerModelsFromDefaults(recheckDefaults)[backend] || null;
console.log(`⚖️ Re-checking challenge on ${taskId} via ${backend} (${model || 'model from the backend'}${effort ? `, ${effort} effort` : ''})`);
const review = await runLocalCodeReview({ backend, model, effort, diff: recheck?.diff });
if (!review?.ok) {
diff --git a/server/services/persistentMindWorkspacePreflight.js b/server/services/persistentMindWorkspacePreflight.js
index c290028ccd..3b8755f135 100644
--- a/server/services/persistentMindWorkspacePreflight.js
+++ b/server/services/persistentMindWorkspacePreflight.js
@@ -20,7 +20,7 @@ import {
} from '../lib/persistentMindCapabilities.js';
import {
isCliReviewer,
- REVIEWER_VALUES,
+ isReviewer,
} from '../lib/validation.js';
import { compareVersions } from '../../scripts/checkNodeVersion.js';
import * as codeReview from './codeReview.js';
@@ -564,7 +564,7 @@ const inspectReviewers = async (forge, dependencies, reviewerProbe = reviewerPro
status: 'unknown',
};
}
- const fixedReviewers = Array.isArray(defaults.reviewers) ? defaults.reviewers.filter((value) => REVIEWER_VALUES.includes(value)) : [];
+ const fixedReviewers = Array.isArray(defaults.reviewers) ? defaults.reviewers.filter((value) => isReviewer(value)) : [];
const usernames = Array.isArray(defaults.usernames) ? defaults.usernames.filter((value) => typeof value === 'string' && value.trim()) : [];
const optional = new Set(Array.isArray(defaults.optionalReviewers) ? defaults.optionalReviewers : []);
const requiredEntries = fixedReviewers
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index a051d487e4..ed83bd82e1 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -2,7 +2,7 @@
* Review-loop, CI-gate, and merge prompt sections.
*/
-import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, reviewerModelFlag, resolveKeyedReviewers, buildReviewWithArgs, prioritizeToolFreeReviewers } from '../../lib/reviewerConfig.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isToolFreeReviewer, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, reviewerModelFlag, resolveKeyedReviewers, buildReviewWithArgs, prioritizeToolFreeReviewers } from '../../lib/reviewerConfig.js';
import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';
import { detectForgeCli } from '../../lib/gitForge.js';
import { shellQuote } from '../../lib/shellQuote.js';
@@ -210,7 +210,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// The orchestrator applies independently validated findings in a later step.
const reviewerApplies = false;
const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);
- const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));
+ const hasLocalLlm = reviewers.some(r => isToolFreeReviewer(r));
// Spawnable-CLI reviewers, in configured order.
const cliReviewers = reviewers.filter(isCliReviewer);
const hasCli = cliReviewers.length > 0;
@@ -377,7 +377,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// configured rather than a fixed `<lmstudio|ollama>` placeholder: naming a
// backend that isn't in the list is a 400 from the route's `z.enum`, and a
// single configured backend needs no substitution step at all.
- const localLlmBackends = LOCAL_LLM_REVIEWERS.filter(r => reviewers.includes(r));
+ const localLlmBackends = reviewers.filter(isToolFreeReviewer);
const localLlmBackendToken = localLlmBackends.length === 1
? localLlmBackends[0]
: `<${localLlmBackends.join('|')}>`;
@@ -385,8 +385,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
? ''
: ` Substitute the active reviewer name for \`${localLlmBackendToken}\`.`;
const pinnedString = (map, r) => (typeof map[r] === 'string' && map[r] ? map[r] : null);
- const localLlmPins = LOCAL_LLM_REVIEWERS
- .filter(r => reviewers.includes(r))
+ const localLlmPins = reviewers.filter(isToolFreeReviewer)
.map(r => ({ reviewer: r, model: pinnedString(reviewerModelMap, r), effort: pinnedString(reviewerEffortMap, r) }))
.filter(p => p.model || p.effort);
const localLlmPinNote = localLlmPins.map(({ reviewer, model, effort }) => {
@@ -747,7 +746,7 @@ export function buildLocalReviewLoopSection({
taskId, branchName, baseBranch, localAgentLoopBody, localAgentLoopBodyPath = null,
reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, reviewerPositions = [],
}) {
- const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || LOCAL_LLM_REVIEWERS.includes(reviewer));
+ const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer));
if (!localReviewers.length) return '';
const localReviewRequired = localReviewers.some(reviewer =>
!(Array.isArray(optionalReviewers) && optionalReviewers.some(optional => optional.toLowerCase() === reviewer.toLowerCase()))