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

Generalize review-loop CLI reviewer model threading to a reviewer-keyed map

[._.]/ Adam Eivy85570ac511d3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0662cf4707..a54aa39fdd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changes
+- **The Claude reviewer now takes an optional model, including an Ollama-backed Claude for local-only setups (#2377).** Code Review Defaults gains a **Claude model** field alongside the existing Codex one: pick a Claude tier, or — if you run `claude` pointed at a local Ollama daemon — type or pick one of your installed Ollama models, and the Review Loop invokes the reviewer as `claude --model <id>`. Under the hood the codex-only model threading is generalized into a reviewer-keyed model map, so any CLI reviewer that supports `--model` (today: Codex and Claude) threads its configured model through the review-loop follow-up with a single code path instead of a per-reviewer special case. Older in-flight review tasks that stored only the legacy Codex tier still work unchanged.
+
- **The offline service worker's cold-first-visit route gap is now a documented, accepted trade-off rather than an open question (#2424).** A route visited *only* during the very first page load (before the SW registers at `window.load`) has an uncached chunk, so an offline reload of exactly that route boots the shell but can't render until the route is visited online once more. Fully closing this would require a build-time precache manifest (workbox / vite-plugin-pwa or an emitted asset-manifest) that precaches *every* build chunk upfront — which spends first-visit bandwidth on routes the user may never open, directly against this SW's low-bandwidth goal. For a single-user app the mitigation is a one-time online load per route, so the limitation is deliberately left in place; the reasoning is now recorded inline in `client/public/sw.js` so it doesn't dangle-point at a closed issue. No behavior change.
- **CoS task-learning success rates now decay via a recency window, so a since-resolved failure burst stops signaling Layered Intelligence that work is needed (#2460).** The `byTaskType` counters in `data/cos/learning.json` are lifetime-cumulative and never age out — a provider misconfig or PTY-capture artifacts recorded as failures on a now-retired task type permanently depressed the success rate the LI reasoner reads via its `cosMetrics` source (default-on for PortOS), long after the root cause was fixed. Each task-type bucket now also carries a bounded `recentOutcomes` ring (`{ t, s }`, cap 50, mirroring the `failureSignatures.recent` precedent) that `recordTaskCompletion` appends to; a new pure `computeWindowedStats` derives a `recentSuccessRate` windowed by BOTH count and age (defaults: last 30 runs / 30 days, configurable), exposed via `getWindowedStats(taskType, { maxCount, maxAgeMs })`. The LI `cosMetrics` source now surfaces lifetime and windowed rates labeled distinctly, so a resolved failure burst self-heals without a manual `resetTaskTypeLearning`, while the lifetime counters stay intact for the dashboard/telemetry views. `recentSuccessRate` uses a `null` sentinel (never a fabricated `0%`) when the window has no samples, so the reasoner falls back to the lifetime rate. Store version bumped 1→2 with an idempotent migration (188) that initializes an EMPTY ring per task type — deliberately not backfilled from failure-only history, which would fabricate an all-failure window.
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index be56645f8c..53190667ee 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -89,7 +89,7 @@ export const AGENT_OPTIONS = [
// `server/lib/validation.js`.
export const REVIEWER_OPTIONS = [
{ value: 'copilot', label: 'Copilot', description: 'GitHub Copilot (GitHub-only)' },
- { value: 'claude', label: 'Claude', description: 'Claude CLI reviews the PR diff' },
+ { value: 'claude', label: 'Claude', description: 'Claude CLI reviews the PR diff (optional model on AI Providers → Code Review Defaults; supports an Ollama-backed Claude for local-only setups)' },
{ value: 'antigravity', label: 'Antigravity', description: 'Antigravity CLI (agy) reviews the PR diff' },
{ value: 'codex', label: 'Codex', description: 'Codex CLI reviews the PR diff (optional model tier on AI Providers → Code Review Defaults)' },
{ value: 'grok', label: 'Grok', description: 'Grok Build CLI (grok) reviews the PR diff' },
diff --git a/client/src/components/providers/CodeReviewDefaultsPanel.jsx b/client/src/components/providers/CodeReviewDefaultsPanel.jsx
index f0bc2c40ca..c1cd0f7183 100644
--- a/client/src/components/providers/CodeReviewDefaultsPanel.jsx
+++ b/client/src/components/providers/CodeReviewDefaultsPanel.jsx
@@ -21,6 +21,8 @@ export default function CodeReviewDefaultsPanel() {
const lmStudioSelectId = useId();
const ollamaSelectId = useId();
const codexSelectId = useId();
+ const claudeSelectId = useId();
+ const claudeListId = useId();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);
@@ -30,8 +32,10 @@ export default function CodeReviewDefaultsPanel() {
const [lmstudioModel, setLmstudioModel] = useState('');
const [ollamaModel, setOllamaModel] = useState('');
const [codexModel, setCodexModel] = useState('');
+ const [claudeModel, setClaudeModel] = useState('');
const [localLlmStatus, setLocalLlmStatus] = useState(null);
const [codexProvider, setCodexProvider] = useState(null);
+ const [claudeProvider, setClaudeProvider] = useState(null);
useEffect(() => {
let cancelled = false;
@@ -49,11 +53,14 @@ export default function CodeReviewDefaultsPanel() {
setLmstudioModel(defaults.lmstudioModel || '');
setOllamaModel(defaults.ollamaModel || '');
setCodexModel(defaults.codexModel || '');
+ setClaudeModel(defaults.claudeModel || '');
}
setLocalLlmStatus(status || null);
- // Codex is a CLI reviewer, so its selectable model tiers come from the
- // provider catalog (not the local-LLM status probe the others use).
- setCodexProvider((providers?.providers || []).find((p) => p.id === 'codex') || null);
+ // Codex and Claude are CLI reviewers, so their selectable model tiers come
+ // from the provider catalog (not the local-LLM status probe the others use).
+ const providerList = providers?.providers || [];
+ setCodexProvider(providerList.find((p) => p.id === 'codex') || null);
+ setClaudeProvider(providerList.find((p) => p.id === 'claude-code') || null);
setLoading(false);
});
return () => { cancelled = true; };
@@ -62,6 +69,7 @@ export default function CodeReviewDefaultsPanel() {
const needsLmStudio = reviewers.includes('lmstudio');
const needsOllama = reviewers.includes('ollama');
const needsCodex = reviewers.includes('codex');
+ const needsClaude = reviewers.includes('claude');
const lmStudioModels = useMemo(
() => localLlmStatus?.lmstudio?.models?.map((m) => m.id).filter(Boolean) || [],
@@ -75,6 +83,15 @@ export default function CodeReviewDefaultsPanel() {
() => codexProvider ? filterSelectableModels(codexProvider.models || [codexProvider.defaultModel]) : [],
[codexProvider]
);
+ // Claude reviewer suggestions span BOTH usage modes: the `claude-code` provider
+ // tiers (normal Claude) and installed Ollama models (an Ollama-backed `claude`
+ // reviewer, where `--model` selects the local model). Deduped, order-preserving.
+ // A datalist (not a hard <select>) so a user whose Ollama model id isn't in the
+ // probe list can still type it — ollama-backed model ids are arbitrary.
+ const claudeModelSuggestions = useMemo(() => {
+ const tiers = claudeProvider ? filterSelectableModels(claudeProvider.models || [claudeProvider.defaultModel]) : [];
+ return Array.from(new Set([...tiers, ...ollamaModels].filter(Boolean)));
+ }, [claudeProvider, ollamaModels]);
const handleSave = async () => {
setSaving(true);
@@ -89,6 +106,7 @@ export default function CodeReviewDefaultsPanel() {
lmstudioModel: lmstudioModel || undefined,
ollamaModel: ollamaModel || undefined,
codexModel: codexModel || undefined,
+ claudeModel: claudeModel.trim() || undefined,
};
const ok = await api.updateSettings({ codeReview: payload }, { silent: true })
.then(() => true)
@@ -133,7 +151,7 @@ export default function CodeReviewDefaultsPanel() {
<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. Local-LLM reviewers route the diff through PortOS's local code-review endpoint; the Codex reviewer invokes the Codex CLI directly. Each runs the model selected below.
+ Default Review Loop reviewer chain — used by ad-hoc CoS tasks and task-type schedules that haven't pinned their own. Local-LLM reviewers route the diff through PortOS's local code-review endpoint; the Codex and Claude reviewers invoke their CLI directly. Each runs the model selected below (Claude also supports an Ollama-backed CLI for local-only setups).
</p>
{loading ? (
@@ -157,6 +175,26 @@ export default function CodeReviewDefaultsPanel() {
{needsLmStudio && renderModelPicker('LM Studio', 'lmstudio', lmstudioModel, setLmstudioModel, lmStudioModels, lmStudioSelectId)}
{needsOllama && renderModelPicker('Ollama', 'ollama', ollamaModel, setOllamaModel, ollamaModels, ollamaSelectId)}
{needsCodex && renderModelPicker('Codex', 'codex', codexModel, setCodexModel, codexModels, codexSelectId, 'No selectable Codex models — configure the Codex provider on the AI Providers page (or leave blank to use the Codex CLI default).')}
+ {needsClaude && (
+ <div className="flex flex-col gap-1 mt-2">
+ <label htmlFor={claudeSelectId} className="text-xs text-gray-500">Claude model (optional):</label>
+ <input
+ id={claudeSelectId}
+ type="text"
+ list={claudeListId}
+ value={claudeModel}
+ onChange={(e) => setClaudeModel(e.target.value)}
+ placeholder="Leave blank for the Claude CLI default"
+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px] max-w-md"
+ />
+ <datalist id={claudeListId}>
+ {claudeModelSuggestions.map((id) => <option key={id} value={id}>{id}</option>)}
+ </datalist>
+ <p className="text-xs text-gray-500">
+ Passed as <code>claude --model &lt;id&gt;</code>. Pick a Claude tier, or — if you run an Ollama-backed <code>claude</code> — type or pick one of your installed Ollama models.
+ </p>
+ </div>
+ )}
<div className="flex justify-end">
<button
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 2ead33ead8..98d4547b6e 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -29,6 +29,17 @@ export const DEFAULT_REVIEWERS = ['copilot'];
// bot). Used by the code-review endpoint, settings panel, and prompt builder
// to gate model-id resolution.
export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];
+// CLI reviewers whose binary accepts a `--model <id>` tier the user can pin on
+// the Code Review Defaults panel (stored as a `<reviewer>Model` settings scalar,
+// e.g. `codexModel` / `claudeModel`). The review-loop follow-up threads each as a
+// reviewer-keyed model map (`reviewLoopReviewerModels`) so the prompt emits
+// `<reviewer> --model <id>` per configured reviewer. `claude` covers both a
+// normal Claude tier and an Ollama-backed `claude` (see isOllamaClaudeProvider)
+// where `--model` selects the local Ollama model. Copilot/local-LLM reviewers are
+// excluded — the former has no CLI, the latter get their model injected
+// server-side by `POST /api/code-review/local`. Add a reviewer here (and a
+// matching `<reviewer>Model` schema field) when its CLI gains model selection.
+export const MODEL_CAPABLE_CLI_REVIEWERS = ['codex', 'claude'];
// Stop-mode for the multi-reviewer loop (slashdo `--review-stop-on-*`).
export const REVIEW_STOP_MODES = ['all', 'on-findings', 'on-clean'];
export const DEFAULT_REVIEW_STOP_MODE = 'all';
@@ -395,9 +406,11 @@ export const generateWeeklyDigestSchema = z.object({
// up spawner reads it as the fallback for `reviewers` when none are passed in.
// `lmstudioModel` / `ollamaModel` are the installed model ids the local-LLM
// reviewer should run with (empty/undefined = pick the active default model).
-// `codexModel` is the Codex CLI model tier (e.g. `gpt-5.6-sol`) threaded into
-// the review-loop follow-up prompt as `codex --model <id>` (empty/undefined =
-// let the Codex CLI pick its own default).
+// `codexModel` / `claudeModel` are per-CLI-reviewer model tiers (see
+// MODEL_CAPABLE_CLI_REVIEWERS) threaded into the review-loop follow-up prompt as
+// `<reviewer> --model <id>` (empty/undefined = let that CLI pick its own default).
+// `claudeModel` doubles as the Ollama model id when the user runs an
+// Ollama-backed `claude` (isOllamaClaudeProvider) as their reviewer.
export const codeReviewSettingsSchema = z.object({
reviewers: z.preprocess(
v => Array.isArray(v) ? v.map(r => (typeof r === 'string' ? (REVIEWER_ALIASES[r] ?? r) : r)) : v,
@@ -416,6 +429,7 @@ export const codeReviewSettingsSchema = z.object({
lmstudioModel: z.preprocess(emptyToUndefined, z.string().optional()),
ollamaModel: z.preprocess(emptyToUndefined, z.string().optional()),
codexModel: z.preprocess(emptyToUndefined, z.string().optional()),
+ claudeModel: z.preprocess(emptyToUndefined, z.string().optional()),
}).strict();
// =============================================================================
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 502ff7d0d0..69d53493c6 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -109,6 +109,7 @@ describe('validation.js', () => {
lmstudioModel: 'qwen2.5-coder:7b',
ollamaModel: 'codellama',
codexModel: 'gpt-5.6-sol',
+ claudeModel: 'qwen2.5:7b',
})
expect(r.success).toBe(true)
})
@@ -119,6 +120,15 @@ describe('validation.js', () => {
expect(r.data.codexModel).toBeUndefined()
})
+ it('accepts a claudeModel and coerces an empty one to undefined', () => {
+ const ok = codeReviewSettingsSchema.safeParse({ reviewers: ['claude'], claudeModel: 'qwen2.5:7b' })
+ expect(ok.success).toBe(true)
+ expect(ok.data.claudeModel).toBe('qwen2.5:7b')
+ const empty = codeReviewSettingsSchema.safeParse({ reviewers: ['claude'], claudeModel: '' })
+ expect(empty.success).toBe(true)
+ expect(empty.data.claudeModel).toBeUndefined()
+ })
+
it('accepts an empty object (all fields optional)', () => {
expect(codeReviewSettingsSchema.safeParse({}).success).toBe(true)
})
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 2dc1a28f49..d012a68268 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -16,7 +16,7 @@ import { getToolsSummaryForPrompt } from './tools.js';
import { getActiveProvider } from './providers.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUtils.js';
-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, resolveKeyedReviewers, buildReviewWithArgs } from '../lib/validation.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, resolveKeyedReviewers, buildReviewWithArgs } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { isOpencodeCommand } from '../lib/providerModels.js';
import { shellQuote } from '../lib/shellQuote.js';
@@ -306,14 +306,22 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));
const hasCli = reviewers.some(r => r !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(r));
const hasGithubUser = usernames.length > 0;
- // Optional Codex CLI model tier chosen on the Code Review Defaults panel.
- // Only surfaced when `codex` is actually one of the reviewers; the CLI takes
- // it as `codex --model <id>` (empty = let the Codex CLI use its own default).
- const codexModel = (reviewers.includes('codex') && typeof metadata.reviewLoopCodexModel === 'string' && metadata.reviewLoopCodexModel)
- ? metadata.reviewLoopCodexModel
- : '';
- const codexModelNote = codexModel
- ? ` When invoking the \`codex\` reviewer, pass its model tier: \`codex --model ${codexModel} …\`.`
+ // Optional per-CLI-reviewer model tiers chosen on the Code Review Defaults panel,
+ // threaded as a reviewer-keyed map. Each configured, model-capable reviewer that
+ // is actually in this loop's list gets a `<reviewer> --model <id>` note (empty =
+ // let that CLI use its own default). For an Ollama-backed `claude` reviewer the id
+ // is the local Ollama model. Falls back to the legacy codex-scalar metadata key so
+ // a follow-up task persisted by an older install still threads its codex model.
+ const reviewerModelMap = (metadata.reviewLoopReviewerModels && typeof metadata.reviewLoopReviewerModels === 'object')
+ ? metadata.reviewLoopReviewerModels
+ : (typeof metadata.reviewLoopCodexModel === 'string' && metadata.reviewLoopCodexModel
+ ? { codex: metadata.reviewLoopCodexModel }
+ : {});
+ const reviewerModelEntries = MODEL_CAPABLE_CLI_REVIEWERS
+ .filter(r => reviewers.includes(r) && typeof reviewerModelMap[r] === 'string' && reviewerModelMap[r])
+ .map(r => `\`${r} --model ${reviewerModelMap[r]} …\``);
+ const reviewerModelNote = reviewerModelEntries.length
+ ? ` When invoking a reviewer with a pinned model, pass it: ${reviewerModelEntries.join(', ')}.`
: '';
// "multi" reflects the TOTAL number of review sources (keyed reviewers +
// username reviewers) so the ordered per-reviewer loop wording kicks in as
@@ -346,11 +354,11 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
hasCopilot ? `**copilot**: ${copilotIsFirst
? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)'
: 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,
- hasCli ? `**codex / antigravity / claude / grok**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${codexModelNote}` : null,
+ hasCli ? `**codex / antigravity / claude / grok**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${reviewerModelNote}` : null,
hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,
hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,
].filter(Boolean).join(' ');
- const singleCliInvocation = `Invoke the ${reviewerLabel} CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${codexModelNote}`;
+ const singleCliInvocation = `Invoke the ${reviewerLabel} CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${reviewerModelNote}`;
// Resolved sequentially so a future reviewer kind only adds one branch
// instead of deepening the nested ternary.
let waitOrInvokeStep;
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 5cbbaa080b..be3b002f0c 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -582,7 +582,42 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/--review-with copilot/);
});
- it('threads the configured Codex model tier into the CLI invocation when codex reviews', () => {
+ it('threads a reviewer-keyed model map into each CLI invocation', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopReviewers: ['codex', 'claude'],
+ reviewLoopReviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' },
+ sourceTaskId: 'task-src-map',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/codex --model gpt-5\.6-sol/);
+ expect(prompt).toMatch(/claude --model qwen2\.5:7b/);
+ });
+
+ it('threads a configured claude model (Ollama-backed reviewer) via the map', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopReviewers: ['claude'],
+ reviewLoopReviewerModels: { claude: 'qwen2.5:7b' },
+ sourceTaskId: 'task-src-cl',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/claude --model qwen2\.5:7b/);
+ });
+
+ it('falls back to the legacy codex-scalar metadata key when the map is absent', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: {
reviewLoopFollowUp: true,
@@ -590,6 +625,7 @@ describe('buildLightContextPrompt', () => {
reviewLoopPRBranch: 'b',
reviewLoopPRNumber: 9,
reviewLoopReviewers: ['codex'],
+ // Written by an older install: only the codex scalar, no map.
reviewLoopCodexModel: 'gpt-5.6-sol',
sourceTaskId: 'task-src-cx',
}}),
@@ -599,7 +635,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/codex --model gpt-5\.6-sol/);
});
- it('omits the Codex model note when codex is not among the reviewers', () => {
+ it('does not leak a stale legacy codex scalar into a claude-only review', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: {
reviewLoopFollowUp: true,
@@ -607,8 +643,8 @@ describe('buildLightContextPrompt', () => {
reviewLoopPRBranch: 'b',
reviewLoopPRNumber: 9,
reviewLoopReviewers: ['claude'],
- // Stale model tier from a prior codex config — must not leak into a
- // claude-only review.
+ // Stale model tier from a prior codex config — the legacy fallback maps
+ // it to codex, which is NOT among the reviewers, so it must not leak.
reviewLoopCodexModel: 'gpt-5.6-sol',
sourceTaskId: 'task-src-noncx',
}}),
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 19375d44b3..e9f5999c8c 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -22,7 +22,7 @@ import { removeWorktree } from './worktreeManager.js';
import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers, normalizeReviewUsernames } from '../lib/validation.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames } from '../lib/validation.js';
/**
* Clean up a worktree for a completed agent.
@@ -41,7 +41,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normaliz
* the worktree branch into the source workspace because `gh pr merge` already handled it.
* Otherwise, merges the worktree branch back to the source branch on success.
*/
-export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
if (!agentState?.metadata?.isWorktree) return [];
@@ -180,7 +180,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
usernames,
reviewStopMode,
reviewerApplies,
- codexModel
+ reviewerModels
}).catch(err => {
emitLog('warn', `🤖 Failed to spawn review-loop follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
warnings.push(`Review-loop follow-up spawn failed for ${prResult.url}: ${err.message}`);
@@ -238,7 +238,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
* branch (via createWorktree's `existingBranch` option) so it can fix-and-push
* without trampling concurrent agents.
*/
-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null }) {
if (!prUrl || !prBranch) return null;
const parsedPr = git.parsePullRequestUrl(prUrl);
@@ -255,6 +255,15 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
const effectiveUsernames = normalizeReviewUsernames(usernames);
if (effectiveReviewers.length === 0 && effectiveUsernames.length === 0) return null;
+ // Reviewer-keyed CLI model map, narrowed to the model-capable reviewers actually
+ // in this loop's list (e.g. `{ codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }`); the
+ // prompt threads each as `<reviewer> --model <id>`. `reviewerModels` is already
+ // coerced to string values upstream (resolveReviewLoopOptions).
+ const narrowedReviewerModels = {};
+ for (const r of effectiveReviewers) {
+ if (MODEL_CAPABLE_CLI_REVIEWERS.includes(r) && reviewerModels?.[r]) narrowedReviewerModels[r] = reviewerModels[r];
+ }
+
const appId = originalTask?.metadata?.app || null;
const sourceTaskDesc = originalTask?.description || 'CoS automated task';
const firstLine = sourceTaskDesc.split(/[\r\n]/).find(l => l.trim()) || sourceTaskDesc;
@@ -292,10 +301,13 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
reviewLoopReviewerUsernames: effectiveUsernames,
reviewLoopStopMode: reviewStopMode,
reviewLoopReviewerApplies: reviewerApplies,
- // Codex CLI model tier (e.g. `gpt-5.6-sol`) — only meaningful when `codex`
- // is in the reviewer list; the prompt threads it as `codex --model <id>`.
- // `codexModel` is already coerced to string|null upstream (resolveReviewLoopOptions).
- reviewLoopCodexModel: (effectiveReviewers.includes('codex') && codexModel) ? codexModel : null,
+ // Empty → null so the prompt builder's "no models configured" path is unambiguous.
+ reviewLoopReviewerModels: Object.keys(narrowedReviewerModels).length ? narrowedReviewerModels : null,
+ // Back-compat: older installs' prompt builder reads only the codex-scalar key.
+ // Mirror the (already-narrowed) codex entry so a follow-up task persisted by this
+ // version still threads a codex model after a downgrade. Remove once no supported
+ // peer reads it.
+ reviewLoopCodexModel: narrowedReviewerModels.codex || null,
sourceTaskId: originalTask?.id || null,
sourceAgentId: originalAgentId || null,
// This follow-up may legitimately exit with zero new commits when every
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 1d02a48952..c1be4f1e50 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -601,7 +601,8 @@ describe('cleanupAgentWorktree - openPR path', () => {
await cleanupAgentWorktree('agent-1', true, {
openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'codex', 'antigravity'],
- reviewStopMode: 'on-findings', reviewerApplies: true, codexModel: 'gpt-5.6-sol', description: 'Build',
+ reviewStopMode: 'on-findings', reviewerApplies: true,
+ reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',
originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
});
@@ -611,23 +612,46 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(followUp.metadata.reviewLoopReviewers).toEqual(['copilot', 'codex', 'antigravity']);
expect(followUp.metadata.reviewLoopStopMode).toBe('on-findings');
expect(followUp.metadata.reviewLoopReviewerApplies).toBe(true);
- // Codex model tier rides along only because `codex` is in the list.
+ // Only the codex entry rides along — codex is in the list, claude is not, so
+ // the map is narrowed to the reviewers actually running.
+ expect(followUp.metadata.reviewLoopReviewerModels).toEqual({ codex: 'gpt-5.6-sol' });
+ // Back-compat mirror of the codex entry for an older prompt builder.
expect(followUp.metadata.reviewLoopCodexModel).toBe('gpt-5.6-sol');
});
- it('drops the Codex model tier when codex is not among the reviewers', async () => {
+ it('threads the claude model when claude is among the reviewers (Ollama-backed reviewer)', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/60' });
+ git.requestCopilotReview.mockResolvedValue({ success: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-cl' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'claude'],
+ reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',
+ originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
+ });
+
+ const [followUp] = addTask.mock.calls[0];
+ // claude is in the list, codex is not — map narrows to claude only.
+ expect(followUp.metadata.reviewLoopReviewerModels).toEqual({ claude: 'qwen2.5:7b' });
+ // No codex reviewer → no legacy codex mirror.
+ expect(followUp.metadata.reviewLoopCodexModel).toBeNull();
+ });
+
+ it('drops the model map entirely when no model-capable reviewer is in the list', async () => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/59' });
git.requestCopilotReview.mockResolvedValue({ success: true });
addTask.mockResolvedValue({ id: 'sys-rl-nc' });
await cleanupAgentWorktree('agent-1', true, {
- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'claude'],
- codexModel: 'gpt-5.6-sol', description: 'Build',
+ openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'antigravity'],
+ reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',
originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
});
const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewerModels).toBeNull();
expect(followUp.metadata.reviewLoopCodexModel).toBeNull();
});
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 5478469303..0b714baa6a 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -16,6 +16,7 @@ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
import {
LOCAL_LLM_REVIEWERS,
+ MODEL_CAPABLE_CLI_REVIEWERS,
DEFAULT_REVIEWERS,
DEFAULT_REVIEW_STOP_MODE,
REVIEWER_ALIASES,
@@ -67,6 +68,7 @@ export function pickCodeReviewDefaults(settings) {
lmstudioModel: typeof raw?.lmstudioModel === 'string' && raw.lmstudioModel ? raw.lmstudioModel : null,
ollamaModel: typeof raw?.ollamaModel === 'string' && raw.ollamaModel ? raw.ollamaModel : null,
codexModel: typeof raw?.codexModel === 'string' && raw.codexModel ? raw.codexModel : null,
+ claudeModel: typeof raw?.claudeModel === 'string' && raw.claudeModel ? raw.claudeModel : null,
}
}
@@ -102,11 +104,14 @@ export async function getCodeReviewDefaults() {
* module doesn't have to import it directly — keeps validation.js as the
* single source of truth for the reviewer enum & fallback rules.
*
- * `codexModel` (the Codex CLI model tier for a `codex` reviewer) comes from the
- * Code Review Defaults panel. Unlike the local-LLM models — which the
- * `/api/code-review/local` endpoint injects server-side — the Codex CLI is
- * invoked directly by the follow-up agent, so this value has to ride along into
- * the follow-up's prompt.
+ * `reviewerModels` is a reviewer-keyed model map (e.g. `{ codex: 'gpt-5.6-sol',
+ * claude: 'qwen2.5:7b' }`) built from the per-CLI-reviewer model scalars on the
+ * Code Review Defaults panel (see MODEL_CAPABLE_CLI_REVIEWERS). Unlike the
+ * local-LLM models — which the `/api/code-review/local` endpoint injects
+ * server-side — these CLIs are invoked directly by the follow-up agent, so each
+ * configured model has to ride along into the follow-up's prompt as
+ * `<reviewer> --model <id>`. Only reviewers with a non-empty configured model
+ * appear in the map (absent = let that CLI pick its own default).
*
* Errors in settings I/O fall back to the hardcoded defaults — settings read
* failures shouldn't block agent completion.
@@ -122,8 +127,15 @@ export async function resolveReviewLoopOptions(metadata, { normalize, isTruthyMe
const reviewerApplies = metadata?.reviewerApplies !== undefined
? isTruthyMeta(metadata?.reviewerApplies)
: (defaults?.reviewerApplies === true)
- const codexModel = defaults?.codexModel || null
- return { reviewers, usernames, reviewStopMode, reviewerApplies, codexModel }
+ // Reviewer-keyed model map from the `<reviewer>Model` scalars. spawnReviewLoopFollowUp
+ // further narrows it to the reviewers actually in the list; here we surface every
+ // configured one so the caller doesn't need to know the list yet.
+ const reviewerModels = {}
+ for (const r of MODEL_CAPABLE_CLI_REVIEWERS) {
+ const model = defaults?.[`${r}Model`]
+ if (model) reviewerModels[r] = model
+ }
+ return { reviewers, usernames, reviewStopMode, reviewerApplies, reviewerModels }
}
const CODE_REVIEW_SYSTEM_PROMPT = `You are a careful senior code reviewer. The user will paste a unified PR diff. Review only what the diff changes (not the whole repo). Produce findings as a markdown list grouped by severity:
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index dacc101645..3b3d00d71e 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -21,10 +21,19 @@ import {
isLocalLlmReviewer,
pickCodeReviewDefaults,
getCodeReviewDefaults,
+ resolveReviewLoopOptions,
runLocalCodeReview,
__resetCodeReviewDefaultsCache,
} from './codeReview.js'
+// Minimal stand-ins for the deps resolveReviewLoopOptions is handed by its
+// callers (agentCliSpawning / agentCompletionCleanup) — kept trivial so the
+// test exercises the resolver's own model-map assembly, not validation.js.
+const testDeps = {
+ normalize: (meta, fallback) => (Array.isArray(meta?.reviewers) && meta.reviewers.length ? meta.reviewers : (fallback || ['copilot'])),
+ isTruthyMeta: (v) => v === true,
+}
+
describe('codeReview helpers', () => {
afterEach(() => {
mockedSettings.current = {}
@@ -53,6 +62,7 @@ describe('codeReview helpers', () => {
lmstudioModel: null,
ollamaModel: null,
codexModel: null,
+ claudeModel: null,
})
expect(pickCodeReviewDefaults({})).toEqual({
reviewers: ['copilot'],
@@ -62,6 +72,7 @@ describe('codeReview helpers', () => {
lmstudioModel: null,
ollamaModel: null,
codexModel: null,
+ claudeModel: null,
})
})
@@ -88,6 +99,7 @@ describe('codeReview helpers', () => {
lmstudioModel: '',
ollamaModel: 42,
codexModel: '',
+ claudeModel: '',
},
})
expect(out.stopMode).toBe('all')
@@ -95,6 +107,7 @@ describe('codeReview helpers', () => {
expect(out.lmstudioModel).toBeNull()
expect(out.ollamaModel).toBeNull()
expect(out.codexModel).toBeNull()
+ expect(out.claudeModel).toBeNull()
})
it('passes through a valid full payload', () => {
@@ -106,6 +119,7 @@ describe('codeReview helpers', () => {
lmstudioModel: 'qwen2.5-coder:7b',
ollamaModel: 'codellama',
codexModel: 'gpt-5.6-sol',
+ claudeModel: 'qwen2.5:7b',
},
})
expect(out).toEqual({
@@ -116,6 +130,7 @@ describe('codeReview helpers', () => {
lmstudioModel: 'qwen2.5-coder:7b',
ollamaModel: 'codellama',
codexModel: 'gpt-5.6-sol',
+ claudeModel: 'qwen2.5:7b',
})
})
@@ -145,6 +160,35 @@ describe('codeReview helpers', () => {
})
})
+ describe('resolveReviewLoopOptions', () => {
+ it('assembles a reviewer-keyed model map from the per-CLI-reviewer scalars', async () => {
+ mockedSettings.current = {
+ codeReview: {
+ reviewers: ['codex', 'claude'],
+ codexModel: 'gpt-5.6-sol',
+ claudeModel: 'qwen2.5:7b',
+ },
+ }
+ const out = await resolveReviewLoopOptions({}, testDeps)
+ expect(out.reviewerModels).toEqual({ codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' })
+ // The codex-scalar option is gone — callers thread the map now.
+ expect(out.codexModel).toBeUndefined()
+ })
+
+ it('omits reviewers with no configured model (absent = CLI default)', async () => {
+ mockedSettings.current = { codeReview: { reviewers: ['codex', 'claude'], codexModel: 'gpt-5.6-sol' } }
+ const out = await resolveReviewLoopOptions({}, testDeps)
+ expect(out.reviewerModels).toEqual({ codex: 'gpt-5.6-sol' })
+ })
+
+ it('returns an empty map when no CLI-reviewer model is configured', async () => {
+ mockedSettings.current = { codeReview: { reviewers: ['copilot', 'ollama'], ollamaModel: 'codellama' } }
+ const out = await resolveReviewLoopOptions({}, testDeps)
+ // ollama's model is injected server-side by /api/code-review/local, never threaded here.
+ expect(out.reviewerModels).toEqual({})
+ })
+ })
+
describe('runLocalCodeReview', () => {
beforeEach(() => {
// Default fetch mock — chat-completions success with a static body. Each