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

refactor: collapse the reviewer-pin duplication the effort pin exposed

[._.]/ Adam Eivy9e02d956f399
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsx
index 9319b1c646..a45bc8b0d1 100644
--- a/client/src/components/cos/ReviewerPicker.jsx
+++ b/client/src/components/cos/ReviewerPicker.jsx
@@ -220,38 +220,59 @@ export default function ReviewerPicker({
reviewerEfforts: level ? { ...efforts.without(token), [token]: level } : efforts.without(token)
});
+ // The "this reviewer has no such control" cell, shared by the Model and Effort
+ // columns so both read identically when the pin doesn't apply.
+ const renderNoPinCell = (title) => (
+ <span className="text-[11px] text-gray-700" title={title}>—</span>
+ );
+
+ // The closed-list pin `<select>` behind both the Effort column and the Model
+ // column's local-backend variant. They share one non-obvious contract: a stored
+ // value that is no longer in `options` (pinned on another machine, or before a
+ // CLI dropped a tier / a model was uninstalled) STILL gets an `<option>` — a
+ // select whose value isn't in its list renders blank and reads as "unset" while
+ // the value is in fact stored. `staleSuffix` names why it's absent; `setClass`
+ // differs only so the two columns stay visually distinguishable — passed as a
+ // COMPLETE class string, never interpolated, or Tailwind's scanner won't emit it.
+ const renderPinSelect = ({ selectId, value, options, onChange, ariaLabel, title, staleSuffix, setClass, maxWidthClass }) => (
+ <select
+ id={selectId}
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onChange(e.target.value)}
+ aria-label={ariaLabel}
+ title={title}
+ className={`w-full min-w-0 ${maxWidthClass} px-1.5 py-0.5 text-[11px] font-mono rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${value
+ ? setClass
+ : 'text-gray-500 border-port-border/60'}`}
+ >
+ <option value="">— default —</option>
+ {value && !options.includes(value) && <option value={value}>{value} {staleSuffix}</option>}
+ {options.map((option) => <option key={option} value={option}>{option}</option>)}
+ </select>
+ );
+
// The Effort cell. Only EFFORT_SELECTABLE_REVIEWERS get one, and each offers
// only its own CLI's ladder — copilot has no CLI, grok's takes no effort flag,
// and a `@username` reviewer is a person.
const renderEffortCell = (token) => {
const levels = reviewerEffortLevels(token);
- if (!levels?.length) {
- return <span className="text-[11px] text-gray-700" title={`${labelFor(token)} has no reasoning-effort control`}>—</span>;
- }
+ if (!levels?.length) return renderNoPinCell(`${labelFor(token)} has no reasoning-effort control`);
const subject = labelFor(token);
- // A pin whose level left this reviewer's ladder (set on another machine, or
- // before a CLI dropped a tier) still needs an <option>, or the select renders
- // blank and reads as "unset" while the value is in fact stored.
const stored = efforts.get(token) ?? '';
- return (
- <select
- id={`${id}-effort-${token}`}
- value={stored}
- disabled={disabled}
- onChange={(e) => setEffort(token, e.target.value)}
- aria-label={`Reasoning effort for ${subject}`}
- title={stored
- ? `${subject} reviews at ${stored} reasoning effort. Choose "default" to let it decide.`
- : `${subject} reasons at its own default. Pick a tier to make it think harder (slower, pricier) or lighter.`}
- className={`w-full min-w-0 max-w-[8rem] px-1.5 py-0.5 text-[11px] font-mono rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${stored
- ? 'text-port-accent-2 border-port-accent-2/50'
- : 'text-gray-500 border-port-border/60'}`}
- >
- <option value="">— default —</option>
- {stored && !levels.includes(stored) && <option value={stored}>{stored} (unsupported)</option>}
- {levels.map((level) => <option key={level} value={level}>{level}</option>)}
- </select>
- );
+ return renderPinSelect({
+ selectId: `${id}-effort-${token}`,
+ value: stored,
+ options: levels,
+ onChange: (level) => setEffort(token, level),
+ ariaLabel: `Reasoning effort for ${subject}`,
+ title: stored
+ ? `${subject} reviews at ${stored} reasoning effort. Choose "default" to let it decide.`
+ : `${subject} reasons at its own default. Pick a tier to make it think harder (slower, pricier) or lighter.`,
+ staleSuffix: '(unsupported)',
+ setClass: 'text-port-accent-2 border-port-accent-2/50',
+ maxWidthClass: 'max-w-[8rem]'
+ });
};
// The `~opt` non-blocking toggle rendered on every reviewer/username row.
@@ -315,9 +336,7 @@ export default function ReviewerPicker({
// 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 <span className="text-[11px] text-gray-700" title={`${labelFor(token)} takes no model`}>—</span>;
- }
+ if (!MODEL_SELECTABLE_REVIEWERS.includes(token)) return renderNoPinCell(`${labelFor(token)} takes no model`);
const subject = labelFor(token);
const value = models.get(token) ?? '';
const options = modelOptions?.optionsByReviewer?.[token] || [];
@@ -336,28 +355,19 @@ export default function ReviewerPicker({
: null;
if (!freeText) {
- return (
- <select
- id={inputId}
- value={value}
- disabled={disabled}
- onChange={(e) => setModel(token, e.target.value)}
- aria-label={`Model for ${subject}`}
- title={value
- ? `${subject} reviews with ${value}. Choose "default" to let it pick.`
- : `${subject} uses the model configured for its backend. Pick one to pin it for this run.`}
- className={`w-full min-w-0 max-w-[190px] px-1.5 py-0.5 text-[11px] font-mono rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${value
- ? 'text-port-accent border-port-accent/50'
- : 'text-gray-500 border-port-border/60'}`}
- >
- <option value="">— default —</option>
- {/* A pin the probe no longer lists (model uninstalled, or set on
- another machine) still needs an <option>, or the select would render
- blank and read as "unset" while the value is in fact stored. */}
- {value && !options.includes(value) && <option value={value}>{value} (not installed)</option>}
- {options.map((m) => <option key={m} value={m}>{m}</option>)}
- </select>
- );
+ return renderPinSelect({
+ selectId: inputId,
+ value,
+ options,
+ onChange: (model) => setModel(token, model),
+ ariaLabel: `Model for ${subject}`,
+ title: value
+ ? `${subject} reviews with ${value}. Choose "default" to let it pick.`
+ : `${subject} uses the model configured for its backend. Pick one to pin it for this run.`,
+ staleSuffix: '(not installed)',
+ setClass: 'text-port-accent border-port-accent/50',
+ maxWidthClass: 'max-w-[190px]'
+ });
}
return (
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9e16d2e1a0..9491376c36 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -151,7 +151,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCityViewport` | Classifies the window width into `phone` / `compact` / `desktop` brackets (mirrors Tailwind `sm`/`lg`) so the City HUD can branch between the desktop cockpit and the compact/phone disclosure layout in JS (only one tree mounts). Returns `{ mode, isPhone, isCompact, isDesktop, isCondensed }`. | CyberCity HUD responsive layout only. |
| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
| `useColorMatch` | Drives a song color-match run: counts the singer in with the metronome, walks the notated score in tempo, grades each note against the live mic pitch (#1022 tracker + colorMatch lib), and exposes `{ running, countingIn, noteColors, summary, activeIndex, start, stop }` for the `<ScoreSheet>` + an accuracy readout. Taps the passed recording stream (no second mic); tears down on stop/unmount. | The Song editor's color-match panel. Don't re-wire the metronome + tracker + grading loop by hand. |
-| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
+| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + every per-reviewer `<reviewer>Model` / `<reviewer>Effort` pin scalar) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
| `useGoalDetail` | All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. |
diff --git a/client/src/lib/reviewerModels.js b/client/src/lib/reviewerModels.js
index 53b5871955..7188f8b419 100644
--- a/client/src/lib/reviewerModels.js
+++ b/client/src/lib/reviewerModels.js
@@ -23,61 +23,67 @@ import {
*/
/**
- * Scalars → `{ codex: 'gpt-…', ollama: 'qwen…' }`. Blank/absent scalars are omitted,
- * as is a value the server's token builders would drop — an over-long id or one
- * carrying a structural delimiter. settings.json is hand-editable, so a stored
- * value that predates the schema's validation must not surface as a pin the picker
+ * Build the scalar↔map adapter pair for ONE pin kind. The two pins differ on
+ * exactly three axes — which reviewers can carry the pin, the scalar's key
+ * suffix, and how a single value is validated — so they're parameters here
+ * rather than a second hand-copied pair of loops. Twin of the server's
+ * `keyedReviewerPinNormalizer` factory.
+ *
+ * `fromDefaults` OMITS anything `validateOne` rejects: settings.json is
+ * hand-editable and a reviewer's accepted values move with its CLI, so a stored
+ * value the server's normalizer would drop must not surface as a pin the picker
* DISPLAYS but no reviewer ever receives.
+ *
+ * `toDefaults` gives EVERY reviewer in the roster a key, so an unpinned one
+ * sends `undefined` and the schema's `emptyToUndefined` preprocess CLEARS the
+ * stored scalar. Omitting absent keys instead would leave a stale value
+ * persisted after the user cleared the field.
+ *
+ * @param {readonly string[]} roster - reviewers that can carry this pin.
+ * @param {string} suffix - scalar key suffix (`'Model'` → `codexModel`).
+ * @param {(raw: string, reviewer: string) => string|undefined} validateOne
*/
-export function reviewerModelsFromDefaults(defaults) {
- const out = {};
- for (const reviewer of MODEL_SELECTABLE_REVIEWERS) {
- const raw = defaults?.[`${reviewer}Model`];
- if (typeof raw !== 'string') continue;
- const model = sanitizeReviewerModelInput(raw).trim();
- if (model && model.length <= MAX_REVIEWER_MODEL_LENGTH && model === raw.trim()) out[reviewer] = model;
- }
- return out;
+function pinScalarAdapters(roster, suffix, validateOne) {
+ return {
+ fromDefaults: (defaults) => {
+ const out = {};
+ for (const reviewer of roster) {
+ const raw = defaults?.[`${reviewer}${suffix}`];
+ if (typeof raw !== 'string') continue;
+ const value = validateOne(raw, reviewer);
+ if (value) out[reviewer] = value;
+ }
+ return out;
+ },
+ toDefaults: (pins) => Object.fromEntries(
+ roster.map((reviewer) => [`${reviewer}${suffix}`, pins?.[reviewer] || undefined])
+ )
+ };
}
-/**
- * Map → scalars, for a settings PATCH. EVERY model-selectable reviewer gets a key,
- * so an unpinned one sends `undefined` and the schema's `emptyToUndefined`
- * preprocess CLEARS the stored scalar. Omitting absent keys instead would leave a
- * stale model persisted after the user cleared the field.
- */
-export function reviewerModelsToDefaults(models) {
- return Object.fromEntries(
- MODEL_SELECTABLE_REVIEWERS.map((reviewer) => [`${reviewer}Model`, models?.[reviewer] || undefined])
- );
-}
+// A model id survives only if it round-trips the sanitizer unchanged — a value
+// carrying a structural delimiter (or an over-long one) is what the server's
+// token builders would drop.
+const modelAdapters = pinScalarAdapters(MODEL_SELECTABLE_REVIEWERS, 'Model', (raw) => {
+ const model = sanitizeReviewerModelInput(raw).trim();
+ return model && model.length <= MAX_REVIEWER_MODEL_LENGTH && model === raw.trim() ? model : undefined;
+});
-/**
- * Effort twin of `reviewerModelsFromDefaults`: scalars → `{ codex: 'high' }`.
- * Each value is re-checked against that reviewer's OWN ladder, so a level stored
- * before the reviewer's CLI dropped it (or hand-edited into settings.json) doesn't
- * surface as a pin the server's normalizer would then drop — the picker would
- * otherwise DISPLAY an effort no reviewer ever receives.
- */
-export function reviewerEffortsFromDefaults(defaults) {
- const out = {};
- for (const reviewer of EFFORT_SELECTABLE_REVIEWERS) {
- const raw = defaults?.[`${reviewer}Effort`];
- if (typeof raw !== 'string') continue;
- const effort = raw.trim().toLowerCase();
- if (reviewerEffortLevels(reviewer)?.includes(effort)) out[reviewer] = effort;
- }
- return out;
-}
+// An effort is re-checked against that reviewer's OWN ladder, so a level stored
+// before the reviewer's CLI dropped it doesn't survive into the picker.
+const effortAdapters = pinScalarAdapters(EFFORT_SELECTABLE_REVIEWERS, 'Effort', (raw, reviewer) => {
+ const effort = raw.trim().toLowerCase();
+ return reviewerEffortLevels(reviewer)?.includes(effort) ? effort : undefined;
+});
-/**
- * Map → scalars, for a settings PATCH. Same every-key contract as
- * `reviewerModelsToDefaults`: an unpinned reviewer sends `undefined` so the
- * schema's `emptyToUndefined` preprocess CLEARS the stored scalar instead of
- * leaving a stale effort behind.
- */
-export function reviewerEffortsToDefaults(efforts) {
- return Object.fromEntries(
- EFFORT_SELECTABLE_REVIEWERS.map((reviewer) => [`${reviewer}Effort`, efforts?.[reviewer] || undefined])
- );
-}
+/** Scalars → `{ codex: 'gpt-…', ollama: 'qwen…' }`. */
+export const reviewerModelsFromDefaults = modelAdapters.fromDefaults;
+
+/** Map → scalars, for a settings PATCH. */
+export const reviewerModelsToDefaults = modelAdapters.toDefaults;
+
+/** Effort twin: scalars → `{ codex: 'high' }`. */
+export const reviewerEffortsFromDefaults = effortAdapters.fromDefaults;
+
+/** Map → scalars, for a settings PATCH. */
+export const reviewerEffortsToDefaults = effortAdapters.toDefaults;
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 7e43eec174..ae60cf7064 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -546,6 +546,55 @@ export const normalizeReviewerEfforts = keyedReviewerPinNormalizer(normalizeRevi
*/
export const resolveReviewerEfforts = keyedReviewerPinResolver(normalizeReviewerEfforts);
+/**
+ * Resolve a task's whole reviewer configuration against the Code Review Defaults
+ * in one call — the reviewer list plus every per-reviewer pin, each with the same
+ * task-over-default precedence its own resolver defines.
+ *
+ * The prompt builder resolves this set at three separate spawn paths (the review
+ * follow-up, the claim prompt, and the light/cleanup prompt). Hand-copying six
+ * resolver calls per site meant adding a pin kind was a three-site edit where a
+ * missed site is silent: the pin is configured, persisted, and displayed, but
+ * never reaches the reviewer, and no test fails. One bundle, one edit.
+ *
+ * Shape matches `resolveReviewLoopOptions`'s in `services/codeReview.js`, minus
+ * the stop-mode/applies fields that come from elsewhere at these call sites.
+ */
+export function resolveReviewerConfig(metadata, codeReviewDefaults, defaultReviewers) {
+ return {
+ reviewers: normalizeReviewers(metadata, defaultReviewers),
+ usernames: resolveReviewUsernames(metadata?.usernames, codeReviewDefaults?.usernames),
+ optionalReviewers: resolveOptionalReviewers(metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers),
+ reviewerMaxRounds: resolveReviewerMaxRounds(metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds),
+ reviewerModels: resolveReviewerModels(metadata?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults)),
+ reviewerEfforts: resolveReviewerEfforts(metadata?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults))
+ };
+}
+
+/**
+ * Every token-keyed per-reviewer pin, as `[metadataKey, normalizeMap]`.
+ *
+ * The three pins share one persist contract, so the two places that copy them
+ * out of caller input — `sanitizeTaskMetadata` here and `addTask` in
+ * `cosTaskStore.js` — iterate this table instead of hand-copying a block per
+ * pin. Adding a fourth pin kind is then a one-line change that reaches both
+ * persist paths at once; a hand-copied block missed at one site would silently
+ * drop the pin at write time while every other layer still carried it.
+ *
+ * Shared semantics for all three: the value is a MAP keyed by the emitted
+ * `--review-with` token, and an explicitly empty map is KEPT — that's a real
+ * "override the Code Review Defaults back to each reviewer's own default" choice,
+ * distinct from an absent key (fall back to the defaults). Individual entries the
+ * normalizer can't validate are DROPPED rather than coerced, so a hand-edited
+ * settings.json can't smuggle in a cap slashdo would read as "loop until clean"
+ * (`~max=0`), a model a reviewer doesn't take, or an effort level its CLI rejects.
+ */
+export const KEYED_REVIEWER_PINS = [
+ ['reviewerMaxRounds', normalizeReviewerMaxRounds],
+ ['reviewerModels', normalizeReviewerModels],
+ ['reviewerEfforts', normalizeReviewerEfforts]
+];
+
/**
* Fold the Code Review Defaults' per-reviewer effort SCALARS (`codexEffort` /
* `claudeEffort` / `antigravityEffort` / `lmstudioEffort` / `ollamaEffort`) into
@@ -1346,32 +1395,13 @@ export function sanitizeTaskMetadata(raw) {
clean.optionalReviewers = normalizeOptionalReviewers(raw.optionalReviewers) || [];
hasKeys = true;
}
- // `reviewerMaxRounds` caps each reviewer's review→fix→re-review cycles (slashdo
- // `~max=<n>`). Like `optionalReviewers`, an explicitly empty MAP is KEPT so a
- // task/type can override the Code Review Defaults' caps back to "no caps."
- // Individual entries with no usable cap are dropped by the normalizer rather
- // than becoming `0`, which slashdo reads as "loop until clean."
- if (raw.reviewerMaxRounds && typeof raw.reviewerMaxRounds === 'object' && !Array.isArray(raw.reviewerMaxRounds)) {
- clean.reviewerMaxRounds = normalizeReviewerMaxRounds(raw.reviewerMaxRounds) || {};
- hasKeys = true;
- }
- // `reviewerModels` pins the model each reviewer runs with (slashdo's
- // `[<model>]` / the follow-up prompt's `--model <id>`). Like `reviewerMaxRounds`,
- // an explicitly empty MAP is KEPT so a task/type can override the Code Review
- // Defaults' pins back to "each reviewer's own default"; an entry naming a
- // reviewer that takes no model, or a blank id, is dropped by the normalizer.
- if (raw.reviewerModels && typeof raw.reviewerModels === 'object' && !Array.isArray(raw.reviewerModels)) {
- clean.reviewerModels = normalizeReviewerModels(raw.reviewerModels) || {};
- hasKeys = true;
- }
- // `reviewerEfforts` pins how hard each reviewer thinks (the follow-up prompt's
- // `--effort <level>` / `-c model_reasoning_effort=<level>`, or a local reviewer's
- // `reasoning_effort` body field). Like `reviewerModels`, an explicitly empty MAP
- // is KEPT so a task/type can override the Code Review Defaults' efforts back to
- // "each reviewer's own default"; an entry naming a reviewer with no effort
- // control, or a level that reviewer's CLI rejects, is dropped by the normalizer.
- if (raw.reviewerEfforts && typeof raw.reviewerEfforts === 'object' && !Array.isArray(raw.reviewerEfforts)) {
- clean.reviewerEfforts = normalizeReviewerEfforts(raw.reviewerEfforts) || {};
+ // The token-keyed per-reviewer pins (caps / model / effort). Like
+ // `optionalReviewers`, an explicitly empty MAP is KEPT so a task/type can
+ // override the Code Review Defaults back to "each reviewer's own default" —
+ // see KEYED_REVIEWER_PINS for the shared contract.
+ for (const [key, normalizeMap] of KEYED_REVIEWER_PINS) {
+ if (!isPlainObject(raw[key])) continue;
+ clean[key] = normalizeMap(raw[key]) || {};
hasKeys = true;
}
if (Object.prototype.hasOwnProperty.call(raw, 'reviewStopMode') && REVIEW_STOP_MODES.includes(raw.reviewStopMode)) {
diff --git a/server/routes/codeReview.js b/server/routes/codeReview.js
index d2146e319d..2c10d65a87 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, LOCAL_LLM_EFFORT_LEVELS, reviewerEffortsFromDefaults } from '../lib/validation.js'
+import { validateRequest, LOCAL_LLM_REVIEWERS, normalizeReviewerEffort, reviewerEffortLevels, reviewerEffortsFromDefaults } from '../lib/validation.js'
import { getSettings } from '../services/settings.js'
import { runLocalCodeReview, getCodeReviewDefaults, getReviewerCliInstalled } from '../services/codeReview.js'
@@ -11,13 +11,27 @@ const router = Router()
// when omitted (or empty) we fall back to the model / reasoning effort configured
// on the Code Review Defaults panel. The diff is sent as-is; agents can pipe
// `gh pr diff <N>` straight into it without preprocessing.
+// `effort` is checked against the ladder for the REQUESTED backend rather than a
+// flat union of every local level: the two backends are separate identities in
+// `REVIEWER_EFFORT_LEVELS`, so a union would accept a level valid only for the
+// other one, and `runLocalCodeReview`'s inner `normalizeReviewerEffort` would then
+// 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),
model: z.string().optional(),
- effort: z.enum(LOCAL_LLM_EFFORT_LEVELS).optional(),
+ effort: z.string().optional(),
diff: z.string().min(1, 'diff must be non-empty'),
timeoutMs: z.number().int().positive().max(600000).optional(),
-}).strict()
+}).strict().superRefine((body, ctx) => {
+ if (body.effort === undefined) return
+ if (normalizeReviewerEffort(body.effort, body.backend)) return
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['effort'],
+ message: `Invalid effort for the ${body.backend} reviewer — expected one of: ${(reviewerEffortLevels(body.backend) || []).join(', ')}`,
+ })
+})
// GET /api/code-review/defaults — resolved global defaults (settings.codeReview
// + hardcoded fallback). The AI Providers panel reads this to render the
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
index c3b7cf3644..52f5cc1c6e 100644
--- a/server/routes/codeReview.test.js
+++ b/server/routes/codeReview.test.js
@@ -73,6 +73,36 @@ describe('POST /api/code-review/local', () => {
expect(codeReviewSvc.runLocalCodeReview).not.toHaveBeenCalled()
})
+ // The effort check is keyed on the REQUESTED backend, not a flat union of every
+ // local level, so a level the chosen backend doesn't accept is a 400 here rather
+ // than a 200 with the effort silently dropped by the service's own normalizer.
+ it('accepts an effort the requested backend takes, case-folded', async () => {
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({
+ ok: true, backend: 'ollama', model: 'm', effort: 'high', findings: 'No findings.',
+ })
+
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'ollama', model: 'm', effort: 'High', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(200)
+ expect(codeReviewSvc.runLocalCodeReview).toHaveBeenCalledWith(
+ expect.objectContaining({ effort: 'High' }),
+ )
+ })
+
+ it('returns 400 for an effort outside the requested backend ladder', async () => {
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'ollama', model: 'm', effort: 'max', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(400)
+ // `max` is a real level for some CLI reviewers, just not for a local backend —
+ // the message names the ladder that DID apply so the caller can tell which.
+ expect(JSON.stringify(res.body)).toContain('low, medium, high')
+ expect(codeReviewSvc.runLocalCodeReview).not.toHaveBeenCalled()
+ })
+
it('falls back to the settings model when model is omitted', async () => {
settingsSvc.getSettings.mockResolvedValue({
codeReview: { lmstudioModel: 'settings-model' },
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 1fc5c4a0ee..e844c08bb9 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -17,7 +17,7 @@ import { getActiveProvider } from './providers.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.js';
import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';
-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewUsernames, resolveOptionalReviewers, resolveReviewerMaxRounds, resolveReviewerModels, reviewerModelsFromDefaults, resolveReviewerEfforts, reviewerEffortsFromDefaults, reviewerEffortArgs, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewUsernames, resolveOptionalReviewers, resolveReviewerConfig, reviewerEffortArgs, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { canTypeSlashCommands, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
import { shellQuote } from '../lib/shellQuote.js';
@@ -386,12 +386,14 @@ async function applySlashdoInvocation(task, {
// single `reviewer` string and the defaults' `optionalReviewers` — pruning for
// one reviewer while the run resolved another, and pinning an optional reviewer
// as blocking.
- const resolvedReviewers = normalizeReviewers(task.metadata, defaultReviewers);
- const resolvedUsernames = resolveReviewUsernames(task.metadata?.usernames, codeReviewDefaults?.usernames);
- const resolvedOptional = resolveOptionalReviewers(task.metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers);
- const resolvedMaxRounds = resolveReviewerMaxRounds(task.metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds);
- const resolvedModels = resolveReviewerModels(task.metadata?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults));
- const resolvedEfforts = resolveReviewerEfforts(task.metadata?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults));
+ const {
+ reviewers: resolvedReviewers,
+ usernames: resolvedUsernames,
+ optionalReviewers: resolvedOptional,
+ reviewerMaxRounds: resolvedMaxRounds,
+ reviewerModels: resolvedModels,
+ reviewerEfforts: resolvedEfforts
+ } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);
// A resolved lone `copilot` with no usernames is ambiguous: it's what an
// unconfigured install produces (`pickCodeReviewDefaults` and
@@ -552,7 +554,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// the literal command line the agent must run. Reviewers are listed rather than
// filtered to MODEL_CAPABLE_CLI_REVIEWERS because `agy` takes an effort but no
// PortOS-pinnable model — it would otherwise have no way to receive one.
- const reviewerModelEntries = cliReviewers
+ const reviewerPinEntries = cliReviewers
.map((r) => {
const flags = [];
// Thread each configured model id VERBATIM. We deliberately don't env-map it
@@ -573,8 +575,8 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
return flags.length ? `\`${reviewerCliBinary(r) || r} ${flags.join(' ')} …\`` : null;
})
.filter(Boolean);
- const reviewerModelNote = reviewerModelEntries.length
- ? ` When invoking a reviewer with a pinned model or reasoning effort, pass it: ${reviewerModelEntries.join(', ')}.`
+ const reviewerPinNote = reviewerPinEntries.length
+ ? ` When invoking a reviewer with a pinned model or reasoning effort, pass it: ${reviewerPinEntries.join(', ')}.`
: '';
// When the slashdo local-agent review loop is inlined below (a spawnable CLI
// reviewer is in the list), point the invocation step at it so the agent runs
@@ -647,17 +649,27 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// `model: "…"` placeholder would have the agent send the literal ellipsis, and
// the route's `body.model || configured` prefers that truthy junk over the
// install default — turning a pinned-effort review into a model-not-found error.
- const localLlmPinKeys = new Set();
- const localLlmPinNote = LOCAL_LLM_REVIEWERS
+ const pinnedString = (map, r) => (typeof map[r] === 'string' && map[r] ? map[r] : null);
+ const localLlmPins = LOCAL_LLM_REVIEWERS
.filter(r => reviewers.includes(r))
- .map((r) => {
- const keys = [];
- if (typeof reviewerModelMap[r] === 'string' && reviewerModelMap[r]) { keys.push(`"model": "${reviewerModelMap[r]}"`); localLlmPinKeys.add('model'); }
- if (typeof reviewerEffortMap[r] === 'string' && reviewerEffortMap[r]) { keys.push(`"effort": "${reviewerEffortMap[r]}"`); localLlmPinKeys.add('effort'); }
- return keys.length ? `\`${r}\` → \`${keys.join(', ')}\`` : null;
- })
- .filter(Boolean);
- const localLlmPinJq = ['backend: "…"', ...[...localLlmPinKeys].map(k => `${k}: "…"`), 'diff: .'].join(', ');
+ .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 }) => {
+ const keys = [
+ ...(model ? [`"model": "${model}"`] : []),
+ ...(effort ? [`"effort": "${effort}"`] : [])
+ ];
+ return `\`${reviewer}\` → \`${keys.join(', ')}\``;
+ });
+ // Both strings derive from the same `localLlmPins` array rather than the jq line
+ // reading a Set the note's `.map` filled as a side effect — that coupling meant
+ // hoisting one line above the other silently emptied the key list.
+ const localLlmPinJq = [
+ 'backend: "…"',
+ ...(localLlmPins.some(p => p.model) ? ['model: "…"'] : []),
+ ...(localLlmPins.some(p => p.effort) ? ['effort: "…"'] : []),
+ 'diff: .'
+ ].join(', ');
const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it. Substitute the active reviewer name for \`<lmstudio|ollama>\`:
\`\`\`bash
REVIEW_RESPONSE=$(mktemp)
@@ -681,13 +693,13 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
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 ? `**${cliReviewerHeading}**: 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).${cliBinaryNote}${reviewerModelNote}${cliProcedurePointer}` : null,
+ hasCli ? `**${cliReviewerHeading}**: 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).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : null,
hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,
hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,
].filter(Boolean).join(' ');
// Name the BINARY, not the slug: `Invoke the \`antigravity\` CLI` sent a
// follow-up agent hunting for a command that does not exist.
- const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} 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}${cliProcedurePointer}`;
+ const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} 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.${reviewerPinNote}${cliProcedurePointer}`;
// Resolved sequentially so a future reviewer kind only adds one branch
// instead of deepening the nested ternary.
let waitOrInvokeStep;
@@ -1371,12 +1383,14 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
// a task pinning no reviewer config would silently drop the configured gating
// reviewers / stop-mode / reviewer-applies here while the non-PR-owning CLI
// follow-up path honored them — same defaults, different gating by provider.
- const taskReviewers = normalizeReviewers(task.metadata, defaultReviewers);
- const taskReviewerUsernames = resolveReviewUsernames(task.metadata?.usernames, codeReviewDefaults?.usernames);
- const taskOptionalReviewers = resolveOptionalReviewers(task.metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers);
- const taskReviewerMaxRounds = resolveReviewerMaxRounds(task.metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds);
- const taskReviewerModels = resolveReviewerModels(task.metadata?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults));
- const taskReviewerEfforts = resolveReviewerEfforts(task.metadata?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults));
+ const {
+ reviewers: taskReviewers,
+ usernames: taskReviewerUsernames,
+ optionalReviewers: taskOptionalReviewers,
+ reviewerMaxRounds: taskReviewerMaxRounds,
+ reviewerModels: taskReviewerModels,
+ reviewerEfforts: taskReviewerEfforts
+ } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);
const taskReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;
const taskReviewerApplies = task.metadata?.reviewerApplies !== undefined
? isTruthyMetaFn(task.metadata?.reviewerApplies)
@@ -1699,12 +1713,14 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// [--reviewer-applies]`. All five fields fall back to the defaults with
// task-over-default precedence (see the matching block in buildAgentPrompt and
// resolveReviewLoopOptions) — not just the reviewer list.
- const lightReviewers = normalizeReviewers(task.metadata, defaultReviewers);
- const lightReviewerUsernames = resolveReviewUsernames(task.metadata?.usernames, codeReviewDefaults?.usernames);
- const lightOptionalReviewers = resolveOptionalReviewers(task.metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers);
- const lightReviewerMaxRounds = resolveReviewerMaxRounds(task.metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds);
- const lightReviewerModels = resolveReviewerModels(task.metadata?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults));
- const lightReviewerEfforts = resolveReviewerEfforts(task.metadata?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults));
+ const {
+ reviewers: lightReviewers,
+ usernames: lightReviewerUsernames,
+ optionalReviewers: lightOptionalReviewers,
+ reviewerMaxRounds: lightReviewerMaxRounds,
+ reviewerModels: lightReviewerModels,
+ reviewerEfforts: lightReviewerEfforts
+ } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);
const lightReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;
const lightReviewerApplies = task.metadata?.reviewerApplies !== undefined
? isTruthyMetaFn(task.metadata?.reviewerApplies)
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 4a899d59de..c7c73c0490 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -16,7 +16,8 @@ import { readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';
-import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, normalizeReviewerModels, normalizeReviewerEfforts, reviewerEffortsFromDefaults } from '../lib/validation.js';
+import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, KEYED_REVIEWER_PINS } from '../lib/validation.js';
+import { isPlainObject } from '../lib/objects.js';
import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
@@ -382,26 +383,15 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (Array.isArray(taskData.optionalReviewers)) {
metadata.optionalReviewers = normalizeOptionalReviewers(taskData.optionalReviewers) || [];
}
- // Per-reviewer `~max=<n>` iteration caps, keyed by emitted `--review-with`
- // token. An explicitly empty MAP overrides the Code Review Defaults' caps;
- // an entry with no usable cap is dropped rather than coerced to `0`, which
- // slashdo reads as "loop until clean" (absent ≠ 0).
- if (taskData.reviewerMaxRounds && typeof taskData.reviewerMaxRounds === 'object' && !Array.isArray(taskData.reviewerMaxRounds)) {
- metadata.reviewerMaxRounds = normalizeReviewerMaxRounds(taskData.reviewerMaxRounds) || {};
- }
- // Per-reviewer model pins, keyed by the same emitted token. Same
- // explicit-empty semantics as the caps above: an empty MAP is a real "use each
+ // The token-keyed per-reviewer pins (caps / model / effort), keyed by the
+ // emitted `--review-with` token. An explicitly empty MAP is a real "use each
// reviewer's own default for this task" choice that overrides the Code Review
- // Defaults' pins. An entry naming a reviewer that takes no model, or a blank
- // id, is dropped by the normalizer.
- if (taskData.reviewerModels && typeof taskData.reviewerModels === 'object' && !Array.isArray(taskData.reviewerModels)) {
- metadata.reviewerModels = normalizeReviewerModels(taskData.reviewerModels) || {};
- }
- // Per-reviewer reasoning-effort pins, same token keying and same explicit-empty
- // semantics. An entry naming a reviewer with no effort control, or a level that
- // reviewer's CLI rejects, is dropped by the normalizer.
- if (taskData.reviewerEfforts && typeof taskData.reviewerEfforts === 'object' && !Array.isArray(taskData.reviewerEfforts)) {
- metadata.reviewerEfforts = normalizeReviewerEfforts(taskData.reviewerEfforts) || {};
+ // Defaults; unvalidatable entries are dropped rather than coerced. Iterates
+ // the shared table so this persist path can't drift from
+ // `sanitizeTaskMetadata`'s — see KEYED_REVIEWER_PINS.
+ for (const [key, normalizeMap] of KEYED_REVIEWER_PINS) {
+ if (!isPlainObject(taskData[key])) continue;
+ metadata[key] = normalizeMap(taskData[key]) || {};
}
if (REVIEW_STOP_MODES.includes(taskData.reviewStopMode)) metadata.reviewStopMode = taskData.reviewStopMode;
if (taskData.reviewerApplies === true) metadata.reviewerApplies = true;
@@ -1141,8 +1131,11 @@ export async function resolveTaskChallengeWithRecheck(taskId, { recheck, resolve
// disputed rejection is upheld or escalated to the user, and deriving it from a
// pass run at a weaker effort than the user configured is the same silent
// downgrade the pin exists to prevent.
+ // Read straight off the picked defaults: `pickCodeReviewDefaults` already ran
+ // every `<reviewer>Effort` scalar through `reviewerEffortsFromDefaults`, so a
+ // stale level is null by the time it reaches here — same as the model read below.
const recheckDefaults = await getCodeReviewDefaults().catch(() => null);
- const effort = reviewerEffortsFromDefaults(recheckDefaults)[backend] || null;
+ const effort = recheckDefaults?.[`${backend}Effort`] || null;
let model = recheck?.model;
if (!model) {
model = backend === 'ollama' ? recheckDefaults?.ollamaModel : recheckDefaults?.lmstudioModel;