Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(cos): multiple ordered code-review agents per task (#459)

[._.]/ Adam Eivy29d3f2aeb647
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cca7237cb9..b5034ea7b8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,7 +6,10 @@
- New layout `data/universes/{id}/index.json` for the universe builder, plus a type-level `data/universes/index.json` carrying `{ schemaVersion: 5, type, updatedAt, config: { runs } }`. Migration 034 (`scripts/migrations/034-split-universe-builder-to-per-uuid.js`) splits the legacy monolithic `data/universe-builder.json` (1.4MB / ~30 universes that previously rewrote in full on every mutation) into per-record files at boot. The legacy file is renamed to `universe-builder.json.bak-034` (not deleted) as a recovery path. Idempotent — partial-completion re-runs finish the split; full-completion re-runs are no-ops.
- **Cross-instance sync now gates on schema version.** New `server/lib/schemaVersions.js` is the single source of truth for the per-category storage-layout contract (`PORTOS_SCHEMA_VERSIONS = { universes: 5 }`); future category bumps add entries. Every outbound sync payload (federated peer push, 60s snapshot sync, share-bucket manifest) carries a `portosMeta { portosVersion, schemaVersions }` envelope. Receivers run `compareSchemaVersions(sender, local)`; when the sender is **ahead** on any category the receiver REJECTS — federated peer push returns 409 + `{ code: PEER_SYNC_SCHEMA_VERSION_AHEAD, context: { details: { ahead, behind, senderPortosVersion, receiverSchemaVersions } } }`, snapshot sync surfaces `blockedBySchema` on the peer record, share-bucket import skips the manifest with reason `portos-schema-ahead` and emits a `sharing:portos-schema-ahead` socket event. Senders persist the gap (`sub.blockedBySchema` on peer subscriptions, `peer.schemaGaps[category]` on peer records via `updatePeer`) and pause retries (5-minute cooldown; `peer:online` reconnect bypasses to re-probe in case the peer upgraded). Legacy senders without `portosMeta` pass through unchanged. The Instances page renders a new `<SchemaGapBadge>` per peer card explaining the gap in both directions: "Peer X is on an older PortOS — they need to update before we can sync universes" / "Peer X is on a newer PortOS — update PortOS to receive their universe updates." A "sender behind" mismatch DOES NOT gate — the existing sanitizer chain backfills older inputs.
+- **Multiple, ordered code-review agents per task.** The custom-task form (`TaskAddForm`) and scheduled-task form (`ScheduleTab`) now expose an ordered multi-reviewer picker (new `client/src/components/cos/ReviewerPicker.jsx`) instead of a single reviewer dropdown: click reviewers to add them (run order = click order, numbered badges), reorder with ↑↓, remove with ✕, plus a **stop-mode** selector (`run all` / `stop on first fix` / `stop on first clean`) and a **reviewer-applies** toggle. Task metadata gains `reviewers: string[]` (ordered, replacing the single `reviewer`), `reviewStopMode`, and `reviewerApplies`; a read-side `normalizeReviewers()` (server `server/lib/validation.js` + client mirror in `constants.js`) keeps legacy single-`reviewer` tasks/schedules working. The agent prompts thread the list through as slashdo `--review-with a,b,c [--review-stop-on-findings|--review-stop-on-clean] [--reviewer-applies]` on the self-completion path, and the system-spawned review-loop follow-up agent runs each reviewer in the configured order (`buildReviewWithArgs()` builds the flag string; Copilot is pre-requested only when it *leads* the list — otherwise the follow-up requests it at its turn so it reviews the post-fix diff — and the follow-up still runs the CLI reviewers on non-GitHub forges where Copilot is unavailable).
+
## Changed
+- **Bumped the bundled `lib/slashdo` submodule v2.18.0 → v3.1.0.** v3.1.0's `/do:pr` / `/do:release` accept an ordered, comma-separated `--review-with` list plus `--review-stop-on-*` and `--reviewer-applies` flags — the slashdo capability this release wires into the task forms. Added `.claude/commands/do/` symlinks for the new `depfree` / `pr-better` / `scan` commands so the in-repo project slash-command set matches the vendored submodule.
- `data.sample/` renamed to `data.reference/` to reflect its actual role: the canonical reference / seed source consumed by `scripts/setup-data.js` (and by migrations that look up the post-migration shipped version of a file). The old name implied "optional samples"; the new name conveys "this is what `./data/` is bootstrapped from and compared against." All code, tests, and active docs (CLAUDE.md, README, docs/) updated; historical `.changelog/v*.md` entries kept as-is since they describe past releases. The `DATA_SAMPLE_DIR` constant in `server/index.js` is now `DATA_REFERENCE_DIR`; `sampleDir` in `setup-data.js` is now `referenceDir`.
- `server/services/universeBuilder.js` rewritten to consume `collectionStore` instead of `readJSONFile` + `atomicWrite` against a monolithic file. The per-entity `CURRENT_SCHEMA_VERSION = 4` (stamped INSIDE each universe record) is preserved unchanged — it describes record shape and is orthogonal to the new type-level `schemaVersion: 5` (storage layout). Cross-record state (`runs[]` history) moves to `data/universes/index.json` under `config.runs`. Per-record edits no longer serialize against unrelated universe edits — concurrent PATCHes on different universes now run in parallel.
- `server/services/dataSync.js` universe-sync category points at the new `data/universes/` directory. `readFingerprintMap` walks two levels deep so per-record edits invalidate the cache; the dir layout's `index.json` mtime catches add/remove/edit at every nesting level. `getUniverseSnapshot()` reads via `listUniverses({ includeDeleted: true })` so peer sync sees the same set tombstones included.
diff --git a/.claude/commands/do/depfree.md b/.claude/commands/do/depfree.md
new file mode 120000
index 0000000000..968f644da1
--- /dev/null
+++ b/.claude/commands/do/depfree.md
@@ -0,0 +1 @@
+../../../lib/slashdo/commands/do/depfree.md
\ No newline at end of file
diff --git a/.claude/commands/do/pr-better.md b/.claude/commands/do/pr-better.md
new file mode 120000
index 0000000000..a4ce7a32ae
--- /dev/null
+++ b/.claude/commands/do/pr-better.md
@@ -0,0 +1 @@
+../../../lib/slashdo/commands/do/pr-better.md
\ No newline at end of file
diff --git a/.claude/commands/do/scan.md b/.claude/commands/do/scan.md
new file mode 120000
index 0000000000..ab98da7da6
--- /dev/null
+++ b/.claude/commands/do/scan.md
@@ -0,0 +1 @@
+../../../lib/slashdo/commands/do/scan.md
\ No newline at end of file
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsx
new file mode 100644
index 0000000000..42f66394ba
--- /dev/null
+++ b/client/src/components/cos/ReviewerPicker.jsx
@@ -0,0 +1,150 @@
+import { useId } from 'react';
+import { Plus, X, ChevronUp, ChevronDown } from 'lucide-react';
+import {
+ REVIEWER_OPTIONS,
+ REVIEW_STOP_MODES,
+ DEFAULT_REVIEW_STOP_MODE
+} from './constants';
+
+const labelFor = (value) => REVIEWER_OPTIONS.find(o => o.value === value)?.label || value;
+
+/**
+ * Ordered multi-reviewer picker. Click a reviewer to append it (run order =
+ * click order), reorder with the arrows, remove with ✕. Maps to slashdo's
+ * `--review-with a,b,c` plus the stop-mode / `--reviewer-applies` flags.
+ *
+ * Controlled: emits the full next shape via onChange so the parent can store
+ * `reviewers` / `reviewStopMode` / `reviewerApplies` however it persists them.
+ */
+export default function ReviewerPicker({
+ reviewers = [],
+ stopMode = DEFAULT_REVIEW_STOP_MODE,
+ reviewerApplies = false,
+ onChange,
+ disabled = false
+}) {
+ const id = useId();
+ // 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
+ // reorder/remove. An empty list shows the "defaults to Copilot" hint and lets
+ // the user clear copilot; the server/submit layer resolves [] → ['copilot'].
+ const selected = Array.isArray(reviewers) ? [...new Set(reviewers)] : [];
+ const available = REVIEWER_OPTIONS.filter(o => !selected.includes(o.value));
+ const hasNonCopilot = selected.some(r => r !== 'copilot');
+
+ const emit = (next) => onChange?.({
+ reviewers: selected,
+ stopMode,
+ reviewerApplies,
+ ...next
+ });
+
+ const add = (value) => emit({ reviewers: [...selected, value] });
+ const remove = (value) => emit({ reviewers: selected.filter(r => r !== value) });
+ const move = (index, delta) => {
+ const target = index + delta;
+ if (target < 0 || target >= selected.length) return;
+ const next = [...selected];
+ [next[index], next[target]] = [next[target], next[index]];
+ emit({ reviewers: next });
+ };
+
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-xs text-gray-500 mr-1">Reviewers (in order):</span>
+ {selected.map((value, index) => (
+ <span
+ key={value}
+ className="inline-flex items-center gap-1 pl-1.5 pr-1 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300"
+ title={REVIEWER_OPTIONS.find(o => o.value === value)?.description}
+ >
+ <span className="text-port-accent font-mono">{index + 1}.</span>
+ {labelFor(value)}
+ <button
+ type="button"
+ disabled={disabled || index === 0}
+ onClick={() => move(index, -1)}
+ className="text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
+ aria-label={`Move ${labelFor(value)} earlier`}
+ >
+ <ChevronUp size={12} />
+ </button>
+ <button
+ type="button"
+ disabled={disabled || index === selected.length - 1}
+ onClick={() => move(index, 1)}
+ className="text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
+ aria-label={`Move ${labelFor(value)} later`}
+ >
+ <ChevronDown size={12} />
+ </button>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => remove(value)}
+ className="text-gray-500 hover:text-port-error"
+ aria-label={`Remove ${labelFor(value)}`}
+ >
+ <X size={12} />
+ </button>
+ </span>
+ ))}
+ {selected.length === 0 && (
+ <span className="text-xs text-gray-600 italic">none — defaults to Copilot</span>
+ )}
+ </div>
+
+ {available.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-xs text-gray-600 mr-1">Add:</span>
+ {available.map(opt => (
+ <button
+ key={opt.value}
+ type="button"
+ disabled={disabled}
+ onClick={() => add(opt.value)}
+ title={opt.description}
+ 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} />
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {selected.length >= 2 && (
+ <div className="flex items-center gap-2">
+ <label htmlFor={`${id}-stopmode`} className="text-xs text-gray-500">Stop mode:</label>
+ <select
+ id={`${id}-stopmode`}
+ value={stopMode}
+ disabled={disabled}
+ onChange={e => emit({ stopMode: e.target.value })}
+ className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px]"
+ >
+ {REVIEW_STOP_MODES.map(m => (
+ <option key={m.value} value={m.value} title={m.description}>{m.label}</option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {hasNonCopilot && (
+ <label htmlFor={`${id}-applies`} className="flex items-center gap-2 cursor-pointer select-none text-xs text-gray-500">
+ <input
+ id={`${id}-applies`}
+ type="checkbox"
+ checked={reviewerApplies}
+ disabled={disabled}
+ onChange={e => emit({ reviewerApplies: e.target.checked })}
+ className="w-3.5 h-3.5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0"
+ />
+ Reviewer applies fixes (CLI edits the working tree; no effect on Copilot)
+ </label>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/ReviewerPicker.test.jsx b/client/src/components/cos/ReviewerPicker.test.jsx
new file mode 100644
index 0000000000..7462eefc87
--- /dev/null
+++ b/client/src/components/cos/ReviewerPicker.test.jsx
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import ReviewerPicker from './ReviewerPicker';
+
+describe('ReviewerPicker', () => {
+ it('renders the selected reviewers in order with numbered badges', () => {
+ render(<ReviewerPicker reviewers={['codex', 'gemini', 'copilot']} onChange={() => {}} />);
+ expect(screen.getByText('1.')).toBeInTheDocument();
+ expect(screen.getByText('2.')).toBeInTheDocument();
+ expect(screen.getByText('3.')).toBeInTheDocument();
+ // The not-yet-selected reviewer (claude) shows in the Add row.
+ expect(screen.getByRole('button', { name: /Claude/ })).toBeInTheDocument();
+ });
+
+ it('shows the empty-state hint when no reviewers are selected', () => {
+ render(<ReviewerPicker reviewers={[]} onChange={() => {}} />);
+ expect(screen.getByText(/none — defaults to Copilot/)).toBeInTheDocument();
+ });
+
+ it('de-dupes a malformed list with duplicates (order-preserving)', () => {
+ render(<ReviewerPicker reviewers={['codex', 'codex', 'gemini']} onChange={() => {}} />);
+ // Two distinct pills (badges 1 and 2), not three.
+ expect(screen.getByText('1.')).toBeInTheDocument();
+ expect(screen.getByText('2.')).toBeInTheDocument();
+ expect(screen.queryByText('3.')).not.toBeInTheDocument();
+ });
+
+ it('emits an empty list when the last reviewer is removed (server resolves to copilot)', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<ReviewerPicker reviewers={['copilot']} onChange={onChange} />);
+ await user.click(screen.getByLabelText('Remove Copilot'));
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ reviewers: [] }));
+ });
+
+ it('appends a reviewer in click order on add', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<ReviewerPicker reviewers={['copilot']} onChange={onChange} />);
+ await user.click(screen.getByRole('button', { name: /Codex/ }));
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ reviewers: ['copilot', 'codex'] }));
+ });
+
+ it('reorders with the up arrow', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<ReviewerPicker reviewers={['codex', 'gemini', 'copilot']} onChange={onChange} />);
+ await user.click(screen.getByLabelText('Move Gemini earlier'));
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ reviewers: ['gemini', 'codex', 'copilot'] }));
+ });
+
+ it('removes a reviewer', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<ReviewerPicker reviewers={['codex', 'copilot']} onChange={onChange} />);
+ await user.click(screen.getByLabelText('Remove Codex'));
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ reviewers: ['copilot'] }));
+ });
+
+ it('shows the stop-mode select only for 2+ reviewers', () => {
+ const { rerender } = render(<ReviewerPicker reviewers={['codex']} onChange={() => {}} />);
+ expect(screen.queryByText('Stop mode:')).not.toBeInTheDocument();
+ rerender(<ReviewerPicker reviewers={['codex', 'gemini']} onChange={() => {}} />);
+ expect(screen.getByText('Stop mode:')).toBeInTheDocument();
+ });
+
+ it('shows the reviewer-applies toggle only when a non-copilot reviewer is present', () => {
+ const { rerender } = render(<ReviewerPicker reviewers={['copilot']} onChange={() => {}} />);
+ expect(screen.queryByText(/Reviewer applies fixes/)).not.toBeInTheDocument();
+ rerender(<ReviewerPicker reviewers={['codex']} onChange={() => {}} />);
+ expect(screen.getByText(/Reviewer applies fixes/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index dcbe84c76f..422833df69 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -6,7 +6,8 @@ import * as api from '../../services/api';
import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';
import { formatBytes } from '../../utils/formatters';
import { filterSelectableModels, isTuiProvider, isCliProvider } from '../../utils/providers';
-import { REVIEWER_OPTIONS, DEFAULT_REVIEWER } from './constants';
+import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from './constants';
+import ReviewerPicker from './ReviewerPicker';
const isCodexProvider = (provider) => {
if (!provider) return false;
@@ -24,7 +25,9 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [openPR, setOpenPR] = useState(false);
const [simplify, setSimplify] = useState(true);
const [reviewLoop, setReviewLoop] = useState(false);
- const [reviewer, setReviewer] = useState(DEFAULT_REVIEWER);
+ const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);
+ const [reviewStopMode, setReviewStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);
+ const [reviewerApplies, setReviewerApplies] = useState(false);
const [createJiraTicket, setCreateJiraTicket] = useState(false);
const [screenshots, setScreenshots] = useState([]);
const [attachments, setAttachments] = useState([]);
@@ -221,7 +224,9 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
openPR,
simplify,
reviewLoop,
- reviewer: reviewLoop ? reviewer : undefined,
+ reviewers: reviewLoop ? reviewers : undefined,
+ reviewStopMode: reviewLoop ? reviewStopMode : undefined,
+ reviewerApplies: reviewLoop ? reviewerApplies : undefined,
screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,
attachments: attachments.length > 0 ? attachments.map(a => ({
filename: a.filename,
@@ -454,17 +459,18 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
</span>
</label>
{reviewLoop && (
- <select
- value={reviewer}
- onChange={(e) => setReviewer(e.target.value)}
- className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px]"
- title="Override the default reviewer for the review loop (--review-with)"
- aria-label="Reviewer for review loop"
- >
- {REVIEWER_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value} title={opt.description}>{opt.label}</option>
- ))}
- </select>
+ <div className="basis-full mt-1">
+ <ReviewerPicker
+ reviewers={reviewers}
+ stopMode={reviewStopMode}
+ reviewerApplies={reviewerApplies}
+ onChange={({ reviewers: r, stopMode, reviewerApplies: ra }) => {
+ setReviewers(r);
+ setReviewStopMode(stopMode);
+ setReviewerApplies(ra);
+ }}
+ />
+ </div>
)}
{appHasJira && (
<label className="flex items-center gap-2 cursor-pointer select-none whitespace-nowrap py-1">
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 4a854d4195..1b583366ec 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -70,6 +70,33 @@ export const REVIEWER_OPTIONS = [
{ value: 'codex', label: 'Codex', description: 'Codex CLI reviews the PR diff' }
];
export const DEFAULT_REVIEWER = 'copilot';
+export const DEFAULT_REVIEWERS = ['copilot'];
+
+// 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 = [
+ { value: 'all', label: 'Run all', description: 'Run every reviewer in order before merging (default)' },
+ { value: 'on-findings', label: 'Stop on first fix', description: 'Stop after the first reviewer that landed a fix' },
+ { value: 'on-clean', label: 'Stop on first clean', description: 'Stop after the first reviewer that reports zero findings' }
+];
+export const DEFAULT_REVIEW_STOP_MODE = 'all';
+
+// Resolve metadata to an ordered, deduped reviewer list (client mirror of the
+// server's normalizeReviewers): prefers `reviewers`, falls back to legacy
+// single `reviewer`, defaults to `['copilot']`.
+const REVIEWER_VALUES = REVIEWER_OPTIONS.map(o => o.value);
+export function normalizeReviewers(meta) {
+ 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) {
+ if (REVIEWER_VALUES.includes(r) && !seen.has(r)) { seen.add(r); out.push(r); }
+ }
+ return out.length ? out : [...DEFAULT_REVIEWERS];
+}
// Returns the Tailwind className string for an agent option toggle button.
// effective: whether the option is on (global + override resolved)
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index a08ce6863b..f19bae8b80 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -28,7 +28,7 @@ import MarkdownOutput from '../MarkdownOutput';
import Modal from '../../ui/Modal';
import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
-import { DEFAULT_REVIEWER } from '../constants';
+import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
// Extract task type from description (matches server-side extractTaskType)
@@ -606,13 +606,20 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
Simplify
</span>
)}
- {agent.metadata.configReviewLoop && (
- <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-indigo-500/15 text-indigo-400"
- title={`Review loop enabled — agent will iterate on PR feedback (reviewer: ${agent.metadata.configReviewer || DEFAULT_REVIEWER})`}>
- <RefreshCw size={10} aria-hidden="true" />
- Review{agent.metadata.configReviewer && agent.metadata.configReviewer !== DEFAULT_REVIEWER ? `: ${agent.metadata.configReviewer}` : ''}
- </span>
- )}
+ {agent.metadata.configReviewLoop && (() => {
+ const reviewers = normalizeReviewers({
+ reviewers: agent.metadata.configReviewers,
+ reviewer: agent.metadata.configReviewer
+ });
+ const isDefault = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER;
+ return (
+ <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-indigo-500/15 text-indigo-400"
+ title={`Review loop enabled — agent will iterate on PR feedback (reviewers: ${reviewers.join(' → ')})`}>
+ <RefreshCw size={10} aria-hidden="true" />
+ Review{isDefault ? '' : `: ${reviewers.join(', ')}`}
+ </span>
+ );
+ })()}
</div>
)}
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 8f5c1e5f8c..f57435c829 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -5,7 +5,8 @@ import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import AppIcon from '../../AppIcon';
import CronInput from '../../CronInput';
-import { AGENT_OPTIONS, REVIEWER_OPTIONS, DEFAULT_REVIEWER, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';
+import { AGENT_OPTIONS, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';
+import ReviewerPicker from '../ReviewerPicker';
import { isCronExpression, describeCron } from '../../../utils/cronHelpers';
import ToggleSwitch from '../../ToggleSwitch';
import { filterSelectableModels } from '../../../utils/providers';
@@ -498,23 +499,20 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,
})}
</div>
{(config.taskMetadata?.reviewLoop || config.taskMetadata?.openPR) && (
- <div className="mt-3 flex items-center gap-2 pl-2">
- <label htmlFor={`reviewer-${taskType}`} className="text-xs text-gray-500">Reviewer:</label>
- <select
- id={`reviewer-${taskType}`}
- value={config.taskMetadata?.reviewer || DEFAULT_REVIEWER}
- onChange={e => onUpdate(taskType, {
- taskMetadata: { ...(config.taskMetadata || {}), reviewer: e.target.value }
- })}
+ <div className="mt-3 pl-2">
+ <ReviewerPicker
+ reviewers={config.taskMetadata?.reviewers ?? (config.taskMetadata?.reviewer ? [config.taskMetadata.reviewer] : DEFAULT_REVIEWERS)}
+ stopMode={config.taskMetadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE}
+ reviewerApplies={config.taskMetadata?.reviewerApplies === true || config.taskMetadata?.reviewerApplies === 'true'}
disabled={updating}
- className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px]"
- title="Reviewer for the post-PR review loop (--review-with). Copilot = GitHub's auto-review; the others run a local CLI critique via /do:rpr."
- aria-label="Reviewer for review loop"
- >
- {REVIEWER_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value} title={opt.description}>{opt.label}</option>
- ))}
- </select>
+ onChange={({ reviewers, stopMode, reviewerApplies }) => {
+ // Drop the legacy single `reviewer` key so storage converges on `reviewers`.
+ const { reviewer, ...rest } = config.taskMetadata || {};
+ onUpdate(taskType, {
+ taskMetadata: { ...rest, reviewers, reviewStopMode: stopMode, reviewerApplies }
+ });
+ }}
+ />
</div>
)}
</div>
diff --git a/lib/slashdo b/lib/slashdo
index e3dabea334..19c6a7d552 160000
--- a/lib/slashdo
+++ b/lib/slashdo
@@ -1 +1 @@
-Subproject commit e3dabea334fd797cdeeee0254c29d4d823adc728
+Subproject commit 19c6a7d552e7b19eaca2d34fa997003bec7e2e65
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 7b25c268ee..8da83deb16 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -552,6 +552,48 @@ export const searchQuerySchema = z.object({
// client/src/components/cos/constants.js → REVIEWER_OPTIONS.
export const REVIEWER_VALUES = ['copilot', 'claude', 'gemini', 'codex'];
export const DEFAULT_REVIEWER = 'copilot';
+export const DEFAULT_REVIEWERS = ['copilot'];
+// 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';
+
+/**
+ * Resolve task metadata to an ordered, deduped reviewer list. Prefers the new
+ * `reviewers` array; falls back to the legacy single `reviewer` string; defaults
+ * to `['copilot']`. Filters to known reviewers and preserves first-occurrence order.
+ */
+export function normalizeReviewers(meta) {
+ 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) {
+ if (REVIEWER_VALUES.includes(r) && !seen.has(r)) { seen.add(r); out.push(r); }
+ }
+ return out.length ? out : [...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).
+ */
+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);
+ const parts = [];
+ if (!isDefaultOnly) parts.push(`--review-with ${list.join(',')}`);
+ if (list.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(' ');
+}
export const createCosTaskSchema = z.object({
description: z.string().min(1),
@@ -591,6 +633,12 @@ export const createCosTaskSchema = z.object({
v => v === '' ? undefined : v,
z.enum(REVIEWER_VALUES).optional()
),
+ reviewers: z.array(z.enum(REVIEWER_VALUES)).optional(),
+ reviewStopMode: z.enum(REVIEW_STOP_MODES).optional(),
+ reviewerApplies: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
});
export const updateCosTaskSchema = z.object({
@@ -1063,8 +1111,12 @@ export const MAX_TOTAL_SPAWNS = 5;
const ALLOWED_TASK_METADATA_KEYS = [...PIPELINE_BEHAVIOR_FLAGS, 'readOnly'];
/**
- * Sanitize taskMetadata to only allowed agent-option keys with boolean values.
- * Prevents prototype pollution and reserved metadata field overrides.
+ * Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
+ * (`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.
* Returns a clean plain object or null if input is empty/invalid.
*/
export function sanitizeTaskMetadata(raw) {
@@ -1077,11 +1129,28 @@ export function sanitizeTaskMetadata(raw) {
hasKeys = true;
}
}
- // `reviewer` is a constrained string (copilot/claude/gemini/codex), not a boolean.
+ // `reviewer` is a legacy single constrained string (copilot/claude/gemini/codex).
if (Object.prototype.hasOwnProperty.call(raw, 'reviewer') && REVIEWER_VALUES.includes(raw.reviewer)) {
clean.reviewer = raw.reviewer;
hasKeys = true;
}
+ // `reviewers` is the ordered multi-reviewer list — filter to known values, dedupe, preserve order.
+ if (Array.isArray(raw.reviewers)) {
+ const seen = new Set();
+ const list = [];
+ for (const r of raw.reviewers) {
+ if (REVIEWER_VALUES.includes(r) && !seen.has(r)) { seen.add(r); list.push(r); }
+ }
+ if (list.length) { clean.reviewers = list; hasKeys = true; }
+ }
+ if (Object.prototype.hasOwnProperty.call(raw, 'reviewStopMode') && REVIEW_STOP_MODES.includes(raw.reviewStopMode)) {
+ clean.reviewStopMode = raw.reviewStopMode;
+ hasKeys = true;
+ }
+ if (Object.prototype.hasOwnProperty.call(raw, 'reviewerApplies') && typeof raw.reviewerApplies === 'boolean') {
+ clean.reviewerApplies = raw.reviewerApplies;
+ hasKeys = true;
+ }
// Pass through pipeline config (validated shape: object with stages array)
if (raw.pipeline && typeof raw.pipeline === 'object' && Array.isArray(raw.pipeline.stages)) {
clean.pipeline = raw.pipeline;
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index bf8c91fac1..f6868f3c68 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -9,7 +9,10 @@ import {
featureAgentUpdateSchema,
validate,
sanitizeTaskMetadata,
- stageConfigUpdateSchema
+ stageConfigUpdateSchema,
+ normalizeReviewers,
+ buildReviewWithArgs,
+ createCosTaskSchema
} from './validation.js';
describe('validation.js', () => {
@@ -511,6 +514,79 @@ describe('validation.js', () => {
.toEqual({ useWorktree: true });
});
+ it('should accept an ordered reviewers list, dedupe, and drop unknowns', () => {
+ expect(sanitizeTaskMetadata({ reviewers: ['codex', 'gemini', 'copilot'] }))
+ .toEqual({ reviewers: ['codex', 'gemini', 'copilot'] });
+ expect(sanitizeTaskMetadata({ reviewers: ['codex', 'codex', 'bogus', 'gemini'] }))
+ .toEqual({ reviewers: ['codex', 'gemini'] });
+ expect(sanitizeTaskMetadata({ reviewers: ['nope'] })).toBeNull();
+ });
+
+ it('should accept reviewStopMode and reviewerApplies', () => {
+ expect(sanitizeTaskMetadata({ reviewStopMode: 'on-clean' })).toEqual({ reviewStopMode: 'on-clean' });
+ expect(sanitizeTaskMetadata({ reviewStopMode: 'bogus' })).toBeNull();
+ expect(sanitizeTaskMetadata({ reviewerApplies: true })).toEqual({ reviewerApplies: true });
+ expect(sanitizeTaskMetadata({ reviewerApplies: 'yes' })).toBeNull();
+ });
+ });
+
+ describe('normalizeReviewers', () => {
+ it('defaults to [copilot] when absent/empty', () => {
+ expect(normalizeReviewers(undefined)).toEqual(['copilot']);
+ expect(normalizeReviewers({})).toEqual(['copilot']);
+ expect(normalizeReviewers({ reviewers: [] })).toEqual(['copilot']);
+ expect(normalizeReviewers({ reviewers: ['bogus'] })).toEqual(['copilot']);
+ });
+
+ it('prefers reviewers, falls back to legacy reviewer, preserves order + dedupes', () => {
+ expect(normalizeReviewers({ reviewer: 'codex' })).toEqual(['codex']);
+ expect(normalizeReviewers({ reviewers: ['gemini', 'codex', 'gemini'] })).toEqual(['gemini', 'codex']);
+ // `reviewers` wins over legacy `reviewer`.
+ expect(normalizeReviewers({ reviewers: ['claude'], reviewer: 'codex' })).toEqual(['claude']);
+ });
+ });
+
+ describe('buildReviewWithArgs', () => {
+ it('emits nothing for the lone default copilot', () => {
+ expect(buildReviewWithArgs(['copilot'])).toBe('');
+ expect(buildReviewWithArgs([])).toBe('');
+ });
+
+ it('emits the ordered comma list when not lone-default', () => {
+ expect(buildReviewWithArgs(['codex'])).toBe('--review-with codex');
+ expect(buildReviewWithArgs(['codex', 'gemini', 'copilot'])).toBe('--review-with codex,gemini,copilot');
+ });
+
+ it('adds stop-mode only for 2+ reviewers and reviewer-applies only with a CLI reviewer', () => {
+ expect(buildReviewWithArgs(['codex', 'copilot'], 'on-findings', true))
+ .toBe('--review-with codex,copilot --review-stop-on-findings --reviewer-applies');
+ // single reviewer → no stop-mode flag
+ expect(buildReviewWithArgs(['codex'], 'on-clean', true))
+ .toBe('--review-with codex --reviewer-applies');
+ // copilot-only → reviewer-applies suppressed (no-op on copilot)
+ expect(buildReviewWithArgs(['copilot'], 'all', true)).toBe('');
+ });
+ });
+
+ describe('createCosTaskSchema reviewers fields', () => {
+ it('accepts reviewers/reviewStopMode/reviewerApplies', () => {
+ const parsed = createCosTaskSchema.safeParse({
+ description: 'do a thing',
+ reviewers: ['codex', 'gemini', 'copilot'],
+ reviewStopMode: 'on-clean',
+ reviewerApplies: true
+ });
+ expect(parsed.success).toBe(true);
+ expect(parsed.data.reviewers).toEqual(['codex', 'gemini', 'copilot']);
+ expect(parsed.data.reviewStopMode).toBe('on-clean');
+ expect(parsed.data.reviewerApplies).toBe(true);
+ });
+
+ it('rejects an unknown reviewer or stop-mode', () => {
+ expect(createCosTaskSchema.safeParse({ description: 'x', reviewers: ['bogus'] }).success).toBe(false);
+ expect(createCosTaskSchema.safeParse({ description: 'x', reviewStopMode: 'nope' }).success).toBe(false);
+ });
+
it('should reject prototype pollution keys', () => {
expect(sanitizeTaskMetadata({ __proto__: { malicious: true } })).toBeNull();
expect(sanitizeTaskMetadata({ constructor: true })).toBeNull();
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index e6ec7edbc9..726e9abdf9 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -18,8 +18,8 @@ import { completeExecution, errorExecution } from './toolStateMachine.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
-import { activeAgents, userTerminatedAgents, metaStringOr } from './agentState.js';
-import { DEFAULT_REVIEWER } from '../lib/validation.js';
+import { activeAgents, userTerminatedAgents } from './agentState.js';
+import { normalizeReviewers, DEFAULT_REVIEW_STOP_MODE } from '../lib/validation.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
@@ -582,7 +582,9 @@ export async function spawnDirectly({
await cleanupWorktreeFn(agentId, finalSuccess, {
openPR: directAgentOwnsPR ? false : directOpenPR,
requestCopilotReview: !directAgentOwnsPR && directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
- reviewer: metaStringOr(task.metadata?.reviewer, DEFAULT_REVIEWER),
+ reviewers: normalizeReviewers(task.metadata),
+ reviewStopMode: task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE,
+ reviewerApplies: isTruthyMetaFn(task.metadata?.reviewerApplies),
skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
description: task.description,
agentOutput: outputBuffer,
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index e529d1c854..7a9ed0885e 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -268,4 +268,35 @@ describe('stream error containment', () => {
);
expect(logged).toBe(true);
});
+
+ it('threads the ordered reviewers list (not a stale singular `reviewer`) into worktree cleanup', async () => {
+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ const args = {
+ ...minimalArgs,
+ task: {
+ id: 'task-rv',
+ description: 'do stuff',
+ metadata: { reviewers: ['codex', 'gemini'], reviewStopMode: 'on-clean', reviewerApplies: true },
+ },
+ cleanupWorktreeFn,
+ isTruthyMetaFn: (v) => v === true,
+ };
+
+ spawnDirectly(args);
+ await new Promise((r) => setTimeout(r, 10));
+ fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));
+ await new Promise((r) => setTimeout(r, 50));
+ fakeProcess.emit('close', 0);
+ // The close handler is fire-and-forget (spawnDirectly returns agentId
+ // synchronously) — wait for the async handler's finally block to run.
+ await new Promise((r) => setTimeout(r, 80));
+
+ expect(cleanupWorktreeFn).toHaveBeenCalledTimes(1);
+ const opts = cleanupWorktreeFn.mock.calls[0][2];
+ expect(opts.reviewers).toEqual(['codex', 'gemini']);
+ expect(opts.reviewStopMode).toBe('on-clean');
+ expect(opts.reviewerApplies).toBe(true);
+ // The removed singular key must NOT be passed.
+ expect(opts.reviewer).toBeUndefined();
+ });
});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 3129b87562..a13d230720 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -34,8 +34,8 @@ import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import { selectModelForTask } from './agentModelSelection.js';
import { processAgentCompletion } from './agentCompletion.js';
-import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta, metaStringOr } from './agentState.js';
-import { DEFAULT_REVIEWER } from '../lib/validation.js';
+import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers } from '../lib/validation.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { writeFile } from 'fs/promises';
@@ -512,7 +512,7 @@ export async function spawnAgentForTask(task) {
configOpenPR: isTruthyMeta(task.metadata?.openPR),
configSimplify: isTruthyMeta(task.metadata?.simplify),
configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),
- configReviewer: metaStringOr(task.metadata?.reviewer, null),
+ configReviewers: normalizeReviewers(task.metadata),
configUseWorktree: !!worktreeInfo,
configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,
configCodingOnMain: !worktreeInfo && !jiraBranchName
@@ -1311,7 +1311,9 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {
openPR: agentOwnsPR ? false : taskOpenPR,
requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,
- reviewer: metaStringOr(agent.task?.metadata?.reviewer, DEFAULT_REVIEWER),
+ reviewers: normalizeReviewers(agent.task?.metadata),
+ reviewStopMode: agent.task?.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE,
+ reviewerApplies: isTruthyMeta(agent.task?.metadata?.reviewerApplies),
skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
description: task?.description,
agentOutput: outputBuffer,
@@ -1355,17 +1357,20 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
* Clean up a worktree for a completed agent.
* Reads worktree metadata from the agent's registered state and removes the worktree.
* When openPR is true, pushes the branch and creates a PR instead of auto-merging.
- * When requestCopilotReview is also true, requests an initial Copilot review on the new
- * PR and spawns a follow-up internal task that runs the full /do:rpr loop and merges
- * once the review is clean — that follow-up is the part the user expects to "keep
- * looping until ready to merge." `reviewer` selects which reviewer the follow-up uses
- * (default `copilot` requests a native GitHub Copilot review; `claude`/`gemini`/`codex`
- * skip the GH reviewer-API call and let the follow-up agent drive the CLI-based review).
+ * When requestCopilotReview is also true, spawns a follow-up internal task that drives
+ * the multi-reviewer loop and merges once the review chain is clean — that follow-up is
+ * the part the user expects to "keep looping until ready to merge."
+ * `reviewers` is the ordered reviewer list (e.g. `[codex, gemini, copilot]`); the native
+ * GitHub Copilot review is pre-requested here only when copilot LEADS the list (otherwise
+ * the follow-up requests it at its turn so Copilot sees the post-fix diff). `reviewStopMode`
+ * (`all`/`on-findings`/`on-clean`) and `reviewerApplies` are threaded into the follow-up's
+ * metadata. CLI reviewers (claude/gemini/codex) are always driven by the follow-up agent,
+ * which works on any forge; copilot is GitHub-only and dropped on non-GitHub remotes.
* When skipMerge is true (review-loop follow-up agents), the cleanup never auto-merges
* 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, reviewer = DEFAULT_REVIEWER, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, 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 [];
@@ -1443,38 +1448,37 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
const cliName = prResult.cli || 'gh';
emitLog('success', `🌳 Created PR: ${prResult.url} (${cliName}${prResult.account ? ` authed as ${prResult.account}` : ''})`, { agentId, branchName: worktreeBranch, cli: prResult.cli, account: prResult.account, owner: prResult.owner, host: prResult.host });
- let copilotReviewOk = false;
- let copilotReviewSkipped = false;
- const usesCopilotReviewer = reviewer === DEFAULT_REVIEWER;
- // Only the `copilot` reviewer maps to the GitHub native reviewer API. For
- // claude/gemini/codex, the follow-up agent invokes the CLI itself, so we
- // skip the GH pre-request but still spawn the follow-up below.
- if (shouldRequestCopilot && usesCopilotReviewer) {
+ const reviewerList = normalizeReviewers({ reviewers });
+ const copilotIsFirst = reviewerList[0] === DEFAULT_REVIEWER;
+ const nonCopilotReviewers = reviewerList.filter(r => r !== DEFAULT_REVIEWER);
+ // Pre-request the native Copilot review ONLY when copilot LEADS the order — it
+ // then reviews the freshly-opened PR. When copilot is configured after a CLI
+ // reviewer (e.g. [codex, copilot]), pre-requesting now would make Copilot review
+ // the stale pre-CLI-fix diff; instead the follow-up agent requests it at copilot's
+ // turn, after the earlier reviewer's fixes are pushed. This pre-request is a
+ // latency optimization only — the follow-up requests Copilot at its turn
+ // regardless, so a failed/absent pre-request is recoverable (no reviewer dropped).
+ if (shouldRequestCopilot && copilotIsFirst) {
const reviewResult = await git.requestCopilotReview(worktreePath, prResult.url).catch(err => ({ success: false, error: err.message }));
if (reviewResult.success && reviewResult.skipped) {
- // Non-GitHub forge (e.g. GitLab MR) — Copilot reviewer doesn't exist there. Log info, no warning.
- emitLog('info', `🤖 Skipping Copilot review request for ${prResult.url} (non-GitHub forge)`, { agentId, prUrl: prResult.url });
- copilotReviewSkipped = true;
+ emitLog('info', `🤖 Skipping Copilot pre-request for ${prResult.url} (non-GitHub forge)`, { agentId, prUrl: prResult.url });
} else if (reviewResult.success) {
- emitLog('success', `🤖 Requested Copilot review on ${prResult.url}`, { agentId, prUrl: prResult.url });
- copilotReviewOk = true;
+ emitLog('success', `🤖 Requested initial Copilot review on ${prResult.url}`, { agentId, prUrl: prResult.url });
} else {
- emitLog('warn', `🤖 Failed to request Copilot review on ${prResult.url}: ${reviewResult.error}`, { agentId, prUrl: prResult.url });
+ emitLog('warn', `🤖 Copilot pre-request failed for ${prResult.url}: ${reviewResult.error} — follow-up will re-request at its turn`, { agentId, prUrl: prResult.url });
warnings.push(`Copilot review request failed for ${prResult.url}: ${reviewResult.error}`);
}
- } else if (shouldRequestCopilot && !usesCopilotReviewer) {
- emitLog('info', `🤖 Skipping native Copilot review request — follow-up will use ${reviewer} CLI`, { agentId, prUrl: prResult.url, reviewer });
+ }
+ if (shouldRequestCopilot && nonCopilotReviewers.length > 0) {
+ emitLog('info', `🤖 Follow-up will run CLI reviewers: ${nonCopilotReviewers.join(', ')}`, { agentId, prUrl: prResult.url });
}
- // Spawn the review-loop follow-up agent that runs /do:rpr until clean and merges.
- // Without this, the loop stops after the initial review request — the user-reported
- // "they only handle one review loop and then finish" bug.
- // For the `copilot` reviewer: only spawn when the GH review request succeeded
- // (the follow-up waits on a Copilot comment). For non-Copilot reviewers there's
- // no pre-request to wait on — the follow-up invokes the CLI itself.
- const canSpawnFollowUp = usesCopilotReviewer
- ? (copilotReviewOk && !copilotReviewSkipped)
- : shouldRequestCopilot;
+ // Spawn the review-loop follow-up agent that runs the multi-reviewer loop until
+ // clean and merges. Hand it the FULL ordered list — the follow-up requests Copilot
+ // at copilot's turn (so a failed pre-request or copilot-only config still gets a
+ // review pass) and invokes the CLI reviewers itself. The only reviewer dropped is
+ // copilot on a non-GitHub forge, handled centrally in spawnReviewLoopFollowUp.
+ const canSpawnFollowUp = shouldRequestCopilot && reviewerList.length > 0;
if (canSpawnFollowUp) {
await spawnReviewLoopFollowUp({
originalAgentId: agentId,
@@ -1482,7 +1486,9 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
prUrl: prResult.url,
prBranch: worktreeBranch,
sourceWorkspace,
- reviewer
+ reviewers: reviewerList,
+ reviewStopMode,
+ reviewerApplies
}).catch(err => {
emitLog('warn', `🤖 Failed to spawn review-loop follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
warnings.push(`Review-loop follow-up spawn failed for ${prResult.url}: ${err.message}`);
@@ -1521,24 +1527,34 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
}
/**
- * Spawn an internal follow-up task that runs the Copilot review-and-fix loop
- * (per /do:rpr) on the just-created PR until it has zero unresolved comments,
- * then merges the PR. This is what makes the user-facing "review loop" actually
- * loop — the original agent only requests the *initial* Copilot review and
- * exits; without this follow-up, the loop ends after one iteration and the PR
- * is never merged.
+ * Spawn an internal follow-up task that drives the ordered multi-reviewer
+ * review-and-fix loop on the just-created PR until the configured reviewer chain
+ * is satisfied, then merges the PR. This is what makes the user-facing "review
+ * loop" actually loop — the original agent only opens the PR (and at most
+ * pre-requests Copilot when it leads) and exits; without this follow-up the loop
+ * ends after one iteration and the PR is never merged.
+ *
+ * `reviewers` is the ordered list (e.g. `[codex, gemini, copilot]`); the follow-up
+ * 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.
*
* 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, reviewer = DEFAULT_REVIEWER }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
if (!prUrl || !prBranch) return null;
const parsedPr = git.parsePullRequestUrl(prUrl);
- // Copilot reviewer is GitHub-only; CLI-based reviewers (claude/gemini/codex)
- // work on any forge because the agent invokes the CLI directly.
- if (reviewer === DEFAULT_REVIEWER && parsedPr && parsedPr.host && parsedPr.host !== 'github.com') return null;
+ // Copilot is GitHub-only; CLI-based reviewers (claude/gemini/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.
+ 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;
const appId = originalTask?.metadata?.app || null;
const sourceTaskDesc = originalTask?.description || 'CoS automated task';
@@ -1571,11 +1587,14 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
reviewLoopPRHost: parsedPr?.host ?? null,
reviewLoopPROwner: parsedPr?.owner ?? null,
reviewLoopPRRepo: parsedPr?.repo ?? null,
- reviewLoopReviewer: reviewer,
+ reviewLoopReviewers: effectiveReviewers,
+ reviewLoopStopMode: reviewStopMode,
+ reviewLoopReviewerApplies: reviewerApplies,
sourceTaskId: originalTask?.id || null,
sourceAgentId: originalAgentId || null,
- // skipCommitCheck: this task may exit cleanly with zero new commits if the
- // initial Copilot review came back clean. Don't false-positive that as failure.
+ // This follow-up may legitimately exit with zero new commits when every
+ // reviewer comes back clean — completion handling must not treat a
+ // zero-commit exit as a failure.
readOnly: false
},
autoApproved: true,
@@ -1583,7 +1602,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
};
await addTask(followUpTask, 'internal', { raw: true });
- emitLog('info', `🔁 Spawned Copilot review-loop follow-up task ${followUpTaskId} for PR ${prUrl}`, {
+ emitLog('info', `🔁 Spawned review-loop follow-up task ${followUpTaskId} (${effectiveReviewers.join(', ')}) for PR ${prUrl}`, {
taskId: followUpTaskId, prUrl, prBranch, sourceAgentId: originalAgentId, sourceTaskId: originalTask?.id
});
return followUpTask;
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 5a3d752399..b41c80641a 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -16,9 +16,8 @@ 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 } from '../lib/validation.js';
+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers, buildReviewWithArgs } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
-import { metaStringOr } from './agentState.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
@@ -214,51 +213,82 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const prOwner = metadata.reviewLoopPROwner ?? '';
const prRepo = metadata.reviewLoopPRRepo ?? '';
const sourceTaskId = metadata.sourceTaskId || 'unknown';
- const reviewer = metaStringOr(metadata.reviewLoopReviewer, DEFAULT_REVIEWER);
- const isCopilot = reviewer === DEFAULT_REVIEWER;
-
- // Per-reviewer wording. The `copilot` flow waits on a GitHub Copilot review
- // pre-requested by the system; non-Copilot flows invoke the chosen CLI
- // (claude/gemini/codex) directly against the PR diff.
- const initialReviewState = isCopilot
- ? 'The system has already requested an initial Copilot code review.'
- : `The system did NOT pre-request a reviewer because \`${reviewer}\` is a CLI-based reviewer — you must invoke \`${reviewer}\` yourself against the PR diff.`;
- const waitOrInvokeStep = isCopilot
- ? 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round).'
- : `Invoke the \`${reviewer}\` CLI against the PR diff (\`gh pr diff ${prNumber || ''}\` or \`gh pr view ${prNumber || ''} --json files\`) to produce a code review. Capture its findings as a list of concrete issues to address.`;
- const rerequestStep = isCopilot
- ? 'Re-request a Copilot review.'
- : `Re-run the \`${reviewer}\` CLI against the latest PR diff to collect a fresh review.`;
- const zeroCommentCondition = isCopilot
- ? 'Copilot returns "0 comments" / no unresolved threads'
- : `\`${reviewer}\` reports no further blocking findings (only nitpicks or approvals)`;
- const repeatedCommentsNote = isCopilot
- ? '**Repeated comments:** If a new Copilot round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on to merge.'
- : `**Repeated comments:** If a new \`${reviewer}\` round only re-raises feedback you intentionally rejected, treat that round as clean and move on to merge.`;
+ // Ordered reviewer list (back-compat: legacy single `reviewLoopReviewer`).
+ const reviewers = normalizeReviewers({
+ reviewers: Array.isArray(metadata.reviewLoopReviewers)
+ ? metadata.reviewLoopReviewers
+ : (metadata.reviewLoopReviewer ? [metadata.reviewLoopReviewer] : undefined)
+ });
+ const stopMode = metadata.reviewLoopStopMode || DEFAULT_REVIEW_STOP_MODE;
+ const reviewerApplies = metadata.reviewLoopReviewerApplies === true;
+ const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);
+ const hasCli = reviewers.some(r => r !== DEFAULT_REVIEWER);
+ const multi = reviewers.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 equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';
+
+ // First step: how to obtain a review. For a single copilot/CLI reviewer keep the
+ // focused wording; for a list, dispatch each reviewer in order. Only emit the
+ // per-reviewer-kind bullet that actually applies to the configured list.
+ 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 / gemini / 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).` : null,
+ ].filter(Boolean).join(' ');
+ const waitOrInvokeStep = multi
+ ? `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`
+ : (hasCopilot
+ ? 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.'
+ : `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.`);
+
+ 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.'
+ : stopMode === 'on-clean'
+ ? '**Stop mode (on-clean):** stop after the FIRST reviewer that reports zero findings; skip the remaining reviewers.'
+ : (multi ? '**Stop mode (all):** run every reviewer in the list, in order, before merging.' : '');
+
+ const applyNote = hasCli
+ ? (reviewerApplies
+ ? '**Reviewer applies:** let each CLI reviewer apply its own fixes to the working tree, then verify, run tests, and push.'
+ : "**Reviewer applies (off):** read each CLI reviewer's findings and apply the fixes yourself (default).")
+ : '';
+
+ const initialReviewState = (hasCopilot && copilotIsFirst)
+ ? 'The system has already requested the initial Copilot code review (Copilot leads the order).'
+ : hasCopilot
+ ? 'Copilot is configured after a CLI 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 CLI reviewers yourself.'
+ : 'The system did NOT pre-request a reviewer because the configured reviewers are CLI-based — you must invoke them 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);
if (verbose) {
return `
## Review-Loop Follow-up (PRIMARY OBJECTIVE)
A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} **Your job is to drive the review-and-fix loop to completion and merge the PR.**
-**Reviewer**: \`${reviewer}\` (equivalent to \`/do:rpr --review-with ${reviewer}\`).
-
-**Run this loop UNTIL the PR is clean per the reviewer OR you hit the iteration cap of 10:**
+**Reviewers (in order)**: ${reviewerLabel}${equiv}.
+${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}
+**Run this loop UNTIL all configured reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**
1. ${waitOrInvokeStep}
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
-3. ${rerequestStep}
-4. Repeat from step 1.
-5. When ${zeroCommentCondition}, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):
+3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
+4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):
\`\`\`bash
gh pr merge "${prUrl}" --squash --delete-branch
\`\`\`
${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : ''}
You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.
-6. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.
-7. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
+5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.
+6. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
-**Hard stop:** if the loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.
+**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.
${repeatedCommentsNote}
@@ -268,31 +298,31 @@ PR Details:
${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}
${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}
- **Source task**: ${sourceTaskId}
-- **Reviewer**: \`${reviewer}\`
-${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the procedure below, substitute \`${reviewer}\` for any reference to Copilot — the loop structure is the same but the reviewer source differs.\n\n${rprBody}\n` : ''}`;
+- **Reviewers**: ${reviewerLabel}
+${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the procedure below, run it once per reviewer in the list (${reviewerLabel}); substitute the active reviewer for any reference to Copilot — the loop structure is the same but the reviewer source differs.\n\n${rprBody}\n` : ''}`;
}
// Compact light-path variant.
return [
'## Review-Loop Follow-up (PRIMARY OBJECTIVE)',
`A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} Drive the review-and-fix loop to completion and merge.`,
- `**Reviewer**: \`${reviewer}\` (equivalent to \`/do:rpr --review-with ${reviewer}\`).`,
+ `**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,
+ ...extraNotes,
'',
- '**Loop UNTIL the reviewer reports clean OR 10 iterations:**',
+ '**Loop UNTIL all reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**',
`1. ${waitOrInvokeStep}`,
- '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (isCopilot ? ', resolve threads.' : '.'),
- `3. ${rerequestStep}`,
- '4. Repeat.',
- '5. When clean, merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',
+ '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),
+ '3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',
+ '4. When the list is exhausted (or the stop mode triggers), merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',
' ```bash',
` gh pr merge "${prUrl}" --squash --delete-branch`,
' ```',
prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : null,
' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',
- `6. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,
- '7. Exit — do NOT run `/do:push` or open a new PR.',
+ `5. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,
+ '6. Exit — do NOT run `/do:push` or open a new PR.',
'',
- '**Hard stop:** if not converged after 10 rounds, post a PR comment summarising blockers and exit.',
+ '**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',
repeatedCommentsNote
].filter(Boolean).join('\n');
}
@@ -433,10 +463,11 @@ Use the findings from the previous stage to inform your work. If the previous st
After completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.
` : '';
- // Resolve the user's reviewer choice (`copilot` default; `claude`/`gemini`/`codex`
- // route the review-loop follow-up through the named CLI). Declared up here so
- // the TUI completion block can thread it down to `/do:pr --review-with …`.
- const taskReviewer = metaStringOr(task.metadata?.reviewer, DEFAULT_REVIEWER);
+ // 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 taskReviewStopMode = task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE;
+ const taskReviewerApplies = isTruthyMetaFn(task.metadata?.reviewerApplies);
// TUI completion section — delegate to the shared light-path builder so
// both prompt paths emit byte-identical workflows. (Background: TUI owns
@@ -448,7 +479,9 @@ After completing your work and before committing, run \`/simplify\` to review th
? buildTuiCompletionSection({
willOpenPR, willReviewLoop, simplifyEnabled,
sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
- reviewer: taskReviewer
+ reviewers: taskReviewers,
+ reviewStopMode: taskReviewStopMode,
+ reviewerApplies: taskReviewerApplies
})
: '';
@@ -463,9 +496,11 @@ After completing your work and before committing, run \`/simplify\` to review th
// review inline — the system-side post-exit handler never fires for TUI.
const reviewLoopSection = willReviewLoop && willOpenPR && !isTui ? `
## Code Review
-After your task completes, the system will spawn a follow-up agent that runs the full review-and-fix loop until the reviewer reports zero comments and merges the PR. The follow-up uses **${taskReviewer}** as the reviewer (\`--review-with ${taskReviewer}\`). ${taskReviewer === DEFAULT_REVIEWER
- ? 'For GitHub PRs the system will also request a native Copilot review automatically (skipped for GitLab MRs and other non-GitHub forges).'
- : `The follow-up agent will invoke the \`${taskReviewer}\` CLI directly to critique the PR diff, then iterate on its feedback.`} You do not need to open the PR, trigger the review, or address feedback yourself — focus on producing high-quality, well-tested code so the review pass goes cleanly.
+After your task completes, the system will spawn a follow-up agent that runs the review-and-fix loop until all configured reviewers are satisfied, then merges the PR. The follow-up uses **${taskReviewers.join(' → ')}** (in order). ${taskReviewers[0] === DEFAULT_REVIEWER
+ ? 'Copilot leads the list, so for GitHub PRs the system pre-requests its initial review automatically (skipped on GitLab MRs and other non-GitHub forges); the follow-up then drives the rest of the chain.'
+ : taskReviewers.includes(DEFAULT_REVIEWER)
+ ? 'The follow-up invokes the CLI reviewers itself and requests Copilot at its turn (Copilot is GitHub-only, so it is skipped on non-GitHub forges).'
+ : 'The follow-up agent will invoke the configured CLI reviewers directly to critique the PR diff, then iterate on their feedback.'} You do not need to open the PR, trigger the review, or address feedback yourself — focus on producing high-quality, well-tested code so the review passes go cleanly.
` : '';
// Build review-loop follow-up section. This is the agent that addresses Copilot's
@@ -642,10 +677,11 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);
const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true;
- // Reviewer choice for the Review Loop. Defaults to `copilot`; the form
- // exposes `claude`/`gemini`/`codex` as alternatives that flow as
- // `/do:pr --review-with <reviewer>` instructions to the agent.
- const lightReviewer = metaStringOr(task.metadata?.reviewer, DEFAULT_REVIEWER);
+ // 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 lightReviewStopMode = task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE;
+ const lightReviewerApplies = isTruthyMetaFn(task.metadata?.reviewerApplies);
// Claude Code CLI providers can drive `/simplify` + `/do:pr` themselves
// (the slashdo submodule mounts those as project-level slash commands).
// Other CLI providers (codex, gemini) can't — they get the legacy
@@ -716,10 +752,10 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
} else if (isTui) {
sections.push(buildTuiCompletionSection({
willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
- reviewer: lightReviewer
+ reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies
}));
} else {
- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo, simplifyEnabled, reviewer: lightReviewer }));
+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo, simplifyEnabled, reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
}
sections.push('Begin working on the task now.');
@@ -758,13 +794,24 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,
* The agent must drive the merge itself — `/do:pr` runs the review loop but
* exits without merging, so without this step the PR sits open and the branch
* leaks. Mirrors the merge contract in the review-loop follow-up section so
- * both agent flows converge on the same final state. `reviewer` only colors
+ * both agent flows converge on the same final state. `reviewers` only colors
* the wording — the merge step itself is reviewer-agnostic.
*/
-function buildPostPRMergeSteps(startStep, { reviewer = DEFAULT_REVIEWER } = {}) {
- const reviewerLabel = reviewer === DEFAULT_REVIEWER ? 'Copilot' : `\`${reviewer}\``;
+function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, 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 ' : '';
+ // 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
+ // explicitly so an unknown/invalid value falls through to the safe default
+ // (only `clean`/`too-large` mergeable).
+ const explicitStopMode = reviewStopMode === 'on-findings' || reviewStopMode === 'on-clean';
+ const mergeStatuses = explicitStopMode
+ ? '`clean`, `partial` (a stop-mode short-circuit you opted into), or `too-large`'
+ : '`clean` (or `too-large`)';
const lines = [
- `${startStep}. **Merge the PR immediately when the ${reviewerLabel} review loop reports \`clean\` (or \`too-large\`)** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--squash --delete-branch\`, nothing else — any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, or \`guardrail\`; leave the PR open for human follow-up.`,
+ `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--squash --delete-branch\`, nothing else — any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,
' ```bash',
' gh pr merge "<PR_URL>" --squash --delete-branch',
' ```',
@@ -777,17 +824,19 @@ function buildPostPRMergeSteps(startStep, { reviewer = DEFAULT_REVIEWER } = {})
* TUI completion-workflow block. The TUI owns its own commit → push → PR
* pipeline via slashdo commands and signals "done" with a sentinel file.
*/
-function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, reviewer = DEFAULT_REVIEWER }) {
+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
const cmd = willOpenPR ? '/do:pr' : '/do:push';
- const reviewerArg = willOpenPR && willReviewLoop && reviewer !== DEFAULT_REVIEWER ? ` --review-with ${reviewer}` : '';
+ const reviewArgs = willOpenPR && willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies) : '';
+ const reviewerArg = reviewArgs ? ` ${reviewArgs}` : '';
+ const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER;
const reviewSuffix = willOpenPR && willReviewLoop
- ? (reviewer === DEFAULT_REVIEWER
- ? ' — after the PR opens, request a Copilot review (e.g. via `gh`).'
- : ` — after the PR opens, invoke the \`${reviewer}\` CLI against the PR diff for review instead of Copilot.`)
+ ? (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.`)
: '';
const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';
const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';
- const merge = willOpenPR ? buildPostPRMergeSteps(3, { reviewer }) : { lines: [], nextStep: 3 };
+ const merge = willOpenPR ? buildPostPRMergeSteps(3, { reviewers, reviewStopMode }) : { lines: [], nextStep: 3 };
const sentinelStep = merge.nextStep;
const quitStep = sentinelStep + 1;
@@ -825,19 +874,20 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
* CLI providers fall through to the legacy commit-only block where PortOS
* handles push+PR on exit.
*/
-function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = false, simplifyEnabled = false, reviewer = DEFAULT_REVIEWER }) {
+function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = false, simplifyEnabled = false, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
if (hasSlashdo && worktreeInfo && willOpenPR) {
const lines = ['## Completion', 'When finished, run these in order:'];
let step = 1;
if (simplifyEnabled) {
lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);
}
- const reviewerArg = reviewer !== DEFAULT_REVIEWER ? ` --review-with ${reviewer}` : '';
- const reviewerNote = reviewer === DEFAULT_REVIEWER
+ const reviewArgs = buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies);
+ const reviewerArg = reviewArgs ? ` ${reviewArgs}` : '';
+ const reviewerNote = (reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER)
? 'Copilot review loop'
- : `\`${reviewer}\`-CLI review loop (\`--review-with ${reviewer}\`)`;
+ : `review loop for ${reviewers.join(', ')} in order`;
lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, opens a pull request against the default branch, and drives the ${reviewerNote} until clean.`);
- const merge = buildPostPRMergeSteps(step, { reviewer });
+ const merge = buildPostPRMergeSteps(step, { reviewers, reviewStopMode });
lines.push(...merge.lines);
step = merge.nextStep;
return lines.join('\n');
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index afa26c8e6c..9db64b944c 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -284,9 +284,10 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);
expect(prompt).toMatch(/MERGED/);
expect(prompt).not.toMatch(/## Completion Workflow/);
- // Default reviewer (copilot) — `--review-with copilot` should still be
- // surfaced so the agent knows the explicit choice.
- expect(prompt).toMatch(/--review-with copilot/);
+ // Default reviewer (copilot, lone) — names copilot but emits no `--review-with`
+ // (the lone default needs no flag).
+ expect(prompt).toMatch(/Reviewers \(in order\)\*\*: `copilot`/);
+ expect(prompt).not.toMatch(/--review-with/);
});
it('threads a non-default reviewer (claude) into the follow-up block via --review-with', () => {
@@ -298,7 +299,7 @@ describe('buildLightContextPrompt', () => {
reviewLoopPRNumber: 9,
reviewLoopPROwner: 'o',
reviewLoopPRRepo: 'r',
- reviewLoopReviewer: 'claude',
+ reviewLoopReviewers: ['claude'],
sourceTaskId: 'task-src-2',
}}),
'/r',
@@ -306,12 +307,34 @@ describe('buildLightContextPrompt', () => {
isTruthyMeta);
expect(prompt).toMatch(/--review-with claude/);
// The Copilot-specific pre-request wording must be replaced for CLI reviewers.
- expect(prompt).toMatch(/CLI-based reviewer/);
+ expect(prompt).toMatch(/CLI-based/);
+ });
+
+ it('threads an ordered multi-reviewer list + flags into the follow-up block', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopReviewers: ['codex', 'gemini', 'copilot'],
+ reviewLoopStopMode: 'on-clean',
+ reviewLoopReviewerApplies: true,
+ sourceTaskId: 'task-src-3',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/--review-with codex,gemini,copilot/);
+ expect(prompt).toMatch(/--review-stop-on-clean/);
+ expect(prompt).toMatch(/--reviewer-applies/);
+ // Ordered run instruction.
+ expect(prompt).toMatch(/For EACH reviewer in order/);
});
it('threads reviewer into the TUI Completion Workflow as `/do:pr --review-with <reviewer>`', () => {
const prompt = buildLightContextPrompt(
- makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: true, reviewer: 'gemini' } }),
+ makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: true, reviewers: ['gemini'] } }),
'/r',
{ branchName: 'feat', worktreePath: '/tmp/wt' },
isTruthyMeta,
@@ -319,6 +342,45 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/`\/do:pr --review-with gemini`/);
});
+ it('allows merging on `partial` in the completion merge step when a stop-mode is set', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'gemini'], reviewStopMode: 'on-clean' } }),
+ '/r',
+ { branchName: 'feat', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: true });
+ expect(prompt).toMatch(/--review-stop-on-clean/);
+ // `partial` is a successful stop-mode short-circuit → mergeable.
+ expect(prompt).toMatch(/`partial`/);
+ });
+
+ it('does NOT merge on `partial` under the default stop-mode (all)', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'gemini'] } }),
+ '/r',
+ { branchName: 'feat', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: true });
+ expect(prompt).not.toMatch(/`partial`/);
+ });
+
+ it('tells the follow-up to request Copilot at its turn when copilot does NOT lead the list', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopReviewers: ['codex', 'copilot'],
+ sourceTaskId: 'task-src-4',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ // Must instruct requesting Copilot at its turn — not claim a pre-request happened.
+ expect(prompt).toMatch(/request a Copilot review when you reach its turn/);
+ expect(prompt).not.toMatch(/already requested the initial Copilot/);
+ });
+
it('worktreeCommitGuidance: existing-branch wins over slashdo/PR — emits the review-fix push wording', () => {
// When the worktree reuses a pre-existing PR branch (e.g. a review-loop
// follow-up agent picking up where the prior agent left off), the agent
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 9d4e87f69a..706cf8cb87 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -507,18 +507,22 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(followUp.autoApproved).toBe(true);
});
- it('should NOT spawn a review-loop follow-up when Copilot review request fails', async () => {
+ it('STILL spawns the review-loop follow-up when the Copilot pre-request fails (follow-up re-requests at its turn)', async () => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });
git.requestCopilotReview.mockResolvedValue({ success: false, error: 'gh exited 1' });
+ addTask.mockResolvedValue({ id: 'sys-rl-q' });
await cleanupAgentWorktree('agent-1', true, {
openPR: true, requestCopilotReview: true, description: 'X',
originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
});
- // No follow-up because the initial review never landed — nothing to wait on
- expect(addTask).not.toHaveBeenCalled();
+ // A failed pre-request is recoverable — the follow-up requests Copilot itself at
+ // its turn. Not spawning would leave the PR open with no review loop (the bug).
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewers).toEqual(['copilot']);
expect(removeWorktree).toHaveBeenCalled();
});
@@ -551,13 +555,13 @@ describe('cleanupAgentWorktree - openPR path', () => {
// --- non-Copilot reviewer (--review-with claude/gemini/codex) ---
- it('should NOT call the native GH Copilot reviewer API when reviewer is not "copilot"', async () => {
+ it('should NOT call the native GH Copilot reviewer API when the list has no copilot', async () => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/55' });
addTask.mockResolvedValue({ id: 'sys-rl-y' });
await cleanupAgentWorktree('agent-1', true, {
- openPR: true, requestCopilotReview: true, reviewer: 'claude', description: 'X',
+ openPR: true, requestCopilotReview: true, reviewers: ['claude'], description: 'X',
originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
});
@@ -570,16 +574,53 @@ describe('cleanupAgentWorktree - openPR path', () => {
addTask.mockResolvedValue({ id: 'sys-rl-z' });
await cleanupAgentWorktree('agent-1', true, {
- openPR: true, requestCopilotReview: true, reviewer: 'codex', description: 'Build with codex review',
+ openPR: true, requestCopilotReview: true, reviewers: ['codex'], description: 'Build with codex review',
originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
});
expect(addTask).toHaveBeenCalledTimes(1);
const [followUp] = addTask.mock.calls[0];
- expect(followUp.metadata.reviewLoopReviewer).toBe('codex');
+ expect(followUp.metadata.reviewLoopReviewers).toEqual(['codex']);
expect(followUp.metadata.reviewLoopFollowUp).toBe(true);
});
+ it('pre-requests Copilot only when it LEADS the list, and threads stop-mode/applies through', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/57' });
+ git.requestCopilotReview.mockResolvedValue({ success: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-w' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'codex', 'gemini'],
+ reviewStopMode: 'on-findings', reviewerApplies: true, description: 'Build',
+ originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
+ });
+
+ expect(git.requestCopilotReview).toHaveBeenCalledTimes(1);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewers).toEqual(['copilot', 'codex', 'gemini']);
+ expect(followUp.metadata.reviewLoopStopMode).toBe('on-findings');
+ expect(followUp.metadata.reviewLoopReviewerApplies).toBe(true);
+ });
+
+ it('does NOT pre-request Copilot when it trails a CLI reviewer, but keeps it in the follow-up list', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/58' });
+ addTask.mockResolvedValue({ id: 'sys-rl-v' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, reviewers: ['codex', 'gemini', 'copilot'], description: 'Build',
+ originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }
+ });
+
+ // Copilot is not first → no stale pre-request; the follow-up requests it at its turn.
+ expect(git.requestCopilotReview).not.toHaveBeenCalled();
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewers).toEqual(['codex', 'gemini', 'copilot']);
+ });
+
// --- skipMerge tests for review-loop follow-up cleanup ---
it('should pass merge: false in the auto-merge fallback when skipMerge is true (review-loop follow-up cleanup)', async () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index e9e00a47d4..cdef2500ba 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -37,7 +37,7 @@ import { generateProactiveTasks as generateMissionTasks, getStats as getMissionS
import { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';
import { checkJobGate, hasGate } from './jobGates.js';
import { ensureDir, formatDuration, safeJSONParse, PATHS } from '../lib/fileUtils.js';
-import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, DEFAULT_REVIEWER } from '../lib/validation.js';
+import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
import { isRecoveryTask } from './recoveryTasks.js';
@@ -1952,12 +1952,12 @@ async function generateManagedAppImprovementTask(app, state) {
const promptTemplate = metadata.pipeline?.stages
? await taskSchedule.getStagePrompt(nextType, 0)
: await taskSchedule.getTaskPrompt(nextType);
- const reviewer = metadata.reviewer || DEFAULT_REVIEWER;
+ const reviewersCsv = normalizeReviewers(metadata).join(',');
const description = promptTemplate
.replace(/\{appName\}/g, app.name)
.replace(/\{repoPath\}/g, app.repoPath)
.replace(/\{appId\}/g, app.id)
- .replace(/\{reviewer\}/g, reviewer)
+ .replace(/\{reviewers\}/g, reviewersCsv)
.replace(/\{planConstraint\}/g, () => planConstraintBlock);
applyAppWorktreeDefault(metadata, app);
@@ -2098,13 +2098,13 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {
return null;
}
const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
- const reviewer = metadata.reviewer || DEFAULT_REVIEWER;
+ const reviewersCsv = normalizeReviewers(metadata).join(',');
const description = promptTemplate
.replace(/\{appName\}/g, app.name)
.replace(/\{repoPath\}/g, app.repoPath)
.replace(/\{appId\}/g, app.id)
- .replace(/\{reviewer\}/g, reviewer)
+ .replace(/\{reviewers\}/g, reviewersCsv)
// Use a replacer function — String.replace with a replacement STRING
// interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors
// legitimately contain `$` (env-var docs, prices, awk snippets) and
@@ -2384,7 +2384,13 @@ export async function addTask(taskData, taskType = 'user', { raw = false } = {})
else if (taskData.simplify === false) metadata.simplify = false;
if (taskData.reviewLoop === true) metadata.reviewLoop = true;
else if (taskData.reviewLoop === false) metadata.reviewLoop = false;
- if (typeof taskData.reviewer === 'string' && taskData.reviewer) metadata.reviewer = taskData.reviewer;
+ // Ordered multi-reviewer list (normalizes legacy single `reviewer` too).
+ if (Array.isArray(taskData.reviewers) || (typeof taskData.reviewer === 'string' && taskData.reviewer)) {
+ metadata.reviewers = normalizeReviewers(taskData);
+ }
+ 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;
if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;
if (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;
if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;
diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.js
index 5bbac29e9b..50c55c22b8 100644
--- a/server/services/referenceRepos.js
+++ b/server/services/referenceRepos.js
@@ -605,7 +605,7 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {
.replace(/\{appName\}/g, () => app.name)
.replace(/\{repoPath\}/g, () => app.repoPath)
.replace(/\{appId\}/g, () => app.id)
- .replace(/\{reviewer\}/g, () => DEFAULT_REVIEWER)
+ .replace(/\{reviewers\}/g, () => DEFAULT_REVIEWER)
.replace(/\{referenceData\}/g, () => referenceDataBlock)
.replace(/\{planConstraint\}/g, () => '');
diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.js
index 4dbb1c8793..c0c0069afa 100644
--- a/server/services/referenceRepos.test.js
+++ b/server/services/referenceRepos.test.js
@@ -44,7 +44,7 @@ const addTaskMock = vi.fn(async (task) => task);
vi.mock('./cos.js', () => ({
addTask: (...args) => addTaskMock(...args),
}));
-const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewer}\n{referenceData}\n{planConstraint}');
+const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}');
vi.mock('./taskSchedule.js', () => ({
getTaskPrompt: (...args) => getTaskPromptMock(...args),
}));
@@ -69,7 +69,7 @@ beforeEach(async () => {
addTaskMock.mockReset();
addTaskMock.mockImplementation(async (task) => task);
getTaskPromptMock.mockReset();
- getTaskPromptMock.mockImplementation(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewer}\n{referenceData}\n{planConstraint}');
+ getTaskPromptMock.mockImplementation(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}');
existsMock.mockReset();
existsMock.mockReturnValue(false);
svc = await import('./referenceRepos.js');
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 50b820b77d..621b27833e 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1711,3 +1711,16 @@ export async function __resetForTests() {
uninstallPeerSyncListener();
await writeTail.catch(() => {});
}
+
+/**
+ * Test-only: await the in-flight write/push tail WITHOUT resetting state or
+ * detaching listeners, so a test can deterministically settle the fire-and-forget
+ * pushes a `subscribePeer` kicks off before asserting on the network mock. Awaits
+ * twice because a push's `persistPushSuccess` only enqueues on `writeTail` after
+ * its `peerFetch` resolves — i.e. a tick after the subscribe returned.
+ */
+export async function __drainForTests() {
+ await writeTail.catch(() => {});
+ await new Promise((r) => setTimeout(r, 0));
+ await writeTail.catch(() => {});
+}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index e90bd246b8..b25edfd094 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -65,6 +65,7 @@ import {
autoSubscribePeerToAllRecords,
retryPendingPushesForPeer,
__resetForTests,
+ __drainForTests,
} from './peerSync.js';
import { getInstanceId, getPeers } from '../instances.js';
@@ -561,7 +562,10 @@ describe('peerSync', () => {
// and pay N subscribePeer readState calls per online transition.
vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }, { id: 'u2' }]);
await autoSubscribePeerToAllRecords('peer-a', 'universe');
- await new Promise((r) => setTimeout(r, 10));
+ // Deterministically settle the fire-and-forget initial pushes (their
+ // peerFetch fires a tick after subscribe returns) so they don't leak past
+ // a fixed sleep into the assertion window below — the CI flake this fixes.
+ await __drainForTests();
vi.mocked(peerFetch).mockClear();
// Re-run on steady state — no push should fire because the set-diff
// is empty and the for-loop body never runs.
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 82202e42b3..f39ca4da04 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -527,12 +527,12 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop
## Phase 6 — Review and ship
-The configured reviewer for this task is \`{reviewer}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`gemini\` invoke a local-CLI critique via \`/do:rpr --review-with <reviewer>\`.
+The configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`gemini\` invoke a local-CLI critique. When more than one is configured, run each in the listed order before merging — this mirrors slashdo's \`/do:pr --review-with <list>\` (the lone default \`copilot\` needs no flag; multi-reviewer runs may also carry \`--review-stop-on-*\` / \`--reviewer-applies\`).
1. Run \`/simplify\` (three-agent reuse/quality/efficiency review) against your own diff and fix findings in the same diff. BEFORE opening the PR, not retroactively.
2. Push the branch: \`git push -u origin claim/<slug>\`
3. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.
-4. **Wait for the configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Branch on \`{reviewer}\`:
+4. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for each one, apply the matching handling below before advancing to the next:
- **\`copilot\`** — This repo has GitHub Copilot Code Review configured to auto-run on every new PR. Poll until Copilot's review lands or a 10-minute timeout fires:
\`\`\`bash
@@ -558,7 +558,7 @@ The configured reviewer for this task is \`{reviewer}\`. \`copilot\` waits for G
\`\`\`
Leave the local \`claim/<slug>\` branch and the open PR alone. Do NOT run Phase 7 — that phase assumes a merged PR. PLAN.md and \`.changelog/NEXT.md\` were already updated in Phase 5, and that's fine even though the merge didn't happen: the next \`plan-task\` run will see the slug as in-flight via the open PR and pick a different item.
- - **\`claude\` / \`codex\` / \`gemini\`** — Invoke slashdo's \`/do:rpr --review-with {reviewer}\` against the PR. \`/do:rpr\` runs the chosen CLI in headless mode to critique the diff, applies fixes, and re-pushes. It owns its own iteration cap and clean-vs-dirty merge gate; on a clean status it returns control here for the merge.
+ - **\`claude\` / \`codex\` / \`gemini\`** — Invoke that CLI in headless mode against the PR diff to critique it, apply the fixes, run tests, and re-push. Iterate until the CLI reports no further blocking findings, then advance to the next configured reviewer (or merge if it's the last). Cap at **3 rounds** here — this inline claim flow is intentionally more conservative than the dedicated CoS-spawned review-loop follow-up (which allows up to 10 iterations per reviewer); after 3 rounds, leave the PR for human follow-up.
5. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\` into main or any other branch. The repo may allow only one of \`--merge\` / \`--squash\` / \`--rebase\`, so don't hardcode a method. Try in this order and use the first one that succeeds:
\`\`\`bash