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
feat(cos): gate merges on arbitrary GitHub reviewer usernames in Code Review Defaults
Adam Eivyd1b7dd5b9db0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 80c5218d08..18277a5504 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,8 @@## Features+- **Code Review Defaults can now gate merges on arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`).** The Review Loop was limited to a fixed set of reviewer kinds (Copilot, the Claude/Antigravity/Codex CLIs, and the local LM Studio/Ollama backends); there was no way to require a specific GitHub bot or teammate as a PR reviewer. The reviewer picker (AI Providers → Code Review Defaults, plus per-task in the task form and per-task-type in the Schedule config) grows a **"GitHub reviewers (gate merge)"** row where you type any GitHub username or `org/team` slug. Those usernames are appended to slashdo's `--review-with` as `@user` tokens after the keyed reviewers, and the review-loop follow-up agent is instructed to request each as a PR reviewer (`gh pr edit … --add-reviewer`), wait for their review, and treat their approval as a merge gate — end to end through the original-agent completion prompt, the follow-up loop, and the `/do:next` claim flow. Usernames are stored without the `@`, validated against a shell-safe GitHub-username charset (1–39 chars, alphanumeric/hyphen, optional `/team`), case-insensitively deduped, and capped at 20, so a hand-edited `settings.json` can't smuggle in an unsafe or oversized token. They're a distinct class from the behavior reviewers — external PR reviewers that gate the merge, not CLIs that apply fixes — so `--reviewer-applies` never turns on for a username-only addition, and a username reviewer is forge-agnostic (kept even when Copilot is stripped on a non-GitHub forge, and able to drive the loop on its own). New config key: `settings.codeReview.usernames` (+ per-task `metadata.usernames`); no migration needed (absent = none).+- **Layered Intelligence now learns from its own results — the feedback loop is closed (#2428).** The LI reasoner used to file improvement proposals as tracker issues and then never read back whether they were merged, rejected, or abandoned, so it proposed in a vacuum (re-suggesting scopes with a 0% adoption rate). LI now records every filed proposal in a lightweight per-app outcome store (`data/cos/li-outcomes/`, a `createCollectionStore` collection with per-slug records and 30-day auto-GC), reconciles each proposal's outcome from the live tracker state on the next run (GitHub `stateReason` maps *not-planned* → rejected, any other close → merged; still-open stays unresolved), and folds a merge-rate report — totals, per-scope adoption, common rejection reasons — back into the reasoning prompt with guidance to prefer higher-merge scopes and justify low-merge ones. Gated behind a new `Proposal outcomes` telemetry source toggle in the per-app LI config (default **on** for the PortOS install, **off** for managed apps). No migration needed — the store is created on first use and existing LI behavior is unchanged when the toggle is off.- **Audio → MIDI transcription now installs its runtime automatically on first use.** Clicking *Transcribe MIDI* (Rounds reference audio) or *MIDI* (Music Video source track) used to dead-end on a toast telling you to run `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` in a terminal. Now, when the MuScriptor venv isn't provisioned yet, PortOS opens an in-app installer that streams the setup line-by-line — the same experience as the image and video model runtimes — and, on completion, automatically runs the transcription you originally asked for. A new `GET /api/midi-runtime/install` endpoint reuses the shared `RuntimeInstallModal`/SSE-install path (in-flight singleton, detached process group so a cancel kills pip/git children, post-install venv re-probe); `useMidiTranscription` catches the `503 MIDI_RUNTIME_MISSING` kickoff, gates the modal, and retries once installed (with a loop guard so a genuinely-failed install surfaces its error instead of relooping).diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsxindex f024eecced..c3f8549907 100644--- a/client/src/components/cos/ReviewerPicker.jsx+++ b/client/src/components/cos/ReviewerPicker.jsx@@ -1,9 +1,12 @@-import { useId } from 'react';+import { useId, useState } from 'react';import { Plus, X, ChevronUp, ChevronDown } from 'lucide-react';import {REVIEWER_OPTIONS,REVIEW_STOP_MODES,- DEFAULT_REVIEW_STOP_MODE+ DEFAULT_REVIEW_STOP_MODE,+ MAX_REVIEW_USERNAMES,+ cleanReviewUsername,+ normalizeReviewUsernames} from './constants';const labelFor = (value) => REVIEWER_OPTIONS.find(o => o.value === value)?.label || value;@@ -14,17 +17,25 @@ const normalizeReviewerValue = (value) => value === 'gemini' ? 'antigravity' : v* click order), reorder with the arrows, remove with ✕. Maps to slashdo's* `--review-with a,b,c` plus the stop-mode / `--reviewer-applies` flags.*+ * A second "GitHub reviewers" row collects arbitrary usernames (e.g.+ * `@CodeReviewbot`) requested as PR reviewers to gate the merge — appended to+ * `--review-with` as `@user` tokens after the keyed reviewers.+ ** Controlled: emits the full next shape via onChange so the parent can store- * `reviewers` / `reviewStopMode` / `reviewerApplies` however it persists them.+ * `reviewers` / `usernames` / `reviewStopMode` / `reviewerApplies` however it+ * persists them.*/export default function ReviewerPicker({reviewers = [],+ usernames = [],stopMode = DEFAULT_REVIEW_STOP_MODE,reviewerApplies = false,onChange,disabled = false}) {const id = useId();+ const [usernameInput, setUsernameInput] = useState('');+ const [usernameError, setUsernameError] = useState('');// Render the parent's list (de-duped, order-preserving) so display === stored// state for valid input while staying robust to malformed/legacy duplicates —// dupes would otherwise collide on the `key={value}` below and corrupt@@ -33,14 +44,38 @@ export default function ReviewerPicker({const selected = Array.isArray(reviewers) ? [...new Set(reviewers.map(normalizeReviewerValue))] : [];const available = REVIEWER_OPTIONS.filter(o => !selected.includes(o.value));const hasNonCopilot = selected.some(r => r !== 'copilot');+ const selectedUsernames = normalizeReviewUsernames(usernames);+ const atMaxUsernames = selectedUsernames.length >= MAX_REVIEW_USERNAMES;const emit = (next) => onChange?.({reviewers: selected,+ usernames: selectedUsernames,stopMode,reviewerApplies,...next});+ const addUsername = () => {+ const clean = cleanReviewUsername(usernameInput);+ if (!clean) {+ setUsernameError('Enter a valid GitHub username (letters, numbers, hyphens; optional org/team).');+ return;+ }+ if (selectedUsernames.some(u => u.toLowerCase() === clean.toLowerCase())) {+ setUsernameInput('');+ setUsernameError('Already added.');+ return;+ }+ if (atMaxUsernames) {+ setUsernameError(`At most ${MAX_REVIEW_USERNAMES} reviewer usernames.`);+ return;+ }+ emit({ usernames: [...selectedUsernames, clean] });+ setUsernameInput('');+ setUsernameError('');+ };+ const removeUsername = (value) => emit({ usernames: selectedUsernames.filter(u => u !== value) });+const add = (value) => emit({ reviewers: [...selected, value] });const remove = (value) => emit({ reviewers: selected.filter(r => r !== value) });const move = (index, delta) => {@@ -116,6 +151,60 @@ export default function ReviewerPicker({</div>)}+ {/* GitHub reviewer usernames — arbitrary PR reviewers (bots/humans) that+ gate the merge. Appended to `--review-with` as `@user` tokens. */}+ <div className="flex flex-col gap-1.5 pt-1 border-t border-port-border/50">+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="text-xs text-gray-500 mr-1">GitHub reviewers (gate merge):</span>+ {selectedUsernames.map((value) => (+ <span+ key={value}+ className="inline-flex items-center gap-1 pl-1.5 pr-1 py-0.5 bg-port-bg border border-port-accent/40 rounded text-xs text-gray-300"+ title="GitHub username requested as a PR reviewer to gate the merge"+ >+ <span className="text-port-accent font-mono">@</span>+ {value}+ <button+ type="button"+ disabled={disabled}+ onClick={() => removeUsername(value)}+ className="text-gray-500 hover:text-port-error"+ aria-label={`Remove @${value}`}+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {selectedUsernames.length === 0 && (+ <span className="text-xs text-gray-600 italic">none</span>+ )}+ </div>+ <div className="flex items-center gap-1.5">+ <span className="text-xs text-gray-600 font-mono">@</span>+ <input+ id={`${id}-username`}+ type="text"+ value={usernameInput}+ disabled={disabled || atMaxUsernames}+ placeholder="CodeReviewbot"+ aria-label="Add a GitHub reviewer username"+ onChange={(e) => { setUsernameInput(e.target.value); if (usernameError) setUsernameError(''); }}+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addUsername(); } }}+ className="flex-1 min-w-0 max-w-[200px] px-2 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px] focus:border-port-accent focus:outline-none disabled:opacity-50"+ />+ <button+ type="button"+ disabled={disabled || !usernameInput.trim() || atMaxUsernames}+ onClick={addUsername}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-transparent border border-port-border rounded text-xs text-gray-400 hover:text-white hover:border-port-accent disabled:opacity-50"+ >+ <Plus size={11} />+ Add+ </button>+ </div>+ {usernameError && <span className="text-xs text-port-error">{usernameError}</span>}+ </div>+{selected.length >= 2 && (<div className="flex items-center gap-2"><label htmlFor={`${id}-stopmode`} className="text-xs text-gray-500">Stop mode:</label>diff --git a/client/src/components/cos/ReviewerPicker.test.jsx b/client/src/components/cos/ReviewerPicker.test.jsxindex 0cec85e2aa..66072a7a32 100644--- a/client/src/components/cos/ReviewerPicker.test.jsx+++ b/client/src/components/cos/ReviewerPicker.test.jsx@@ -76,4 +76,39 @@ describe('ReviewerPicker', () => {rerender(<ReviewerPicker reviewers={['codex']} onChange={() => {}} />);expect(screen.getByText(/Reviewer applies fixes/)).toBeInTheDocument();});++ it('adds a GitHub reviewer username (strips @) via the Add button', async () => {+ const onChange = vi.fn();+ const user = userEvent.setup();+ render(<ReviewerPicker reviewers={['copilot']} onChange={onChange} />);+ await user.type(screen.getByLabelText('Add a GitHub reviewer username'), '@CodeReviewbot');+ await user.click(screen.getByRole('button', { name: /^Add$/ }));+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ usernames: ['CodeReviewbot'] }));+ });++ it('adds a username on Enter', async () => {+ const onChange = vi.fn();+ const user = userEvent.setup();+ render(<ReviewerPicker reviewers={['copilot']} onChange={onChange} />);+ await user.type(screen.getByLabelText('Add a GitHub reviewer username'), 'reviewer-bot{Enter}');+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ usernames: ['reviewer-bot'] }));+ });++ it('rejects an invalid username and surfaces an error without emitting', async () => {+ const onChange = vi.fn();+ const user = userEvent.setup();+ render(<ReviewerPicker reviewers={['copilot']} onChange={onChange} />);+ await user.type(screen.getByLabelText('Add a GitHub reviewer username'), 'bad token!{Enter}');+ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByText(/valid GitHub username/)).toBeInTheDocument();+ });++ it('renders existing username pills and removes one', async () => {+ const onChange = vi.fn();+ const user = userEvent.setup();+ render(<ReviewerPicker reviewers={['copilot']} usernames={['CodeReviewbot', 'other-bot']} onChange={onChange} />);+ expect(screen.getByText('CodeReviewbot')).toBeInTheDocument();+ await user.click(screen.getByLabelText('Remove @CodeReviewbot'));+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ usernames: ['other-bot'] }));+ });});diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex 0f33b3077d..b8c7e220c9 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -26,6 +26,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = faconst [simplify, setSimplify] = useState(true);const [reviewLoop, setReviewLoop] = useState(false);const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);+ const [reviewUsernames, setReviewUsernames] = useState([]);const [reviewStopMode, setReviewStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);const [reviewerApplies, setReviewerApplies] = useState(false);const [createJiraTicket, setCreateJiraTicket] = useState(false);@@ -61,6 +62,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa.then((d) => {if (cancelled || !d) return;if (Array.isArray(d.reviewers) && d.reviewers.length) setReviewers(d.reviewers);+ if (Array.isArray(d.usernames)) setReviewUsernames(d.usernames);if (d.stopMode) setReviewStopMode(d.stopMode);if (d.reviewerApplies === true) setReviewerApplies(true);})@@ -263,6 +265,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fasimplify,reviewLoop,reviewers: reviewLoop ? reviewers : undefined,+ usernames: reviewLoop ? reviewUsernames : undefined,reviewStopMode: reviewLoop ? reviewStopMode : undefined,reviewerApplies: reviewLoop ? reviewerApplies : undefined,screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,@@ -504,10 +507,12 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa<div className="basis-full mt-1"><ReviewerPickerreviewers={reviewers}+ usernames={reviewUsernames}stopMode={reviewStopMode}reviewerApplies={reviewerApplies}- onChange={({ reviewers: r, stopMode, reviewerApplies: ra }) => {+ onChange={({ reviewers: r, usernames: u, stopMode, reviewerApplies: ra }) => {setReviewers(r);+ setReviewUsernames(u);setReviewStopMode(stopMode);setReviewerApplies(ra);}}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 34f3decb9d..377457e132 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -141,6 +141,41 @@ export const SWARM_COUNT_OPTIONS = [export const DEFAULT_REVIEWER = 'copilot';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+// `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).+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})?$/;++// Validate a single raw username entry (strip `@`, trim). Returns the clean+// token or null if it isn't a shell-safe GitHub username/team slug.+export function cleanReviewUsername(raw) {+ if (typeof raw !== 'string') return null;+ const trimmed = raw.trim().replace(/^@+/, '');+ return trimmed && REVIEW_USERNAME_RE.test(trimmed) ? trimmed : null;+}++// Normalize a raw list: drop invalid tokens, case-insensitively dedupe while+// preserving order, cap at MAX_REVIEW_USERNAMES. Returns clean usernames sans `@`.+export function normalizeReviewUsernames(list) {+ if (!Array.isArray(list)) return [];+ const seen = new Set();+ const out = [];+ for (const raw of list) {+ const clean = cleanReviewUsername(raw);+ if (!clean) continue;+ const key = clean.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(clean);+ if (out.length >= MAX_REVIEW_USERNAMES) break;+ }+ return out;+}+// Stop-mode for the multi-reviewer loop (slashdo `--review-stop-on-*`).// Keep in sync with REVIEW_STOP_MODES in `server/lib/validation.js`.export const REVIEW_STOP_MODES = [diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex 2261134fb6..6a9c1cd33a 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -412,16 +412,17 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri<div className="mt-3 pl-2"><ReviewerPickerreviewers={config.taskMetadata?.reviewers ?? (config.taskMetadata?.reviewer ? [config.taskMetadata.reviewer] : reviewDefaults.reviewers)}+ usernames={config.taskMetadata?.usernames ?? reviewDefaults.usernames}stopMode={config.taskMetadata?.reviewStopMode || reviewDefaults.stopMode || DEFAULT_REVIEW_STOP_MODE}reviewerApplies={config.taskMetadata?.reviewerApplies !== undefined? (config.taskMetadata?.reviewerApplies === true || config.taskMetadata?.reviewerApplies === 'true'): reviewDefaults.reviewerApplies}disabled={updating}- onChange={({ reviewers, stopMode, reviewerApplies }) => {+ onChange={({ reviewers, usernames, stopMode, reviewerApplies }) => {// Drop the legacy single `reviewer` key so storage converges on `reviewers`.const { reviewer: _reviewer, ...rest } = config.taskMetadata || {};onUpdate(taskType, {- taskMetadata: { ...rest, reviewers, reviewStopMode: stopMode, reviewerApplies }+ taskMetadata: { ...rest, reviewers, usernames, reviewStopMode: stopMode, reviewerApplies }});}}/>diff --git a/client/src/components/providers/CodeReviewDefaultsPanel.jsx b/client/src/components/providers/CodeReviewDefaultsPanel.jsxindex 2a50247350..f0bc2c40ca 100644--- a/client/src/components/providers/CodeReviewDefaultsPanel.jsx+++ b/client/src/components/providers/CodeReviewDefaultsPanel.jsx@@ -24,6 +24,7 @@ export default function CodeReviewDefaultsPanel() {const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);+ const [usernames, setUsernames] = useState([]);const [stopMode, setStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);const [reviewerApplies, setReviewerApplies] = useState(false);const [lmstudioModel, setLmstudioModel] = useState('');@@ -42,6 +43,7 @@ export default function CodeReviewDefaultsPanel() {if (cancelled) return;if (defaults) {setReviewers(Array.isArray(defaults.reviewers) && defaults.reviewers.length ? defaults.reviewers : DEFAULT_REVIEWERS);+ setUsernames(Array.isArray(defaults.usernames) ? defaults.usernames : []);setStopMode(defaults.stopMode || DEFAULT_REVIEW_STOP_MODE);setReviewerApplies(defaults.reviewerApplies === true);setLmstudioModel(defaults.lmstudioModel || '');@@ -81,6 +83,7 @@ export default function CodeReviewDefaultsPanel() {// than writing the literal "" the <select> renders.const payload = {reviewers,+ usernames,stopMode,reviewerApplies,lmstudioModel: lmstudioModel || undefined,@@ -139,11 +142,13 @@ export default function CodeReviewDefaultsPanel() {<><ReviewerPickerreviewers={reviewers}+ usernames={usernames}stopMode={stopMode}reviewerApplies={reviewerApplies}disabled={saving}- onChange={({ reviewers: r, stopMode: s, reviewerApplies: a }) => {+ onChange={({ reviewers: r, usernames: u, stopMode: s, reviewerApplies: a }) => {setReviewers(r);+ setUsernames(u);setStopMode(s);setReviewerApplies(a);}}diff --git a/client/src/hooks/useCodeReviewDefaults.jsx b/client/src/hooks/useCodeReviewDefaults.jsxindex 321058bbc1..8415471feb 100644--- a/client/src/hooks/useCodeReviewDefaults.jsx+++ b/client/src/hooks/useCodeReviewDefaults.jsx@@ -9,6 +9,7 @@ import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from '../components/cos/c// regardless of whether it reads context or calls the API directly.const FALLBACK = Object.freeze({reviewers: DEFAULT_REVIEWERS,+ usernames: [],stopMode: DEFAULT_REVIEW_STOP_MODE,reviewerApplies: false,lmstudioModel: null,@@ -31,6 +32,7 @@ export function CodeReviewDefaultsProvider({ children }) {if (cancelled || !d) return;setValue({reviewers: Array.isArray(d.reviewers) && d.reviewers.length ? d.reviewers : DEFAULT_REVIEWERS,+ usernames: Array.isArray(d.usernames) ? d.usernames : [],stopMode: d.stopMode || DEFAULT_REVIEW_STOP_MODE,reviewerApplies: d.reviewerApplies === true,lmstudioModel: d.lmstudioModel || null,diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 181e34ac97..9e7b19b92c 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -33,6 +33,57 @@ export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];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);+}+/*** Resolve task metadata to an ordered, deduped reviewer list. Prefers the new* `reviewers` array; falls back to the legacy single `reviewer` string. When@@ -67,18 +118,50 @@ export function normalizeReviewers(meta, fallback = DEFAULT_REVIEWERS) {}/**- * Build the slashdo review flag string for an ordered reviewer list.- * - `--review-with a,b,c` only when the list isn't the lone default copilot.- * - `--review-stop-on-*` only when 2+ reviewers (stop-mode is meaningless for one).- * - `--reviewer-applies` only when a non-copilot reviewer is present (no-op on copilot).+ * 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 buildReviewWithArgs(reviewers, stopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false) {- const list = normalizeReviewers({ reviewers });- const isDefaultOnly = list.length === 1 && list[0] === DEFAULT_REVIEWER;- const hasNonCopilot = list.some(r => r !== DEFAULT_REVIEWER);+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.+ * The flag-string variant is `buildReviewWithArgs`.+ */+export function buildReviewersCsv(reviewers, usernames = []) {+ const keyed = Array.isArray(reviewers) && reviewers.length ? reviewers : [...DEFAULT_REVIEWERS];+ const users = normalizeReviewUsernames(usernames);+ return [...keyed, ...users.map(u => `@${u}`)].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).+ */+export function buildReviewWithArgs(reviewers, stopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, usernames = []) {+ const users = normalizeReviewUsernames(usernames);+ const keyed = resolveKeyedReviewers(reviewers, users.length > 0);+ const combined = [...keyed, ...users.map(u => `@${u}`)];+ const isDefaultOnly = combined.length === 1 && combined[0] === DEFAULT_REVIEWER;+ const hasNonCopilot = keyed.some(r => r !== DEFAULT_REVIEWER);const parts = [];- if (!isDefaultOnly) parts.push(`--review-with ${list.join(',')}`);- if (list.length >= 2) {+ if (!isDefaultOnly) parts.push(`--review-with ${combined.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');}@@ -160,6 +243,14 @@ export const createCosTaskSchema = z.object({v => v === 'true' ? true : v === 'false' ? false : v,z.boolean().optional()),+ // Arbitrary GitHub reviewer usernames requested as PR reviewers to gate the+ // merge. Normalized (strip `@`, drop unsafe/duplicate tokens) so the schema+ // can't accept a shell-unsafe or oversized list. Absent → undefined (not `[]`)+ // so an omitted field isn't persisted as an empty override.+ usernames: z.preprocess(+ v => Array.isArray(v) ? normalizeReviewUsernames(v) : undefined,+ z.array(z.string()).optional()+ ),});export const updateCosTaskSchema = z.object({@@ -271,6 +362,14 @@ export const codeReviewSettingsSchema = z.object({v => Array.isArray(v) ? v.map(r => (typeof r === 'string' ? (REVIEWER_ALIASES[r] ?? r) : r)) : v,z.array(z.enum(REVIEWER_VALUES)).optional()),+ // Arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`) requested as PR+ // reviewers to gate the merge, appended to `--review-with` after the keyed+ // reviewers. Normalized so a hand-edited settings.json can't smuggle in a+ // shell-unsafe or oversized token list. Absent → undefined (not `[]`).+ usernames: z.preprocess(+ v => Array.isArray(v) ? normalizeReviewUsernames(v) : undefined,+ z.array(z.string()).optional()+ ),stopMode: z.enum(REVIEW_STOP_MODES).optional(),reviewerApplies: z.boolean().optional(),lmstudioModel: z.preprocess(emptyToUndefined, z.string().optional()),@@ -335,8 +434,9 @@ export const SWARM_COUNT_MAX = 6;* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)* are kept only when actually boolean; the review-loop keys are constrained by* value — `reviewer` to a known reviewer, `reviewers` to a filtered/deduped list- * of known reviewers, `reviewStopMode` to a known stop-mode — plus a validated- * `pipeline` object. Prevents prototype pollution and reserved-field overrides.+ * of known reviewers, `usernames` to shell-safe GitHub reviewer usernames,+ * `reviewStopMode` to a known stop-mode — plus a validated `pipeline` object.+ * Prevents prototype pollution and reserved-field overrides.* Returns a clean plain object or null if input is empty/invalid.*/export function sanitizeTaskMetadata(raw) {@@ -365,6 +465,12 @@ export function sanitizeTaskMetadata(raw) {}if (list.length) { clean.reviewers = list; hasKeys = true; }}+ // `usernames` is the arbitrary GitHub reviewer-username list — normalize to+ // shell-safe, deduped, capped tokens (strips `@`, drops bogus entries).+ if (Array.isArray(raw.usernames)) {+ const usernames = normalizeReviewUsernames(raw.usernames);+ if (usernames.length) { clean.usernames = usernames; hasKeys = true; }+ }if (Object.prototype.hasOwnProperty.call(raw, 'reviewStopMode') && REVIEW_STOP_MODES.includes(raw.reviewStopMode)) {clean.reviewStopMode = raw.reviewStopMode;hasKeys = true;diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 853976623d..e114facb7c 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -11,6 +11,10 @@ import {sanitizeTaskMetadata,stageConfigUpdateSchema,normalizeReviewers,+ normalizeReviewUsernames,+ resolveReviewUsernames,+ resolveKeyedReviewers,+ buildReviewersCsv,buildReviewWithArgs,createCosTaskSchema,featureProviderConfigSchema,@@ -134,6 +138,20 @@ describe('validation.js', () => {it('rejects an unknown stopMode', () => {expect(codeReviewSettingsSchema.safeParse({ stopMode: 'nope' }).success).toBe(false)})++ it('normalizes reviewer usernames (strips @, drops unsafe, dedupes)', () => {+ const r = codeReviewSettingsSchema.safeParse({+ usernames: ['@CodeReviewbot', 'codereviewbot', 'bad token', 'my-org/reviewers'],+ })+ expect(r.success).toBe(true)+ expect(r.data.usernames).toEqual(['CodeReviewbot', 'my-org/reviewers'])+ })++ it('leaves usernames undefined when absent', () => {+ const r = codeReviewSettingsSchema.safeParse({ reviewers: ['copilot'] })+ expect(r.success).toBe(true)+ expect(r.data.usernames).toBeUndefined()+ })})describe('processSchema', () => {@@ -706,6 +724,17 @@ describe('validation.js', () => {expect(sanitizeTaskMetadata({ reviewers: ['nope'] })).toBeNull();});+ it('should normalize reviewer usernames and drop an all-invalid/empty list', () => {+ expect(sanitizeTaskMetadata({ usernames: ['@CodeReviewbot', 'codereviewbot', 'bad token'] }))+ .toEqual({ usernames: ['CodeReviewbot'] });+ // An all-invalid or empty usernames list contributes no keys → null.+ expect(sanitizeTaskMetadata({ usernames: ['bad token', '$(x)'] })).toBeNull();+ expect(sanitizeTaskMetadata({ usernames: [] })).toBeNull();+ // Keeps a valid sibling key when the usernames are dropped.+ expect(sanitizeTaskMetadata({ reviewLoop: true, usernames: ['@Bot'] }))+ .toEqual({ reviewLoop: true, usernames: ['Bot'] });+ });+it('should accept reviewStopMode and reviewerApplies', () => {expect(sanitizeTaskMetadata({ reviewStopMode: 'on-clean' })).toEqual({ reviewStopMode: 'on-clean' });expect(sanitizeTaskMetadata({ reviewStopMode: 'bogus' })).toBeNull();@@ -746,6 +775,75 @@ describe('validation.js', () => {});});+ describe('normalizeReviewUsernames', () => {+ it('strips a leading @, trims, and preserves order', () => {+ expect(normalizeReviewUsernames(['@CodeReviewbot', ' reviewer-two '])).toEqual(['CodeReviewbot', 'reviewer-two']);+ });++ it('case-insensitively dedupes while keeping first occurrence', () => {+ expect(normalizeReviewUsernames(['@Bot', 'bot', 'BOT', 'other'])).toEqual(['Bot', 'other']);+ });++ it('drops shell-unsafe / non-username tokens', () => {+ expect(normalizeReviewUsernames(['ok', 'bad token', 'semi;rm', '$(x)', 'a`b', 42, null, '', ' ']))+ .toEqual(['ok']);+ });++ it('accepts org/team slugs', () => {+ expect(normalizeReviewUsernames(['my-org/reviewers'])).toEqual(['my-org/reviewers']);+ });++ it('caps the list at MAX_REVIEW_USERNAMES (20)', () => {+ const many = Array.from({ length: 30 }, (_, i) => `user${i}`);+ expect(normalizeReviewUsernames(many)).toHaveLength(20);+ });++ it('returns [] for non-array input', () => {+ expect(normalizeReviewUsernames(undefined)).toEqual([]);+ expect(normalizeReviewUsernames('nope')).toEqual([]);+ });+ });++ describe('resolveKeyedReviewers', () => {+ it('keeps an explicitly empty list empty only when usernames carry the review', () => {+ expect(resolveKeyedReviewers([], true)).toEqual([]);+ // No usernames → falls back to the copilot default (can never be empty).+ expect(resolveKeyedReviewers([], false)).toEqual(['copilot']);+ });++ it('normalizes a populated list and defaults absent/legacy input to copilot', () => {+ expect(resolveKeyedReviewers(['codex', 'gemini'], true)).toEqual(['codex', 'antigravity']);+ expect(resolveKeyedReviewers(undefined, true)).toEqual(['copilot']);+ });+ });++ describe('resolveReviewUsernames', () => {+ it('lets a task-level list (even empty) override the defaults', () => {+ expect(resolveReviewUsernames(['@Bot'], ['Default'])).toEqual(['Bot']);+ // Explicit empty task list wins over the defaults (username-only override).+ expect(resolveReviewUsernames([], ['Default'])).toEqual([]);+ });++ it('falls back to the defaults when the task did not pin its own', () => {+ expect(resolveReviewUsernames(undefined, ['@Default', 'bad token'])).toEqual(['Default']);+ });+ });++ describe('buildReviewersCsv', () => {+ it('joins keyed reviewers then @user tokens', () => {+ expect(buildReviewersCsv(['copilot', 'codex'], ['@Bot'])).toBe('copilot,codex,@Bot');+ });++ it('falls back to the copilot default when the keyed list is empty', () => {+ expect(buildReviewersCsv([], [])).toBe('copilot');+ expect(buildReviewersCsv([], ['Bot'])).toBe('copilot,@Bot');+ });++ it('normalizes/strips bogus usernames', () => {+ expect(buildReviewersCsv(['codex'], ['@Bot', 'bad token', 'bot'])).toBe('codex,@Bot');+ });+ });+describe('buildReviewWithArgs', () => {it('emits nothing for the lone default copilot', () => {expect(buildReviewWithArgs(['copilot'])).toBe('');@@ -766,6 +864,31 @@ describe('validation.js', () => {// copilot-only → reviewer-applies suppressed (no-op on copilot)expect(buildReviewWithArgs(['copilot'], 'all', true)).toBe('');});++ it('appends username reviewers as @user tokens after the keyed reviewers', () => {+ // copilot + a username is no longer "lone default" → the flag is emitted.+ expect(buildReviewWithArgs(['copilot'], 'all', false, ['CodeReviewbot']))+ .toBe('--review-with copilot,@CodeReviewbot');+ expect(buildReviewWithArgs(['codex', 'copilot'], 'all', false, ['@Bot']))+ .toBe('--review-with codex,copilot,@Bot');+ });++ it('counts usernames toward the 2+ stop-mode gate', () => {+ // one keyed reviewer + one username = two review sources → stop-mode applies.+ expect(buildReviewWithArgs(['copilot'], 'on-clean', false, ['Bot']))+ .toBe('--review-with copilot,@Bot --review-stop-on-clean');+ });++ it('does not enable reviewer-applies for username-only additions', () => {+ // usernames are external PR reviewers, not CLIs that apply fixes.+ expect(buildReviewWithArgs(['copilot'], 'all', true, ['Bot']))+ .toBe('--review-with copilot,@Bot');+ });++ it('normalizes/strips bogus usernames before emitting', () => {+ expect(buildReviewWithArgs(['copilot'], 'all', false, ['@Bot', 'bad token', 'bot']))+ .toBe('--review-with copilot,@Bot');+ });});describe('createCosTaskSchema reviewers fields', () => {@@ -787,6 +910,19 @@ describe('validation.js', () => {expect(createCosTaskSchema.safeParse({ description: 'x', reviewStopMode: 'nope' }).success).toBe(false);});+ it('normalizes reviewer usernames and leaves the field undefined when absent', () => {+ const withUsers = createCosTaskSchema.safeParse({+ description: 'x',+ usernames: ['@CodeReviewbot', 'bad token', 'codereviewbot'],+ });+ expect(withUsers.success).toBe(true);+ expect(withUsers.data.usernames).toEqual(['CodeReviewbot']);+ // Absent → undefined (not coerced to []), so it isn't persisted as an override.+ const withoutUsers = createCosTaskSchema.safeParse({ description: 'x' });+ expect(withoutUsers.success).toBe(true);+ expect(withoutUsers.data.usernames).toBeUndefined();+ });+it('accepts multiple image screenshots and attachment objects', () => {const parsed = createCosTaskSchema.safeParse({description: 'do a thing',diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 964073c6d0..b88c208d30 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -19,8 +19,8 @@ import {updateCosTaskSchema,validateRequest,normalizeReviewers,+ buildReviewersCsv,LOCAL_LLM_REVIEWERS,- DEFAULT_REVIEWERS,isPaginationRequested,parsePagination,} from '../lib/validation.js';@@ -45,7 +45,9 @@ async function resolveClaimReviewersCsv() {const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);const list = normalizeReviewers({}, codeReviewDefaults?.reviewers).filter((r) => !LOCAL_LLM_REVIEWERS.includes(r));- return (list.length ? list : [...DEFAULT_REVIEWERS]).join(',');+ // Arbitrary GitHub reviewer usernames from the Code Review Defaults, appended+ // as `@user` tokens so the play button's claim gates the merge on them too.+ return buildReviewersCsv(list, codeReviewDefaults?.usernames);}// Append a "claim exactly this ticket" constraint to the claim-issue-jira bodydiff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 5986cff66f..948974c073 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -16,7 +16,7 @@ import { getToolsSummaryForPrompt } from './tools.js';import { getActiveProvider } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUtils.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, normalizeReviewers, buildReviewWithArgs } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, resolveKeyedReviewers, buildReviewWithArgs } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { isOpencodeCommand } from '../lib/providerModels.js';import { shellQuote } from '../lib/shellQuote.js';@@ -258,17 +258,23 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const prOwner = metadata.reviewLoopPROwner ?? '';const prRepo = metadata.reviewLoopPRRepo ?? '';const sourceTaskId = metadata.sourceTaskId || 'unknown';- // Ordered reviewer list (back-compat: legacy single `reviewLoopReviewer`).- const reviewers = normalizeReviewers({- reviewers: Array.isArray(metadata.reviewLoopReviewers)- ? metadata.reviewLoopReviewers- : (metadata.reviewLoopReviewer ? [metadata.reviewLoopReviewer] : undefined)- });+ // Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to+ // the review flow after the keyed reviewers.+ const usernames = normalizeReviewUsernames(metadata.reviewLoopReviewerUsernames);+ // Ordered keyed reviewer list (back-compat: legacy single `reviewLoopReviewer`).+ // `reviewLoopReviewers` from spawnReviewLoopFollowUp is authoritative (copilot+ // already stripped on non-GitHub forges); resolveKeyedReviewers keeps an+ // explicit empty list empty when usernames carry the review (username-only).+ const reviewerSource = Array.isArray(metadata.reviewLoopReviewers)+ ? metadata.reviewLoopReviewers+ : (metadata.reviewLoopReviewer ? [metadata.reviewLoopReviewer] : undefined);+ const reviewers = resolveKeyedReviewers(reviewerSource, usernames.length > 0);const stopMode = metadata.reviewLoopStopMode || DEFAULT_REVIEW_STOP_MODE;const reviewerApplies = metadata.reviewLoopReviewerApplies === true;const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));const hasCli = reviewers.some(r => r !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(r));+ const hasGithubUser = usernames.length > 0;// Optional Codex CLI model tier chosen on the Code Review Defaults panel.// Only surfaced when `codex` is actually one of the reviewers; the CLI takes// it as `codex --model <id>` (empty = let the Codex CLI use its own default).@@ -278,13 +284,19 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const codexModelNote = codexModel? ` When invoking the \`codex\` reviewer, pass its model tier: \`codex --model ${codexModel} …\`.`: '';- const multi = reviewers.length > 1;+ // "multi" reflects the TOTAL number of review sources (keyed reviewers ++ // username reviewers) so the ordered per-reviewer loop wording kicks in as+ // soon as there's more than one thing to satisfy.+ const multi = (reviewers.length + usernames.length) > 1;// The system pre-requests the initial Copilot review only when copilot LEADS the// order; otherwise the agent must request it at copilot's turn (so Copilot reviews// the post-CLI-fix state, not a stale diff).const copilotIsFirst = reviewers[0] === DEFAULT_REVIEWER;- const reviewerLabel = reviewers.map(r => `\`${r}\``).join(' → ');- const equivArgs = buildReviewWithArgs(reviewers, stopMode, reviewerApplies);+ const reviewerLabel = [+ ...reviewers.map(r => `\`${r}\``),+ ...usernames.map(u => `\`@${u}\``),+ ].join(' → ');+ const equivArgs = buildReviewWithArgs(reviewers, stopMode, reviewerApplies, usernames);const equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';// First step: how to obtain a review. For a single copilot/CLI reviewer keep the@@ -295,12 +307,17 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// the diff and returns findings text. The agent always reaches it via// `http://localhost:5555` (the canonical loopback API port).const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint: \`gh pr diff ${prNumber || '<PR_NUMBER>'} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @-\`. Substitute the active reviewer name for \`<lmstudio|ollama>\`. The response \`.findings\` field is the review text — treat it like any other reviewer's findings.`;+ // Instruct the agent to request each username reviewer as a PR reviewer and+ // gate the merge on their approval. `gh pr edit --add-reviewer` takes the bare+ // login, so strip the `@`.+ const githubUsersInvocation = `request ${usernames.map(u => `\`@${u}\``).join(', ')} as PR reviewer${usernames.length > 1 ? 's' : ''} (\`gh pr edit ${prNumber || '<PR_NUMBER>'} --add-reviewer <user>\`, drop the \`@\`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.`;const multiBullets = [hasCopilot ? `**copilot**: ${copilotIsFirst? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)': 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,hasCli ? `**codex / antigravity / claude**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${codexModelNote}` : null,hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,+ hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,].filter(Boolean).join(' ');const singleCliInvocation = `Invoke the ${reviewerLabel} CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${codexModelNote}`;// Resolved sequentially so a future reviewer kind only adds one branch@@ -309,7 +326,8 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,if (multi) waitOrInvokeStep = `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`;else if (hasCopilot) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';else if (hasLocalLlm) waitOrInvokeStep = localLlmInvocation;- else waitOrInvokeStep = singleCliInvocation;+ else if (hasCli) waitOrInvokeStep = singleCliInvocation;+ else waitOrInvokeStep = `To obtain a review, ${githubUsersInvocation}`;const stopModeNote = stopMode === 'on-findings'? '**Stop mode (on-findings):** stop after the FIRST reviewer whose findings you actually fixed and committed; skip the remaining reviewers.'@@ -327,7 +345,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,? 'The system has already requested the initial Copilot code review (Copilot leads the order).': hasCopilot? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.'- : 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must invoke each configured reviewer yourself against the PR diff.';+ : 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must request/invoke each configured reviewer yourself against the PR diff.';const repeatedCommentsNote = '**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.';const extraNotes = [stopModeNote, applyNote].filter(Boolean);@@ -619,6 +637,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an// Resolve the user's ordered reviewer list + flags (default `[copilot]`). Declared// up here so the TUI completion block can thread `--review-with …` into `/do:pr`.const taskReviewers = normalizeReviewers(task.metadata);+ const taskReviewerUsernames = normalizeReviewUsernames(task.metadata?.usernames);const taskReviewStopMode = task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE;const taskReviewerApplies = isTruthyMetaFn(task.metadata?.reviewerApplies);@@ -641,6 +660,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix anwillOpenPR, willReviewLoop, simplifyEnabled, providerId,sentinelPath,reviewers: taskReviewers,+ usernames: taskReviewerUsernames,reviewStopMode: taskReviewStopMode,reviewerApplies: taskReviewerApplies})@@ -876,6 +896,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// Ordered reviewer list + flags for the Review Loop (default `[copilot]`).// Flows as `/do:pr --review-with a,b,c [--review-stop-on-*] [--reviewer-applies]`.const lightReviewers = normalizeReviewers(task.metadata);+ const lightReviewerUsernames = normalizeReviewUsernames(task.metadata?.usernames);const lightReviewStopMode = task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE;const lightReviewerApplies = isTruthyMetaFn(task.metadata?.reviewerApplies);// Claude Code CLI providers can drive `/simplify` + `/do:pr` themselves@@ -980,10 +1001,10 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetsentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,branchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,- reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies+ reviewers: lightReviewers, usernames: lightReviewerUsernames, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies}));} else {- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop, hasSlashdo, simplifyEnabled, reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop, hasSlashdo, simplifyEnabled, reviewers: lightReviewers, usernames: lightReviewerUsernames, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));}return { taskSections, contractSections };@@ -1025,10 +1046,11 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,* both agent flows converge on the same final state. `reviewers` only colors* the wording — the merge step itself is reviewer-agnostic.*/-function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {+function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {// Trailing space when present so the sentence reads "the Copilot review loop"- // (lone copilot) or "the review loop" (multi/CLI) — never "the the review loop".- const reviewerLabel = (reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER) ? 'Copilot ' : '';+ // (lone copilot, no usernames) or "the review loop" (multi/CLI/username) —+ // never "the the review loop".+ const reviewerLabel = (reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && usernames.length === 0) ? 'Copilot ' : '';// Under an explicit stop-mode, the multi-reviewer loop can exit `partial` (later// reviewers intentionally skipped after the short-circuit) — that's a successful// outcome the user opted into, so merge on it too. Match the known stop-modes@@ -1056,25 +1078,27 @@ function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, revie* slash commands), the agent can't run `/do:pr` / `/do:push`, so it delegates to* the plain-git/`gh` variant below — same sentinel handshake, no slashdo.*/-function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {if (slashdoFree) {// The manual path never auto-merges (it opens the PR for review), so it// doesn't need willReviewLoop — the review gate holds unconditionally.return buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinelPath, branchName, baseBranch });}const cmd = willOpenPR ? '/do:pr' : '/do:push';+ const reviewUsernames = normalizeReviewUsernames(usernames);// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out// when the task's Review Loop control is off so that default cannot start a// Copilot (or other external) review unexpectedly.const reviewArgs = willOpenPR- ? (willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies) : '--review-with none')+ ? (willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies, reviewUsernames) : '--review-with none'): '';const reviewerArg = reviewArgs ? ` ${reviewArgs}` : '';- const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER;+ const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0;+ const reviewerListLabel = [...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ');const reviewSuffix = willOpenPR && willReviewLoop? (copilotOnly? ' — `/do:pr` runs the Copilot review loop after the PR opens.'- : ` — \`/do:pr\` runs the review loop for ${reviewers.join(', ')} in order after the PR opens.`)+ : ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order after the PR opens.`): (willOpenPR ? ' — external review is disabled for this task.' : '');// `/simplify` is a Claude Code TUI built-in. Non-Claude TUI providers// (codex-tui, antigravity-tui) can't run it, so give them the inline equivalent.@@ -1085,7 +1109,7 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled: '1. (simplify disabled — skip)';const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';const merge = willOpenPR && willReviewLoop- ? buildPostPRMergeSteps(3, { reviewers, reviewStopMode })+ ? buildPostPRMergeSteps(3, { reviewers, usernames: reviewUsernames, reviewStopMode }): { lines: [], nextStep: 3 };const sentinelStep = merge.nextStep;@@ -1198,7 +1222,8 @@ function buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinel* CLI providers fall through to the legacy commit-only block where PortOS* handles push+PR on exit.*/-function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop = false, hasSlashdo = false, simplifyEnabled = false, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop = false, hasSlashdo = false, simplifyEnabled = false, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+ const reviewUsernames = normalizeReviewUsernames(usernames);if (hasSlashdo && worktreeInfo && willOpenPR) {const lines = ['## Completion', 'When finished, run these in order:'];let step = 1;@@ -1206,17 +1231,17 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop =lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);}const reviewArgs = willReviewLoop- ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies)+ ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies, reviewUsernames): '--review-with none';const reviewerArg = reviewArgs ? ` ${reviewArgs}` : '';const completionNote = willReviewLoop- ? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER)+ ? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0)? 'and drives the Copilot review loop until clean.'- : `and drives the review loop for ${reviewers.join(', ')} in order until clean.`)+ : `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`): 'with external review disabled.';lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);const merge = willReviewLoop- ? buildPostPRMergeSteps(step, { reviewers, reviewStopMode })+ ? buildPostPRMergeSteps(step, { reviewers, usernames: reviewUsernames, reviewStopMode }): { lines: [], nextStep: step };lines.push(...merge.lines);step = merge.nextStep;diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 5c8b5a0576..2bb944948d 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -490,6 +490,46 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/For EACH reviewer in order/);});+ it('appends GitHub reviewer usernames as @user tokens and instructs requesting them', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'b',+ reviewLoopPRNumber: 9,+ reviewLoopReviewers: ['copilot'],+ reviewLoopReviewerUsernames: ['CodeReviewbot'],+ sourceTaskId: 'task-src-u',+ }}),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta);+ expect(prompt).toMatch(/--review-with copilot,@CodeReviewbot/);+ // The agent is told to request the username as a PR reviewer that gates merge.+ expect(prompt).toMatch(/--add-reviewer/);+ expect(prompt).toMatch(/@CodeReviewbot/);+ });++ it('drives a username-only review loop (no keyed reviewer)', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'b',+ reviewLoopPRNumber: 9,+ // Empty keyed list (e.g. copilot stripped on a non-GitHub forge) + a username.+ reviewLoopReviewers: [],+ reviewLoopReviewerUsernames: ['CodeReviewbot'],+ sourceTaskId: 'task-src-uonly',+ }}),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta);+ expect(prompt).toMatch(/--review-with @CodeReviewbot/);+ // No copilot fallback re-introduced.+ expect(prompt).not.toMatch(/--review-with copilot/);+ });+it('threads the configured Codex model tier into the CLI invocation when codex reviews', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: {diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 7194db2eba..150be821b7 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -22,7 +22,7 @@ import { removeWorktree } from './worktreeManager.js';import { isTruthyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers, normalizeReviewUsernames } from '../lib/validation.js';/*** Clean up a worktree for a completed agent.@@ -41,7 +41,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normaliz* the worktree branch into the source workspace because `gh pr merge` already handled it.* Otherwise, merges the worktree branch back to the source branch on success.*/-export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {const { getAgent: getAgentState } = await import('./cos.js');const agentState = await getAgentState(agentId).catch(() => null);if (!agentState?.metadata?.isWorktree) return [];@@ -177,6 +177,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, rprBranch: worktreeBranch,sourceWorkspace,reviewers: reviewerList,+ usernames,reviewStopMode,reviewerApplies,codexModel@@ -229,23 +230,30 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r* runs each in order — invoking the CLI reviewers itself and requesting Copilot at* its turn — honoring `reviewStopMode` (`all`/`on-findings`/`on-clean`) and* `reviewerApplies`. Copilot is GitHub-only, so it is stripped here on non-GitHub- * forges; if that empties the list, no follow-up is spawned.+ * forges; if that empties the list AND no `usernames` are configured, no follow-up+ * is spawned. `usernames` are arbitrary GitHub reviewer usernames the follow-up+ * requests as PR reviewers to gate the merge — forge-agnostic, so never stripped.** The follow-up task uses an isolated worktree attached to the existing PR* branch (via createWorktree's `existingBranch` option) so it can fix-and-push* without trampling concurrent agents.*/-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null }) {+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, codexModel = null }) {if (!prUrl || !prBranch) return null;const parsedPr = git.parsePullRequestUrl(prUrl);// Copilot is GitHub-only; CLI-based reviewers (claude/antigravity/codex) work on any// forge because the agent invokes the CLI directly. On a non-GitHub forge, drop- // copilot from the list — if nothing's left, there's no review to run.+ // copilot from the list — if nothing's left (and no username reviewers), there's+ // no review to run.const isNonGithubForge = parsedPr && parsedPr.host && parsedPr.host !== 'github.com';const reviewerList = normalizeReviewers({ reviewers });const effectiveReviewers = isNonGithubForge ? reviewerList.filter(r => r !== DEFAULT_REVIEWER) : reviewerList;- if (effectiveReviewers.length === 0) return null;+ // GitHub reviewer usernames are forge-agnostic requested reviewers, so they are+ // NOT stripped on a non-GitHub forge — a username reviewer alone can drive the+ // loop even when copilot was dropped.+ const effectiveUsernames = normalizeReviewUsernames(usernames);+ if (effectiveReviewers.length === 0 && effectiveUsernames.length === 0) return null;const appId = originalTask?.metadata?.app || null;const sourceTaskDesc = originalTask?.description || 'CoS automated task';@@ -279,6 +287,9 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, previewLoopPROwner: parsedPr?.owner ?? null,reviewLoopPRRepo: parsedPr?.repo ?? null,reviewLoopReviewers: effectiveReviewers,+ // Arbitrary GitHub reviewer usernames the follow-up requests as PR reviewers+ // and gates the merge on (appended to `--review-with` as `@user`).+ reviewLoopReviewerUsernames: effectiveUsernames,reviewLoopStopMode: reviewStopMode,reviewLoopReviewerApplies: reviewerApplies,// Codex CLI model tier (e.g. `gpt-5.6-sol`) — only meaningful when `codex`@@ -297,7 +308,8 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p};await addTask(followUpTask, 'internal', { raw: true });- emitLog('info', `🔁 Spawned review-loop follow-up task ${followUpTaskId} (${effectiveReviewers.join(', ')}) for PR ${prUrl}`, {+ const reviewLoopLabel = [...effectiveReviewers, ...effectiveUsernames.map(u => `@${u}`)].join(', ');+ emitLog('info', `🔁 Spawned review-loop follow-up task ${followUpTaskId} (${reviewLoopLabel}) for PR ${prUrl}`, {taskId: followUpTaskId, prUrl, prBranch, sourceAgentId: originalAgentId, sourceTaskId: originalTask?.id});return followUpTask;diff --git a/server/services/codeReview.js b/server/services/codeReview.jsindex 1c5ba145c5..5478469303 100644--- a/server/services/codeReview.js+++ b/server/services/codeReview.js@@ -21,6 +21,8 @@ import {REVIEWER_ALIASES,REVIEWER_VALUES,REVIEW_STOP_MODES,+ normalizeReviewUsernames,+ resolveReviewUsernames,} from '../lib/validation.js'import { getSettings, settingsEvents } from './settings.js'import { getBaseUrl as getLmStudioBaseUrl } from './lmStudioManager.js'@@ -55,6 +57,11 @@ export function pickCodeReviewDefaults(settings) {: []return {reviewers: reviewers.length ? reviewers : [...DEFAULT_REVIEWERS],+ // Arbitrary GitHub reviewer usernames appended to `--review-with` to gate the+ // merge. Normalized so a hand-edited settings.json can't smuggle in unsafe+ // tokens. Empty array = none configured (distinct from the copilot fallback+ // reviewers get).+ usernames: normalizeReviewUsernames(raw?.usernames),stopMode: REVIEW_STOP_MODES.includes(raw?.stopMode) ? raw.stopMode : DEFAULT_REVIEW_STOP_MODE,reviewerApplies: raw?.reviewerApplies === true,lmstudioModel: typeof raw?.lmstudioModel === 'string' && raw.lmstudioModel ? raw.lmstudioModel : null,@@ -107,12 +114,16 @@ export async function getCodeReviewDefaults() {export async function resolveReviewLoopOptions(metadata, { normalize, isTruthyMeta }) {const defaults = await getCodeReviewDefaults().catch(() => null)const reviewers = normalize(metadata, defaults?.reviewers)+ // GitHub reviewer usernames: a task-level list (even empty) overrides the+ // global default; only fall back to the Code Review Defaults when the task+ // didn't pin its own. Mirrors the reviewers precedence.+ const usernames = resolveReviewUsernames(metadata?.usernames, defaults?.usernames)const reviewStopMode = metadata?.reviewStopMode || defaults?.stopMode || DEFAULT_REVIEW_STOP_MODEconst reviewerApplies = metadata?.reviewerApplies !== undefined? isTruthyMeta(metadata?.reviewerApplies): (defaults?.reviewerApplies === true)const codexModel = defaults?.codexModel || null- return { reviewers, reviewStopMode, reviewerApplies, codexModel }+ return { reviewers, usernames, reviewStopMode, reviewerApplies, codexModel }}const CODE_REVIEW_SYSTEM_PROMPT = `You are a careful senior code reviewer. The user will paste a unified PR diff. Review only what the diff changes (not the whole repo). Produce findings as a markdown list grouped by severity:diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsindex d560f58ebd..dacc101645 100644--- a/server/services/codeReview.test.js+++ b/server/services/codeReview.test.js@@ -47,6 +47,7 @@ describe('codeReview helpers', () => {it('returns the hardcoded fallback when settings has no codeReview slice', () => {expect(pickCodeReviewDefaults(null)).toEqual({reviewers: ['copilot'],+ usernames: [],stopMode: 'all',reviewerApplies: false,lmstudioModel: null,@@ -55,6 +56,7 @@ describe('codeReview helpers', () => {})expect(pickCodeReviewDefaults({})).toEqual({reviewers: ['copilot'],+ usernames: [],stopMode: 'all',reviewerApplies: false,lmstudioModel: null,@@ -108,6 +110,7 @@ describe('codeReview helpers', () => {})expect(out).toEqual({reviewers: ['codex', 'lmstudio'],+ usernames: [],stopMode: 'on-clean',reviewerApplies: true,lmstudioModel: 'qwen2.5-coder:7b',@@ -115,6 +118,19 @@ describe('codeReview helpers', () => {codexModel: 'gpt-5.6-sol',})})++ it('normalizes arbitrary reviewer usernames (strips @, dedupes, drops unsafe)', () => {+ const out = pickCodeReviewDefaults({+ codeReview: {+ usernames: ['@CodeReviewbot', 'codereviewbot', 'bad token!', 'my-org/reviewers'],+ },+ })+ expect(out.usernames).toEqual(['CodeReviewbot', 'my-org/reviewers'])+ })++ it('defaults usernames to an empty array when absent', () => {+ expect(pickCodeReviewDefaults({ codeReview: { reviewers: ['copilot'] } }).usernames).toEqual([])+ })})describe('getCodeReviewDefaults', () => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 5c38eb1001..634c5b58f7 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -22,7 +22,7 @@import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers, LOCAL_LLM_REVIEWERS, DEFAULT_REVIEWERS, SWARM_COUNT_MIN } from '../lib/validation.js';+import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers, resolveReviewUsernames, buildReviewersCsv, LOCAL_LLM_REVIEWERS, SWARM_COUNT_MIN } from '../lib/validation.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';import { getDomainMode } from '../lib/domainAutonomy.js';@@ -323,15 +323,19 @@ export async function buildClaimWorkTask(app, { issueAuthorFilter, reviewers } =// local-LLM reviewers the claim prompts can't drive, falling back to the// hardcoded default when filtering empties the list. A settings read error// degrades to the default inside normalizeReviewers, so it never blocks.+ const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);let reviewersList;if (reviewers !== undefined) {reviewersList = (Array.isArray(reviewers) ? reviewers : [reviewers]).filter(Boolean);} else {- const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);reviewersList = normalizeReviewers(metadata, codeReviewDefaults?.reviewers).filter((r) => !LOCAL_LLM_REVIEWERS.includes(r));}- const reviewersCsv = (reviewersList.length ? reviewersList : [...DEFAULT_REVIEWERS]).join(',');+ // Arbitrary GitHub reviewer usernames appended as `@user` tokens so the+ // claim prompt's `/do:next --review-with` gates the merge on them too. A+ // task-level list overrides the Code Review Defaults.+ const promptUsernames = resolveReviewUsernames(metadata.usernames, codeReviewDefaults?.usernames);+ const reviewersCsv = buildReviewersCsv(reviewersList, promptUsernames);const issueAuthorFilterBlock = resolveIssueAuthorFilterBlock(promptTaskType, resolvedAuthorFilter);// Swarm mode (`/do:next --swarm`) is prepended (not an in-template// placeholder) so it stays an opt-in orchestration wrapper that needs no@@ -2003,7 +2007,11 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// copilot default when filtering empties the list.const promptReviewers = normalizeReviewers(metadata, codeReviewDefaults?.reviewers).filter((r) => !LOCAL_LLM_REVIEWERS.includes(r));- const reviewersCsv = (promptReviewers.length ? promptReviewers : [...DEFAULT_REVIEWERS]).join(',');+ // Arbitrary GitHub reviewer usernames appended as `@user` tokens so the claim+ // prompt's `/do:next --review-with` gates the merge on them too. A task-level+ // list overrides the Code Review Defaults; forge-agnostic, so not filtered.+ const promptUsernames = resolveReviewUsernames(metadata.usernames, codeReviewDefaults?.usernames);+ const reviewersCsv = buildReviewersCsv(promptReviewers, promptUsernames);// {issueAuthorFilter} directive — the filter was already merged (global →// per-app override) and value-constrained by sanitizeTaskMetadata, so read it// from `metadata` (default 'self', the slashdo `/do:next --self` securitydiff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex fe83fe4a92..ff763627be 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -149,10 +149,11 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {it('filters local-LLM reviewers out of the prompt token (no invocation instructions in claim/plan prompts)', () => {// lmstudio/ollama defaults must not reach {reviewers}: the claim/plan- // prompts can't drive them, so the loop would stall. The filter falls- // through to the hardcoded copilot default when it empties the list.+ // prompts can't drive them, so the loop would stall. The filtered list flows+ // into buildReviewersCsv, which owns the fallback to the hardcoded copilot+ // default when the filter empties the list (unit-tested in validation.test.js).expect(GEN_SRC).toContain('.filter((r) => !LOCAL_LLM_REVIEWERS.includes(r))');- expect(GEN_SRC).toContain('promptReviewers.length ? promptReviewers : [...DEFAULT_REVIEWERS]');+ expect(GEN_SRC).toContain('buildReviewersCsv(promptReviewers, promptUsernames)');});});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 31283d6307..51c384728e 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -16,7 +16,7 @@ import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';-import { REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';+import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames } from '../lib/validation.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';@@ -263,6 +263,13 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignoreif (Array.isArray(taskData.reviewers) || (typeof taskData.reviewer === 'string' && taskData.reviewer)) {metadata.reviewers = normalizeReviewers(taskData);}+ // Arbitrary GitHub reviewer usernames (gate-only PR reviewers). Persist the+ // normalized list when present, or an explicit empty array so a per-task+ // "no username reviewers" choice overrides the Code Review Defaults instead+ // of silently inheriting them.+ if (Array.isArray(taskData.usernames)) {+ metadata.usernames = normalizeReviewUsernames(taskData.usernames);+ }if (REVIEW_STOP_MODES.includes(taskData.reviewStopMode)) metadata.reviewStopMode = taskData.reviewStopMode;if (taskData.reviewerApplies === true) metadata.reviewerApplies = true;else if (taskData.reviewerApplies === false) metadata.reviewerApplies = false;