Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: split the reviewer vocabulary out of cosValidation.js (#5702)
Adam Eivyc334288544ae
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex a53e6b7efe..7045edc55c 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -378,7 +378,7 @@ export const DEFAULT_REVIEWERS = ['copilot'];// Arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`) requested as PR// reviewers to gate merging, appended to slashdo's `--review-with` after the-// keyed reviewers. Client mirror of server/lib/cosValidation.js+// keyed reviewers. Client mirror of server/lib/reviewerConfig.js// `normalizeReviewUsernames` + MAX_REVIEW_USERNAMES — keep the pattern/cap in// sync so the picker rejects the same tokens the server would drop. Stored// WITHOUT the leading `@` (added back only for display / the flag string).@@ -412,7 +412,7 @@ export function normalizeReviewUsernames(list) {}// Upper bound on a per-reviewer `~max=<n>` round cap. Client mirror of-// MAX_REVIEWER_MAX_ROUNDS in `server/lib/cosValidation.js` — a value above it is+// MAX_REVIEWER_MAX_ROUNDS in `server/lib/reviewerConfig.js` — a value above it is// dropped server-side, so the input must not offer one. `0` is valid and means// "loop until clean" (slashdo's unlimited mode, bounded by its own guardrail);// blank/absent means "no cap requested" and keeps slashdo's built-in default.diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex eb74c8c425..aab8df7f27 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -52,7 +52,7 @@ grep -i "what you want to do" client/src/lib/README.md| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. || `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. || `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/cosValidation.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`. || `reviewerPins.js` | Client mirrors of 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 the server's own ladders, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. || `loraEffect.js` | Mirror of the LoRA adapter-effect report vocabulary in `server/lib/loraEffect.js` (#4872): `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`), `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (badge label and Tailwind tone — only `zero` is styled as an error, because only `zero` refuses a render server-side), and `formatLoraEffect(report)`, the same one-line summary the server logs, returning `null` when the badge already says everything. Pinned by `loraEffect.parity.test.js`. || `loraTriggers.js` | Mirror of the trigger-word predicates in `server/lib/loraTriggers.js` (#4665): `firstTriggerWord` (the canonical activation token of a Civitai `trainedWords` list) and `promptHasTriggerWord` (whole-token, case-insensitive presence — `aria_tok` does not match inside `aria_token`). Plus `appendTriggerWords(prompt, words, effectivePrompt?)` — the "+ trigger" button's append, which 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. Lets the LoRA picker warn that the server is about to append a token, with the button and the hint sharing one presence rule. |diff --git a/client/src/lib/reviewerModels.js b/client/src/lib/reviewerModels.jsindex 7188f8b419..3cd9641ef6 100644--- a/client/src/lib/reviewerModels.js+++ b/client/src/lib/reviewerModels.js@@ -19,7 +19,7 @@ import {* one documented conversion point rather than a hand-rolled loop in each consumer.** Server mirror: `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in- * `server/lib/cosValidation.js`.+ * `server/lib/reviewerConfig.js`.*//**diff --git a/client/src/lib/reviewerPins.js b/client/src/lib/reviewerPins.jsindex f9e99d75db..d34fe43737 100644--- a/client/src/lib/reviewerPins.js+++ b/client/src/lib/reviewerPins.js@@ -8,13 +8,13 @@ import {/*** Client mirrors of the per-reviewer PIN vocabularies in- * `server/lib/cosValidation.js` — which reviewers can carry a model or an effort+ * `server/lib/reviewerConfig.js` — which reviewers can carry a model or an effort* pin, and which values each one accepts.** **Why these live in a leaf module rather than in `components/cos/constants.js`.*** The server suite pins this mirror against the server's own derived ladders (see* the `client mirror of the reviewer effort ladders` test in- * `server/lib/cosValidation.test.js`) — a level offered here but rejected there+ * `server/lib/reviewerConfig.test.js`) — a level offered here but rejected there* would show the user a pin that silently never persists, and the reverse would* hide a tier their CLI accepts. That test runs in the SERVER workspace, which has* no client dependencies installed, so anything it imports must not reach for one.diff --git a/server/lib/README.md b/server/lib/README.mdindex 23ecfd27a1..c7d1d5e395 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -69,7 +69,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `appleHealthValidation.js` | Apple Health import payloads. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). || `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |-| `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Review-Loop reviewer vocabulary + helpers (`normalizeReviewers`/`buildReviewWithArgs`), the Code-Review settings slice, and the task-metadata sanitizer. |+| `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Code-Review settings slice, and the task-metadata sanitizer. The Review-Loop reviewer vocabulary lives in `reviewerConfig.js` (#5702) and is re-exported flat from here. || `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. Brief field caps are mirrored by the commission form in `client/src/components/creative-commission/commissionForm.js` (parity: `creativeCommissionValidation.mirror.test.js`). || `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. `CREATIVE_DIRECTOR_GOAL_MAX` is mirrored in `client/src/lib/creativeDirectorPlan.js` (parity: `creativeDirectorValidation.mirror.test.js`). || `digitalTwinValidation.js` | Digital twin document/category schemas. |@@ -142,6 +142,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`), 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. || `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. |diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 0efc74d85a..1b2afcebb0 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -1,1178 +1,53 @@/**- * Chief-of-Staff (CoS) Zod schemas + reviewer config (split out of validation.js,- * issue #1831).+ * Chief-of-Staff (CoS) Zod schemas (split out of validation.js, issue #1831).*- * Covers CoS tasks, the Review-Loop reviewer vocabulary + helpers- * (`normalizeReviewers` / `buildReviewWithArgs`), the Code-Review settings slice,- * recurring jobs, loops, learning insights, and the task-metadata sanitizer.- * validation.js re-exports everything here (flat) so existing deep imports keep- * working; the barrel surfaces it as the `cosValidation` namespace.+ * Covers CoS tasks, the Code-Review settings slice, recurring jobs, loops,+ * learning insights, and the task-metadata sanitizer. The Review-Loop reviewer+ * vocabulary + helpers (`normalizeReviewers` / `buildReviewWithArgs`) moved to+ * `reviewerConfig.js` (issue #5702) and are re-exported flat from here, so+ * existing deep imports keep working. validation.js re-exports everything here+ * (flat); the barrel surfaces it as the `cosValidation` namespace.*/import { z } from 'zod';import { emptyToUndefined, emptyToNull } from './zodCompat.js';import { isPlainObject } from './objects.js';-import { EFFORT_LEVELS, effortLevelsForProvider, buildEffortArgs, foldCursorEffortIntoModel, splitAntigravityModel } from './providerModels.js';-import { ANTIGRAVITY_COMMAND } from './antigravity.js';-import { CURSOR_COMMAND } from './cursor.js';+import { EFFORT_LEVELS } from './providerModels.js';import { isValidSlashdoCommand } from './slashdoInvocation.js';import { PR_COMPLETION_VALUES } from './prDisposition.js';import { PUBLIC_REVIEW_EXECUTION_PROFILES } from './agentExecutionProfiles.js';import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';import { recurrenceRuleSchema } from './recurrenceValidation.js';import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';+import {+ EFFORT_SELECTABLE_REVIEWERS,+ KEYED_REVIEWER_PINS,+ LOCAL_LLM_REVIEWERS,+ MAX_REVIEWER_MAX_ROUNDS,+ MAX_REVIEWER_MODEL_LENGTH,+ MODEL_CAPABLE_CLI_REVIEWERS,+ MODEL_SELECTABLE_REVIEWERS,+ REVIEWER_ALIASES,+ REVIEWER_VALUES,+ REVIEW_STOP_MODES,+ normalizeOptionalReviewers,+ normalizeReviewUsernames,+ normalizeReviewerEffort,+ normalizeReviewerEfforts,+ normalizeReviewerMaxRounds,+ normalizeReviewerModel,+ normalizeReviewerModels,+ resolveReviewUsernames,+} from './reviewerConfig.js';export { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';+// Transitional shim: the reviewer vocabulary lives in reviewerConfig.js but is+// still reachable from every existing `cosValidation.js` / `validation.js` import.+export * from './reviewerConfig.js';// =============================================================================// COS TASK SCHEMAS// =============================================================================-// Reviewer choices for the Review Loop. `copilot` requests a native GitHub-// Copilot review; `claude`/`antigravity`/`codex`/`grok`/`cursor` instruct the review-loop-// follow-up agent to invoke the named CLI to critique the PR diff; `lmstudio`/`ollama`-// route the diff through PortOS's local code-review endpoint-// (`POST /api/code-review/local`) which runs the configured local LLM model.-// Mirrored in client/src/components/cos/constants.js → REVIEWER_OPTIONS.-export const REVIEWER_VALUES = ['copilot', 'claude', 'antigravity', 'codex', 'grok', 'cursor', 'lmstudio', 'ollama'];-export const REVIEWER_ALIASES = { gemini: 'antigravity', 'cursor-agent': 'cursor' };-export const DEFAULT_REVIEWER = 'copilot';-export const DEFAULT_REVIEWERS = ['copilot'];-// Reviewers that resolve to a local-LLM backend (rather than a CLI or GitHub-// bot). Used by the code-review endpoint, settings panel, and prompt builder-// to gate model-id resolution.-export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];-// Reviewers PortOS serves ITSELF, with no counterpart in slashdo's reviewer-// vocabulary: `lmstudio` runs through `POST /api/code-review/local`, which takes-// its model in the request body. slashdo has no such slug, so it can neither-// carry a `[<model>]` bracket nor appear in a `--review-with` list (an unknown-// value aborts the command). One constant so a future addition can't be fixed-// in one of those two places and missed in the other.-export const PORTOS_ONLY_REVIEWERS = ['lmstudio'];-// 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` / `antigravityModel`). 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. `antigravity` runs `agy --model <id>`; an effort-suffixed-// agy id is reconciled with the effort pin by `pairReviewerModelsAndEfforts`.-// `grok` runs `grok --model <id>` (slashdo's `grok[<model>]` bracket); it takes a-// model but NO effort at all, which is why this roster and-// EFFORT_SELECTABLE_REVIEWERS are genuinely different sets rather than two names-// for one list. `cursor` runs `cursor-agent --model <id>` and DOES take an-// effort — but as a parameter of the model id (`gpt-5[effort=max]`), not a flag,-// so its pin rides this roster's `--model` rather than an `--effort` argv.-// 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 when its CLI gains model selection; the `<reviewer>Model`-// settings scalar is generated from this roster (codeReviewSettingsSchema).-export const MODEL_CAPABLE_CLI_REVIEWERS = ['codex', 'claude', 'antigravity', 'grok', 'cursor'];-// Every reviewer whose model the user can PICK in the UI: the model-capable CLIs-// above (threaded into the follow-up prompt as `<reviewer> --model <id>`) plus the-// local-LLM backends (whose id is injected server-side by-// `POST /api/code-review/local`, or emitted as slashdo's `[<model>]` bracket for a-// claim flow). `copilot` and `@username` reviewers are excluded — neither is a-// model-taking backend, matching slashdo rejecting `copilot[…]`/`@login[…]`.-export const MODEL_SELECTABLE_REVIEWERS = [...MODEL_CAPABLE_CLI_REVIEWERS, ...LOCAL_LLM_REVIEWERS];-// The executable a CLI reviewer's slug actually resolves to on PATH. Every slug-// except `antigravity` names its own binary; `antigravity` is the STORED,-// federated reviewer identity (aliased from the older `gemini`) while the-// shipped executable is `agy` — there is no `antigravity` command. A prompt that-// names only the slug sends the follow-up agent looking for a binary that does-// not exist: one CoS review-loop agent probed `command -v antigravity`, found-// nothing, declared "no reviewer available", and merged its own PR on a-// self-review. Prompt builders must resolve the slug through-// `reviewerCliBinary()` before telling an agent what to invoke.-// A reviewer absent from this map has no spawnable CLI (`copilot` is a GitHub-// API review, `lmstudio`/`ollama` go through `POST /api/code-review/local`).-export const REVIEWER_CLI_BINARIES = {- claude: 'claude',- antigravity: ANTIGRAVITY_COMMAND,- codex: 'codex',- grok: 'grok',- cursor: CURSOR_COMMAND,-};--/**- * Is this reviewer a CLI the agent spawns itself? Derived by EXCLUSION rather- * than from REVIEWER_CLI_BINARIES so a newly added CLI reviewer still drives the- * review loop before anyone remembers to map its binary (the map's coverage is- * pinned separately by cosValidation.test.js).- *- * The one definition of the rule — the prompt builder and the coverage test both- * call it, so neither can re-implement (and quietly diverge from) it.- *- * @param {string} reviewer - reviewer slug- * @returns {boolean}- */-export function isCliReviewer(reviewer) {- return reviewer !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(reviewer);-}--/**- * The PATH executable for a CLI reviewer slug, or `null` when the reviewer is- * not a spawnable CLI. Accepts the `gemini` alias.- *- * A null here means "no binary is mapped", NOT "not a CLI" — use isCliReviewer- * for that question. The two can disagree for exactly one reviewer: a new CLI- * reviewer added to REVIEWER_VALUES before its REVIEWER_CLI_BINARIES entry.- * That reviewer still drives the loop (isCliReviewer says yes) and its prompt- * falls back to naming the slug — the pre-existing behavior — rather than being- * silently dropped. cosValidation.test.js pins the map's coverage so the window- * closes at review time.- *- * @param {string} reviewer - reviewer slug (`antigravity`, `gemini`, `codex`, …)- * @returns {string|null}- */-export function reviewerCliBinary(reviewer) {- if (typeof reviewer !== 'string') return null;- const slug = reviewer.trim().toLowerCase();- return REVIEWER_CLI_BINARIES[REVIEWER_ALIASES[slug] || slug] || null;-}--/**- * Render a reviewer slug for an agent prompt as the command it must actually- * run, keeping the slug visible so the text still lines up with the configured- * reviewer list and slashdo's `--review-with` token.- *- * `antigravity` → ```agy` (the `antigravity` reviewer)``; every other reviewer,- * whose binary equals its slug, → ```codex` `` with no redundant restatement.- *- * @param {string} reviewer - reviewer slug- * @returns {string} markdown fragment- */-export function describeReviewerCli(reviewer) {- if (typeof reviewer !== 'string' || !reviewer) return '';- const binary = reviewerCliBinary(reviewer);- if (!binary || binary === reviewer) return `\`${reviewer}\``;- return `\`${binary}\` (the \`${reviewer}\` reviewer)`;-}-// 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';--// Arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`) requested as PR-// reviewers to gate merging — a class distinct from the fixed REVIEWER_VALUES-// enum (which either invoke a CLI, hit the local-LLM endpoint, or request the-// native Copilot reviewer). Usernames are appended to slashdo's `--review-with`-// as `@user` tokens after the keyed reviewers; the review-loop follow-up prompt-// instructs the agent to request each as a PR reviewer and gate the merge on it.-//-// Stored WITHOUT the leading `@` (added back only in the flag string). The-// charset is deliberately shell-safe — a GitHub username (1–39 chars,-// alphanumeric + single hyphens, no leading/trailing hyphen) optionally followed-// by a `/team-slug` for org-team mentions. No shell metacharacters, so the token-// stays inert wherever it lands in a command string.-export const MAX_REVIEW_USERNAMES = 20;-const REVIEW_USERNAME_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\/[A-Za-z0-9._-]{1,100})?$/;--/**- * Normalize a raw list of reviewer usernames: strip an optional leading `@`,- * trim, drop anything that isn't a shell-safe GitHub username/team slug,- * case-insensitively dedupe (GitHub logins are case-insensitive) while- * preserving first-occurrence order, and cap at MAX_REVIEW_USERNAMES. Returns- * a clean array of usernames WITHOUT the `@` prefix. Non-array input → [].- */-export function normalizeReviewUsernames(list) {- if (!Array.isArray(list)) return [];- const seen = new Set();- const out = [];- for (const raw of list) {- if (typeof raw !== 'string') continue;- const trimmed = raw.trim().replace(/^@+/, '');- if (!trimmed || !REVIEW_USERNAME_RE.test(trimmed)) continue;- const key = trimmed.toLowerCase();- if (seen.has(key)) continue;- seen.add(key);- out.push(trimmed);- if (out.length >= MAX_REVIEW_USERNAMES) break;- }- return out;-}--/**- * Resolve reviewer usernames with task-over-default precedence: a task-level- * list (even explicitly empty) overrides the Code Review Defaults; only fall- * back to the defaults when the task didn't pin its own. Mirrors how- * `normalizeReviewers`'s fallback param works for the keyed reviewers.- */-export function resolveReviewUsernames(metadataUsernames, defaultUsernames) {- return Array.isArray(metadataUsernames)- ? normalizeReviewUsernames(metadataUsernames)- : normalizeReviewUsernames(defaultUsernames);-}--/**- * Normalize ONE raw reviewer identity to the exact token `--review-with` emits:- * a keyed slug from `REVIEWER_VALUES` (aliasing `gemini` → `antigravity`) or an- * `@<username>`. Returns null for anything else. Single definition of the token- * identity shared by `normalizeOptionalReviewers` and- * `normalizeReviewerMaxRounds`, so the `~opt` set and the `~max=<n>` map can't- * disagree about what a reviewer is called.- */-function normalizeReviewerToken(raw) {- if (typeof raw !== 'string') return null;- const trimmed = raw.trim();- if (!trimmed) return null;- if (trimmed.startsWith('@')) {- const [user] = normalizeReviewUsernames([trimmed]);- return user ? `@${user}` : null;- }- const slug = REVIEWER_ALIASES[trimmed] ?? trimmed;- return REVIEWER_VALUES.includes(slug) ? slug : null;-}--/**- * Reviewer identities the user marked OPTIONAL (non-blocking). slashdo's `~opt`- * suffix is appended to each matching `--review-with` token, so an *inconclusive*- * verdict from that reviewer (timeout / no-verdict / partial) no longer gates the- * merge — a hard-error from it still does (slashdo `lib/multi-reviewer-loop.md`).- * This is the escape hatch for a valuable-but-flaky reviewer (a local Ollama- * model that often returns nothing) that would otherwise strand every PR on an- * `inconclusive` aggregate.- *- * Each entry mirrors an *emitted* `--review-with` token so the builder's- * membership test is a plain lookup: a keyed slug from `REVIEWER_VALUES`- * (`ollama`, `lmstudio`, …) or an `@<username>`. Normalizes like the sibling- * helpers — drop non-strings/unknown slugs/unsafe usernames, alias `gemini` →- * `antigravity`, dedupe case-insensitively preserving order. Non-array → undefined- * (an omitted field isn't persisted as an empty override).- */-export function normalizeOptionalReviewers(list) {- if (!Array.isArray(list)) return undefined;- const seen = new Set();- const out = [];- for (const raw of list) {- const token = normalizeReviewerToken(raw);- if (!token) continue;- const key = token.toLowerCase();- if (seen.has(key)) continue;- seen.add(key);- out.push(token);- }- return out;-}--/**- * Resolve optional (non-blocking) reviewers with task-over-default precedence:- * a task-level list (even explicitly empty) overrides the Code Review Defaults;- * only fall back to the defaults when the task didn't pin its own. Mirrors- * `resolveReviewUsernames`.- */-export function resolveOptionalReviewers(metadataOptional, defaultOptional) {- return Array.isArray(metadataOptional)- ? (normalizeOptionalReviewers(metadataOptional) || [])- : (normalizeOptionalReviewers(defaultOptional) || []);-}--/**- * Factory for the token-keyed per-reviewer PIN normalizers (`~max=<n>` caps,- * model ids, reasoning efforts). All three share one contract and only differ in- * how they validate a single value, so the contract lives here once:- *- * - Non-object input → `undefined`, so an omitted field isn't persisted as an- * empty override (an explicitly empty `{}` IS kept — it's a real "clear the- * defaults for this task" choice).- * - Keys are normalized to the exact token `--review-with` emits- * (`normalizeReviewerToken`), so the maps can't disagree about what a reviewer- * is called; unknown tokens are dropped.- * - First spelling wins for two names of one reviewer (`gemini`/`antigravity`,- * `@Bot`/`@bot`) — mirrors `normalizeOptionalReviewers`' dedupe.- * - A value `normalizeOne` rejects is DROPPED, never coerced — for every pin- * kind, "absent" and "a falsy value" mean different things downstream.- *- * `Object.create(null)` while building so a reviewer token can't collide with- * `Object.prototype` keys; spread on return so callers get a plain object.- *- * @param {(value: unknown, token: string) => unknown} normalizeOne - returns the- * validated value, or a falsy value to drop the entry.- */-function keyedReviewerPinNormalizer(normalizeOne) {- return (map) => {- if (!isPlainObject(map)) return undefined;- const out = Object.create(null);- for (const [rawKey, rawValue] of Object.entries(map)) {- const token = normalizeReviewerToken(rawKey);- if (!token) continue;- const value = normalizeOne(rawValue, token);- if (!value && value !== 0) continue;- if (Object.prototype.hasOwnProperty.call(out, token)) continue;- out[token] = value;- }- return { ...out };- };-}--/**- * Factory for the matching task-over-default resolvers: a task-level map — even- * an explicitly empty one — overrides the Code Review Defaults; only an- * absent/malformed one falls back. Mirrors `resolveOptionalReviewers`.- *- * @param {(map: unknown) => Object|undefined} normalizeMap - the normalizer this- * pin kind was built with.- */-function keyedReviewerPinResolver(normalizeMap) {- return (metadataMap, defaultMap) => (isPlainObject(metadataMap)- ? (normalizeMap(metadataMap) || {})- : (normalizeMap(defaultMap) || {}));-}--// Ceiling on a per-reviewer `~max=<n>` cap. slashdo's inner loops carry their own-// 10-iteration safety guardrail, so a budget above it can never be spent —-// accepting one would just be a lie in the flag string.-export const MAX_REVIEWER_MAX_ROUNDS = 10;--/**- * Per-reviewer iteration caps — slashdo's `~max=<n>` suffix (v3.25.0). Caps how- * many review → fix → re-review cycles ONE reviewer runs before it stops, so a- * slow local model can be included in a chain without paying for its otherwise- * hardcoded 3 rounds (`--review-with claude~max=2,ollama~max=1,codex~max=3`).- * Stored as a token-keyed map (`{ ollama: 1, '@flaky-bot': 0 }`) rather than a- * list because the cap carries a value; the key is the same *emitted*- * `--review-with` token `normalizeOptionalReviewers` uses.- *- * **Absent ≠ 0.** slashdo reads `~max=0` as "loop until this reviewer is clean"- * (bounded by its own 10-round guardrail), which is the OPPOSITE of "no cap- * requested" (that keeps slashdo's built-in default of 3 for CLI/Ollama- * reviewers). So a missing key and an explicit `0` must never collapse: an entry- * whose value isn't a usable cap is DROPPED rather than coerced to `0`.- * Drops unknown tokens, non-integers, negatives, and anything above- * MAX_REVIEWER_MAX_ROUNDS so a hand-edited settings.json can't smuggle in an- * unbounded budget. Non-object input → undefined (an omitted field isn't- * persisted as an empty override).- *- * `0` is the one pin value that is falsy AND meaningful, which is why the shared- * factory keeps it explicitly.- */-export const normalizeReviewerMaxRounds = keyedReviewerPinNormalizer((rawValue) => (- // Only a genuine non-negative integer is a cap. A string "2", null, NaN, or- // 1.5 is not — and must NOT fall through to 0, which slashdo reads as- // "unlimited".- (Number.isInteger(rawValue) && rawValue >= 0 && rawValue <= MAX_REVIEWER_MAX_ROUNDS)- ? rawValue- : undefined-));--/**- * Resolve per-reviewer iteration caps with task-over-default precedence: a- * task-level map (even explicitly empty) overrides the Code Review Defaults;- * only fall back to the defaults when the task didn't pin its own. Mirrors- * `resolveOptionalReviewers`.- */-export const resolveReviewerMaxRounds = keyedReviewerPinResolver(normalizeReviewerMaxRounds);--// Upper bound on a pinned reviewer model id. Generous (Bedrock/Ollama ids get-// long) but present so a hand-edited settings.json can't smuggle in a blob that-// then round-trips the TASKS.md store.-export const MAX_REVIEWER_MODEL_LENGTH = 200;--// Characters a model id may not contain, because they are STRUCTURAL in the-// emitted `--review-with` token and there is no escape for them:-// - `]` would close the `[<model>]` selector early (`foo]~opt` → a corrupt entry-// whose remainder slashdo then parses as suffixes),-// - `[` would open a nested one,-// - `,` would split the entry list, turning one reviewer into two bogus ones,-// - whitespace that breaks lines would split the single-line flag string.-// Everything else stays legal on purpose: the value is free-form in slashdo's-// grammar (`agy[Gemini 3.5 Flash (High)]` is valid), and the field has to accept-// whatever id the user's environment actually needs. A space is fine; a newline is-// not.-const REVIEWER_MODEL_FORBIDDEN_RE = /[[\],\r\n\t]/;--/**- * Validate ONE reviewer model id — the single definition shared by the- * token-keyed map normalizer, the `<reviewer>Model` settings scalars, and the- * defaults→map adapter, so a pin can't be accepted by one path and dropped by- * another (which would show the user a stored pin that never reaches a reviewer).- *- * Returns the trimmed id, or `undefined` when it isn't usable: a non-string, a- * blank/whitespace-only value (absent ≠ `''` — a `--model ` with no id would break- * the invocation), an over-long one, one carrying a structural delimiter, or one- * naming a reviewer that takes no model. Pass `reviewer` to apply that last check.- */-function normalizeReviewerModel(raw, reviewer = null) {- if (reviewer !== null && !MODEL_SELECTABLE_REVIEWERS.includes(reviewer)) return undefined;- if (typeof raw !== 'string') return undefined;- const model = raw.trim();- if (!model || model.length > MAX_REVIEWER_MODEL_LENGTH) return undefined;- if (REVIEWER_MODEL_FORBIDDEN_RE.test(model)) return undefined;- return model;-}--// Reviewers whose slashdo `--review-with` entry accepts a `[<model>]` bracket-// (`lib/multi-reviewer-loop.md`: codex/claude/agy/grok/cursor/ollama). A-// PORTOS_ONLY_REVIEWERS entry has no slashdo counterpart at all, so a pinned-// model for it never becomes a bracket, and `copilot`/`@login` entries reject-// one outright.-export const BRACKET_MODEL_REVIEWERS = MODEL_SELECTABLE_REVIEWERS.filter(r => !PORTOS_ONLY_REVIEWERS.includes(r));--/**- * Per-reviewer model pins — the model id ONE reviewer runs with, keyed by the- * same emitted `--review-with` token as `normalizeOptionalReviewers` /- * `normalizeReviewerMaxRounds` (e.g. `{ codex: 'gpt-5.6-sol', ollama: 'qwen2.5:7b' }`).- *- * The value is free-text on purpose: a reviewer CLI is spawned by the *agent*,- * not by PortOS's argv builder, so the id the user needs is environment-specific- * (a Bedrock-form Claude id on a Bedrock box, an installed Ollama model for an- * Ollama-backed `claude`). We validate the shape, not the catalog.- *- * Only MODEL_SELECTABLE_REVIEWERS can carry a pin — `copilot` has no CLI and a- * `@username` reviewer is a human/bot, mirroring slashdo rejecting `copilot[…]`- * and `@login[…]`. An absent key means "let that reviewer pick its own default",- * which is NOT the same as an empty string, so a blank/whitespace value is- * DROPPED rather than persisted as `''` (a `--model ` with no id would break the- * reviewer invocation). Non-object input → undefined, so an omitted field isn't- * persisted as an empty override.- *- * An id carrying a character that is structural in the emitted token- * (REVIEWER_MODEL_FORBIDDEN_RE — `[`, `]`, `,`, line breaks) is dropped rather- * than emitted: there's no escape for them inside `[<model>]`, so `foo]~opt` would- * close the selector early and leave slashdo parsing the remainder as a suffix.- * Dropping is the safe failure — the reviewer falls back to its own default model- * instead of running against a corrupt reviewer list.- */-export const normalizeReviewerModels = keyedReviewerPinNormalizer(normalizeReviewerModel);--/**- * Resolve per-reviewer model pins with task-over-default precedence: a- * task-level map (even explicitly empty) overrides the Code Review Defaults;- * only fall back to the defaults when the task didn't pin its own. Mirrors- * `resolveReviewerMaxRounds`.- */-export const resolveReviewerModels = keyedReviewerPinResolver(normalizeReviewerModels);--/**- * Fold the Code Review Defaults' per-reviewer model SCALARS- * (`codexModel` / `claudeModel` / `lmstudioModel` / `ollamaModel`) into the- * token-keyed map shape the resolvers and the picker UI both speak.- *- * The scalars are the persisted settings encoding and stay that way — they cross- * installs, and rewriting them to a map would need a migration for zero gain.- * This is the one adapter between the two shapes; everything downstream works in- * map form.- */-export function reviewerModelsFromDefaults(defaults) {- const out = {};- 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- // builders would then drop.- const model = normalizeReviewerModel(defaults?.[`${r}Model`], r);- if (model) out[r] = model;- }- return out;-}--// Reasoning-effort ladder for the local-LLM reviewers. Their review request goes-// out as an OpenAI-compatible `/v1/chat/completions` call, whose `reasoning_effort`-// field both LM Studio and Ollama accept for thinking models — but only over the-// low/medium/high tier names. The wider CLI ladder (`minimal`/`xhigh`/`max`/-// `ultra`) is vendor-CLI vocabulary that an OpenAI-shaped backend can reject, so-// the local reviewers get their own, narrower set.-export const LOCAL_LLM_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);--/**- * Reviewer slug → the reasoning-effort ladder that reviewer accepts. Only- * reviewers WITH an effort control appear: `copilot` is a GitHub review, `grok`'s- * CLI has no effort control of any kind, and an `@username` reviewer is a person.- *- * A ladder here means "the user can PICK a level", not "the CLI takes an- * `--effort` flag" — `cursor` accepts a level only as a variant baked into its- * model id, so it appears here while `reviewerEffortArgs` returns `[]` for it- * and `reviewerModelArg` folds the level into `--model` instead.- *- * Built once at module load and DERIVED from `effortLevelsForProvider` rather- * than restated, so a reviewer's ladder here is exactly the one- * `reviewerEffortArgs` (and the agent-spawn argv builder) will accept — a CLI- * that gains or loses a tier moves both at once. The lookup goes through- * `reviewerCliBinary` because that's what identifies the CLI: the `antigravity`- * slug names no executable, `agy` does.- *- * Mirrored in `client/src/components/cos/constants.js` (pinned by a parity test)- * so the picker only offers a level the server would keep.- */-export const REVIEWER_EFFORT_LEVELS = Object.freeze(Object.fromEntries(- REVIEWER_VALUES- .map((slug) => {- if (LOCAL_LLM_REVIEWERS.includes(slug)) return [slug, LOCAL_LLM_EFFORT_LEVELS];- const binary = reviewerCliBinary(slug);- return [slug, binary ? effortLevelsForProvider({ id: slug, command: binary }) : null];- })- .filter(([, levels]) => levels?.length)-));--/**- * Every reviewer the user can pick an effort for — the effort-capable CLIs- * (`claude`, `codex`, `antigravity`, `cursor`) plus the local-LLM backends.- */-export const EFFORT_SELECTABLE_REVIEWERS = Object.freeze(Object.keys(REVIEWER_EFFORT_LEVELS));--/**- * The ladder for ONE reviewer token, or `null` when it takes no effort. Accepts- * the `gemini` alias; an `@username` token resolves to null like any non-reviewer.- *- * @param {string} reviewer - reviewer slug- * @returns {readonly string[]|null}- */-export function reviewerEffortLevels(reviewer) {- if (typeof reviewer !== 'string') return null;- const slug = reviewer.trim().toLowerCase();- return REVIEWER_EFFORT_LEVELS[REVIEWER_ALIASES[slug] ?? slug] || null;-}--/**- * Validate ONE reviewer effort — the single definition shared by the token-keyed- * map normalizer and the `<reviewer>Effort` settings scalars, so a level can't be- * accepted by one path and dropped by another.- *- * `reviewer` is REQUIRED — this is the tight branch by design. Defaulting it to- * "any known effort" would validate against the union of every ladder, so a- * caller that forgot the argument would quietly accept `ollama: 'ultra'` and- * `antigravity: 'max'`, the exact values the drop-don't-clamp contract exists to- * reject.- *- * Returns the level, or `undefined` when it isn't usable: a non-string, a level- * outside that reviewer's own ladder (`agy` really does reject `--effort max`),- * or a reviewer with no effort control at all. Deliberately NOT clamped the way- * `resolveCliEffort` clamps a provider pin: this value is user-chosen from a- * per-reviewer list, so an out-of-ladder entry means the stored config is stale- * or hand-edited, and silently reviewing at a *different* effort than the one- * displayed is worse than falling back to the reviewer's own default.- */-export function normalizeReviewerEffort(raw, reviewer) {- if (typeof raw !== 'string') return undefined;- const effort = raw.trim().toLowerCase();- if (!effort) return undefined;- return reviewerEffortLevels(reviewer)?.includes(effort) ? effort : undefined;-}--/**- * Per-reviewer reasoning-effort pins — how hard ONE reviewer thinks, keyed by the- * same emitted `--review-with` token as `normalizeReviewerModels` (e.g.- * `{ codex: 'high', ollama: 'low' }`).- *- * Three carriers, depending on who invokes the reviewer. On a slashdo invocation- * it rides the emitted token as `~effort=<level>` (`markSuffixes`), which slashdo- * turns into the reviewer's own flag. Where PortOS drives the invocation itself it- * is spelled out instead: the review-loop follow-up prompt's CLI command line- * (`codex -c model_reasoning_effort=high`, `claude --effort high`) and the- * `reasoning_effort` field of the local reviewer's `/api/code-review/local` body.- *- * An absent key means "let that reviewer use its own default effort", which is- * NOT the same as a blank string, so an unusable value is DROPPED rather than- * persisted. Non-object input → undefined, so an omitted field isn't persisted as- * an empty override.- */-export const normalizeReviewerEfforts = keyedReviewerPinNormalizer(normalizeReviewerEffort);--/**- * Resolve per-reviewer effort pins with task-over-default precedence: a- * task-level map (even explicitly empty) overrides the Code Review Defaults;- * only fall back to the defaults when the task didn't pin its own. Mirrors- * `resolveReviewerModels`.- */-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: prioritizeToolFreeReviewers(normalizeReviewers(metadata, defaultReviewers)),- usernames: resolveReviewUsernames(metadata?.usernames, codeReviewDefaults?.usernames),- optionalReviewers: resolveOptionalReviewers(metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers),- reviewerMaxRounds: resolveReviewerMaxRounds(metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds),- ...resolveReviewerPins(metadata, codeReviewDefaults)- };-}--/** The reviewer a claim flow falls back to when its resolved list is unusable. */-const CLAIM_REVIEWER_FALLBACK = ['codex'];--/**- * Constrain an already-resolved reviewer list to what an UNATTENDED claim run can- * actually invoke: `copilot` is a forge-side PR reviewer with no CLI, so a claim- * agent told to "review with copilot" has nothing to run and stalls (#2507).- * An empty result falls back to `codex` rather than to `DEFAULT_REVIEWERS`- * (which is `copilot`, the very thing being removed).- */-export function claimSafeReviewers(reviewers) {- const kept = (Array.isArray(reviewers) ? reviewers : []).filter((reviewer) => reviewer !== 'copilot');- return kept.length ? kept : [...CLAIM_REVIEWER_FALLBACK];-}--/**- * Put tool-free local-LLM reviewers ahead of every reviewer that can execute- * tools or reach a forge. Public issue comments and contributor diffs cross the- * trust boundary in that first pass; later reviewers see a chain that has- * already received a no-tool inspection. Stable partitioning preserves the- * user's order within the local and non-local groups.- */-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)),- ];-}--/**- * `resolveReviewerConfig` plus the claim flow's copilot guard and the emitted- * `--review-with` token list — the ONE resolver a claim prompt's reviewer text- * and a claim task's persisted `reviewers` metadata both go through, so the two- * cannot name different reviewers.- *- * The generators resolve their list before a task record exists (they read- * schedule metadata + Code Review Defaults); the prompt builder resolves it from- * the persisted task metadata at spawn time. Feeding both the same function is- * what makes `reviewerConfigMetadata`'s round-trip exact.- */-export function resolveClaimReviewerConfig(metadata, codeReviewDefaults, defaultReviewers) {- const config = resolveReviewerConfig(metadata, codeReviewDefaults, defaultReviewers);- const reviewers = claimSafeReviewers(config.reviewers);- return {- ...config,- reviewers,- csv: buildReviewersCsv(reviewers, config.usernames, config.optionalReviewers, config.reviewerMaxRounds, config.reviewerModels, config.reviewerEfforts)- };-}--/**- * The reviewer fields a task must PERSIST so a later- * `resolveReviewerConfig(task.metadata, …)` resolves the same list its prompt- * names, instead of re-deriving the install-wide Code Review Defaults (#4770).- *- * All six travel together: resolving only `reviewers` still lets the usernames,- * `~opt` set, and the three keyed pins fall back to the defaults, which is the- * same disagreement one field down. Sanitized on the way out so a hand-crafted- * request body can't smuggle an unrecognized key onto the task record, and every- * value is re-validated rather than trusted.- */-export function reviewerConfigMetadata(config) {- return sanitizeTaskMetadata({- reviewers: config?.reviewers,- usernames: config?.usernames,- optionalReviewers: config?.optionalReviewers,- reviewerMaxRounds: config?.reviewerMaxRounds,- reviewerModels: config?.reviewerModels,- reviewerEfforts: config?.reviewerEfforts- }) || {};-}--/**- * Resolve the model and effort pins TOGETHER — `{ reviewerModels, reviewerEfforts }`- * with task-over-default precedence, already reconciled into a pair the reviewer's- * CLI accepts (`pairReviewerModelsAndEfforts`).- *- * The two are never legitimately resolved apart: an `antigravity` model id can- * carry its effort as a suffix, so whoever resolves the models must also be- * holding the efforts to hand the suffix to. Resolving them separately is the- * footgun — three prompt-building sites in `cosTaskGenerator.js` had already- * hand-copied the pair of calls, and each would have emitted an- * `agy --model <suffixed-id> --effort <tier>` invocation agy rejects. This is the- * one call every site makes instead.- *- * Deliberately NOT expressed on `lib/llmRoutePin.js` (#4793). That module owns a- * single `{ providerId, model, effort }` triple; a reviewer pin is two maps keyed- * by reviewer slug, with no provider dimension at all — the slug IS the routing- * key — and its precedence is whole-MAP (an explicitly empty task map overrides- * the defaults), not per-field. Its effort is also validated against each- * reviewer's OWN ladder via `normalizeReviewerEffort`, which is strictly narrower- * than the union `EFFORT_LEVELS` enum the shared schema uses: `agy` really does- * reject `--effort max`. There is no shape the two can meet in without losing- * that narrowing, so this stays hand-rolled.- *- * @param {Object} [pins] - task metadata (or explicit options) carrying- * `reviewerModels` / `reviewerEfforts` maps; an absent map falls back to the- * Code Review Defaults, an explicitly empty one overrides them.- * @param {Object} [codeReviewDefaults] - the `<reviewer>Model` / `<reviewer>Effort` scalars- * @returns {{reviewerModels: Object<string,string>, reviewerEfforts: Object<string,string>}}- */-export function resolveReviewerPins(pins, codeReviewDefaults) {- return pairReviewerModelsAndEfforts(- resolveReviewerModels(pins?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults)),- resolveReviewerEfforts(pins?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults))- );-}--/**- * Reconcile the resolved model and effort pins into a pair the reviewer's CLI- * will actually accept, and return them as `{ reviewerModels, reviewerEfforts }`.- *- * Only `antigravity` needs reconciling. `agy models` enumerates its reasoning- * tiers as separate model ids (`gemini-3.6-flash-high`), so a hand-typed pin can- * carry an effort inside the model — and `agy` validates the PAIR, so- * `--model gemini-3.6-flash-high --effort high` is not the same thing as the- * `--model <base> --effort high` it expects. Splitting here mirrors what- * `resolveAntigravityModelAndEffort` already does for PortOS's own agy spawns:- * the base id becomes the model, and the baked tier supplies the effort ONLY when- * the user pinned none (an explicit pick always wins).- *- * Applied once inside `resolveReviewerPins` rather than at each emission site, so- * the slashdo `agy[<model>]` bracket, the effort instruction, and the review-loop- * prompt's literal command line all describe the same invocation.- *- * @param {Object<string,string>} [reviewerModels]- * @param {Object<string,string>} [reviewerEfforts]- * @returns {{reviewerModels: Object<string,string>, reviewerEfforts: Object<string,string>}}- */-export function pairReviewerModelsAndEfforts(reviewerModels, reviewerEfforts) {- const models = { ...(reviewerModels || {}) };- const efforts = { ...(reviewerEfforts || {}) };- const { base, effort } = splitAntigravityModel(models.antigravity);- if (effort && base) {- models.antigravity = base;- if (!normalizeReviewerEffort(efforts.antigravity, 'antigravity')) efforts.antigravity = effort;- }- return { reviewerModels: models, reviewerEfforts: efforts };-}--/**- * 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- * the token-keyed map shape the resolvers and the picker UI both speak — the- * effort twin of `reviewerModelsFromDefaults`, and the one adapter between the- * two shapes.- */-export function reviewerEffortsFromDefaults(defaults) {- const out = {};- for (const r of EFFORT_SELECTABLE_REVIEWERS) {- // Re-checked, not trusted: settings.json is hand-editable, and a stale level- // must not surface as a pin the invocation builders would then drop.- const effort = normalizeReviewerEffort(defaults?.[`${r}Effort`], r);- if (effort) out[r] = effort;- }- return out;-}--/**- * The argv fragment a CLI reviewer takes for a reasoning-effort override —- * `['--effort', 'high']` for claude/agy, `['-c', 'model_reasoning_effort=high']`- * for codex, `[]` for everything else. Delegates to `buildEffortArgs` so the flag- * shape has exactly one home (the spawn builders use the same one).- *- * **`cursor` is deliberately `[]` despite having a ladder.** `cursor-agent` has- * no `--effort` flag and exits non-zero on one, so its level rides `--model`- * instead — build that with `reviewerModelArg`. Anything that renders a cursor- * invocation must call BOTH, or it will silently drop the pin (or, worse,- * hand-roll the `--effort` this returns nothing for).- *- * **Normalizes first, deliberately.** `buildEffortArgs` CLAMPS an out-of-ladder- * value (`agy` + `max` → `--effort high`), which is right for a provider pin the- * user set against a different provider, but wrong here: a reviewer effort is- * chosen from that reviewer's own list, so an out-of-ladder value means stale or- * hand-edited state — and emitting a clamped flag would run the review at an- * effort the picker displays as `unsupported`. Dropping to the reviewer's own- * default is the honest failure, matching `normalizeReviewerEffort`'s contract.- * The normalize is here rather than left to callers because this function is- * reached with raw task metadata (`reviewLoopReviewerEfforts`), which no- * normalizer has necessarily touched.- *- * @param {string} reviewer - reviewer slug- * @param {string|null|undefined} effort- * @returns {string[]}- */-export function reviewerEffortArgs(reviewer, effort) {- const binary = reviewerCliBinary(reviewer);- if (!binary) return [];- const level = normalizeReviewerEffort(effort, reviewer);- if (!level) return [];- return buildEffortArgs(level, { id: reviewer, command: binary });-}--/**- * The id a CLI reviewer's `--model` flag should carry, or `null` when there is- * no model to pin. The twin of `reviewerEffortArgs`: together they are the whole- * invocation a pinned reviewer needs, and the ONLY place that knows which of the- * two carries a cursor effort.- *- * For every reviewer but `cursor` this is just the pinned id, threaded verbatim- * (the id is environment-specific free text — see `normalizeReviewerModels`).- * For `cursor` the effort is folded in as Cursor's native model variant- * (`gpt-5` + `max` → `gpt-5[effort=max]`), matching slashdo's own fold, because- * `cursor-agent` has no `--effort` flag. A cursor effort with no model pinned- * returns `null` — there is nothing to attach the variant to, and emitting a- * flag cursor rejects is worse than letting it use its default tier. (The picker- * says so on the row, so the dropped tier isn't silent to the user.)- *- * The extend-an-existing-bracket and leave-an-`effort=`-alone arms of the fold- * can't be reached by a STORED reviewer pin today — `normalizeReviewerModel`- * rejects `[`/`]`/`,` because they're structural in the emitted `--review-with`- * token. They serve the paths that don't go through that gate: a provider's own- * `defaultModel` and hand-written task metadata.- *- * @param {string} reviewer - reviewer slug- * @param {string|null|undefined} model - the pinned model id- * @param {string|null|undefined} [effort] - the pinned effort (cursor only)- * @returns {string|null}- */-export function reviewerModelArg(reviewer, model, effort) {- const id = typeof model === 'string' ? model.trim() : '';- if (!id) return null;- const slug = typeof reviewer === 'string' ? reviewer.trim().toLowerCase() : '';- if ((REVIEWER_ALIASES[slug] ?? slug) !== 'cursor') return id;- const level = normalizeReviewerEffort(effort, 'cursor');- return level ? foldCursorEffortIntoModel(id, level) : id;-}--/**- * Prose instruction carrying the per-reviewer effort pins into a prompt whose- * agent spawns the reviewer CLI ITSELF — the claim flows (which run each- * configured reviewer by hand, no `--review-with` anywhere in the prompt) and a- * slashdo invocation that pins no reviewer list.- *- * **Not for an invocation that pins `--review-with`.** slashdo's entry grammar is- * `<agent>[<model>](~opt|~max=<n>|~effort=<level>)*`, and `markSuffixes` emits- * that `~effort=` suffix, so the pin already reaches the CLI the loop spawns.- * Restating it as prose there is worse than silent: the agent passes the flag a- * second time, or hand-runs a reviewer the loop was about to run. Pass the- * emitted `--review-with` text as `reviewWith` and this returns '' when it sees- * the suffix — one check, so a caller can't decide wrong.- *- * Scoped to CLI reviewers on purpose — `ollama`/`lmstudio` have no binary to- * name (their effort rides the `POST /api/code-review/local` body instead).- *- * `cursor` needs its MODEL to say anything at all: its level is a variant of the- * model id, never a flag, so pass `reviewerModels` — a cursor pin with no model- * emits nothing rather than an `--effort` its CLI rejects.- *- * @param {string[]} reviewers - the reviewer slugs the invocation emits- * @param {Object<string, string>} [reviewerEfforts] - token-keyed effort pins- * @param {Object} [options]- * @param {string} [options.reviewWith] - the `--review-with` text this prompt- * emits, if any. A `~effort=` in it means slashdo already carries the pin.- * @param {Object<string, string>} [options.reviewerModels] - token-keyed model- * pins, needed only to render a cursor invocation (see above)- * @returns {string} a single sentence, or '' when nothing is left to say- */-export function buildReviewerEffortNote(reviewers, reviewerEfforts = {}, { reviewWith = '', reviewerModels = {} } = {}) {- if (typeof reviewWith === 'string' && reviewWith.includes('~effort=')) return '';- const efforts = normalizeReviewerEfforts(reviewerEfforts) || {};- const models = normalizeReviewerModels(reviewerModels) || {};- const entries = (Array.isArray(reviewers) ? reviewers : [])- .map((r) => {- // No binary, nothing to name: `lmstudio`/`ollama` reach their backend over- // HTTP, and copilot/@username aren't commands at all. Checked FIRST so no- // branch below can render a `null` command into a prompt.- const binary = reviewerCliBinary(r);- if (!binary) return null;- const args = reviewerEffortArgs(r, efforts[r]);- if (args.length) return `\`${binary} ${args.join(' ')}\``;- // No effort ARGV, but the reviewer may still carry the level inside- // --model (cursor). Gated on the effort pin so this stays an effort note:- // a model-only pin is not this sentence's business.- if (!normalizeReviewerEffort(efforts[r], r)) return null;- const model = reviewerModelArg(r, models[r], efforts[r]);- return model ? `\`${binary} --model ${model}\`` : null;- })- .filter(Boolean);- if (!entries.length) return '';- return `Invoke each reviewer CLI at its pinned reasoning effort: ${entries.join(', ')}. Pass the flag yourself when you spawn the reviewer — nothing else in this prompt applies it (a \`~effort=<level>\` suffix in a reviewer list is slashdo's own grammar, which only its \`--review-with\` parses).`;-}--// Examples of slashdo commands that run a review loop and therefore resolve-// `--review-with` from a saved default when the invocation doesn't pin one.-// EXAMPLES, deliberately — the rule is stated over "any `/do:*` that reviews"-// because the real roster is larger and moves with the submodule (`/do:review`,-// `/do:better`, `/do:better-swift`, `/do:depfree`, `/do:release` all read it-// too). A hand-maintained enumeration is the part that rots, and a command-// missing from it would read as exempt.-const REVIEW_LOOP_SLASHDO_EXAMPLES_MD = ['/do:pr', '/do:next', '/do:review', '/do:rpr']- .map(command => `\`${command}\``).join(', ');--/**- * The reviewer slug inside an emitted `--review-with` token, without its- * `[<model>]` / `~<suffix>` decoration — the inverse of `markSuffixes`, which is- * the only thing that ever builds one. Kept beside its emitter, and pinned to it- * by a round-trip test, so a grammar change can't silently mis-slug here.- */-export const reviewerTokenSlug = (token) => String(token).split('[')[0].split('~')[0].trim().toLowerCase();--/**- * Prose block pinning a claim prompt's reviewer list against slashdo's SAVED- * defaults.- *- * The claim flows hand-run their reviewers, so the prompt names the list and- * emits no flag. But the claim agent is usually a Claude Code session with- * slashdo installed, and reaching for `/do:pr` mid-flow is a short step from- * the phase text — at which point slashdo resolves `--review-with` from the- * host's saved defaults (`.slashdo.json` at the repo root, or the host CLI's- * `.slashdo-config.json`), i.e. some OTHER user-level reviewer set, plus- * whatever `merge` default rides with it. That silently replaces the reviewers- * PortOS resolved for this run. So state the pin once, in the prompt, with the- * exact token list to pass.- *- * `reviewersCsv` must be the text `buildReviewersCsv` emits — the same- * `<agent>[<model>]~opt~max=<n>~effort=<level>` grammar `--review-with` parses —- * so the agent can paste it verbatim.- *- * Unlike `buildReviewWithArgs` this does NOT suppress a lone bare `copilot`- * (the #2507 stall): every claim path resolves its list through- * `claimSafeReviewers`, which strips `copilot` and falls back to `codex`,- * so the suppressed case cannot reach here. A future caller that skips that- * normalizer has to add the guard rather than assume it.- *- * @param {string} reviewersCsv - the emitted reviewer token list- * @returns {string} a Markdown block, or '' when there is no list to pin- */-export function buildReviewerPinNote(reviewersCsv) {- const csv = typeof reviewersCsv === 'string' ? reviewersCsv.trim() : '';- if (!csv) return '';- // A `@login` entry is always a valid slashdo reviewer; a keyed one is valid- // unless PortOS serves it itself. Emitting a PORTOS_ONLY_REVIEWERS slug in a- // `--review-with` list would abort the command outright, so it is dropped from- // the flag text and named separately with the procedure that DOES run it.- const tokens = csv.split(',').map(t => t.trim()).filter(Boolean);- const flagTokens = tokens.filter(t => t.startsWith('@') || !PORTOS_ONLY_REVIEWERS.includes(reviewerTokenSlug(t)));- // Named by bare slug: the `[<model>]`/`~<suffix>` decoration is slashdo- // grammar, and these reviewers never reach a slashdo parser.- const portosOnly = [...new Set(tokens.filter(t => !flagTokens.includes(t)).map(reviewerTokenSlug))];-- return [- '## Reviewer pin — use the reviewers PortOS configured',- `PortOS resolved this run's reviewers from its own configuration: \`${csv}\`. That list is authoritative for every review in this run — it is the same list the phases above name. Never substitute a different reviewer set for it.`,- flagTokens.length- && `**A saved slashdo default must never stand in for it.** If you invoke ANY slashdo \`/do:*\` command that runs a review loop (${REVIEW_LOOP_SLASHDO_EXAMPLES_MD}, and others), pass \`--review-with ${flagTokens.join(',')}\` explicitly. A bare invocation resolves \`--review-with\` from the host's saved defaults instead — \`.slashdo.json\` at the repo root, or the host CLI's \`.slashdo-config.json\` — which name a different reviewer set and can carry an auto-merge default this run never asked for.`,- flagTokens.length- && 'Pass those tokens exactly as written: their `[<model>]`, `~opt`, `~max=<n>`, and `~effort=<level>` suffixes are slashdo grammar and already carry each reviewer\'s pinned model, optional/blocking status, round cap, and reasoning effort — so do not also apply those by hand on that path.',- portosOnly.length- && `PortOS runs \`${portosOnly.join('`, `')}\` itself — no slashdo slug, so never a \`--review-with\` value. That review happens through the Local Reviewer Procedure below, and leaving it out of a slashdo invocation is not permission to skip it.`,- ].filter(Boolean).join('\n\n');-}--/**- * Build the set of lowercased optional-reviewer tokens for a fast membership- * test in the builders. Tolerates the raw (unnormalized) list.- */-function optionalReviewerSet(optionalReviewers) {- return new Set((normalizeOptionalReviewers(optionalReviewers) || []).map(t => t.toLowerCase()));-}--/**- * Build a lowercased-token → cap lookup for the builders. Tolerates the raw- * (unnormalized) map. A `Map` (not a plain object) so a reviewer token can never- * collide with `Object.prototype` keys, and so `.get()` distinguishes an absent- * cap (`undefined`) from an explicit `0`.- */-function reviewerMaxRoundsLookup(reviewerMaxRounds) {- const normalized = normalizeReviewerMaxRounds(reviewerMaxRounds) || {};- return new Map(Object.entries(normalized).map(([token, max]) => [token.toLowerCase(), max]));-}--/**- * Build a lowercased-token → model-id lookup for the builders. Tolerates the raw- * (unnormalized) map. A `Map` for the same reasons as the cap lookup.- */-function reviewerModelLookup(reviewerModels) {- const normalized = normalizeReviewerModels(reviewerModels) || {};- return new Map(Object.entries(normalized).map(([token, model]) => [token.toLowerCase(), model]));-}--/**- * Build a lowercased-token → effort-level lookup for the builders. Tolerates the raw- * (unnormalized) map. A `Map` for the same reasons as the cap and model lookups.- */-function reviewerEffortLookup(reviewerEfforts) {- const normalized = normalizeReviewerEfforts(reviewerEfforts) || {};- return new Map(Object.entries(normalized).map(([token, effort]) => [token.toLowerCase(), effort]));-}--/**- * Render one emitted `--review-with` entry: the reviewer token, its optional- * `[<model>]` selector, then slashdo's per-entry suffixes in canonical storage- * order — `~opt`, `~max=<n>`, then `~effort=<level>`.- *- * Order matters. slashdo's grammar is- * `entry := ( <agent> [ "[" <model> "]" ] | "@" <login> ) ( "~opt" | "~max=" <n> | "~effort=" <level> )*`- * and its parser strips the `~` suffixes from the RIGHT before reading the- * bracket — so the bracket has to sit between the slug and the suffixes.- *- * A reviewer with no pinned model emits no bracket, which is what leaves that- * reviewer's own default in place; likewise a reviewer with no cap emits no- * `~max` at all (`~max=0` is a real, distinct value meaning "loop until clean"), and- * a reviewer with no effort level emits no `~effort`.- * Only BRACKET_MODEL_REVIEWERS get a bracket — `copilot`/`@login` reject one, and- * PortOS's `lmstudio` reviewer has no slashdo slug at all (its model rides in the- * `POST /api/code-review/local` body instead).- */-function markSuffixes(token, optSet, maxLookup, modelLookup, effortLookup) {- const key = token.toLowerCase();- const max = maxLookup?.get(key);- const model = BRACKET_MODEL_REVIEWERS.includes(key) ? modelLookup?.get(key) : undefined;- const effort = effortLookup?.get(key);- return `${token}${model ? `[${model}]` : ''}${optSet.has(key) ? '~opt' : ''}${max === undefined ? '' : `~max=${max}`}${effort ? `~effort=${effort}` : ''}`;-}--/**- * Resolve task metadata to an ordered, deduped reviewer list. Prefers the new- * `reviewers` array; falls back to the legacy single `reviewer` string. When- * the metadata yields nothing, returns `fallback` (default `['copilot']`) —- * pass the settings-resolved defaults here so a Review Loop run picks up the- * user's Code Review Defaults instead of the hardcoded copilot when the task- * itself didn't pin reviewers. Filters to known reviewers and preserves- * first-occurrence order.- */-export function normalizeReviewers(meta, fallback = DEFAULT_REVIEWERS) {- const raw = meta && typeof meta === 'object' && !Array.isArray(meta) ? meta : {};- const source = Array.isArray(raw.reviewers)- ? raw.reviewers- : (typeof raw.reviewer === 'string' && raw.reviewer ? [raw.reviewer] : []);- const seen = new Set();- 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 (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)) {- fallbackSeen.add(normalized);- fallbackList.push(normalized);- }- }- return fallbackList.length ? [...fallbackList] : [...DEFAULT_REVIEWERS];-}--/**- * Resolve the keyed (enum) reviewer list, honoring the "username-only" case: an- * EXPLICITLY empty keyed list with username reviewers present (e.g. copilot was- * stripped on a non-GitHub forge) stays empty rather than falling back to the- * copilot default normalizeReviewers would apply. Absent/legacy input still- * normalizes to the default. Single source for the guard shared by- * `buildReviewWithArgs` and the review-loop follow-up prompt builder.- */-export function resolveKeyedReviewers(reviewers, hasUsernames) {- if (Array.isArray(reviewers) && reviewers.length === 0 && hasUsernames) return [];- return normalizeReviewers({ reviewers });-}--/**- * Build the comma-separated reviewer token list used to fill the `{reviewers}`- * placeholder in claim/plan prompts: keyed reviewers (falling back to the- * default when empty) followed by `@user` tokens for the reviewer usernames.- * Reviewers in `optionalReviewers` get slashdo's `~opt` non-blocking suffix, and- * reviewers carrying a `reviewerMaxRounds` cap get `~max=<n>` after it. A- * reviewer with a `reviewerModels` pin gets slashdo's `[<model>]` selector- * between the slug and those suffixes, and a reviewer with a `reviewerEfforts` pin- * gets `~effort=<level>`.- * The flag-string variant is `buildReviewWithArgs`.- */-export function buildReviewersCsv(reviewers, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}) {- const keyed = Array.isArray(reviewers) && reviewers.length ? reviewers : [...DEFAULT_REVIEWERS];- const users = normalizeReviewUsernames(usernames);- const optSet = optionalReviewerSet(optionalReviewers);- const maxLookup = reviewerMaxRoundsLookup(reviewerMaxRounds);- const modelLookup = reviewerModelLookup(reviewerModels);- const effortLookup = reviewerEffortLookup(reviewerEfforts);- const combined = [...keyed, ...users.map(u => `@${u}`)];- return combined.map(t => markSuffixes(t, optSet, maxLookup, modelLookup, effortLookup)).join(',');-}--/**- * Build the slashdo review flag string for an ordered reviewer list plus any- * arbitrary GitHub reviewer usernames.- * - `--review-with a,b,@user` only when the effective list isn't the lone default- * copilot (any username, or any non-default keyed reviewer, forces it on).- * Usernames are appended as `@user` tokens after the keyed reviewers.- * - `--review-stop-on-*` only when the effective list is 2+ (stop-mode is- * meaningless for one).- * - `--reviewer-applies` only when a non-copilot KEYED reviewer is present (a- * username reviewer is an external PR reviewer, not a CLI that applies fixes).- * - Reviewers in `optionalReviewers` get slashdo's `~opt` non-blocking suffix on- * their emitted token, so an inconclusive verdict from them doesn't gate the- * merge. Reviewers with a `reviewerMaxRounds` cap get `~max=<n>` after it,- * a reviewer with a `reviewerModels` pin gets a `[<model>]` selector before both,- * and a reviewer with a `reviewerEfforts` pin gets `~effort=<level>`.- * A lone default `copilot` that is marked optional, carries a cap, or carries an- * effort DOES force the flag on (otherwise the suffix — the whole point — would be- * dropped with the flag).- *- * Everything past `reviewers` is an options object: the two reviewer-name lists- * (`usernames` / `optionalReviewers`) and the three per-reviewer lookup maps- * (`reviewerMaxRounds` / `reviewerModels` / `reviewerEfforts`) are same-shaped.- *- * @param {string[]} reviewers - ordered keyed reviewer slugs- * @param {Object} [options]- * @param {string} [options.stopMode] - review stop mode (`all` / `on-findings` / `on-clean`)- * @param {boolean} [options.reviewerApplies] - emit `--reviewer-applies`- * @param {string[]} [options.usernames] - GitHub reviewer usernames (emitted as `@user`)- * @param {string[]} [options.optionalReviewers] - reviewers that get the `~opt` suffix- * @param {Object<string, number>} [options.reviewerMaxRounds] - per-reviewer `~max=<n>` caps- * @param {Object<string, string>} [options.reviewerModels] - per-reviewer `[<model>]` pins- * @param {Object<string, string>} [options.reviewerEfforts] - per-reviewer `~effort=<level>` pins- * @returns {string} the slashdo review flag string (possibly empty)- */-export function buildReviewWithArgs(reviewers, {- stopMode = DEFAULT_REVIEW_STOP_MODE,- reviewerApplies = false,- usernames = [],- optionalReviewers = [],- reviewerMaxRounds = {},- reviewerModels = {},- reviewerEfforts = {},-} = {}) {- const users = normalizeReviewUsernames(usernames);- const keyed = resolveKeyedReviewers(reviewers, users.length > 0);- const combined = [...keyed, ...users.map(u => `@${u}`)];- const optSet = optionalReviewerSet(optionalReviewers);- const maxLookup = reviewerMaxRoundsLookup(reviewerMaxRounds);- const modelLookup = reviewerModelLookup(reviewerModels);- const effortLookup = reviewerEffortLookup(reviewerEfforts);- // The lone-default-copilot suppression only applies when copilot carries NO- // per-entry suffix — a `copilot~opt` / `copilot~max=2` / `copilot~effort=high` list must still- // emit the flag to carry that suffix.- const isDefaultOnly = combined.length === 1 && combined[0] === DEFAULT_REVIEWER- && !optSet.has(DEFAULT_REVIEWER) && maxLookup.get(DEFAULT_REVIEWER) === undefined- && effortLookup.get(DEFAULT_REVIEWER) === undefined;- const hasNonCopilot = keyed.some(r => r !== DEFAULT_REVIEWER);- const parts = [];- if (!isDefaultOnly) parts.push(`--review-with ${combined.map(t => markSuffixes(t, optSet, maxLookup, modelLookup, effortLookup)).join(',')}`);- if (combined.length >= 2) {- if (stopMode === 'on-findings') parts.push('--review-stop-on-findings');- else if (stopMode === 'on-clean') parts.push('--review-stop-on-clean');- }- if (reviewerApplies && hasNonCopilot) parts.push('--reviewer-applies');- return parts.join(' ');-}// A generic file attachment uploaded via POST /api/attachments and referenced// by the returned metadata — matches the fileInfo shape TaskAddForm.jsx sends@@ -2120,6 +995,32 @@ export function sanitizeTaskMetadata(raw) {return hasKeys ? { ...clean } : null;}+// `reviewerConfigMetadata` stays here rather than in reviewerConfig.js (#5702):+// it is a thin wrapper over `sanitizeTaskMetadata` above, and reviewerConfig.js+// must not import this module (that would close a cycle and drag Zod back into+// the reviewer vocabulary). Re-exported to callers unchanged.+/**+ * The reviewer fields a task must PERSIST so a later+ * `resolveReviewerConfig(task.metadata, …)` resolves the same list its prompt+ * names, instead of re-deriving the install-wide Code Review Defaults (#4770).+ *+ * All six travel together: resolving only `reviewers` still lets the usernames,+ * `~opt` set, and the three keyed pins fall back to the defaults, which is the+ * same disagreement one field down. Sanitized on the way out so a hand-crafted+ * request body can't smuggle an unrecognized key onto the task record, and every+ * value is re-validated rather than trusted.+ */+export function reviewerConfigMetadata(config) {+ return sanitizeTaskMetadata({+ reviewers: config?.reviewers,+ usernames: config?.usernames,+ optionalReviewers: config?.optionalReviewers,+ reviewerMaxRounds: config?.reviewerMaxRounds,+ reviewerModels: config?.reviewerModels,+ reviewerEfforts: config?.reviewerEfforts+ }) || {};+}+// =============================================================================// CoS RUN EVENT LEDGER (read-only diagnostics, #4540)// =============================================================================diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.jsindex b6bcb3c168..693ad67328 100644--- a/server/lib/cosValidation.test.js+++ b/server/lib/cosValidation.test.js@@ -4,42 +4,10 @@ import {updateCosTaskSchema,createCosJobSchema,updateCosJobSchema,- describeReviewerCli,- isCliReviewer,- reviewerCliBinary,- DEFAULT_REVIEWER,- LOCAL_LLM_REVIEWERS,- REVIEWER_ALIASES,- REVIEWER_CLI_BINARIES,- REVIEWER_VALUES,- EFFORT_SELECTABLE_REVIEWERS,- MODEL_CAPABLE_CLI_REVIEWERS,- MODEL_SELECTABLE_REVIEWERS,- pairReviewerModelsAndEfforts,- reviewerModelsFromDefaults,- buildReviewWithArgs,- LOCAL_LLM_EFFORT_LEVELS,- reviewerEffortLevels,- normalizeReviewerEfforts,- resolveReviewerEfforts,- reviewerEffortsFromDefaults,- reviewerEffortArgs,- reviewerModelArg,- buildReviewerEffortNote,- buildReviewerPinNote,- buildReviewersCsv,- claimSafeReviewers,- prioritizeToolFreeReviewers,- resolveReviewerConfig,- resolveClaimReviewerConfig,- reviewerConfigMetadata,- reviewerTokenSlug,sanitizeTaskMetadata,- codeReviewSettingsSchema,taskTemplateSettingsSchema,} from './cosValidation.js';-import { LOCAL_AGENT_REVIEWERS } from './slashdoInvocation.js';-import { EFFORT_LEVELS, CLAUDE_EFFORT_LEVELS, CODEX_EFFORT_LEVELS, ANTIGRAVITY_EFFORT_LEVELS, CURSOR_EFFORT_LEVELS, GROK_EFFORT_LEVELS } from './providerModels.js';+import { EFFORT_LEVELS } from './providerModels.js';describe('cosValidation effort field', () => {it('accepts every EFFORT_LEVELS value on create and rejects unknown values', () => {@@ -267,589 +235,22 @@ describe('cosValidation non-worktree completion choice', () => {});});-describe('cosValidation reviewer CLI binaries', () => {- // The bug this exists to prevent: `antigravity` is the stored, federated- // reviewer identity, but the shipped executable is `agy` — no `antigravity`- // command exists. A review-loop follow-up agent handed the bare slug ran- // `command -v antigravity`, got nothing, concluded "no reviewer is available",- // self-reviewed, and merged its own PR.- it('maps the antigravity slug (and its gemini alias) to the agy binary', () => {- expect(reviewerCliBinary('antigravity')).toBe('agy');- expect(reviewerCliBinary('gemini')).toBe('agy');- expect(reviewerCliBinary('ANTIGRAVITY')).toBe('agy');- expect(describeReviewerCli('antigravity')).toBe('`agy` (the `antigravity` reviewer)');- });-- it('leaves same-named reviewers alone rather than restating the slug', () => {- for (const slug of ['claude', 'codex', 'grok']) {- expect(reviewerCliBinary(slug)).toBe(slug);- expect(describeReviewerCli(slug)).toBe(`\`${slug}\``);- }- expect(reviewerCliBinary('cursor')).toBe('cursor-agent');- expect(reviewerCliBinary('cursor-agent')).toBe('cursor-agent');- expect(describeReviewerCli('cursor')).toBe('`cursor-agent` (the `cursor` reviewer)');- });-- it('returns null for reviewers that have no spawnable CLI', () => {- // copilot is a GitHub API review; lmstudio/ollama go through- // POST /api/code-review/local. Prompt builders must not tell an agent to- // run these as commands.- for (const slug of [DEFAULT_REVIEWER, ...LOCAL_LLM_REVIEWERS]) {- expect(reviewerCliBinary(slug)).toBeNull();- }- expect(reviewerCliBinary(undefined)).toBeNull();- expect(describeReviewerCli(undefined)).toBe('');- });-- // Guard the guard: a NEW CLI reviewer added to REVIEWER_VALUES without a- // binary mapping must be caught here rather than shipping another slug an- // agent will fruitlessly probe for. Aliases resolve first, so `gemini` is not- // itself expected in the map. Uses isCliReviewer rather than re-spelling the- // exclusion, so a change to that rule can actually fail this test.- it('every CLI reviewer in REVIEWER_VALUES maps to a binary', () => {- const cliReviewers = REVIEWER_VALUES.filter(isCliReviewer);- expect(cliReviewers.length).toBeGreaterThan(0);- for (const slug of cliReviewers) {- expect(reviewerCliBinary(slug), `reviewerCliBinary('${slug}')`).toBeTruthy();- }- for (const alias of Object.keys(REVIEWER_ALIASES)) {- expect(reviewerCliBinary(alias)).toBe(reviewerCliBinary(REVIEWER_ALIASES[alias]));- }- });-- it('agrees with isCliReviewer on which reviewers are spawnable CLIs', () => {- for (const slug of REVIEWER_VALUES) {- expect(Boolean(reviewerCliBinary(slug)), slug).toBe(isCliReviewer(slug));- }- expect(isCliReviewer(DEFAULT_REVIEWER)).toBe(false);- expect(LOCAL_LLM_REVIEWERS.some(isCliReviewer)).toBe(false);- });-- // slashdoInvocation keeps its own copy of the roster to decide which slashdo- // `lib/*` includes a reviewer needs. Two hand-maintained lists of the same- // reviewers drift the moment one gains a member — the `grok` addition is the- // precedent — so pin them to each other rather than making slashdoInvocation- // import this module (cosValidation already imports IT, and a cycle here would- // be worse than the duplication).- it('matches slashdoInvocation LOCAL_AGENT_REVIEWERS', () => {- expect([...LOCAL_AGENT_REVIEWERS].sort()).toEqual(Object.keys(REVIEWER_CLI_BINARIES).sort());- });-});--describe('per-reviewer reasoning effort (reviewerEfforts)', () => {- it('offers each reviewer only the ladder its own CLI accepts', () => {- expect(reviewerEffortLevels('claude')).toEqual(CLAUDE_EFFORT_LEVELS);- expect(reviewerEffortLevels('codex')).toEqual(CODEX_EFFORT_LEVELS);- expect(reviewerEffortLevels('antigravity')).toEqual(ANTIGRAVITY_EFFORT_LEVELS);- // The `gemini` alias resolves to the same ladder as `antigravity`.- expect(reviewerEffortLevels('gemini')).toEqual(ANTIGRAVITY_EFFORT_LEVELS);- expect(reviewerEffortLevels('ollama')).toEqual(LOCAL_LLM_EFFORT_LEVELS);- expect(reviewerEffortLevels('lmstudio')).toEqual(LOCAL_LLM_EFFORT_LEVELS);- // cursor has a ladder even though `cursor-agent` takes no `--effort` flag:- // the level is a variant of its model id, folded in by `reviewerModelArg`.- expect(reviewerEffortLevels('cursor')).toEqual(CURSOR_EFFORT_LEVELS);- expect(reviewerEffortLevels('cursor-agent')).toEqual(CURSOR_EFFORT_LEVELS);- // grok's ladder stops at xhigh — derived from effortLevelsForProvider, so it- // is exactly what `grok --reasoning-effort` accepts.- expect(reviewerEffortLevels('grok')).toEqual(GROK_EFFORT_LEVELS);- // No effort control: copilot is a GitHub review, and a `@username` reviewer- // is a person.- expect(reviewerEffortLevels('copilot')).toBeNull();- expect(reviewerEffortLevels('@somebody')).toBeNull();- });-- it('EFFORT_SELECTABLE_REVIEWERS is exactly the reviewers with a non-empty ladder', () => {- expect([...EFFORT_SELECTABLE_REVIEWERS].sort())- .toEqual(['antigravity', 'claude', 'codex', 'cursor', 'grok', 'lmstudio', 'ollama']);- for (const reviewer of REVIEWER_VALUES) {- expect(EFFORT_SELECTABLE_REVIEWERS.includes(reviewer))- .toBe((reviewerEffortLevels(reviewer) || []).length > 0);- }- });-- it('normalizes a token-keyed map: aliases, case, and out-of-ladder levels', () => {- expect(normalizeReviewerEfforts({- gemini: 'HIGH', // alias + case-folded- codex: 'xhigh', // in codex's ladder only- claude: 'medium',- ollama: ' low ', // trimmed- })).toEqual({ antigravity: 'high', codex: 'xhigh', claude: 'medium', ollama: 'low' });- });-- it('DROPS rather than clamps a level the reviewer rejects — a displayed effort must be the one it runs', () => {- // `agy` really does reject `--effort max`; clamping it to `high` would review- // at a different effort than the picker shows.- expect(normalizeReviewerEfforts({ antigravity: 'max' })).toEqual({});- // grok rejects `max` the way agy rejects it — dropped, not clamped.- expect(normalizeReviewerEfforts({ grok: 'max' })).toEqual({});- expect(normalizeReviewerEfforts({ grok: 'xhigh' })).toEqual({ grok: 'xhigh' });- // Reviewers with no effort control at all.- expect(normalizeReviewerEfforts({ copilot: 'high', '@bot': 'high' })).toEqual({});- // Non-strings and blanks are absent, never an empty pin.- expect(normalizeReviewerEfforts({ codex: '', claude: null, ollama: 3 })).toEqual({});- // Non-object input is undefined so an omitted field isn't persisted as `{}`.- expect(normalizeReviewerEfforts(undefined)).toBeUndefined();- expect(normalizeReviewerEfforts(['codex'])).toBeUndefined();- });-- it('resolves task-over-default, with an explicitly empty task map overriding', () => {- expect(resolveReviewerEfforts({ codex: 'high' }, { codex: 'low' })).toEqual({ codex: 'high' });- expect(resolveReviewerEfforts({}, { codex: 'low' })).toEqual({});- expect(resolveReviewerEfforts(undefined, { codex: 'low' })).toEqual({ codex: 'low' });- });-- it('folds the settings scalars into the map, re-checking each against its ladder', () => {- expect(reviewerEffortsFromDefaults({- codexEffort: 'high',- claudeEffort: 'xhigh',- antigravityEffort: 'max', // not in agy's ladder — dropped, not clamped- ollamaEffort: 'medium',- lmstudioEffort: 'ultra', // OpenAI-shaped backends don't take this tier- grokEffort: 'high', // in grok's ladder — kept- })).toEqual({ codex: 'high', claude: 'xhigh', ollama: 'medium', grok: 'high' });- expect(reviewerEffortsFromDefaults(null)).toEqual({});- });-- it('renders the argv fragment each CLI actually takes', () => {- expect(reviewerEffortArgs('claude', 'high')).toEqual(['--effort', 'high']);- expect(reviewerEffortArgs('codex', 'high')).toEqual(['-c', 'model_reasoning_effort=high']);- // The `antigravity` slug names no executable — `agy` does, and it takes --effort.- expect(reviewerEffortArgs('antigravity', 'low')).toEqual(['--effort', 'low']);- // grok's CLI takes `--reasoning-effort`, aliased `--effort` — the alias is- // what buildEffortArgs emits, and `max` is outside its ladder so it drops.- expect(reviewerEffortArgs('grok', 'xhigh')).toEqual(['--effort', 'xhigh']);- expect(reviewerEffortArgs('grok', 'max')).toEqual([]);- expect(reviewerEffortArgs('copilot', 'high')).toEqual([]);- expect(reviewerEffortArgs('claude', null)).toEqual([]);- });-- it('NEVER emits --effort for cursor, at any level — the CLI has no such flag', () => {- // `cursor-agent --effort high` exits non-zero. Cursor's ladder exists so the- // level can be PICKED; `reviewerModelArg` is what carries it. A regression- // here reaches an agent as a literal command line it runs verbatim.- for (const level of CURSOR_EFFORT_LEVELS) {- expect(reviewerEffortArgs('cursor', level), level).toEqual([]);- expect(reviewerEffortArgs('cursor-agent', level), level).toEqual([]);- }- expect(reviewerEffortArgs('cursor', 'minimal')).toEqual([]);- });-- it('folds a cursor effort into --model, leaving every other reviewer id verbatim', () => {- // Cursor's native model-variant syntax, matching slashdo's own fold so the- // same pin means the same invocation on either side.- expect(reviewerModelArg('cursor', 'gpt-5', 'max')).toBe('gpt-5[effort=max]');- // An existing bracket gains an `,effort=` parameter, not a second bracket.- expect(reviewerModelArg('cursor', 'claude-opus-4-7[thinking=true]', 'high'))- .toBe('claude-opus-4-7[thinking=true,effort=high]');- // A model that already names its own effort wins over the ladder pin.- expect(reviewerModelArg('cursor', 'gpt-5[effort=low]', 'max')).toBe('gpt-5[effort=low]');- // No effort pinned, or one cursor's ladder rejects → the bare id.- expect(reviewerModelArg('cursor', 'gpt-5')).toBe('gpt-5');- expect(reviewerModelArg('cursor', 'gpt-5', 'minimal')).toBe('gpt-5');- // No model to attach the variant to → nothing at all.- expect(reviewerModelArg('cursor', '', 'max')).toBeNull();- expect(reviewerModelArg('cursor', null, 'max')).toBeNull();- // The alias resolves like every other lookup here.- expect(reviewerModelArg('cursor-agent', 'gpt-5', 'max')).toBe('gpt-5[effort=max]');- // Every other reviewer keeps its id verbatim — its effort rides its own flag.- expect(reviewerModelArg('codex', 'gpt-5.6-sol', 'high')).toBe('gpt-5.6-sol');- expect(reviewerModelArg('antigravity', 'Gemini 3.5 Flash (High)', 'high')).toBe('Gemini 3.5 Flash (High)');- });-- it('DROPS an out-of-ladder effort instead of clamping it, even from unnormalized input', () => {- // The underlying `buildEffortArgs` clamps (agy `max` → `--effort high`), which- // is right for a provider pin carried across providers but wrong for a reviewer- // effort picked from that reviewer's own list: emitting a clamped flag would run- // the review at a tier the picker labels `unsupported`. This function is reached- // with RAW task metadata (`reviewLoopReviewerEfforts`), so it must normalize- // itself rather than trust the caller.- expect(reviewerEffortArgs('antigravity', 'max')).toEqual([]);- expect(reviewerEffortArgs('antigravity', 'ultra')).toEqual([]);- // Case/whitespace still normalize through rather than being rejected.- expect(reviewerEffortArgs('codex', ' HIGH ')).toEqual(['-c', 'model_reasoning_effort=high']);- });-- it('builds the hand-invocation note only for CLI reviewers carrying an effort', () => {- const note = buildReviewerEffortNote(['codex', 'claude', 'copilot'], { codex: 'high', claude: 'low', copilot: 'high' });- expect(note).toContain('`codex -c model_reasoning_effort=high`');- expect(note).toContain('`claude --effort low`');- expect(note).not.toContain('copilot');- // A reviewer not in the list contributes nothing, and no pins at all = no note.- expect(buildReviewerEffortNote(['copilot'], { codex: 'high' })).toBe('');- expect(buildReviewerEffortNote(['codex'], {})).toBe('');- expect(buildReviewerEffortNote(undefined, { codex: 'high' })).toBe('');- // slashdo's local-model loop calls the backend itself, so there's no flag to- // name for lmstudio/ollama in this path.- expect(buildReviewerEffortNote(['ollama'], { ollama: 'high' })).toBe('');- // …including when it carries a MODEL pin too: a local reviewer names no- // binary, so there is no command line to print (a `null --model …` would be- // handed to an agent as something to run).- expect(buildReviewerEffortNote(['ollama'], { ollama: 'high' }, { reviewerModels: { ollama: 'qwen2.5:7b' } })).toBe('');- expect(buildReviewerEffortNote(['copilot'], { copilot: 'high' }, { reviewerModels: { copilot: 'x' } })).toBe('');- });-- it('names cursor with its folded --model instead of an --effort it would reject', () => {- const note = buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewerModels: { cursor: 'gpt-5' } });- expect(note).toContain('`cursor-agent --model gpt-5[effort=max]`');- expect(note).not.toContain('--effort');- // No model to fold into: nothing is emitted rather than a bogus flag.- expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' })).toBe('');- expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewerModels: {} })).toBe('');- // A model with NO effort pin is not this sentence's business.- expect(buildReviewerEffortNote(['cursor'], {}, { reviewerModels: { cursor: 'gpt-5' } })).toBe('');- // The pin still round-trips through the emitted --review-with token, which- // suppresses the note exactly as it does for every other reviewer.- const reviewWith = buildReviewWithArgs(['cursor'], { reviewerModels: { cursor: 'gpt-5' }, reviewerEfforts: { cursor: 'max' } });- expect(reviewWith).toContain('cursor[gpt-5]~effort=max');- expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewWith, reviewerModels: { cursor: 'gpt-5' } })).toBe('');- });-- it('goes SILENT once the emitted --review-with carries the effort itself', () => {- // slashdo has parsed `~effort=<level>` since v3.31, and markSuffixes emits it —- // so on a pinned invocation the loop already runs the reviewer at that effort.- // Repeating it as prose tells the agent to pass the flag a second time, or to- // hand-run a reviewer `/do:pr` was about to run.- const reviewWith = buildReviewWithArgs(['codex', 'claude'], { reviewerEfforts: { codex: 'high', claude: 'low' } });- expect(reviewWith).toContain('codex~effort=high');- expect(buildReviewerEffortNote(['codex', 'claude'], { codex: 'high', claude: 'low' }, { reviewWith })).toBe('');- // An invocation that pins reviewers but NO effort leaves the note as the only- // carrier, and an absent/blank pin is the unpinned case.- const noEffort = buildReviewWithArgs(['codex', 'claude'], {});- expect(noEffort).not.toContain('~effort=');- expect(buildReviewerEffortNote(['codex'], { codex: 'high' }, { reviewWith: noEffort })).toContain('`codex -c model_reasoning_effort=high`');- expect(buildReviewerEffortNote(['codex'], { codex: 'high' }, { reviewWith: '' })).toContain('`codex -c model_reasoning_effort=high`');- // And a lone copilot can't carry an effort at all (no ladder — see the DROPS- // test above), which is why the lone-default suppression stays correct without- // an effort clause of its own in applySlashdoInvocation.- expect(buildReviewWithArgs(['copilot'], { reviewerEfforts: { copilot: 'high' } })).toBe('');- });-- it('never claims --review-with lacks an effort suffix', () => {- // The note predates slashdo's `~effort=` support and used to justify itself- // with "`--review-with` has no effort suffix". It does have one — an agent- // reading that next to its own `codex~effort=high` token is being misled.- const note = buildReviewerEffortNote(['codex'], { codex: 'high' });- expect(note).not.toContain('has no effort suffix');- expect(note).toContain('Pass the flag yourself when you spawn the reviewer');- });-- it('carries reviewerEfforts through the task schema and the metadata sanitizer', () => {- const parsed = createCosTaskSchema.parse({- description: 'x',- reviewerEfforts: { codex: 'high', antigravity: 'max', copilot: 'low' },- });- expect(parsed.reviewerEfforts).toEqual({ codex: 'high' });- expect(createCosTaskSchema.parse({ description: 'x' }).reviewerEfforts).toBeUndefined();- // An explicitly empty MAP is KEPT: it's a real "use each reviewer's own- // default for this task" choice that must override the Code Review Defaults.- expect(sanitizeTaskMetadata({ reviewerEfforts: {} })).toEqual({ reviewerEfforts: {} });- expect(sanitizeTaskMetadata({ reviewerEfforts: { claude: 'high', grok: 'max' } }))- .toEqual({ reviewerEfforts: { claude: 'high' } });- });-- it('accepts each per-reviewer effort scalar on the code-review settings slice', () => {- const parsed = codeReviewSettingsSchema.parse({- claudeEffort: 'max', codexEffort: 'minimal', antigravityEffort: 'high',- ollamaEffort: 'low', lmstudioEffort: 'high',- });- expect(parsed).toEqual({- claudeEffort: 'max', codexEffort: 'minimal', antigravityEffort: 'high',- ollamaEffort: 'low', lmstudioEffort: 'high',- });- // An unusable stored value clears the field rather than persisting a pin no- // invocation would carry.- expect(codeReviewSettingsSchema.parse({ antigravityEffort: 'max' }).antigravityEffort).toBeUndefined();- expect(codeReviewSettingsSchema.parse({ codexEffort: 'bogus' }).codexEffort).toBeUndefined();- });-});--// The picker's Effort cell is driven by a CLIENT mirror of these ladders. A level-// offered there but rejected here would show the user a pin that silently never-// persists (and the reverse would hide a tier their CLI accepts), so the mirror is-// pinned rather than trusted to a "keep in sync" comment.-describe('client mirror of the reviewer effort ladders', () => {- it('matches server reviewerEffortLevels for every reviewer', async () => {- // The dependency-free leaf, NOT `components/cos/constants.js` (which re-exports- // these but also imports `lucide-react` — absent from the server workspace, so- // importing it here fails CI with ERR_MODULE_NOT_FOUND).- const client = await import('../../client/src/lib/reviewerPins.js');- expect([...client.EFFORT_SELECTABLE_REVIEWERS].sort()).toEqual([...EFFORT_SELECTABLE_REVIEWERS].sort());- expect(client.LOCAL_LLM_EFFORT_LEVELS).toEqual(LOCAL_LLM_EFFORT_LEVELS);- for (const reviewer of REVIEWER_VALUES) {- expect(client.reviewerEffortLevels(reviewer) ?? null).toEqual(reviewerEffortLevels(reviewer) ?? null);+// The reviewer vocabulary moved to reviewerConfig.js (#5702); cosValidation.js+// re-exports it flat and validation.js re-exports cosValidation.js. Dropping+// either hop fails no reviewer test (those import the new module directly) — it+// surfaces as `undefined is not a function` inside prompt assembly for a+// scheduled review-loop task, so pin both hops as SAME-object re-exports.+describe('reviewerConfig transitional re-export shim (#5702)', () => {+ it('re-exports every reviewerConfig symbol through cosValidation.js and validation.js', async () => {+ const reviewerConfig = await import('./reviewerConfig.js');+ const cos = await import('./cosValidation.js');+ const validation = await import('./validation.js');+ const keys = Object.keys(reviewerConfig);+ expect(keys).toContain('buildReviewWithArgs');+ expect(keys).toContain('REVIEWER_VALUES');+ for (const key of keys) {+ expect(cos[key], `cosValidation.js re-export of '${key}'`).toBe(reviewerConfig[key]);+ expect(validation[key], `validation.js re-export of '${key}'`).toBe(reviewerConfig[key]);}- // Alias parity too — the picker keys rows off stored slugs.- expect(client.reviewerEffortLevels('gemini')).toEqual(reviewerEffortLevels('gemini'));- });-- // Same failure mode one column over: a reviewer the picker offers a Model cell- // for but the server drops the pin from (or vice versa — a CLI whose `--model`- // the UI hides). The two rosters drove `antigravity` out of sync until #3728.- it('matches the server model-pin rosters', async () => {- const client = await import('../../client/src/lib/reviewerPins.js');- expect([...client.MODEL_CAPABLE_CLI_REVIEWERS].sort()).toEqual([...MODEL_CAPABLE_CLI_REVIEWERS].sort());- expect([...client.MODEL_SELECTABLE_REVIEWERS].sort()).toEqual([...MODEL_SELECTABLE_REVIEWERS].sort());- });-});--describe('per-reviewer model pins', () => {- it('accepts Cursor Agent in the reviewer config and persists its model pin', () => {- const parsed = codeReviewSettingsSchema.parse({ reviewers: ['cursor-agent'], cursorModel: 'gpt-5' });- expect(parsed.reviewers).toEqual(['cursor']);- expect(parsed.cursorModel).toBe('gpt-5');- expect(reviewerModelsFromDefaults(parsed)).toEqual({ cursor: 'gpt-5' });- });-- it('keeps an antigravity model pin on the code-review settings slice', () => {- // `agy --model <id>` is real (unlike the effort-only support PortOS assumed- // before #3728), so the scalar has to survive the `.strict()` schema.- expect(codeReviewSettingsSchema.parse({ antigravityModel: 'gemini-3.6-flash' }).antigravityModel)- .toBe('gemini-3.6-flash');- // Structural characters would corrupt the emitted `antigravity[<model>]` token.- expect(codeReviewSettingsSchema.parse({ antigravityModel: 'a,b' }).antigravityModel).toBeUndefined();- expect(codeReviewSettingsSchema.parse({ antigravityModel: ' ' }).antigravityModel).toBeUndefined();- });-- it('carries an antigravity model through the task schema and the sanitizer', () => {- expect(createCosTaskSchema.parse({ description: 'x', reviewerModels: { antigravity: 'gemini-3.6-pro' } }).reviewerModels)- .toEqual({ antigravity: 'gemini-3.6-pro' });- expect(sanitizeTaskMetadata({ reviewerModels: { antigravity: 'gemini-3.6-pro', copilot: 'x' } }))- .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-pro' } });- });-- it('splits an effort-suffixed antigravity id into a model/effort pair agy accepts', () => {- expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-high' }, {}))- .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'high' } });- // An explicitly pinned effort wins over the one baked into the id.- expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-high' }, { antigravity: 'low' }))- .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'low' } });- // …but an UNUSABLE stored effort doesn't get to suppress the baked one.- expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-low' }, { antigravity: 'max' }))- .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'low' } });- });-- it('leaves unsuffixed ids and every other reviewer untouched', () => {- expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash', codex: 'gpt-5.6-sol' }, { codex: 'high' }))- .toEqual({- reviewerModels: { antigravity: 'gemini-3.6-flash', codex: 'gpt-5.6-sol' },- reviewerEfforts: { codex: 'high' }- });- // A `-high` suffix on a NON-agy reviewer is part of the id, not an effort.- expect(pairReviewerModelsAndEfforts({ claude: 'qwen2.5:7b-high' }, {}))- .toEqual({ reviewerModels: { claude: 'qwen2.5:7b-high' }, reviewerEfforts: {} });- expect(pairReviewerModelsAndEfforts(undefined, undefined))- .toEqual({ reviewerModels: {}, reviewerEfforts: {} });- });-- it('does not mutate the maps it was handed', () => {- const models = { antigravity: 'gemini-3.6-flash-high' };- const efforts = {};- pairReviewerModelsAndEfforts(models, efforts);- expect(models).toEqual({ antigravity: 'gemini-3.6-flash-high' });- expect(efforts).toEqual({});- });-- // #3729: `grok --model <id>` is real and slashdo accepts a `grok[<model>]`- // bracket, but `grok` was absent from the roster, so every grok review ran on- // the CLI's own default and the picker rendered "Grok takes no model".- it('keeps a grok model pin on the code-review settings slice', () => {- expect(codeReviewSettingsSchema.parse({ grokModel: 'grok-code-fast-1' }).grokModel)- .toBe('grok-code-fast-1');- // Structural characters would corrupt the emitted `grok[<model>]` token.- expect(codeReviewSettingsSchema.parse({ grokModel: 'a]b' }).grokModel).toBeUndefined();- expect(codeReviewSettingsSchema.parse({ grokModel: ' ' }).grokModel).toBeUndefined();- });-- it('carries a grok model through the task schema, sanitizer and defaults adapter', () => {- expect(createCosTaskSchema.parse({ description: 'x', reviewerModels: { grok: 'grok-code-fast-1' } }).reviewerModels)- .toEqual({ grok: 'grok-code-fast-1' });- expect(sanitizeTaskMetadata({ reviewerModels: { grok: 'grok-code-fast-1', copilot: 'x' } }))- .toEqual({ reviewerModels: { grok: 'grok-code-fast-1' } });- expect(reviewerModelsFromDefaults({ grokModel: 'grok-code-fast-1' })).toEqual({ grok: 'grok-code-fast-1' });- });-- it('emits the grok pin as a slashdo bracket, and never splits an effort off it', () => {- expect(buildReviewWithArgs(['grok'], { reviewerModels: { grok: 'grok-code-fast-1' } }))- .toBe('--review-with grok[grok-code-fast-1]');- // Only agy bakes an effort into the model id. A grok id passes through whole,- // and a bare model pin adds no effort pin — grok carries its level on its own- // flag, not inside the model id.- expect(pairReviewerModelsAndEfforts({ grok: 'grok-code-fast-1' }, {}))- .toEqual({ reviewerModels: { grok: 'grok-code-fast-1' }, reviewerEfforts: {} });- expect(reviewerEffortLevels('grok')).toEqual(GROK_EFFORT_LEVELS);- });-});--describe('reviewer pin note (saved slashdo defaults must not win)', () => {- it('names the resolved list AND the exact --review-with text to pass', () => {- const note = buildReviewerPinNote('codex,claude');- // Both halves matter: the list the phases run by hand, and the flag text for- // the moment the agent reaches for a slashdo command instead.- expect(note).toContain('`codex,claude`');- expect(note).toContain('--review-with codex,claude');- expect(note).toContain('/do:pr');- // The failure mode this block exists to prevent, named so the agent can- // recognize it: a bare invocation silently adopting the host's saved config.- expect(note).toMatch(/\.slashdo-config\.json/);- });-- it('carries the per-entry suffixes verbatim so the pinned model/effort survive the paste', () => {- // A reviewer pin is only honored if the agent pastes the whole token — the- // bracket and the ~suffixes ARE the model/optional/cap/effort pins.- const csv = 'antigravity[gemini-3.7-flash]~opt~max=1~effort=medium';- expect(buildReviewerPinNote(csv)).toContain(`--review-with ${csv}`);- });-- it('keeps a PortOS-served reviewer OUT of the pinned flag — slashdo aborts on a slug it does not know', () => {- const note = buildReviewerPinNote('lmstudio~effort=high,ollama,@alice');- // The flag text carries only tokens slashdo can parse...- expect(note).toContain('--review-with ollama,@alice');- expect(note).not.toContain('--review-with lmstudio');- // ...and the dropped reviewer is named by bare slug, pointed at the- // procedure that actually runs it, so dropping it from a slashdo call can't- // read as permission to skip the review.- expect(note).toContain('PortOS runs `lmstudio` itself');- expect(note).toContain('Local Reviewer Procedure');- });-- it('states the pin with no flag text at all when every reviewer is PortOS-only', () => {- const note = buildReviewerPinNote('lmstudio');- expect(note).toContain('authoritative');- // No flag to hand out — the only `--review-with` mention left is the- // prohibition, never an instruction to pass one.- expect(note).not.toMatch(/pass `--review-with/);- });-- it('reads back every slug an emitted token can carry (inverse of markSuffixes)', () => {- // reviewerTokenSlug is the only place the emitted grammar is parsed rather- // than built. Round-trip a fully decorated token through the real emitter so- // a new bracket or ~suffix in markSuffixes fails HERE instead of silently- // mis-slugging a reviewer out of (or into) the pinned flag.- const csv = buildReviewersCsv(- ['antigravity', 'lmstudio'],- ['alice'],- ['antigravity'],- { antigravity: 1 },- { antigravity: 'gemini-3.7-flash', lmstudio: 'qwen' },- { antigravity: 'medium', lmstudio: 'high' }- );- expect(csv.split(',').map(reviewerTokenSlug)).toEqual(['antigravity', 'lmstudio', '@alice']);- });-- it('emits nothing when there is no list to pin', () => {- expect(buildReviewerPinNote('')).toBe('');- expect(buildReviewerPinNote(' ')).toBe('');- expect(buildReviewerPinNote(null)).toBe('');- expect(buildReviewerPinNote(undefined)).toBe('');- });-});--// The claim generators resolve reviewers BEFORE a task record exists and render-// the CSV into `{reviewers}`; the prompt builder re-resolves them from the-// persisted task at spawn time to emit the reviewer pin. Those two resolutions-// have to land on the same list, or the pin names reviewers the prompt does not-// (#4770). `reviewerConfigMetadata` is the round-trip that makes them agree.-describe('claim reviewer round-trip (prompt CSV ↔ persisted metadata)', () => {- const defaults = {- reviewers: ['copilot'],- usernames: ['alice'],- optionalReviewers: ['ollama'],- reviewerMaxRounds: { codex: 2 },- antigravityModel: 'gemini-3.7-flash-high',- codexEffort: 'high'- };-- it('claimSafeReviewers drops copilot and never falls back to it', () => {- expect(claimSafeReviewers(['codex', 'copilot'])).toEqual(['codex']);- expect(claimSafeReviewers(['copilot'])).toEqual(['codex']);- expect(claimSafeReviewers([])).toEqual(['codex']);- expect(claimSafeReviewers(undefined)).toEqual(['codex']);- });-- it('stably prioritizes tool-free local reviewers ahead of tool-enabled reviewers', () => {- expect(prioritizeToolFreeReviewers(['codex', 'ollama', 'copilot', 'lmstudio', 'claude']))- .toEqual(['ollama', 'lmstudio', 'codex', 'copilot', 'claude']);- expect(resolveReviewerConfig({ reviewers: ['codex', 'ollama'] }, null, null).reviewers)- .toEqual(['ollama', 'codex']);- });-- it('resolves through the claim guard from every input shape a claim task can carry', () => {- // The install default is the fallback, the claim guard is applied after it,- // and legacy single-`reviewer` metadata still resolves.- expect(resolveClaimReviewerConfig({}, null, undefined).reviewers).toEqual(['codex']);- expect(resolveClaimReviewerConfig({ reviewers: ['copilot'] }, null, ['copilot']).reviewers).toEqual(['codex']);- expect(resolveClaimReviewerConfig({}, null, ['claude', 'copilot']).reviewers).toEqual(['claude']);- expect(resolveClaimReviewerConfig({ reviewer: 'grok' }, null, ['claude']).reviewers).toEqual(['grok']);- });-- it('resolveClaimReviewerConfig emits a CSV matching its own resolved bundle', () => {- const config = resolveClaimReviewerConfig({ reviewers: ['codex', 'antigravity'] }, defaults, defaults.reviewers);- expect(config.reviewers).toEqual(['codex', 'antigravity']);- expect(config.csv).toBe(buildReviewersCsv(- config.reviewers, config.usernames, config.optionalReviewers,- config.reviewerMaxRounds, config.reviewerModels, config.reviewerEfforts- ));- // The agy model id's baked tier is split off exactly once — resolving the- // persisted config a second time must not re-split or double-apply it.- expect(config.reviewerModels.antigravity).toBe('gemini-3.7-flash');- expect(config.reviewerEfforts.antigravity).toBe('high');- });-- it('persisting reviewerConfigMetadata makes the SECOND resolution reproduce the first CSV', () => {- // Round 1: the generator, with no task record yet.- const generated = resolveClaimReviewerConfig({ reviewers: ['codex', 'antigravity'] }, defaults, defaults.reviewers);- const metadata = { claimFlow: true, ...reviewerConfigMetadata(generated) };- // Round 2: the prompt builder, reading the task back — and deliberately- // WITHOUT the defaults it would otherwise fall through to, to prove the- // persisted values are what carry the list.- const rebuilt = resolveClaimReviewerConfig(metadata, null, null);- expect(rebuilt.csv).toBe(generated.csv);- expect(rebuilt).toMatchObject({- reviewers: generated.reviewers,- usernames: generated.usernames,- optionalReviewers: generated.optionalReviewers,- reviewerMaxRounds: generated.reviewerMaxRounds,- reviewerModels: generated.reviewerModels,- reviewerEfforts: generated.reviewerEfforts- });- // And the plain (non-claim) resolver the prompt builder shares with the- // review loop agrees too — that is the resolution #4770 was silently- // answering from the install-wide defaults.- expect(resolveReviewerConfig(metadata, null, null).reviewers).toEqual(generated.reviewers);- });-- it('a DIFFERENT install default cannot override what the task persisted', () => {- const generated = resolveClaimReviewerConfig({ reviewers: ['grok'] }, defaults, defaults.reviewers);- const metadata = reviewerConfigMetadata(generated);- const otherInstall = { reviewers: ['claude'], usernames: ['bob'], optionalReviewers: ['grok'], reviewerMaxRounds: { grok: 9 } };- expect(resolveClaimReviewerConfig(metadata, otherInstall, otherInstall.reviewers).csv).toBe(generated.csv);- });-- it('sanitizes rather than trusts: unknown keys and junk values never reach the task record', () => {- const meta = reviewerConfigMetadata({- reviewers: ['codex', 'bogus'],- usernames: ['@Alice', 'bad token'],- optionalReviewers: ['nope'],- reviewerMaxRounds: { codex: 'three' },- reviewerModels: {},- reviewerEfforts: {},- swarmCount: 6,- issueAuthorFilter: 'any'- });- expect(meta).toEqual({- reviewers: ['codex'],- usernames: ['Alice'],- optionalReviewers: [],- reviewerMaxRounds: {},- reviewerModels: {},- reviewerEfforts: {}- });- });-- it('returns an empty patch rather than null when nothing survives sanitizing', () => {- // Callers spread this into a task's metadata, so a null would throw at the- // three claim generators rather than degrade.- expect(reviewerConfigMetadata(null)).toEqual({});- expect(reviewerConfigMetadata({ reviewers: ['bogus'] })).toEqual({});});});diff --git a/server/lib/index.js b/server/lib/index.jsindex 95127d7260..6319edf6ee 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -173,6 +173,10 @@ export * from './providerPrerequisites.js';// collision check as flat exports.export * as providerVendors from './providerVendors.js';export * from './providerTranscriptUsage.js';+// Namespaced: reviewerConfig.js is re-exported flat by cosValidation.js (and so+// by validation.js), so a flat `export *` here would trip the barrel's+// duplicate-identifier collision check.+export * as reviewerConfig from './reviewerConfig.js';export * from './quotaBurnConfig.js';export * from './quotaBurnPresets.js';export * from './auditCatalog.js';diff --git a/server/lib/reviewerConfig.js b/server/lib/reviewerConfig.jsnew file mode 100644index 0000000000..048ba8887e--- /dev/null+++ b/server/lib/reviewerConfig.js@@ -0,0 +1,1141 @@+/**+ * Review-Loop reviewer vocabulary: which reviewers exist, what each one's+ * CLI/model/effort contract is, and how a reviewer set renders into slashdo's+ * `--review-with` argv (`buildReviewWithArgs`) and into the human-readable+ * reviewer notes spliced into agent prompts (`buildReviewerPinNote` /+ * `buildReviewerEffortNote`).+ *+ * Split out of cosValidation.js (issue #5702), which keeps the CoS Zod schemas+ * and re-exports everything here (`export * from './reviewerConfig.js'`) so+ * existing deep imports of cosValidation.js / validation.js keep working.+ * This module must stay Zod-free — it is pure reviewer domain vocabulary.+ */+import { isPlainObject } from './objects.js';+import { EFFORT_LEVELS, effortLevelsForProvider, buildEffortArgs, foldCursorEffortIntoModel, splitAntigravityModel } from './providerModels.js';+import { ANTIGRAVITY_COMMAND } from './antigravity.js';+import { CURSOR_COMMAND } from './cursor.js';++// Reviewer choices for the Review Loop. `copilot` requests a native GitHub+// Copilot review; `claude`/`antigravity`/`codex`/`grok`/`cursor` instruct the review-loop+// follow-up agent to invoke the named CLI to critique the PR diff; `lmstudio`/`ollama`+// route the diff through PortOS's local code-review endpoint+// (`POST /api/code-review/local`) which runs the configured local LLM model.+// Mirrored in client/src/components/cos/constants.js → REVIEWER_OPTIONS.+export const REVIEWER_VALUES = ['copilot', 'claude', 'antigravity', 'codex', 'grok', 'cursor', 'lmstudio', 'ollama'];+export const REVIEWER_ALIASES = { gemini: 'antigravity', 'cursor-agent': 'cursor' };+export const DEFAULT_REVIEWER = 'copilot';+export const DEFAULT_REVIEWERS = ['copilot'];+// Reviewers that resolve to a local-LLM backend (rather than a CLI or GitHub+// bot). Used by the code-review endpoint, settings panel, and prompt builder+// to gate model-id resolution.+export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];+// Reviewers PortOS serves ITSELF, with no counterpart in slashdo's reviewer+// vocabulary: `lmstudio` runs through `POST /api/code-review/local`, which takes+// its model in the request body. slashdo has no such slug, so it can neither+// carry a `[<model>]` bracket nor appear in a `--review-with` list (an unknown+// value aborts the command). One constant so a future addition can't be fixed+// in one of those two places and missed in the other.+export const PORTOS_ONLY_REVIEWERS = ['lmstudio'];+// 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` / `antigravityModel`). 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. `antigravity` runs `agy --model <id>`; an effort-suffixed+// agy id is reconciled with the effort pin by `pairReviewerModelsAndEfforts`.+// `grok` runs `grok --model <id>` (slashdo's `grok[<model>]` bracket); it takes a+// model but NO effort at all, which is why this roster and+// EFFORT_SELECTABLE_REVIEWERS are genuinely different sets rather than two names+// for one list. `cursor` runs `cursor-agent --model <id>` and DOES take an+// effort — but as a parameter of the model id (`gpt-5[effort=max]`), not a flag,+// so its pin rides this roster's `--model` rather than an `--effort` argv.+// 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 when its CLI gains model selection; the `<reviewer>Model`+// settings scalar is generated from this roster (codeReviewSettingsSchema).+export const MODEL_CAPABLE_CLI_REVIEWERS = ['codex', 'claude', 'antigravity', 'grok', 'cursor'];+// Every reviewer whose model the user can PICK in the UI: the model-capable CLIs+// above (threaded into the follow-up prompt as `<reviewer> --model <id>`) plus the+// local-LLM backends (whose id is injected server-side by+// `POST /api/code-review/local`, or emitted as slashdo's `[<model>]` bracket for a+// claim flow). `copilot` and `@username` reviewers are excluded — neither is a+// model-taking backend, matching slashdo rejecting `copilot[…]`/`@login[…]`.+export const MODEL_SELECTABLE_REVIEWERS = [...MODEL_CAPABLE_CLI_REVIEWERS, ...LOCAL_LLM_REVIEWERS];+// The executable a CLI reviewer's slug actually resolves to on PATH. Every slug+// except `antigravity` names its own binary; `antigravity` is the STORED,+// federated reviewer identity (aliased from the older `gemini`) while the+// shipped executable is `agy` — there is no `antigravity` command. A prompt that+// names only the slug sends the follow-up agent looking for a binary that does+// not exist: one CoS review-loop agent probed `command -v antigravity`, found+// nothing, declared "no reviewer available", and merged its own PR on a+// self-review. Prompt builders must resolve the slug through+// `reviewerCliBinary()` before telling an agent what to invoke.+// A reviewer absent from this map has no spawnable CLI (`copilot` is a GitHub+// API review, `lmstudio`/`ollama` go through `POST /api/code-review/local`).+export const REVIEWER_CLI_BINARIES = {+ claude: 'claude',+ antigravity: ANTIGRAVITY_COMMAND,+ codex: 'codex',+ grok: 'grok',+ cursor: CURSOR_COMMAND,+};++/**+ * Is this reviewer a CLI the agent spawns itself? Derived by EXCLUSION rather+ * than from REVIEWER_CLI_BINARIES so a newly added CLI reviewer still drives the+ * review loop before anyone remembers to map its binary (the map's coverage is+ * pinned separately by reviewerConfig.test.js).+ *+ * The one definition of the rule — the prompt builder and the coverage test both+ * call it, so neither can re-implement (and quietly diverge from) it.+ *+ * @param {string} reviewer - reviewer slug+ * @returns {boolean}+ */+export function isCliReviewer(reviewer) {+ return reviewer !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(reviewer);+}++/**+ * The PATH executable for a CLI reviewer slug, or `null` when the reviewer is+ * not a spawnable CLI. Accepts the `gemini` alias.+ *+ * A null here means "no binary is mapped", NOT "not a CLI" — use isCliReviewer+ * for that question. The two can disagree for exactly one reviewer: a new CLI+ * reviewer added to REVIEWER_VALUES before its REVIEWER_CLI_BINARIES entry.+ * That reviewer still drives the loop (isCliReviewer says yes) and its prompt+ * falls back to naming the slug — the pre-existing behavior — rather than being+ * silently dropped. reviewerConfig.test.js pins the map's coverage so the window+ * closes at review time.+ *+ * @param {string} reviewer - reviewer slug (`antigravity`, `gemini`, `codex`, …)+ * @returns {string|null}+ */+export function reviewerCliBinary(reviewer) {+ if (typeof reviewer !== 'string') return null;+ const slug = reviewer.trim().toLowerCase();+ return REVIEWER_CLI_BINARIES[REVIEWER_ALIASES[slug] || slug] || null;+}++/**+ * Render a reviewer slug for an agent prompt as the command it must actually+ * run, keeping the slug visible so the text still lines up with the configured+ * reviewer list and slashdo's `--review-with` token.+ *+ * `antigravity` → ```agy` (the `antigravity` reviewer)``; every other reviewer,+ * whose binary equals its slug, → ```codex` `` with no redundant restatement.+ *+ * @param {string} reviewer - reviewer slug+ * @returns {string} markdown fragment+ */+export function describeReviewerCli(reviewer) {+ if (typeof reviewer !== 'string' || !reviewer) return '';+ const binary = reviewerCliBinary(reviewer);+ if (!binary || binary === reviewer) return `\`${reviewer}\``;+ return `\`${binary}\` (the \`${reviewer}\` reviewer)`;+}+// 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';++// Arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`) requested as PR+// reviewers to gate merging — a class distinct from the fixed REVIEWER_VALUES+// enum (which either invoke a CLI, hit the local-LLM endpoint, or request the+// native Copilot reviewer). Usernames are appended to slashdo's `--review-with`+// as `@user` tokens after the keyed reviewers; the review-loop follow-up prompt+// instructs the agent to request each as a PR reviewer and gate the merge on it.+//+// Stored WITHOUT the leading `@` (added back only in the flag string). The+// charset is deliberately shell-safe — a GitHub username (1–39 chars,+// alphanumeric + single hyphens, no leading/trailing hyphen) optionally followed+// by a `/team-slug` for org-team mentions. No shell metacharacters, so the token+// stays inert wherever it lands in a command string.+export const MAX_REVIEW_USERNAMES = 20;+const REVIEW_USERNAME_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\/[A-Za-z0-9._-]{1,100})?$/;++/**+ * Normalize a raw list of reviewer usernames: strip an optional leading `@`,+ * trim, drop anything that isn't a shell-safe GitHub username/team slug,+ * case-insensitively dedupe (GitHub logins are case-insensitive) while+ * preserving first-occurrence order, and cap at MAX_REVIEW_USERNAMES. Returns+ * a clean array of usernames WITHOUT the `@` prefix. Non-array input → [].+ */+export function normalizeReviewUsernames(list) {+ if (!Array.isArray(list)) return [];+ const seen = new Set();+ const out = [];+ for (const raw of list) {+ if (typeof raw !== 'string') continue;+ const trimmed = raw.trim().replace(/^@+/, '');+ if (!trimmed || !REVIEW_USERNAME_RE.test(trimmed)) continue;+ const key = trimmed.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(trimmed);+ if (out.length >= MAX_REVIEW_USERNAMES) break;+ }+ return out;+}++/**+ * Resolve reviewer usernames with task-over-default precedence: a task-level+ * list (even explicitly empty) overrides the Code Review Defaults; only fall+ * back to the defaults when the task didn't pin its own. Mirrors how+ * `normalizeReviewers`'s fallback param works for the keyed reviewers.+ */+export function resolveReviewUsernames(metadataUsernames, defaultUsernames) {+ return Array.isArray(metadataUsernames)+ ? normalizeReviewUsernames(metadataUsernames)+ : normalizeReviewUsernames(defaultUsernames);+}++/**+ * Normalize ONE raw reviewer identity to the exact token `--review-with` emits:+ * a keyed slug from `REVIEWER_VALUES` (aliasing `gemini` → `antigravity`) or an+ * `@<username>`. Returns null for anything else. Single definition of the token+ * identity shared by `normalizeOptionalReviewers` and+ * `normalizeReviewerMaxRounds`, so the `~opt` set and the `~max=<n>` map can't+ * disagree about what a reviewer is called.+ */+function normalizeReviewerToken(raw) {+ if (typeof raw !== 'string') return null;+ const trimmed = raw.trim();+ if (!trimmed) return null;+ if (trimmed.startsWith('@')) {+ const [user] = normalizeReviewUsernames([trimmed]);+ return user ? `@${user}` : null;+ }+ const slug = REVIEWER_ALIASES[trimmed] ?? trimmed;+ return REVIEWER_VALUES.includes(slug) ? slug : null;+}++/**+ * Reviewer identities the user marked OPTIONAL (non-blocking). slashdo's `~opt`+ * suffix is appended to each matching `--review-with` token, so an *inconclusive*+ * verdict from that reviewer (timeout / no-verdict / partial) no longer gates the+ * merge — a hard-error from it still does (slashdo `lib/multi-reviewer-loop.md`).+ * This is the escape hatch for a valuable-but-flaky reviewer (a local Ollama+ * model that often returns nothing) that would otherwise strand every PR on an+ * `inconclusive` aggregate.+ *+ * Each entry mirrors an *emitted* `--review-with` token so the builder's+ * membership test is a plain lookup: a keyed slug from `REVIEWER_VALUES`+ * (`ollama`, `lmstudio`, …) or an `@<username>`. Normalizes like the sibling+ * helpers — drop non-strings/unknown slugs/unsafe usernames, alias `gemini` →+ * `antigravity`, dedupe case-insensitively preserving order. Non-array → undefined+ * (an omitted field isn't persisted as an empty override).+ */+export function normalizeOptionalReviewers(list) {+ if (!Array.isArray(list)) return undefined;+ const seen = new Set();+ const out = [];+ for (const raw of list) {+ const token = normalizeReviewerToken(raw);+ if (!token) continue;+ const key = token.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(token);+ }+ return out;+}++/**+ * Resolve optional (non-blocking) reviewers with task-over-default precedence:+ * a task-level list (even explicitly empty) overrides the Code Review Defaults;+ * only fall back to the defaults when the task didn't pin its own. Mirrors+ * `resolveReviewUsernames`.+ */+export function resolveOptionalReviewers(metadataOptional, defaultOptional) {+ return Array.isArray(metadataOptional)+ ? (normalizeOptionalReviewers(metadataOptional) || [])+ : (normalizeOptionalReviewers(defaultOptional) || []);+}++/**+ * Factory for the token-keyed per-reviewer PIN normalizers (`~max=<n>` caps,+ * model ids, reasoning efforts). All three share one contract and only differ in+ * how they validate a single value, so the contract lives here once:+ *+ * - Non-object input → `undefined`, so an omitted field isn't persisted as an+ * empty override (an explicitly empty `{}` IS kept — it's a real "clear the+ * defaults for this task" choice).+ * - Keys are normalized to the exact token `--review-with` emits+ * (`normalizeReviewerToken`), so the maps can't disagree about what a reviewer+ * is called; unknown tokens are dropped.+ * - First spelling wins for two names of one reviewer (`gemini`/`antigravity`,+ * `@Bot`/`@bot`) — mirrors `normalizeOptionalReviewers`' dedupe.+ * - A value `normalizeOne` rejects is DROPPED, never coerced — for every pin+ * kind, "absent" and "a falsy value" mean different things downstream.+ *+ * `Object.create(null)` while building so a reviewer token can't collide with+ * `Object.prototype` keys; spread on return so callers get a plain object.+ *+ * @param {(value: unknown, token: string) => unknown} normalizeOne - returns the+ * validated value, or a falsy value to drop the entry.+ */+function keyedReviewerPinNormalizer(normalizeOne) {+ return (map) => {+ if (!isPlainObject(map)) return undefined;+ const out = Object.create(null);+ for (const [rawKey, rawValue] of Object.entries(map)) {+ const token = normalizeReviewerToken(rawKey);+ if (!token) continue;+ const value = normalizeOne(rawValue, token);+ if (!value && value !== 0) continue;+ if (Object.prototype.hasOwnProperty.call(out, token)) continue;+ out[token] = value;+ }+ return { ...out };+ };+}++/**+ * Factory for the matching task-over-default resolvers: a task-level map — even+ * an explicitly empty one — overrides the Code Review Defaults; only an+ * absent/malformed one falls back. Mirrors `resolveOptionalReviewers`.+ *+ * @param {(map: unknown) => Object|undefined} normalizeMap - the normalizer this+ * pin kind was built with.+ */+function keyedReviewerPinResolver(normalizeMap) {+ return (metadataMap, defaultMap) => (isPlainObject(metadataMap)+ ? (normalizeMap(metadataMap) || {})+ : (normalizeMap(defaultMap) || {}));+}++// Ceiling on a per-reviewer `~max=<n>` cap. slashdo's inner loops carry their own+// 10-iteration safety guardrail, so a budget above it can never be spent —+// accepting one would just be a lie in the flag string.+export const MAX_REVIEWER_MAX_ROUNDS = 10;++/**+ * Per-reviewer iteration caps — slashdo's `~max=<n>` suffix (v3.25.0). Caps how+ * many review → fix → re-review cycles ONE reviewer runs before it stops, so a+ * slow local model can be included in a chain without paying for its otherwise+ * hardcoded 3 rounds (`--review-with claude~max=2,ollama~max=1,codex~max=3`).+ * Stored as a token-keyed map (`{ ollama: 1, '@flaky-bot': 0 }`) rather than a+ * list because the cap carries a value; the key is the same *emitted*+ * `--review-with` token `normalizeOptionalReviewers` uses.+ *+ * **Absent ≠ 0.** slashdo reads `~max=0` as "loop until this reviewer is clean"+ * (bounded by its own 10-round guardrail), which is the OPPOSITE of "no cap+ * requested" (that keeps slashdo's built-in default of 3 for CLI/Ollama+ * reviewers). So a missing key and an explicit `0` must never collapse: an entry+ * whose value isn't a usable cap is DROPPED rather than coerced to `0`.+ * Drops unknown tokens, non-integers, negatives, and anything above+ * MAX_REVIEWER_MAX_ROUNDS so a hand-edited settings.json can't smuggle in an+ * unbounded budget. Non-object input → undefined (an omitted field isn't+ * persisted as an empty override).+ *+ * `0` is the one pin value that is falsy AND meaningful, which is why the shared+ * factory keeps it explicitly.+ */+export const normalizeReviewerMaxRounds = keyedReviewerPinNormalizer((rawValue) => (+ // Only a genuine non-negative integer is a cap. A string "2", null, NaN, or+ // 1.5 is not — and must NOT fall through to 0, which slashdo reads as+ // "unlimited".+ (Number.isInteger(rawValue) && rawValue >= 0 && rawValue <= MAX_REVIEWER_MAX_ROUNDS)+ ? rawValue+ : undefined+));++/**+ * Resolve per-reviewer iteration caps with task-over-default precedence: a+ * task-level map (even explicitly empty) overrides the Code Review Defaults;+ * only fall back to the defaults when the task didn't pin its own. Mirrors+ * `resolveOptionalReviewers`.+ */+export const resolveReviewerMaxRounds = keyedReviewerPinResolver(normalizeReviewerMaxRounds);++// Upper bound on a pinned reviewer model id. Generous (Bedrock/Ollama ids get+// long) but present so a hand-edited settings.json can't smuggle in a blob that+// then round-trips the TASKS.md store.+export const MAX_REVIEWER_MODEL_LENGTH = 200;++// Characters a model id may not contain, because they are STRUCTURAL in the+// emitted `--review-with` token and there is no escape for them:+// - `]` would close the `[<model>]` selector early (`foo]~opt` → a corrupt entry+// whose remainder slashdo then parses as suffixes),+// - `[` would open a nested one,+// - `,` would split the entry list, turning one reviewer into two bogus ones,+// - whitespace that breaks lines would split the single-line flag string.+// Everything else stays legal on purpose: the value is free-form in slashdo's+// grammar (`agy[Gemini 3.5 Flash (High)]` is valid), and the field has to accept+// whatever id the user's environment actually needs. A space is fine; a newline is+// not.+const REVIEWER_MODEL_FORBIDDEN_RE = /[[\],\r\n\t]/;++/**+ * Validate ONE reviewer model id — the single definition shared by the+ * token-keyed map normalizer, the `<reviewer>Model` settings scalars, and the+ * defaults→map adapter, so a pin can't be accepted by one path and dropped by+ * another (which would show the user a stored pin that never reaches a reviewer).+ *+ * Returns the trimmed id, or `undefined` when it isn't usable: a non-string, a+ * blank/whitespace-only value (absent ≠ `''` — a `--model ` with no id would break+ * the invocation), an over-long one, one carrying a structural delimiter, or one+ * 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 (typeof raw !== 'string') return undefined;+ const model = raw.trim();+ if (!model || model.length > MAX_REVIEWER_MODEL_LENGTH) return undefined;+ if (REVIEWER_MODEL_FORBIDDEN_RE.test(model)) return undefined;+ return model;+}++// Reviewers whose slashdo `--review-with` entry accepts a `[<model>]` bracket+// (`lib/multi-reviewer-loop.md`: codex/claude/agy/grok/cursor/ollama). A+// PORTOS_ONLY_REVIEWERS entry has no slashdo counterpart at all, so a pinned+// model for it never becomes a bracket, and `copilot`/`@login` entries reject+// one outright.+export const BRACKET_MODEL_REVIEWERS = MODEL_SELECTABLE_REVIEWERS.filter(r => !PORTOS_ONLY_REVIEWERS.includes(r));++/**+ * Per-reviewer model pins — the model id ONE reviewer runs with, keyed by the+ * same emitted `--review-with` token as `normalizeOptionalReviewers` /+ * `normalizeReviewerMaxRounds` (e.g. `{ codex: 'gpt-5.6-sol', ollama: 'qwen2.5:7b' }`).+ *+ * The value is free-text on purpose: a reviewer CLI is spawned by the *agent*,+ * not by PortOS's argv builder, so the id the user needs is environment-specific+ * (a Bedrock-form Claude id on a Bedrock box, an installed Ollama model for an+ * Ollama-backed `claude`). We validate the shape, not the catalog.+ *+ * Only MODEL_SELECTABLE_REVIEWERS can carry a pin — `copilot` has no CLI and a+ * `@username` reviewer is a human/bot, mirroring slashdo rejecting `copilot[…]`+ * and `@login[…]`. An absent key means "let that reviewer pick its own default",+ * which is NOT the same as an empty string, so a blank/whitespace value is+ * DROPPED rather than persisted as `''` (a `--model ` with no id would break the+ * reviewer invocation). Non-object input → undefined, so an omitted field isn't+ * persisted as an empty override.+ *+ * An id carrying a character that is structural in the emitted token+ * (REVIEWER_MODEL_FORBIDDEN_RE — `[`, `]`, `,`, line breaks) is dropped rather+ * than emitted: there's no escape for them inside `[<model>]`, so `foo]~opt` would+ * close the selector early and leave slashdo parsing the remainder as a suffix.+ * Dropping is the safe failure — the reviewer falls back to its own default model+ * instead of running against a corrupt reviewer list.+ */+export const normalizeReviewerModels = keyedReviewerPinNormalizer(normalizeReviewerModel);++/**+ * Resolve per-reviewer model pins with task-over-default precedence: a+ * task-level map (even explicitly empty) overrides the Code Review Defaults;+ * only fall back to the defaults when the task didn't pin its own. Mirrors+ * `resolveReviewerMaxRounds`.+ */+export const resolveReviewerModels = keyedReviewerPinResolver(normalizeReviewerModels);++/**+ * Fold the Code Review Defaults' per-reviewer model SCALARS+ * (`codexModel` / `claudeModel` / `lmstudioModel` / `ollamaModel`) into the+ * token-keyed map shape the resolvers and the picker UI both speak.+ *+ * The scalars are the persisted settings encoding and stay that way — they cross+ * installs, and rewriting them to a map would need a migration for zero gain.+ * This is the one adapter between the two shapes; everything downstream works in+ * map form.+ */+export function reviewerModelsFromDefaults(defaults) {+ const out = {};+ 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+ // builders would then drop.+ const model = normalizeReviewerModel(defaults?.[`${r}Model`], r);+ if (model) out[r] = model;+ }+ return out;+}++// Reasoning-effort ladder for the local-LLM reviewers. Their review request goes+// out as an OpenAI-compatible `/v1/chat/completions` call, whose `reasoning_effort`+// field both LM Studio and Ollama accept for thinking models — but only over the+// low/medium/high tier names. The wider CLI ladder (`minimal`/`xhigh`/`max`/+// `ultra`) is vendor-CLI vocabulary that an OpenAI-shaped backend can reject, so+// the local reviewers get their own, narrower set.+export const LOCAL_LLM_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);++/**+ * Reviewer slug → the reasoning-effort ladder that reviewer accepts. Only+ * reviewers WITH an effort control appear: `copilot` is a GitHub review, `grok`'s+ * CLI has no effort control of any kind, and an `@username` reviewer is a person.+ *+ * A ladder here means "the user can PICK a level", not "the CLI takes an+ * `--effort` flag" — `cursor` accepts a level only as a variant baked into its+ * model id, so it appears here while `reviewerEffortArgs` returns `[]` for it+ * and `reviewerModelArg` folds the level into `--model` instead.+ *+ * Built once at module load and DERIVED from `effortLevelsForProvider` rather+ * than restated, so a reviewer's ladder here is exactly the one+ * `reviewerEffortArgs` (and the agent-spawn argv builder) will accept — a CLI+ * that gains or loses a tier moves both at once. The lookup goes through+ * `reviewerCliBinary` because that's what identifies the CLI: the `antigravity`+ * slug names no executable, `agy` does.+ *+ * Mirrored in `client/src/components/cos/constants.js` (pinned by a parity test)+ * so the picker only offers a level the server would keep.+ */+export const REVIEWER_EFFORT_LEVELS = Object.freeze(Object.fromEntries(+ REVIEWER_VALUES+ .map((slug) => {+ if (LOCAL_LLM_REVIEWERS.includes(slug)) return [slug, LOCAL_LLM_EFFORT_LEVELS];+ const binary = reviewerCliBinary(slug);+ return [slug, binary ? effortLevelsForProvider({ id: slug, command: binary }) : null];+ })+ .filter(([, levels]) => levels?.length)+));++/**+ * Every reviewer the user can pick an effort for — the effort-capable CLIs+ * (`claude`, `codex`, `antigravity`, `cursor`) plus the local-LLM backends.+ */+export const EFFORT_SELECTABLE_REVIEWERS = Object.freeze(Object.keys(REVIEWER_EFFORT_LEVELS));++/**+ * The ladder for ONE reviewer token, or `null` when it takes no effort. Accepts+ * the `gemini` alias; an `@username` token resolves to null like any non-reviewer.+ *+ * @param {string} reviewer - reviewer slug+ * @returns {readonly string[]|null}+ */+export function reviewerEffortLevels(reviewer) {+ if (typeof reviewer !== 'string') return null;+ const slug = reviewer.trim().toLowerCase();+ return REVIEWER_EFFORT_LEVELS[REVIEWER_ALIASES[slug] ?? slug] || null;+}++/**+ * Validate ONE reviewer effort — the single definition shared by the token-keyed+ * map normalizer and the `<reviewer>Effort` settings scalars, so a level can't be+ * accepted by one path and dropped by another.+ *+ * `reviewer` is REQUIRED — this is the tight branch by design. Defaulting it to+ * "any known effort" would validate against the union of every ladder, so a+ * caller that forgot the argument would quietly accept `ollama: 'ultra'` and+ * `antigravity: 'max'`, the exact values the drop-don't-clamp contract exists to+ * reject.+ *+ * Returns the level, or `undefined` when it isn't usable: a non-string, a level+ * outside that reviewer's own ladder (`agy` really does reject `--effort max`),+ * or a reviewer with no effort control at all. Deliberately NOT clamped the way+ * `resolveCliEffort` clamps a provider pin: this value is user-chosen from a+ * per-reviewer list, so an out-of-ladder entry means the stored config is stale+ * or hand-edited, and silently reviewing at a *different* effort than the one+ * displayed is worse than falling back to the reviewer's own default.+ */+export function normalizeReviewerEffort(raw, reviewer) {+ if (typeof raw !== 'string') return undefined;+ const effort = raw.trim().toLowerCase();+ if (!effort) return undefined;+ return reviewerEffortLevels(reviewer)?.includes(effort) ? effort : undefined;+}++/**+ * Per-reviewer reasoning-effort pins — how hard ONE reviewer thinks, keyed by the+ * same emitted `--review-with` token as `normalizeReviewerModels` (e.g.+ * `{ codex: 'high', ollama: 'low' }`).+ *+ * Three carriers, depending on who invokes the reviewer. On a slashdo invocation+ * it rides the emitted token as `~effort=<level>` (`markSuffixes`), which slashdo+ * turns into the reviewer's own flag. Where PortOS drives the invocation itself it+ * is spelled out instead: the review-loop follow-up prompt's CLI command line+ * (`codex -c model_reasoning_effort=high`, `claude --effort high`) and the+ * `reasoning_effort` field of the local reviewer's `/api/code-review/local` body.+ *+ * An absent key means "let that reviewer use its own default effort", which is+ * NOT the same as a blank string, so an unusable value is DROPPED rather than+ * persisted. Non-object input → undefined, so an omitted field isn't persisted as+ * an empty override.+ */+export const normalizeReviewerEfforts = keyedReviewerPinNormalizer(normalizeReviewerEffort);++/**+ * Resolve per-reviewer effort pins with task-over-default precedence: a+ * task-level map (even explicitly empty) overrides the Code Review Defaults;+ * only fall back to the defaults when the task didn't pin its own. Mirrors+ * `resolveReviewerModels`.+ */+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: prioritizeToolFreeReviewers(normalizeReviewers(metadata, defaultReviewers)),+ usernames: resolveReviewUsernames(metadata?.usernames, codeReviewDefaults?.usernames),+ optionalReviewers: resolveOptionalReviewers(metadata?.optionalReviewers, codeReviewDefaults?.optionalReviewers),+ reviewerMaxRounds: resolveReviewerMaxRounds(metadata?.reviewerMaxRounds, codeReviewDefaults?.reviewerMaxRounds),+ ...resolveReviewerPins(metadata, codeReviewDefaults)+ };+}++/** The reviewer a claim flow falls back to when its resolved list is unusable. */+const CLAIM_REVIEWER_FALLBACK = ['codex'];++/**+ * Constrain an already-resolved reviewer list to what an UNATTENDED claim run can+ * actually invoke: `copilot` is a forge-side PR reviewer with no CLI, so a claim+ * agent told to "review with copilot" has nothing to run and stalls (#2507).+ * An empty result falls back to `codex` rather than to `DEFAULT_REVIEWERS`+ * (which is `copilot`, the very thing being removed).+ */+export function claimSafeReviewers(reviewers) {+ const kept = (Array.isArray(reviewers) ? reviewers : []).filter((reviewer) => reviewer !== 'copilot');+ return kept.length ? kept : [...CLAIM_REVIEWER_FALLBACK];+}++/**+ * Put tool-free local-LLM reviewers ahead of every reviewer that can execute+ * tools or reach a forge. Public issue comments and contributor diffs cross the+ * trust boundary in that first pass; later reviewers see a chain that has+ * already received a no-tool inspection. Stable partitioning preserves the+ * user's order within the local and non-local groups.+ */+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)),+ ];+}++/**+ * `resolveReviewerConfig` plus the claim flow's copilot guard and the emitted+ * `--review-with` token list — the ONE resolver a claim prompt's reviewer text+ * and a claim task's persisted `reviewers` metadata both go through, so the two+ * cannot name different reviewers.+ *+ * The generators resolve their list before a task record exists (they read+ * schedule metadata + Code Review Defaults); the prompt builder resolves it from+ * the persisted task metadata at spawn time. Feeding both the same function is+ * what makes `reviewerConfigMetadata`'s round-trip exact.+ */+export function resolveClaimReviewerConfig(metadata, codeReviewDefaults, defaultReviewers) {+ const config = resolveReviewerConfig(metadata, codeReviewDefaults, defaultReviewers);+ const reviewers = claimSafeReviewers(config.reviewers);+ return {+ ...config,+ reviewers,+ csv: buildReviewersCsv(reviewers, config.usernames, config.optionalReviewers, config.reviewerMaxRounds, config.reviewerModels, config.reviewerEfforts)+ };+}++/**+ * Resolve the model and effort pins TOGETHER — `{ reviewerModels, reviewerEfforts }`+ * with task-over-default precedence, already reconciled into a pair the reviewer's+ * CLI accepts (`pairReviewerModelsAndEfforts`).+ *+ * The two are never legitimately resolved apart: an `antigravity` model id can+ * carry its effort as a suffix, so whoever resolves the models must also be+ * holding the efforts to hand the suffix to. Resolving them separately is the+ * footgun — three prompt-building sites in `cosTaskGenerator.js` had already+ * hand-copied the pair of calls, and each would have emitted an+ * `agy --model <suffixed-id> --effort <tier>` invocation agy rejects. This is the+ * one call every site makes instead.+ *+ * Deliberately NOT expressed on `lib/llmRoutePin.js` (#4793). That module owns a+ * single `{ providerId, model, effort }` triple; a reviewer pin is two maps keyed+ * by reviewer slug, with no provider dimension at all — the slug IS the routing+ * key — and its precedence is whole-MAP (an explicitly empty task map overrides+ * the defaults), not per-field. Its effort is also validated against each+ * reviewer's OWN ladder via `normalizeReviewerEffort`, which is strictly narrower+ * than the union `EFFORT_LEVELS` enum the shared schema uses: `agy` really does+ * reject `--effort max`. There is no shape the two can meet in without losing+ * that narrowing, so this stays hand-rolled.+ *+ * @param {Object} [pins] - task metadata (or explicit options) carrying+ * `reviewerModels` / `reviewerEfforts` maps; an absent map falls back to the+ * Code Review Defaults, an explicitly empty one overrides them.+ * @param {Object} [codeReviewDefaults] - the `<reviewer>Model` / `<reviewer>Effort` scalars+ * @returns {{reviewerModels: Object<string,string>, reviewerEfforts: Object<string,string>}}+ */+export function resolveReviewerPins(pins, codeReviewDefaults) {+ return pairReviewerModelsAndEfforts(+ resolveReviewerModels(pins?.reviewerModels, reviewerModelsFromDefaults(codeReviewDefaults)),+ resolveReviewerEfforts(pins?.reviewerEfforts, reviewerEffortsFromDefaults(codeReviewDefaults))+ );+}++/**+ * Reconcile the resolved model and effort pins into a pair the reviewer's CLI+ * will actually accept, and return them as `{ reviewerModels, reviewerEfforts }`.+ *+ * Only `antigravity` needs reconciling. `agy models` enumerates its reasoning+ * tiers as separate model ids (`gemini-3.6-flash-high`), so a hand-typed pin can+ * carry an effort inside the model — and `agy` validates the PAIR, so+ * `--model gemini-3.6-flash-high --effort high` is not the same thing as the+ * `--model <base> --effort high` it expects. Splitting here mirrors what+ * `resolveAntigravityModelAndEffort` already does for PortOS's own agy spawns:+ * the base id becomes the model, and the baked tier supplies the effort ONLY when+ * the user pinned none (an explicit pick always wins).+ *+ * Applied once inside `resolveReviewerPins` rather than at each emission site, so+ * the slashdo `agy[<model>]` bracket, the effort instruction, and the review-loop+ * prompt's literal command line all describe the same invocation.+ *+ * @param {Object<string,string>} [reviewerModels]+ * @param {Object<string,string>} [reviewerEfforts]+ * @returns {{reviewerModels: Object<string,string>, reviewerEfforts: Object<string,string>}}+ */+export function pairReviewerModelsAndEfforts(reviewerModels, reviewerEfforts) {+ const models = { ...(reviewerModels || {}) };+ const efforts = { ...(reviewerEfforts || {}) };+ const { base, effort } = splitAntigravityModel(models.antigravity);+ if (effort && base) {+ models.antigravity = base;+ if (!normalizeReviewerEffort(efforts.antigravity, 'antigravity')) efforts.antigravity = effort;+ }+ return { reviewerModels: models, reviewerEfforts: efforts };+}++/**+ * 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+ * the token-keyed map shape the resolvers and the picker UI both speak — the+ * effort twin of `reviewerModelsFromDefaults`, and the one adapter between the+ * two shapes.+ */+export function reviewerEffortsFromDefaults(defaults) {+ const out = {};+ for (const r of EFFORT_SELECTABLE_REVIEWERS) {+ // Re-checked, not trusted: settings.json is hand-editable, and a stale level+ // must not surface as a pin the invocation builders would then drop.+ const effort = normalizeReviewerEffort(defaults?.[`${r}Effort`], r);+ if (effort) out[r] = effort;+ }+ return out;+}++/**+ * The argv fragment a CLI reviewer takes for a reasoning-effort override —+ * `['--effort', 'high']` for claude/agy, `['-c', 'model_reasoning_effort=high']`+ * for codex, `[]` for everything else. Delegates to `buildEffortArgs` so the flag+ * shape has exactly one home (the spawn builders use the same one).+ *+ * **`cursor` is deliberately `[]` despite having a ladder.** `cursor-agent` has+ * no `--effort` flag and exits non-zero on one, so its level rides `--model`+ * instead — build that with `reviewerModelArg`. Anything that renders a cursor+ * invocation must call BOTH, or it will silently drop the pin (or, worse,+ * hand-roll the `--effort` this returns nothing for).+ *+ * **Normalizes first, deliberately.** `buildEffortArgs` CLAMPS an out-of-ladder+ * value (`agy` + `max` → `--effort high`), which is right for a provider pin the+ * user set against a different provider, but wrong here: a reviewer effort is+ * chosen from that reviewer's own list, so an out-of-ladder value means stale or+ * hand-edited state — and emitting a clamped flag would run the review at an+ * effort the picker displays as `unsupported`. Dropping to the reviewer's own+ * default is the honest failure, matching `normalizeReviewerEffort`'s contract.+ * The normalize is here rather than left to callers because this function is+ * reached with raw task metadata (`reviewLoopReviewerEfforts`), which no+ * normalizer has necessarily touched.+ *+ * @param {string} reviewer - reviewer slug+ * @param {string|null|undefined} effort+ * @returns {string[]}+ */+export function reviewerEffortArgs(reviewer, effort) {+ const binary = reviewerCliBinary(reviewer);+ if (!binary) return [];+ const level = normalizeReviewerEffort(effort, reviewer);+ if (!level) return [];+ return buildEffortArgs(level, { id: reviewer, command: binary });+}++/**+ * The id a CLI reviewer's `--model` flag should carry, or `null` when there is+ * no model to pin. The twin of `reviewerEffortArgs`: together they are the whole+ * invocation a pinned reviewer needs, and the ONLY place that knows which of the+ * two carries a cursor effort.+ *+ * For every reviewer but `cursor` this is just the pinned id, threaded verbatim+ * (the id is environment-specific free text — see `normalizeReviewerModels`).+ * For `cursor` the effort is folded in as Cursor's native model variant+ * (`gpt-5` + `max` → `gpt-5[effort=max]`), matching slashdo's own fold, because+ * `cursor-agent` has no `--effort` flag. A cursor effort with no model pinned+ * returns `null` — there is nothing to attach the variant to, and emitting a+ * flag cursor rejects is worse than letting it use its default tier. (The picker+ * says so on the row, so the dropped tier isn't silent to the user.)+ *+ * The extend-an-existing-bracket and leave-an-`effort=`-alone arms of the fold+ * can't be reached by a STORED reviewer pin today — `normalizeReviewerModel`+ * rejects `[`/`]`/`,` because they're structural in the emitted `--review-with`+ * token. They serve the paths that don't go through that gate: a provider's own+ * `defaultModel` and hand-written task metadata.+ *+ * @param {string} reviewer - reviewer slug+ * @param {string|null|undefined} model - the pinned model id+ * @param {string|null|undefined} [effort] - the pinned effort (cursor only)+ * @returns {string|null}+ */+export function reviewerModelArg(reviewer, model, effort) {+ const id = typeof model === 'string' ? model.trim() : '';+ if (!id) return null;+ const slug = typeof reviewer === 'string' ? reviewer.trim().toLowerCase() : '';+ if ((REVIEWER_ALIASES[slug] ?? slug) !== 'cursor') return id;+ const level = normalizeReviewerEffort(effort, 'cursor');+ return level ? foldCursorEffortIntoModel(id, level) : id;+}++/**+ * Prose instruction carrying the per-reviewer effort pins into a prompt whose+ * agent spawns the reviewer CLI ITSELF — the claim flows (which run each+ * configured reviewer by hand, no `--review-with` anywhere in the prompt) and a+ * slashdo invocation that pins no reviewer list.+ *+ * **Not for an invocation that pins `--review-with`.** slashdo's entry grammar is+ * `<agent>[<model>](~opt|~max=<n>|~effort=<level>)*`, and `markSuffixes` emits+ * that `~effort=` suffix, so the pin already reaches the CLI the loop spawns.+ * Restating it as prose there is worse than silent: the agent passes the flag a+ * second time, or hand-runs a reviewer the loop was about to run. Pass the+ * emitted `--review-with` text as `reviewWith` and this returns '' when it sees+ * the suffix — one check, so a caller can't decide wrong.+ *+ * Scoped to CLI reviewers on purpose — `ollama`/`lmstudio` have no binary to+ * name (their effort rides the `POST /api/code-review/local` body instead).+ *+ * `cursor` needs its MODEL to say anything at all: its level is a variant of the+ * model id, never a flag, so pass `reviewerModels` — a cursor pin with no model+ * emits nothing rather than an `--effort` its CLI rejects.+ *+ * @param {string[]} reviewers - the reviewer slugs the invocation emits+ * @param {Object<string, string>} [reviewerEfforts] - token-keyed effort pins+ * @param {Object} [options]+ * @param {string} [options.reviewWith] - the `--review-with` text this prompt+ * emits, if any. A `~effort=` in it means slashdo already carries the pin.+ * @param {Object<string, string>} [options.reviewerModels] - token-keyed model+ * pins, needed only to render a cursor invocation (see above)+ * @returns {string} a single sentence, or '' when nothing is left to say+ */+export function buildReviewerEffortNote(reviewers, reviewerEfforts = {}, { reviewWith = '', reviewerModels = {} } = {}) {+ if (typeof reviewWith === 'string' && reviewWith.includes('~effort=')) return '';+ const efforts = normalizeReviewerEfforts(reviewerEfforts) || {};+ const models = normalizeReviewerModels(reviewerModels) || {};+ const entries = (Array.isArray(reviewers) ? reviewers : [])+ .map((r) => {+ // No binary, nothing to name: `lmstudio`/`ollama` reach their backend over+ // HTTP, and copilot/@username aren't commands at all. Checked FIRST so no+ // branch below can render a `null` command into a prompt.+ const binary = reviewerCliBinary(r);+ if (!binary) return null;+ const args = reviewerEffortArgs(r, efforts[r]);+ if (args.length) return `\`${binary} ${args.join(' ')}\``;+ // No effort ARGV, but the reviewer may still carry the level inside+ // --model (cursor). Gated on the effort pin so this stays an effort note:+ // a model-only pin is not this sentence's business.+ if (!normalizeReviewerEffort(efforts[r], r)) return null;+ const model = reviewerModelArg(r, models[r], efforts[r]);+ return model ? `\`${binary} --model ${model}\`` : null;+ })+ .filter(Boolean);+ if (!entries.length) return '';+ return `Invoke each reviewer CLI at its pinned reasoning effort: ${entries.join(', ')}. Pass the flag yourself when you spawn the reviewer — nothing else in this prompt applies it (a \`~effort=<level>\` suffix in a reviewer list is slashdo's own grammar, which only its \`--review-with\` parses).`;+}++// Examples of slashdo commands that run a review loop and therefore resolve+// `--review-with` from a saved default when the invocation doesn't pin one.+// EXAMPLES, deliberately — the rule is stated over "any `/do:*` that reviews"+// because the real roster is larger and moves with the submodule (`/do:review`,+// `/do:better`, `/do:better-swift`, `/do:depfree`, `/do:release` all read it+// too). A hand-maintained enumeration is the part that rots, and a command+// missing from it would read as exempt.+const REVIEW_LOOP_SLASHDO_EXAMPLES_MD = ['/do:pr', '/do:next', '/do:review', '/do:rpr']+ .map(command => `\`${command}\``).join(', ');++/**+ * The reviewer slug inside an emitted `--review-with` token, without its+ * `[<model>]` / `~<suffix>` decoration — the inverse of `markSuffixes`, which is+ * the only thing that ever builds one. Kept beside its emitter, and pinned to it+ * by a round-trip test, so a grammar change can't silently mis-slug here.+ */+export const reviewerTokenSlug = (token) => String(token).split('[')[0].split('~')[0].trim().toLowerCase();++/**+ * Prose block pinning a claim prompt's reviewer list against slashdo's SAVED+ * defaults.+ *+ * The claim flows hand-run their reviewers, so the prompt names the list and+ * emits no flag. But the claim agent is usually a Claude Code session with+ * slashdo installed, and reaching for `/do:pr` mid-flow is a short step from+ * the phase text — at which point slashdo resolves `--review-with` from the+ * host's saved defaults (`.slashdo.json` at the repo root, or the host CLI's+ * `.slashdo-config.json`), i.e. some OTHER user-level reviewer set, plus+ * whatever `merge` default rides with it. That silently replaces the reviewers+ * PortOS resolved for this run. So state the pin once, in the prompt, with the+ * exact token list to pass.+ *+ * `reviewersCsv` must be the text `buildReviewersCsv` emits — the same+ * `<agent>[<model>]~opt~max=<n>~effort=<level>` grammar `--review-with` parses —+ * so the agent can paste it verbatim.+ *+ * Unlike `buildReviewWithArgs` this does NOT suppress a lone bare `copilot`+ * (the #2507 stall): every claim path resolves its list through+ * `claimSafeReviewers`, which strips `copilot` and falls back to `codex`,+ * so the suppressed case cannot reach here. A future caller that skips that+ * normalizer has to add the guard rather than assume it.+ *+ * @param {string} reviewersCsv - the emitted reviewer token list+ * @returns {string} a Markdown block, or '' when there is no list to pin+ */+export function buildReviewerPinNote(reviewersCsv) {+ const csv = typeof reviewersCsv === 'string' ? reviewersCsv.trim() : '';+ if (!csv) return '';+ // A `@login` entry is always a valid slashdo reviewer; a keyed one is valid+ // unless PortOS serves it itself. Emitting a PORTOS_ONLY_REVIEWERS slug in a+ // `--review-with` list would abort the command outright, so it is dropped from+ // the flag text and named separately with the procedure that DOES run it.+ const tokens = csv.split(',').map(t => t.trim()).filter(Boolean);+ const flagTokens = tokens.filter(t => t.startsWith('@') || !PORTOS_ONLY_REVIEWERS.includes(reviewerTokenSlug(t)));+ // Named by bare slug: the `[<model>]`/`~<suffix>` decoration is slashdo+ // grammar, and these reviewers never reach a slashdo parser.+ const portosOnly = [...new Set(tokens.filter(t => !flagTokens.includes(t)).map(reviewerTokenSlug))];++ return [+ '## Reviewer pin — use the reviewers PortOS configured',+ `PortOS resolved this run's reviewers from its own configuration: \`${csv}\`. That list is authoritative for every review in this run — it is the same list the phases above name. Never substitute a different reviewer set for it.`,+ flagTokens.length+ && `**A saved slashdo default must never stand in for it.** If you invoke ANY slashdo \`/do:*\` command that runs a review loop (${REVIEW_LOOP_SLASHDO_EXAMPLES_MD}, and others), pass \`--review-with ${flagTokens.join(',')}\` explicitly. A bare invocation resolves \`--review-with\` from the host's saved defaults instead — \`.slashdo.json\` at the repo root, or the host CLI's \`.slashdo-config.json\` — which name a different reviewer set and can carry an auto-merge default this run never asked for.`,+ flagTokens.length+ && 'Pass those tokens exactly as written: their `[<model>]`, `~opt`, `~max=<n>`, and `~effort=<level>` suffixes are slashdo grammar and already carry each reviewer\'s pinned model, optional/blocking status, round cap, and reasoning effort — so do not also apply those by hand on that path.',+ portosOnly.length+ && `PortOS runs \`${portosOnly.join('`, `')}\` itself — no slashdo slug, so never a \`--review-with\` value. That review happens through the Local Reviewer Procedure below, and leaving it out of a slashdo invocation is not permission to skip it.`,+ ].filter(Boolean).join('\n\n');+}++/**+ * Build the set of lowercased optional-reviewer tokens for a fast membership+ * test in the builders. Tolerates the raw (unnormalized) list.+ */+function optionalReviewerSet(optionalReviewers) {+ return new Set((normalizeOptionalReviewers(optionalReviewers) || []).map(t => t.toLowerCase()));+}++/**+ * Build a lowercased-token → cap lookup for the builders. Tolerates the raw+ * (unnormalized) map. A `Map` (not a plain object) so a reviewer token can never+ * collide with `Object.prototype` keys, and so `.get()` distinguishes an absent+ * cap (`undefined`) from an explicit `0`.+ */+function reviewerMaxRoundsLookup(reviewerMaxRounds) {+ const normalized = normalizeReviewerMaxRounds(reviewerMaxRounds) || {};+ return new Map(Object.entries(normalized).map(([token, max]) => [token.toLowerCase(), max]));+}++/**+ * Build a lowercased-token → model-id lookup for the builders. Tolerates the raw+ * (unnormalized) map. A `Map` for the same reasons as the cap lookup.+ */+function reviewerModelLookup(reviewerModels) {+ const normalized = normalizeReviewerModels(reviewerModels) || {};+ return new Map(Object.entries(normalized).map(([token, model]) => [token.toLowerCase(), model]));+}++/**+ * Build a lowercased-token → effort-level lookup for the builders. Tolerates the raw+ * (unnormalized) map. A `Map` for the same reasons as the cap and model lookups.+ */+function reviewerEffortLookup(reviewerEfforts) {+ const normalized = normalizeReviewerEfforts(reviewerEfforts) || {};+ return new Map(Object.entries(normalized).map(([token, effort]) => [token.toLowerCase(), effort]));+}++/**+ * Render one emitted `--review-with` entry: the reviewer token, its optional+ * `[<model>]` selector, then slashdo's per-entry suffixes in canonical storage+ * order — `~opt`, `~max=<n>`, then `~effort=<level>`.+ *+ * Order matters. slashdo's grammar is+ * `entry := ( <agent> [ "[" <model> "]" ] | "@" <login> ) ( "~opt" | "~max=" <n> | "~effort=" <level> )*`+ * and its parser strips the `~` suffixes from the RIGHT before reading the+ * bracket — so the bracket has to sit between the slug and the suffixes.+ *+ * A reviewer with no pinned model emits no bracket, which is what leaves that+ * reviewer's own default in place; likewise a reviewer with no cap emits no+ * `~max` at all (`~max=0` is a real, distinct value meaning "loop until clean"), and+ * a reviewer with no effort level emits no `~effort`.+ * Only BRACKET_MODEL_REVIEWERS get a bracket — `copilot`/`@login` reject one, and+ * PortOS's `lmstudio` reviewer has no slashdo slug at all (its model rides in the+ * `POST /api/code-review/local` body instead).+ */+function markSuffixes(token, optSet, maxLookup, modelLookup, effortLookup) {+ const key = token.toLowerCase();+ const max = maxLookup?.get(key);+ const model = BRACKET_MODEL_REVIEWERS.includes(key) ? modelLookup?.get(key) : undefined;+ const effort = effortLookup?.get(key);+ return `${token}${model ? `[${model}]` : ''}${optSet.has(key) ? '~opt' : ''}${max === undefined ? '' : `~max=${max}`}${effort ? `~effort=${effort}` : ''}`;+}++/**+ * Resolve task metadata to an ordered, deduped reviewer list. Prefers the new+ * `reviewers` array; falls back to the legacy single `reviewer` string. When+ * the metadata yields nothing, returns `fallback` (default `['copilot']`) —+ * pass the settings-resolved defaults here so a Review Loop run picks up the+ * user's Code Review Defaults instead of the hardcoded copilot when the task+ * itself didn't pin reviewers. Filters to known reviewers and preserves+ * first-occurrence order.+ */+export function normalizeReviewers(meta, fallback = DEFAULT_REVIEWERS) {+ const raw = meta && typeof meta === 'object' && !Array.isArray(meta) ? meta : {};+ const source = Array.isArray(raw.reviewers)+ ? raw.reviewers+ : (typeof raw.reviewer === 'string' && raw.reviewer ? [raw.reviewer] : []);+ const seen = new Set();+ 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 (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)) {+ fallbackSeen.add(normalized);+ fallbackList.push(normalized);+ }+ }+ return fallbackList.length ? [...fallbackList] : [...DEFAULT_REVIEWERS];+}++/**+ * Resolve the keyed (enum) reviewer list, honoring the "username-only" case: an+ * EXPLICITLY empty keyed list with username reviewers present (e.g. copilot was+ * stripped on a non-GitHub forge) stays empty rather than falling back to the+ * copilot default normalizeReviewers would apply. Absent/legacy input still+ * normalizes to the default. Single source for the guard shared by+ * `buildReviewWithArgs` and the review-loop follow-up prompt builder.+ */+export function resolveKeyedReviewers(reviewers, hasUsernames) {+ if (Array.isArray(reviewers) && reviewers.length === 0 && hasUsernames) return [];+ return normalizeReviewers({ reviewers });+}++/**+ * Build the comma-separated reviewer token list used to fill the `{reviewers}`+ * placeholder in claim/plan prompts: keyed reviewers (falling back to the+ * default when empty) followed by `@user` tokens for the reviewer usernames.+ * Reviewers in `optionalReviewers` get slashdo's `~opt` non-blocking suffix, and+ * reviewers carrying a `reviewerMaxRounds` cap get `~max=<n>` after it. A+ * reviewer with a `reviewerModels` pin gets slashdo's `[<model>]` selector+ * between the slug and those suffixes, and a reviewer with a `reviewerEfforts` pin+ * gets `~effort=<level>`.+ * The flag-string variant is `buildReviewWithArgs`.+ */+export function buildReviewersCsv(reviewers, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}) {+ const keyed = Array.isArray(reviewers) && reviewers.length ? reviewers : [...DEFAULT_REVIEWERS];+ const users = normalizeReviewUsernames(usernames);+ const optSet = optionalReviewerSet(optionalReviewers);+ const maxLookup = reviewerMaxRoundsLookup(reviewerMaxRounds);+ const modelLookup = reviewerModelLookup(reviewerModels);+ const effortLookup = reviewerEffortLookup(reviewerEfforts);+ const combined = [...keyed, ...users.map(u => `@${u}`)];+ return combined.map(t => markSuffixes(t, optSet, maxLookup, modelLookup, effortLookup)).join(',');+}++/**+ * Build the slashdo review flag string for an ordered reviewer list plus any+ * arbitrary GitHub reviewer usernames.+ * - `--review-with a,b,@user` only when the effective list isn't the lone default+ * copilot (any username, or any non-default keyed reviewer, forces it on).+ * Usernames are appended as `@user` tokens after the keyed reviewers.+ * - `--review-stop-on-*` only when the effective list is 2+ (stop-mode is+ * meaningless for one).+ * - `--reviewer-applies` only when a non-copilot KEYED reviewer is present (a+ * username reviewer is an external PR reviewer, not a CLI that applies fixes).+ * - Reviewers in `optionalReviewers` get slashdo's `~opt` non-blocking suffix on+ * their emitted token, so an inconclusive verdict from them doesn't gate the+ * merge. Reviewers with a `reviewerMaxRounds` cap get `~max=<n>` after it,+ * a reviewer with a `reviewerModels` pin gets a `[<model>]` selector before both,+ * and a reviewer with a `reviewerEfforts` pin gets `~effort=<level>`.+ * A lone default `copilot` that is marked optional, carries a cap, or carries an+ * effort DOES force the flag on (otherwise the suffix — the whole point — would be+ * dropped with the flag).+ *+ * Everything past `reviewers` is an options object: the two reviewer-name lists+ * (`usernames` / `optionalReviewers`) and the three per-reviewer lookup maps+ * (`reviewerMaxRounds` / `reviewerModels` / `reviewerEfforts`) are same-shaped.+ *+ * @param {string[]} reviewers - ordered keyed reviewer slugs+ * @param {Object} [options]+ * @param {string} [options.stopMode] - review stop mode (`all` / `on-findings` / `on-clean`)+ * @param {boolean} [options.reviewerApplies] - emit `--reviewer-applies`+ * @param {string[]} [options.usernames] - GitHub reviewer usernames (emitted as `@user`)+ * @param {string[]} [options.optionalReviewers] - reviewers that get the `~opt` suffix+ * @param {Object<string, number>} [options.reviewerMaxRounds] - per-reviewer `~max=<n>` caps+ * @param {Object<string, string>} [options.reviewerModels] - per-reviewer `[<model>]` pins+ * @param {Object<string, string>} [options.reviewerEfforts] - per-reviewer `~effort=<level>` pins+ * @returns {string} the slashdo review flag string (possibly empty)+ */+export function buildReviewWithArgs(reviewers, {+ stopMode = DEFAULT_REVIEW_STOP_MODE,+ reviewerApplies = false,+ usernames = [],+ optionalReviewers = [],+ reviewerMaxRounds = {},+ reviewerModels = {},+ reviewerEfforts = {},+} = {}) {+ const users = normalizeReviewUsernames(usernames);+ const keyed = resolveKeyedReviewers(reviewers, users.length > 0);+ const combined = [...keyed, ...users.map(u => `@${u}`)];+ const optSet = optionalReviewerSet(optionalReviewers);+ const maxLookup = reviewerMaxRoundsLookup(reviewerMaxRounds);+ const modelLookup = reviewerModelLookup(reviewerModels);+ const effortLookup = reviewerEffortLookup(reviewerEfforts);+ // The lone-default-copilot suppression only applies when copilot carries NO+ // per-entry suffix — a `copilot~opt` / `copilot~max=2` / `copilot~effort=high` list must still+ // emit the flag to carry that suffix.+ const isDefaultOnly = combined.length === 1 && combined[0] === DEFAULT_REVIEWER+ && !optSet.has(DEFAULT_REVIEWER) && maxLookup.get(DEFAULT_REVIEWER) === undefined+ && effortLookup.get(DEFAULT_REVIEWER) === undefined;+ const hasNonCopilot = keyed.some(r => r !== DEFAULT_REVIEWER);+ const parts = [];+ if (!isDefaultOnly) parts.push(`--review-with ${combined.map(t => markSuffixes(t, optSet, maxLookup, modelLookup, effortLookup)).join(',')}`);+ if (combined.length >= 2) {+ if (stopMode === 'on-findings') parts.push('--review-stop-on-findings');+ else if (stopMode === 'on-clean') parts.push('--review-stop-on-clean');+ }+ if (reviewerApplies && hasNonCopilot) parts.push('--reviewer-applies');+ return parts.join(' ');+}diff --git a/server/lib/reviewerConfig.test.js b/server/lib/reviewerConfig.test.jsnew file mode 100644index 0000000000..4137755e35--- /dev/null+++ b/server/lib/reviewerConfig.test.js@@ -0,0 +1,624 @@+import { describe, it, expect } from 'vitest';+import {+ describeReviewerCli,+ isCliReviewer,+ reviewerCliBinary,+ DEFAULT_REVIEWER,+ LOCAL_LLM_REVIEWERS,+ REVIEWER_ALIASES,+ REVIEWER_CLI_BINARIES,+ REVIEWER_VALUES,+ EFFORT_SELECTABLE_REVIEWERS,+ MODEL_CAPABLE_CLI_REVIEWERS,+ MODEL_SELECTABLE_REVIEWERS,+ pairReviewerModelsAndEfforts,+ reviewerModelsFromDefaults,+ buildReviewWithArgs,+ LOCAL_LLM_EFFORT_LEVELS,+ reviewerEffortLevels,+ normalizeReviewerEfforts,+ resolveReviewerEfforts,+ reviewerEffortsFromDefaults,+ reviewerEffortArgs,+ reviewerModelArg,+ buildReviewerEffortNote,+ buildReviewerPinNote,+ buildReviewersCsv,+ claimSafeReviewers,+ prioritizeToolFreeReviewers,+ resolveReviewerConfig,+ resolveClaimReviewerConfig,+ reviewerTokenSlug,+} from './reviewerConfig.js';+// The Zod half of the old cosValidation.js — these cases assert that a reviewer+// pin survives the schema that persists it, so they need both modules.+import { createCosTaskSchema, sanitizeTaskMetadata, codeReviewSettingsSchema, reviewerConfigMetadata } from './cosValidation.js';+import { LOCAL_AGENT_REVIEWERS } from './slashdoInvocation.js';+import { CLAUDE_EFFORT_LEVELS, CODEX_EFFORT_LEVELS, ANTIGRAVITY_EFFORT_LEVELS, CURSOR_EFFORT_LEVELS, GROK_EFFORT_LEVELS } from './providerModels.js';++describe('reviewerConfig reviewer CLI binaries', () => {+ // The bug this exists to prevent: `antigravity` is the stored, federated+ // reviewer identity, but the shipped executable is `agy` — no `antigravity`+ // command exists. A review-loop follow-up agent handed the bare slug ran+ // `command -v antigravity`, got nothing, concluded "no reviewer is available",+ // self-reviewed, and merged its own PR.+ it('maps the antigravity slug (and its gemini alias) to the agy binary', () => {+ expect(reviewerCliBinary('antigravity')).toBe('agy');+ expect(reviewerCliBinary('gemini')).toBe('agy');+ expect(reviewerCliBinary('ANTIGRAVITY')).toBe('agy');+ expect(describeReviewerCli('antigravity')).toBe('`agy` (the `antigravity` reviewer)');+ });++ it('leaves same-named reviewers alone rather than restating the slug', () => {+ for (const slug of ['claude', 'codex', 'grok']) {+ expect(reviewerCliBinary(slug)).toBe(slug);+ expect(describeReviewerCli(slug)).toBe(`\`${slug}\``);+ }+ expect(reviewerCliBinary('cursor')).toBe('cursor-agent');+ expect(reviewerCliBinary('cursor-agent')).toBe('cursor-agent');+ expect(describeReviewerCli('cursor')).toBe('`cursor-agent` (the `cursor` reviewer)');+ });++ it('returns null for reviewers that have no spawnable CLI', () => {+ // copilot is a GitHub API review; lmstudio/ollama go through+ // POST /api/code-review/local. Prompt builders must not tell an agent to+ // run these as commands.+ for (const slug of [DEFAULT_REVIEWER, ...LOCAL_LLM_REVIEWERS]) {+ expect(reviewerCliBinary(slug)).toBeNull();+ }+ expect(reviewerCliBinary(undefined)).toBeNull();+ expect(describeReviewerCli(undefined)).toBe('');+ });++ // Guard the guard: a NEW CLI reviewer added to REVIEWER_VALUES without a+ // binary mapping must be caught here rather than shipping another slug an+ // agent will fruitlessly probe for. Aliases resolve first, so `gemini` is not+ // itself expected in the map. Uses isCliReviewer rather than re-spelling the+ // exclusion, so a change to that rule can actually fail this test.+ it('every CLI reviewer in REVIEWER_VALUES maps to a binary', () => {+ const cliReviewers = REVIEWER_VALUES.filter(isCliReviewer);+ expect(cliReviewers.length).toBeGreaterThan(0);+ for (const slug of cliReviewers) {+ expect(reviewerCliBinary(slug), `reviewerCliBinary('${slug}')`).toBeTruthy();+ }+ for (const alias of Object.keys(REVIEWER_ALIASES)) {+ expect(reviewerCliBinary(alias)).toBe(reviewerCliBinary(REVIEWER_ALIASES[alias]));+ }+ });++ it('agrees with isCliReviewer on which reviewers are spawnable CLIs', () => {+ for (const slug of REVIEWER_VALUES) {+ expect(Boolean(reviewerCliBinary(slug)), slug).toBe(isCliReviewer(slug));+ }+ expect(isCliReviewer(DEFAULT_REVIEWER)).toBe(false);+ expect(LOCAL_LLM_REVIEWERS.some(isCliReviewer)).toBe(false);+ });++ // slashdoInvocation keeps its own copy of the roster to decide which slashdo+ // `lib/*` includes a reviewer needs. Two hand-maintained lists of the same+ // reviewers drift the moment one gains a member — the `grok` addition is the+ // precedent — so pin them to each other rather than making slashdoInvocation+ // import this module (cosValidation.js re-exports this module AND imports+ // slashdoInvocation, so a cycle here would be worse than the duplication).+ it('matches slashdoInvocation LOCAL_AGENT_REVIEWERS', () => {+ expect([...LOCAL_AGENT_REVIEWERS].sort()).toEqual(Object.keys(REVIEWER_CLI_BINARIES).sort());+ });+});++describe('per-reviewer reasoning effort (reviewerEfforts)', () => {+ it('offers each reviewer only the ladder its own CLI accepts', () => {+ expect(reviewerEffortLevels('claude')).toEqual(CLAUDE_EFFORT_LEVELS);+ expect(reviewerEffortLevels('codex')).toEqual(CODEX_EFFORT_LEVELS);+ expect(reviewerEffortLevels('antigravity')).toEqual(ANTIGRAVITY_EFFORT_LEVELS);+ // The `gemini` alias resolves to the same ladder as `antigravity`.+ expect(reviewerEffortLevels('gemini')).toEqual(ANTIGRAVITY_EFFORT_LEVELS);+ expect(reviewerEffortLevels('ollama')).toEqual(LOCAL_LLM_EFFORT_LEVELS);+ expect(reviewerEffortLevels('lmstudio')).toEqual(LOCAL_LLM_EFFORT_LEVELS);+ // cursor has a ladder even though `cursor-agent` takes no `--effort` flag:+ // the level is a variant of its model id, folded in by `reviewerModelArg`.+ expect(reviewerEffortLevels('cursor')).toEqual(CURSOR_EFFORT_LEVELS);+ expect(reviewerEffortLevels('cursor-agent')).toEqual(CURSOR_EFFORT_LEVELS);+ // grok's ladder stops at xhigh — derived from effortLevelsForProvider, so it+ // is exactly what `grok --reasoning-effort` accepts.+ expect(reviewerEffortLevels('grok')).toEqual(GROK_EFFORT_LEVELS);+ // No effort control: copilot is a GitHub review, and a `@username` reviewer+ // is a person.+ expect(reviewerEffortLevels('copilot')).toBeNull();+ expect(reviewerEffortLevels('@somebody')).toBeNull();+ });++ it('EFFORT_SELECTABLE_REVIEWERS is exactly the reviewers with a non-empty ladder', () => {+ expect([...EFFORT_SELECTABLE_REVIEWERS].sort())+ .toEqual(['antigravity', 'claude', 'codex', 'cursor', 'grok', 'lmstudio', 'ollama']);+ for (const reviewer of REVIEWER_VALUES) {+ expect(EFFORT_SELECTABLE_REVIEWERS.includes(reviewer))+ .toBe((reviewerEffortLevels(reviewer) || []).length > 0);+ }+ });++ it('normalizes a token-keyed map: aliases, case, and out-of-ladder levels', () => {+ expect(normalizeReviewerEfforts({+ gemini: 'HIGH', // alias + case-folded+ codex: 'xhigh', // in codex's ladder only+ claude: 'medium',+ ollama: ' low ', // trimmed+ })).toEqual({ antigravity: 'high', codex: 'xhigh', claude: 'medium', ollama: 'low' });+ });++ it('DROPS rather than clamps a level the reviewer rejects — a displayed effort must be the one it runs', () => {+ // `agy` really does reject `--effort max`; clamping it to `high` would review+ // at a different effort than the picker shows.+ expect(normalizeReviewerEfforts({ antigravity: 'max' })).toEqual({});+ // grok rejects `max` the way agy rejects it — dropped, not clamped.+ expect(normalizeReviewerEfforts({ grok: 'max' })).toEqual({});+ expect(normalizeReviewerEfforts({ grok: 'xhigh' })).toEqual({ grok: 'xhigh' });+ // Reviewers with no effort control at all.+ expect(normalizeReviewerEfforts({ copilot: 'high', '@bot': 'high' })).toEqual({});+ // Non-strings and blanks are absent, never an empty pin.+ expect(normalizeReviewerEfforts({ codex: '', claude: null, ollama: 3 })).toEqual({});+ // Non-object input is undefined so an omitted field isn't persisted as `{}`.+ expect(normalizeReviewerEfforts(undefined)).toBeUndefined();+ expect(normalizeReviewerEfforts(['codex'])).toBeUndefined();+ });++ it('resolves task-over-default, with an explicitly empty task map overriding', () => {+ expect(resolveReviewerEfforts({ codex: 'high' }, { codex: 'low' })).toEqual({ codex: 'high' });+ expect(resolveReviewerEfforts({}, { codex: 'low' })).toEqual({});+ expect(resolveReviewerEfforts(undefined, { codex: 'low' })).toEqual({ codex: 'low' });+ });++ it('folds the settings scalars into the map, re-checking each against its ladder', () => {+ expect(reviewerEffortsFromDefaults({+ codexEffort: 'high',+ claudeEffort: 'xhigh',+ antigravityEffort: 'max', // not in agy's ladder — dropped, not clamped+ ollamaEffort: 'medium',+ lmstudioEffort: 'ultra', // OpenAI-shaped backends don't take this tier+ grokEffort: 'high', // in grok's ladder — kept+ })).toEqual({ codex: 'high', claude: 'xhigh', ollama: 'medium', grok: 'high' });+ expect(reviewerEffortsFromDefaults(null)).toEqual({});+ });++ it('renders the argv fragment each CLI actually takes', () => {+ expect(reviewerEffortArgs('claude', 'high')).toEqual(['--effort', 'high']);+ expect(reviewerEffortArgs('codex', 'high')).toEqual(['-c', 'model_reasoning_effort=high']);+ // The `antigravity` slug names no executable — `agy` does, and it takes --effort.+ expect(reviewerEffortArgs('antigravity', 'low')).toEqual(['--effort', 'low']);+ // grok's CLI takes `--reasoning-effort`, aliased `--effort` — the alias is+ // what buildEffortArgs emits, and `max` is outside its ladder so it drops.+ expect(reviewerEffortArgs('grok', 'xhigh')).toEqual(['--effort', 'xhigh']);+ expect(reviewerEffortArgs('grok', 'max')).toEqual([]);+ expect(reviewerEffortArgs('copilot', 'high')).toEqual([]);+ expect(reviewerEffortArgs('claude', null)).toEqual([]);+ });++ it('NEVER emits --effort for cursor, at any level — the CLI has no such flag', () => {+ // `cursor-agent --effort high` exits non-zero. Cursor's ladder exists so the+ // level can be PICKED; `reviewerModelArg` is what carries it. A regression+ // here reaches an agent as a literal command line it runs verbatim.+ for (const level of CURSOR_EFFORT_LEVELS) {+ expect(reviewerEffortArgs('cursor', level), level).toEqual([]);+ expect(reviewerEffortArgs('cursor-agent', level), level).toEqual([]);+ }+ expect(reviewerEffortArgs('cursor', 'minimal')).toEqual([]);+ });++ it('folds a cursor effort into --model, leaving every other reviewer id verbatim', () => {+ // Cursor's native model-variant syntax, matching slashdo's own fold so the+ // same pin means the same invocation on either side.+ expect(reviewerModelArg('cursor', 'gpt-5', 'max')).toBe('gpt-5[effort=max]');+ // An existing bracket gains an `,effort=` parameter, not a second bracket.+ expect(reviewerModelArg('cursor', 'claude-opus-4-7[thinking=true]', 'high'))+ .toBe('claude-opus-4-7[thinking=true,effort=high]');+ // A model that already names its own effort wins over the ladder pin.+ expect(reviewerModelArg('cursor', 'gpt-5[effort=low]', 'max')).toBe('gpt-5[effort=low]');+ // No effort pinned, or one cursor's ladder rejects → the bare id.+ expect(reviewerModelArg('cursor', 'gpt-5')).toBe('gpt-5');+ expect(reviewerModelArg('cursor', 'gpt-5', 'minimal')).toBe('gpt-5');+ // No model to attach the variant to → nothing at all.+ expect(reviewerModelArg('cursor', '', 'max')).toBeNull();+ expect(reviewerModelArg('cursor', null, 'max')).toBeNull();+ // The alias resolves like every other lookup here.+ expect(reviewerModelArg('cursor-agent', 'gpt-5', 'max')).toBe('gpt-5[effort=max]');+ // Every other reviewer keeps its id verbatim — its effort rides its own flag.+ expect(reviewerModelArg('codex', 'gpt-5.6-sol', 'high')).toBe('gpt-5.6-sol');+ expect(reviewerModelArg('antigravity', 'Gemini 3.5 Flash (High)', 'high')).toBe('Gemini 3.5 Flash (High)');+ });++ it('DROPS an out-of-ladder effort instead of clamping it, even from unnormalized input', () => {+ // The underlying `buildEffortArgs` clamps (agy `max` → `--effort high`), which+ // is right for a provider pin carried across providers but wrong for a reviewer+ // effort picked from that reviewer's own list: emitting a clamped flag would run+ // the review at a tier the picker labels `unsupported`. This function is reached+ // with RAW task metadata (`reviewLoopReviewerEfforts`), so it must normalize+ // itself rather than trust the caller.+ expect(reviewerEffortArgs('antigravity', 'max')).toEqual([]);+ expect(reviewerEffortArgs('antigravity', 'ultra')).toEqual([]);+ // Case/whitespace still normalize through rather than being rejected.+ expect(reviewerEffortArgs('codex', ' HIGH ')).toEqual(['-c', 'model_reasoning_effort=high']);+ });++ it('builds the hand-invocation note only for CLI reviewers carrying an effort', () => {+ const note = buildReviewerEffortNote(['codex', 'claude', 'copilot'], { codex: 'high', claude: 'low', copilot: 'high' });+ expect(note).toContain('`codex -c model_reasoning_effort=high`');+ expect(note).toContain('`claude --effort low`');+ expect(note).not.toContain('copilot');+ // A reviewer not in the list contributes nothing, and no pins at all = no note.+ expect(buildReviewerEffortNote(['copilot'], { codex: 'high' })).toBe('');+ expect(buildReviewerEffortNote(['codex'], {})).toBe('');+ expect(buildReviewerEffortNote(undefined, { codex: 'high' })).toBe('');+ // slashdo's local-model loop calls the backend itself, so there's no flag to+ // name for lmstudio/ollama in this path.+ expect(buildReviewerEffortNote(['ollama'], { ollama: 'high' })).toBe('');+ // …including when it carries a MODEL pin too: a local reviewer names no+ // binary, so there is no command line to print (a `null --model …` would be+ // handed to an agent as something to run).+ expect(buildReviewerEffortNote(['ollama'], { ollama: 'high' }, { reviewerModels: { ollama: 'qwen2.5:7b' } })).toBe('');+ expect(buildReviewerEffortNote(['copilot'], { copilot: 'high' }, { reviewerModels: { copilot: 'x' } })).toBe('');+ });++ it('names cursor with its folded --model instead of an --effort it would reject', () => {+ const note = buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewerModels: { cursor: 'gpt-5' } });+ expect(note).toContain('`cursor-agent --model gpt-5[effort=max]`');+ expect(note).not.toContain('--effort');+ // No model to fold into: nothing is emitted rather than a bogus flag.+ expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' })).toBe('');+ expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewerModels: {} })).toBe('');+ // A model with NO effort pin is not this sentence's business.+ expect(buildReviewerEffortNote(['cursor'], {}, { reviewerModels: { cursor: 'gpt-5' } })).toBe('');+ // The pin still round-trips through the emitted --review-with token, which+ // suppresses the note exactly as it does for every other reviewer.+ const reviewWith = buildReviewWithArgs(['cursor'], { reviewerModels: { cursor: 'gpt-5' }, reviewerEfforts: { cursor: 'max' } });+ expect(reviewWith).toContain('cursor[gpt-5]~effort=max');+ expect(buildReviewerEffortNote(['cursor'], { cursor: 'max' }, { reviewWith, reviewerModels: { cursor: 'gpt-5' } })).toBe('');+ });++ it('goes SILENT once the emitted --review-with carries the effort itself', () => {+ // slashdo has parsed `~effort=<level>` since v3.31, and markSuffixes emits it —+ // so on a pinned invocation the loop already runs the reviewer at that effort.+ // Repeating it as prose tells the agent to pass the flag a second time, or to+ // hand-run a reviewer `/do:pr` was about to run.+ const reviewWith = buildReviewWithArgs(['codex', 'claude'], { reviewerEfforts: { codex: 'high', claude: 'low' } });+ expect(reviewWith).toContain('codex~effort=high');+ expect(buildReviewerEffortNote(['codex', 'claude'], { codex: 'high', claude: 'low' }, { reviewWith })).toBe('');+ // An invocation that pins reviewers but NO effort leaves the note as the only+ // carrier, and an absent/blank pin is the unpinned case.+ const noEffort = buildReviewWithArgs(['codex', 'claude'], {});+ expect(noEffort).not.toContain('~effort=');+ expect(buildReviewerEffortNote(['codex'], { codex: 'high' }, { reviewWith: noEffort })).toContain('`codex -c model_reasoning_effort=high`');+ expect(buildReviewerEffortNote(['codex'], { codex: 'high' }, { reviewWith: '' })).toContain('`codex -c model_reasoning_effort=high`');+ // And a lone copilot can't carry an effort at all (no ladder — see the DROPS+ // test above), which is why the lone-default suppression stays correct without+ // an effort clause of its own in applySlashdoInvocation.+ expect(buildReviewWithArgs(['copilot'], { reviewerEfforts: { copilot: 'high' } })).toBe('');+ });++ it('never claims --review-with lacks an effort suffix', () => {+ // The note predates slashdo's `~effort=` support and used to justify itself+ // with "`--review-with` has no effort suffix". It does have one — an agent+ // reading that next to its own `codex~effort=high` token is being misled.+ const note = buildReviewerEffortNote(['codex'], { codex: 'high' });+ expect(note).not.toContain('has no effort suffix');+ expect(note).toContain('Pass the flag yourself when you spawn the reviewer');+ });++ it('carries reviewerEfforts through the task schema and the metadata sanitizer', () => {+ const parsed = createCosTaskSchema.parse({+ description: 'x',+ reviewerEfforts: { codex: 'high', antigravity: 'max', copilot: 'low' },+ });+ expect(parsed.reviewerEfforts).toEqual({ codex: 'high' });+ expect(createCosTaskSchema.parse({ description: 'x' }).reviewerEfforts).toBeUndefined();+ // An explicitly empty MAP is KEPT: it's a real "use each reviewer's own+ // default for this task" choice that must override the Code Review Defaults.+ expect(sanitizeTaskMetadata({ reviewerEfforts: {} })).toEqual({ reviewerEfforts: {} });+ expect(sanitizeTaskMetadata({ reviewerEfforts: { claude: 'high', grok: 'max' } }))+ .toEqual({ reviewerEfforts: { claude: 'high' } });+ });++ it('accepts each per-reviewer effort scalar on the code-review settings slice', () => {+ const parsed = codeReviewSettingsSchema.parse({+ claudeEffort: 'max', codexEffort: 'minimal', antigravityEffort: 'high',+ ollamaEffort: 'low', lmstudioEffort: 'high',+ });+ expect(parsed).toEqual({+ claudeEffort: 'max', codexEffort: 'minimal', antigravityEffort: 'high',+ ollamaEffort: 'low', lmstudioEffort: 'high',+ });+ // An unusable stored value clears the field rather than persisting a pin no+ // invocation would carry.+ expect(codeReviewSettingsSchema.parse({ antigravityEffort: 'max' }).antigravityEffort).toBeUndefined();+ expect(codeReviewSettingsSchema.parse({ codexEffort: 'bogus' }).codexEffort).toBeUndefined();+ });+});++// The picker's Effort cell is driven by a CLIENT mirror of these ladders. A level+// offered there but rejected here would show the user a pin that silently never+// persists (and the reverse would hide a tier their CLI accepts), so the mirror is+// pinned rather than trusted to a "keep in sync" comment.+describe('client mirror of the reviewer effort ladders', () => {+ it('matches server reviewerEffortLevels for every reviewer', async () => {+ // The dependency-free leaf, NOT `components/cos/constants.js` (which re-exports+ // these but also imports `lucide-react` — absent from the server workspace, so+ // importing it here fails CI with ERR_MODULE_NOT_FOUND).+ const client = await import('../../client/src/lib/reviewerPins.js');+ expect([...client.EFFORT_SELECTABLE_REVIEWERS].sort()).toEqual([...EFFORT_SELECTABLE_REVIEWERS].sort());+ expect(client.LOCAL_LLM_EFFORT_LEVELS).toEqual(LOCAL_LLM_EFFORT_LEVELS);+ for (const reviewer of REVIEWER_VALUES) {+ expect(client.reviewerEffortLevels(reviewer) ?? null).toEqual(reviewerEffortLevels(reviewer) ?? null);+ }+ // Alias parity too — the picker keys rows off stored slugs.+ expect(client.reviewerEffortLevels('gemini')).toEqual(reviewerEffortLevels('gemini'));+ });++ // Same failure mode one column over: a reviewer the picker offers a Model cell+ // for but the server drops the pin from (or vice versa — a CLI whose `--model`+ // the UI hides). The two rosters drove `antigravity` out of sync until #3728.+ it('matches the server model-pin rosters', async () => {+ const client = await import('../../client/src/lib/reviewerPins.js');+ expect([...client.MODEL_CAPABLE_CLI_REVIEWERS].sort()).toEqual([...MODEL_CAPABLE_CLI_REVIEWERS].sort());+ expect([...client.MODEL_SELECTABLE_REVIEWERS].sort()).toEqual([...MODEL_SELECTABLE_REVIEWERS].sort());+ });+});++describe('per-reviewer model pins', () => {+ it('accepts Cursor Agent in the reviewer config and persists its model pin', () => {+ const parsed = codeReviewSettingsSchema.parse({ reviewers: ['cursor-agent'], cursorModel: 'gpt-5' });+ expect(parsed.reviewers).toEqual(['cursor']);+ expect(parsed.cursorModel).toBe('gpt-5');+ expect(reviewerModelsFromDefaults(parsed)).toEqual({ cursor: 'gpt-5' });+ });++ it('keeps an antigravity model pin on the code-review settings slice', () => {+ // `agy --model <id>` is real (unlike the effort-only support PortOS assumed+ // before #3728), so the scalar has to survive the `.strict()` schema.+ expect(codeReviewSettingsSchema.parse({ antigravityModel: 'gemini-3.6-flash' }).antigravityModel)+ .toBe('gemini-3.6-flash');+ // Structural characters would corrupt the emitted `antigravity[<model>]` token.+ expect(codeReviewSettingsSchema.parse({ antigravityModel: 'a,b' }).antigravityModel).toBeUndefined();+ expect(codeReviewSettingsSchema.parse({ antigravityModel: ' ' }).antigravityModel).toBeUndefined();+ });++ it('carries an antigravity model through the task schema and the sanitizer', () => {+ expect(createCosTaskSchema.parse({ description: 'x', reviewerModels: { antigravity: 'gemini-3.6-pro' } }).reviewerModels)+ .toEqual({ antigravity: 'gemini-3.6-pro' });+ expect(sanitizeTaskMetadata({ reviewerModels: { antigravity: 'gemini-3.6-pro', copilot: 'x' } }))+ .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-pro' } });+ });++ it('splits an effort-suffixed antigravity id into a model/effort pair agy accepts', () => {+ expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-high' }, {}))+ .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'high' } });+ // An explicitly pinned effort wins over the one baked into the id.+ expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-high' }, { antigravity: 'low' }))+ .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'low' } });+ // …but an UNUSABLE stored effort doesn't get to suppress the baked one.+ expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash-low' }, { antigravity: 'max' }))+ .toEqual({ reviewerModels: { antigravity: 'gemini-3.6-flash' }, reviewerEfforts: { antigravity: 'low' } });+ });++ it('leaves unsuffixed ids and every other reviewer untouched', () => {+ expect(pairReviewerModelsAndEfforts({ antigravity: 'gemini-3.6-flash', codex: 'gpt-5.6-sol' }, { codex: 'high' }))+ .toEqual({+ reviewerModels: { antigravity: 'gemini-3.6-flash', codex: 'gpt-5.6-sol' },+ reviewerEfforts: { codex: 'high' }+ });+ // A `-high` suffix on a NON-agy reviewer is part of the id, not an effort.+ expect(pairReviewerModelsAndEfforts({ claude: 'qwen2.5:7b-high' }, {}))+ .toEqual({ reviewerModels: { claude: 'qwen2.5:7b-high' }, reviewerEfforts: {} });+ expect(pairReviewerModelsAndEfforts(undefined, undefined))+ .toEqual({ reviewerModels: {}, reviewerEfforts: {} });+ });++ it('does not mutate the maps it was handed', () => {+ const models = { antigravity: 'gemini-3.6-flash-high' };+ const efforts = {};+ pairReviewerModelsAndEfforts(models, efforts);+ expect(models).toEqual({ antigravity: 'gemini-3.6-flash-high' });+ expect(efforts).toEqual({});+ });++ // #3729: `grok --model <id>` is real and slashdo accepts a `grok[<model>]`+ // bracket, but `grok` was absent from the roster, so every grok review ran on+ // the CLI's own default and the picker rendered "Grok takes no model".+ it('keeps a grok model pin on the code-review settings slice', () => {+ expect(codeReviewSettingsSchema.parse({ grokModel: 'grok-code-fast-1' }).grokModel)+ .toBe('grok-code-fast-1');+ // Structural characters would corrupt the emitted `grok[<model>]` token.+ expect(codeReviewSettingsSchema.parse({ grokModel: 'a]b' }).grokModel).toBeUndefined();+ expect(codeReviewSettingsSchema.parse({ grokModel: ' ' }).grokModel).toBeUndefined();+ });++ it('carries a grok model through the task schema, sanitizer and defaults adapter', () => {+ expect(createCosTaskSchema.parse({ description: 'x', reviewerModels: { grok: 'grok-code-fast-1' } }).reviewerModels)+ .toEqual({ grok: 'grok-code-fast-1' });+ expect(sanitizeTaskMetadata({ reviewerModels: { grok: 'grok-code-fast-1', copilot: 'x' } }))+ .toEqual({ reviewerModels: { grok: 'grok-code-fast-1' } });+ expect(reviewerModelsFromDefaults({ grokModel: 'grok-code-fast-1' })).toEqual({ grok: 'grok-code-fast-1' });+ });++ it('emits the grok pin as a slashdo bracket, and never splits an effort off it', () => {+ expect(buildReviewWithArgs(['grok'], { reviewerModels: { grok: 'grok-code-fast-1' } }))+ .toBe('--review-with grok[grok-code-fast-1]');+ // Only agy bakes an effort into the model id. A grok id passes through whole,+ // and a bare model pin adds no effort pin — grok carries its level on its own+ // flag, not inside the model id.+ expect(pairReviewerModelsAndEfforts({ grok: 'grok-code-fast-1' }, {}))+ .toEqual({ reviewerModels: { grok: 'grok-code-fast-1' }, reviewerEfforts: {} });+ expect(reviewerEffortLevels('grok')).toEqual(GROK_EFFORT_LEVELS);+ });+});++describe('reviewer pin note (saved slashdo defaults must not win)', () => {+ it('names the resolved list AND the exact --review-with text to pass', () => {+ const note = buildReviewerPinNote('codex,claude');+ // Both halves matter: the list the phases run by hand, and the flag text for+ // the moment the agent reaches for a slashdo command instead.+ expect(note).toContain('`codex,claude`');+ expect(note).toContain('--review-with codex,claude');+ expect(note).toContain('/do:pr');+ // The failure mode this block exists to prevent, named so the agent can+ // recognize it: a bare invocation silently adopting the host's saved config.+ expect(note).toMatch(/\.slashdo-config\.json/);+ });++ it('carries the per-entry suffixes verbatim so the pinned model/effort survive the paste', () => {+ // A reviewer pin is only honored if the agent pastes the whole token — the+ // bracket and the ~suffixes ARE the model/optional/cap/effort pins.+ const csv = 'antigravity[gemini-3.7-flash]~opt~max=1~effort=medium';+ expect(buildReviewerPinNote(csv)).toContain(`--review-with ${csv}`);+ });++ it('keeps a PortOS-served reviewer OUT of the pinned flag — slashdo aborts on a slug it does not know', () => {+ const note = buildReviewerPinNote('lmstudio~effort=high,ollama,@alice');+ // The flag text carries only tokens slashdo can parse...+ expect(note).toContain('--review-with ollama,@alice');+ expect(note).not.toContain('--review-with lmstudio');+ // ...and the dropped reviewer is named by bare slug, pointed at the+ // procedure that actually runs it, so dropping it from a slashdo call can't+ // read as permission to skip the review.+ expect(note).toContain('PortOS runs `lmstudio` itself');+ expect(note).toContain('Local Reviewer Procedure');+ });++ it('states the pin with no flag text at all when every reviewer is PortOS-only', () => {+ const note = buildReviewerPinNote('lmstudio');+ expect(note).toContain('authoritative');+ // No flag to hand out — the only `--review-with` mention left is the+ // prohibition, never an instruction to pass one.+ expect(note).not.toMatch(/pass `--review-with/);+ });++ it('reads back every slug an emitted token can carry (inverse of markSuffixes)', () => {+ // reviewerTokenSlug is the only place the emitted grammar is parsed rather+ // than built. Round-trip a fully decorated token through the real emitter so+ // a new bracket or ~suffix in markSuffixes fails HERE instead of silently+ // mis-slugging a reviewer out of (or into) the pinned flag.+ const csv = buildReviewersCsv(+ ['antigravity', 'lmstudio'],+ ['alice'],+ ['antigravity'],+ { antigravity: 1 },+ { antigravity: 'gemini-3.7-flash', lmstudio: 'qwen' },+ { antigravity: 'medium', lmstudio: 'high' }+ );+ expect(csv.split(',').map(reviewerTokenSlug)).toEqual(['antigravity', 'lmstudio', '@alice']);+ });++ it('emits nothing when there is no list to pin', () => {+ expect(buildReviewerPinNote('')).toBe('');+ expect(buildReviewerPinNote(' ')).toBe('');+ expect(buildReviewerPinNote(null)).toBe('');+ expect(buildReviewerPinNote(undefined)).toBe('');+ });+});++// The claim generators resolve reviewers BEFORE a task record exists and render+// the CSV into `{reviewers}`; the prompt builder re-resolves them from the+// persisted task at spawn time to emit the reviewer pin. Those two resolutions+// have to land on the same list, or the pin names reviewers the prompt does not+// (#4770). `reviewerConfigMetadata` is the round-trip that makes them agree.+describe('claim reviewer round-trip (prompt CSV ↔ persisted metadata)', () => {+ const defaults = {+ reviewers: ['copilot'],+ usernames: ['alice'],+ optionalReviewers: ['ollama'],+ reviewerMaxRounds: { codex: 2 },+ antigravityModel: 'gemini-3.7-flash-high',+ codexEffort: 'high'+ };++ it('claimSafeReviewers drops copilot and never falls back to it', () => {+ expect(claimSafeReviewers(['codex', 'copilot'])).toEqual(['codex']);+ expect(claimSafeReviewers(['copilot'])).toEqual(['codex']);+ expect(claimSafeReviewers([])).toEqual(['codex']);+ expect(claimSafeReviewers(undefined)).toEqual(['codex']);+ });++ it('stably prioritizes tool-free local reviewers ahead of tool-enabled reviewers', () => {+ expect(prioritizeToolFreeReviewers(['codex', 'ollama', 'copilot', 'lmstudio', 'claude']))+ .toEqual(['ollama', 'lmstudio', 'codex', 'copilot', 'claude']);+ expect(resolveReviewerConfig({ reviewers: ['codex', 'ollama'] }, null, null).reviewers)+ .toEqual(['ollama', 'codex']);+ });++ it('resolves through the claim guard from every input shape a claim task can carry', () => {+ // The install default is the fallback, the claim guard is applied after it,+ // and legacy single-`reviewer` metadata still resolves.+ expect(resolveClaimReviewerConfig({}, null, undefined).reviewers).toEqual(['codex']);+ expect(resolveClaimReviewerConfig({ reviewers: ['copilot'] }, null, ['copilot']).reviewers).toEqual(['codex']);+ expect(resolveClaimReviewerConfig({}, null, ['claude', 'copilot']).reviewers).toEqual(['claude']);+ expect(resolveClaimReviewerConfig({ reviewer: 'grok' }, null, ['claude']).reviewers).toEqual(['grok']);+ });++ it('resolveClaimReviewerConfig emits a CSV matching its own resolved bundle', () => {+ const config = resolveClaimReviewerConfig({ reviewers: ['codex', 'antigravity'] }, defaults, defaults.reviewers);+ expect(config.reviewers).toEqual(['codex', 'antigravity']);+ expect(config.csv).toBe(buildReviewersCsv(+ config.reviewers, config.usernames, config.optionalReviewers,+ config.reviewerMaxRounds, config.reviewerModels, config.reviewerEfforts+ ));+ // The agy model id's baked tier is split off exactly once — resolving the+ // persisted config a second time must not re-split or double-apply it.+ expect(config.reviewerModels.antigravity).toBe('gemini-3.7-flash');+ expect(config.reviewerEfforts.antigravity).toBe('high');+ });++ it('persisting reviewerConfigMetadata makes the SECOND resolution reproduce the first CSV', () => {+ // Round 1: the generator, with no task record yet.+ const generated = resolveClaimReviewerConfig({ reviewers: ['codex', 'antigravity'] }, defaults, defaults.reviewers);+ const metadata = { claimFlow: true, ...reviewerConfigMetadata(generated) };+ // Round 2: the prompt builder, reading the task back — and deliberately+ // WITHOUT the defaults it would otherwise fall through to, to prove the+ // persisted values are what carry the list.+ const rebuilt = resolveClaimReviewerConfig(metadata, null, null);+ expect(rebuilt.csv).toBe(generated.csv);+ expect(rebuilt).toMatchObject({+ reviewers: generated.reviewers,+ usernames: generated.usernames,+ optionalReviewers: generated.optionalReviewers,+ reviewerMaxRounds: generated.reviewerMaxRounds,+ reviewerModels: generated.reviewerModels,+ reviewerEfforts: generated.reviewerEfforts+ });+ // And the plain (non-claim) resolver the prompt builder shares with the+ // review loop agrees too — that is the resolution #4770 was silently+ // answering from the install-wide defaults.+ expect(resolveReviewerConfig(metadata, null, null).reviewers).toEqual(generated.reviewers);+ });++ it('a DIFFERENT install default cannot override what the task persisted', () => {+ const generated = resolveClaimReviewerConfig({ reviewers: ['grok'] }, defaults, defaults.reviewers);+ const metadata = reviewerConfigMetadata(generated);+ const otherInstall = { reviewers: ['claude'], usernames: ['bob'], optionalReviewers: ['grok'], reviewerMaxRounds: { grok: 9 } };+ expect(resolveClaimReviewerConfig(metadata, otherInstall, otherInstall.reviewers).csv).toBe(generated.csv);+ });++ it('sanitizes rather than trusts: unknown keys and junk values never reach the task record', () => {+ const meta = reviewerConfigMetadata({+ reviewers: ['codex', 'bogus'],+ usernames: ['@Alice', 'bad token'],+ optionalReviewers: ['nope'],+ reviewerMaxRounds: { codex: 'three' },+ reviewerModels: {},+ reviewerEfforts: {},+ swarmCount: 6,+ issueAuthorFilter: 'any'+ });+ expect(meta).toEqual({+ reviewers: ['codex'],+ usernames: ['Alice'],+ optionalReviewers: [],+ reviewerMaxRounds: {},+ reviewerModels: {},+ reviewerEfforts: {}+ });+ });++ it('returns an empty patch rather than null when nothing survives sanitizing', () => {+ // Callers spread this into a task's metadata, so a null would throw at the+ // three claim generators rather than degrade.+ expect(reviewerConfigMetadata(null)).toEqual({});+ expect(reviewerConfigMetadata({ reviewers: ['bogus'] })).toEqual({});+ });+});diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex f4e5db1655..a860140f1c 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -58,7 +58,7 @@ export const SLASHDO_INLINE_BUDGET_CHARS = 24000;* prompt saving is — pruning to a single CLI reviewer measured -23% on `review`,* -27% on `pr`, -28% on `depfree`; the file pointer is the backstop for the rest.*- * Keyed by the PortOS reviewer slug (`REVIEWER_VALUES` in `cosValidation.js`) so+ * Keyed by the PortOS reviewer slug (`REVIEWER_VALUES` in `reviewerConfig.js`) so* the keep-set derives from already-resolved run settings. `copilot` and the* arbitrary-`@login` loop are GitHub-side; `claude`/`codex`/`antigravity`/`grok`/`cursor`* all share slashdo's one local-agent loop; `ollama`/`lmstudio` are the@@ -85,10 +85,11 @@ export const SLASHDO_REVIEWER_INCLUDE_NAMES = Object.freeze(Object.values(SLASHD/*** Reviewer slugs that drive slashdo's shared local-agent (spawnable CLI) loop.*- * Kept here rather than imported from cosValidation.js, which imports THIS- * module — an import back would be a cycle. Exported so cosValidation.test.js- * can pin it against `REVIEWER_CLI_BINARIES` (whose keys are the same roster);- * a reviewer added to one and not the other is a drift the test catches.+ * Kept here rather than imported from reviewerConfig.js, whose importer+ * cosValidation.js imports THIS module — an import back would be a cycle.+ * Exported so reviewerConfig.test.js can pin it against `REVIEWER_CLI_BINARIES`+ * (whose keys are the same roster); a reviewer added to one and not the other+ * is a drift the test catches.*/export const LOCAL_AGENT_REVIEWERS = new Set(['claude', 'codex', 'antigravity', 'grok', 'cursor']);/** Reviewer slugs that drive slashdo's local-model (Ollama-style) loop. */diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex f179efc6bc..a94932187b 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -27,7 +27,7 @@ import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/tasimport { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { detectForgeCli } from '../lib/gitForge.js';import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, prioritizeToolFreeReviewers } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, prioritizeToolFreeReviewers } from '../lib/reviewerConfig.js';// In-flight cleanup per agentId, so two completion paths racing to clean the// SAME agent coalesce onto one run instead of tripping over each other.diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex bc27179ba2..62e3dea4b2 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -3045,7 +3045,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, streturn task;}-// `normalizeClaimReviewers` moved to server/lib/cosValidation.js (#4770): the+// `normalizeClaimReviewers` moved to server/lib/reviewerConfig.js (#4770, #5702): the// prompt builder needs the same copilot guard when it re-resolves reviewers off// a persisted claim task, and a service-level definition would have meant a// second copy there.diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex cef391ac16..ce10bd0fbf 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -502,7 +502,7 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// gets — it runs each reviewer by hand, so a configured cap only reaches the// run if the CSV carries it. Both the scheduled path and buildClaimWorkTask// feed the cap into the shared claim resolver, which applies task-over-default- // precedence (unit-tested in cosValidation.test.js).+ // precedence (unit-tested in reviewerConfig.test.js).expect(GEN_SRC).toContain('reviewerMaxRounds: reviewerMaxRounds ?? metadata.reviewerMaxRounds');expect(GEN_SRC).toContain('resolveClaimReviewerConfig(metadata, codeReviewDefaults, codeReviewDefaults?.reviewers)');expect(GEN_SRC).not.toContain('resolveReviewerMaxRounds(');diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex e00dd42ff2..629f1fc17d 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -2,7 +2,7 @@* Completion workflow, worktree, and sentinel prompt sections.*/-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../../lib/slashdoInvocation.js';import { shellQuote } from '../../lib/shellQuote.js';diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex 3141a019f9..800198edfc 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, resolveKeyedReviewers, buildReviewWithArgs, prioritizeToolFreeReviewers } from '../../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, 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';