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): pick the review-loop reviewer (--review-with copilot/claude/gemini/codex) on the task form (#350)

[._.]/ Adam Eivydea8ed1cf552
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 702c7a34e8..ab6fcc5d4e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **CoS task form: pick the reviewer for the Review Loop (`--review-with`).** A new compact dropdown appears next to the Review Loop checkbox in `TaskAddForm.jsx` (copilot / claude / gemini / codex; default copilot). The choice is persisted on the task as `metadata.reviewer` and flows through the agent prompt, the follow-up agent's prompt (`/do:rpr --review-with <reviewer>`), and the worktree cleanup hook — for non-copilot reviewers, PortOS skips the GitHub Copilot reviewer-API pre-request and instructs the follow-up to invoke the chosen CLI against the PR diff instead. AgentCard chips show the selected reviewer when it isn't the default.
+
- **Deep-linkable image preview modals via `?preview=<filename>`.** Every page hosting `<MediaPreview>` (Media History, Media Collections, Image Gen, Video Gen, Universe Builder variations + cast, Comic Script Stage, Nouns Stage) now drives the lightbox through a `?preview=<filename>` query param, so `/media/history?preview=foo.png` or `/universe-builder/:id?tab=cast&preview=foo.png` re-opens the same image on reload and is shareable. New `usePreviewRoute(items)` hook (`client/src/hooks/usePreviewRoute.js`) owns the URL round-trip — first open pushes a history entry so the browser back button closes the modal; prev/next nav and close replace so the history stack stays clean.
- **Per-bucket exporter hash cache.** Subscription re-exports of large series no longer re-hash every referenced asset to confirm "blob already there." A new `<bucket>/assets/blobs/.index.json` sidecar maps `<sourcePath>:<mtimeMs>:<size> → <hash>` so `server/services/sharing/exporter.js#copyAssetIfPresent` skips both `sha256File` (multi-GB stream read) and the redundant `copyFile` when the cache hit's blob is still on disk. mtime change invalidates automatically because it's part of the key. A 200MB re-export drops from ~200MB of disk reads to a single JSON load + stat per asset.
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index fcc063897a..0a64d902c5 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -6,6 +6,7 @@ import * as api from '../../services/api';
import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';
import { formatBytes } from '../../utils/formatters';
import { filterSelectableModels } from '../../utils/providers';
+import { REVIEWER_OPTIONS, DEFAULT_REVIEWER } from './constants';
const isCodexProvider = (provider) => {
if (!provider) return false;
@@ -23,6 +24,7 @@ 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 [createJiraTicket, setCreateJiraTicket] = useState(false);
const [screenshots, setScreenshots] = useState([]);
const [attachments, setAttachments] = useState([]);
@@ -219,6 +221,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
openPR,
simplify,
reviewLoop,
+ reviewer: reviewLoop ? reviewer : undefined,
screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,
attachments: attachments.length > 0 ? attachments.map(a => ({
filename: a.filename,
@@ -450,6 +453,19 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
Review Loop
</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>
+ )}
{appHasJira && (
<label className="flex items-center gap-2 cursor-pointer select-none whitespace-nowrap py-1">
<input
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index b651b9ceb4..4a854d4195 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -59,6 +59,18 @@ export const AGENT_OPTIONS = [
{ field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'After the agent opens a PR during its run, keep iterating on review feedback until checks pass. Only applies when Open PR is not enabled (manual PR creation by agent).' }
];
+// Reviewer choices for the Review Loop. `copilot` requests a GitHub Copilot
+// review via the native reviewer API; the others instruct the follow-up agent
+// to invoke the named CLI to critique the PR diff (via `/do:rpr --review-with`).
+// Keep in sync with the `reviewer` enum in `server/lib/validation.js`.
+export const REVIEWER_OPTIONS = [
+ { value: 'copilot', label: 'Copilot', description: 'GitHub Copilot (default, GitHub-only)' },
+ { value: 'claude', label: 'Claude', description: 'Claude CLI reviews the PR diff' },
+ { value: 'gemini', label: 'Gemini', description: 'Gemini CLI reviews the PR diff' },
+ { value: 'codex', label: 'Codex', description: 'Codex CLI reviews the PR diff' }
+];
+export const DEFAULT_REVIEWER = 'copilot';
+
// Returns the Tailwind className string for an agent option toggle button.
// effective: whether the option is on (global + override resolved)
// hasOverride: whether there's an explicit per-app override set
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 40f772f780..e3342e5891 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -28,6 +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';
// Extract task type from description (matches server-side extractTaskType)
function extractTaskType(description) {
@@ -606,9 +607,9 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
)}
{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">
+ title={`Review loop enabled — agent will iterate on PR feedback (reviewer: ${agent.metadata.configReviewer || DEFAULT_REVIEWER})`}>
<RefreshCw size={10} aria-hidden="true" />
- Review
+ Review{agent.metadata.configReviewer && agent.metadata.configReviewer !== DEFAULT_REVIEWER ? `: ${agent.metadata.configReviewer}` : ''}
</span>
)}
</div>
diff --git a/server/lib/validation.js b/server/lib/validation.js
index d7eb27b340..e75c86cb5c 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -545,6 +545,13 @@ export const searchQuerySchema = z.object({
// COS TASK SCHEMAS
// =============================================================================
+// Reviewer choices for the Review Loop. `copilot` is the default and requests a
+// native GitHub Copilot review; the others instruct the review-loop follow-up
+// agent to invoke the named CLI to critique the PR diff. Mirrored in
+// client/src/components/cos/constants.js → REVIEWER_OPTIONS.
+export const REVIEWER_VALUES = ['copilot', 'claude', 'gemini', 'codex'];
+export const DEFAULT_REVIEWER = 'copilot';
+
export const createCosTaskSchema = z.object({
description: z.string().min(1),
priority: z.string().optional(),
@@ -579,6 +586,10 @@ export const createCosTaskSchema = z.object({
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
),
+ reviewer: z.preprocess(
+ v => v === '' ? undefined : v,
+ z.enum(REVIEWER_VALUES).optional()
+ ),
});
export const updateCosTaskSchema = z.object({
@@ -993,6 +1004,11 @@ export function sanitizeTaskMetadata(raw) {
hasKeys = true;
}
}
+ // `reviewer` is a constrained string (copilot/claude/gemini/codex), not a boolean.
+ if (Object.prototype.hasOwnProperty.call(raw, 'reviewer') && REVIEWER_VALUES.includes(raw.reviewer)) {
+ clean.reviewer = raw.reviewer;
+ 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 ac4e4e0e35..8b9ae78e7c 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -493,6 +493,23 @@ describe('validation.js', () => {
expect(sanitizeTaskMetadata({ useWorktree: true, foo: 'bar' })).toEqual({ useWorktree: true });
});
+ it('should accept a valid reviewer string', () => {
+ expect(sanitizeTaskMetadata({ reviewer: 'copilot' })).toEqual({ reviewer: 'copilot' });
+ expect(sanitizeTaskMetadata({ reviewer: 'claude' })).toEqual({ reviewer: 'claude' });
+ expect(sanitizeTaskMetadata({ reviewer: 'gemini' })).toEqual({ reviewer: 'gemini' });
+ expect(sanitizeTaskMetadata({ reviewer: 'codex' })).toEqual({ reviewer: 'codex' });
+ expect(sanitizeTaskMetadata({ reviewLoop: true, reviewer: 'claude' }))
+ .toEqual({ reviewLoop: true, reviewer: 'claude' });
+ });
+
+ it('should drop unknown reviewer values', () => {
+ expect(sanitizeTaskMetadata({ reviewer: 'unknown' })).toBeNull();
+ expect(sanitizeTaskMetadata({ reviewer: '' })).toBeNull();
+ expect(sanitizeTaskMetadata({ reviewer: 42 })).toBeNull();
+ expect(sanitizeTaskMetadata({ useWorktree: true, reviewer: 'bogus' }))
+ .toEqual({ useWorktree: true });
+ });
+
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 df488c6f86..22678fdb95 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -18,7 +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 } from './agentState.js';
+import { activeAgents, userTerminatedAgents, metaStringOr } from './agentState.js';
+import { DEFAULT_REVIEWER } from '../lib/validation.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
@@ -580,6 +581,7 @@ 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),
skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
description: task.description,
agentOutput: outputBuffer,
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index f028db6877..e529d1c854 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -27,6 +27,7 @@ vi.mock('./agentLifecycle.js', () => ({
vi.mock('./agentState.js', () => ({
activeAgents: new Map(),
userTerminatedAgents: new Set(),
+ metaStringOr: (value, fallback) => (typeof value === 'string' && value) ? value : fallback,
}));
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 7098be1d74..a49f4c07d7 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -34,7 +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 } from './agentState.js';
+import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta, metaStringOr } from './agentState.js';
+import { DEFAULT_REVIEWER } from '../lib/validation.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { writeFile } from 'fs/promises';
@@ -490,6 +491,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),
configUseWorktree: !!worktreeInfo,
configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,
configCodingOnMain: !worktreeInfo && !jiraBranchName
@@ -1267,6 +1269,7 @@ 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),
skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
description: task?.description,
agentOutput: outputBuffer,
@@ -1313,12 +1316,14 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
* 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."
+ * 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 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, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewer = DEFAULT_REVIEWER, 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 [];
@@ -1398,7 +1403,11 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
let copilotReviewOk = false;
let copilotReviewSkipped = false;
- if (shouldRequestCopilot) {
+ 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 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.
@@ -1411,20 +1420,27 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
emitLog('warn', `🤖 Failed to request Copilot review on ${prResult.url}: ${reviewResult.error}`, { 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 });
}
// 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.
- // Only spawn for GitHub PRs (Copilot reviewer is GitHub-only) and only when the
- // initial review request succeeded — otherwise the follow-up has nothing to wait for.
- if (shouldRequestCopilot && copilotReviewOk && !copilotReviewSkipped) {
+ // 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;
+ if (canSpawnFollowUp) {
await spawnReviewLoopFollowUp({
originalAgentId: agentId,
originalTask,
prUrl: prResult.url,
prBranch: worktreeBranch,
- sourceWorkspace
+ sourceWorkspace,
+ reviewer
}).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}`);
@@ -1474,12 +1490,13 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
* branch (via createWorktree's `existingBranch` option) so it can fix-and-push
* without trampling concurrent agents.
*/
-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewer = DEFAULT_REVIEWER }) {
if (!prUrl || !prBranch) return null;
const parsedPr = git.parsePullRequestUrl(prUrl);
- // Copilot loop is only meaningful on GitHub — on other forges, skip silently
- if (parsedPr && parsedPr.host && parsedPr.host !== 'github.com') return null;
+ // 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;
const appId = originalTask?.metadata?.app || null;
const sourceTaskDesc = originalTask?.description || 'CoS automated task';
@@ -1512,6 +1529,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
reviewLoopPRHost: parsedPr?.host ?? null,
reviewLoopPROwner: parsedPr?.owner ?? null,
reviewLoopPRRepo: parsedPr?.repo ?? null,
+ reviewLoopReviewer: reviewer,
sourceTaskId: originalTask?.id || null,
sourceAgentId: originalAgentId || null,
// skipCommitCheck: this task may exit cleanly with zero new commits if the
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 68928f3998..943fe2a247 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -16,6 +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 { metaStringOr } from './agentState.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
@@ -211,19 +213,42 @@ 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.`;
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}\`. The system has already requested an initial Copilot code review. **Your job is to drive the review-and-fix loop to completion and merge the PR.**
+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.**
-**Run this loop UNTIL the PR has zero unresolved Copilot comments OR you hit the iteration cap of 10:**
+**Reviewer**: \`${reviewer}\` (equivalent to \`/do:rpr --review-with ${reviewer}\`).
-1. Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round).
-2. If there are unresolved review threads, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and resolve the addressed threads.
-3. Re-request a Copilot review.
+**Run this loop UNTIL the PR is clean per the reviewer OR you hit the iteration cap of 10:**
+
+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 Copilot returns "0 comments" / no unresolved threads, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):
+5. When ${zeroCommentCondition}, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):
\`\`\`bash
gh pr merge "${prUrl}" --squash --delete-branch
\`\`\`
@@ -234,7 +259,7 @@ A previous agent finished implementing the work for source task **${sourceTaskId
**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.
-**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.
+${repeatedCommentsNote}
PR Details:
- **URL**: ${prUrl}
@@ -242,18 +267,20 @@ PR Details:
${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}
${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}
- **Source task**: ${sourceTaskId}
-${rprBody ? `\n### /do:rpr Reference (full procedure)\n\n${rprBody}\n` : ''}`;
+- **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` : ''}`;
}
// Compact light-path variant.
return [
'## Review-Loop Follow-up (PRIMARY OBJECTIVE)',
- `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. The system has requested an initial Copilot review. Drive the review-and-fix loop to completion and merge.`,
+ `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}\`).`,
'',
- '**Loop UNTIL zero unresolved Copilot comments OR 10 iterations:**',
- '1. Wait for the latest Copilot review (poll 5–15s, max 5 min per round).',
- '2. If unresolved threads: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, resolve threads.',
- '3. Re-request a Copilot review.',
+ '**Loop UNTIL the reviewer reports clean OR 10 iterations:**',
+ `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):',
' ```bash',
@@ -265,7 +292,7 @@ ${rprBody ? `\n### /do:rpr Reference (full procedure)\n\n${rprBody}\n` : ''}`;
'7. 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.',
- '**Repeated comments:** if a round only re-raises feedback you intentionally rejected (with a reply explaining why), treat as clean and merge.'
+ repeatedCommentsNote
].filter(Boolean).join('\n');
}
@@ -405,6 +432,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);
+
// TUI completion section — delegate to the shared light-path builder so
// both prompt paths emit byte-identical workflows. (Background: TUI owns
// its own `/simplify` → `/do:pr|/do:push` → sentinel → `/quit` sequence
@@ -414,7 +446,8 @@ After completing your work and before committing, run \`/simplify\` to review th
const tuiCompletionSection = isTui
? buildTuiCompletionSection({
willOpenPR, willReviewLoop, simplifyEnabled,
- sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`
+ sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
+ reviewer: taskReviewer
})
: '';
@@ -429,7 +462,9 @@ 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 request a Copilot code review automatically for GitHub PRs (the step is skipped for GitLab MRs and other non-GitHub forges). The system will then spawn a follow-up agent that runs the full review-and-fix loop until Copilot returns zero comments and merges the PR. 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 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.
` : '';
// Build review-loop follow-up section. This is the agent that addresses Copilot's
@@ -606,6 +641,10 @@ 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);
// 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
@@ -675,10 +714,11 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false }));
} else if (isTui) {
sections.push(buildTuiCompletionSection({
- willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`
+ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
+ reviewer: lightReviewer
}));
} else {
- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo, simplifyEnabled }));
+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo, simplifyEnabled, reviewer: lightReviewer }));
}
sections.push('Begin working on the task now.');
@@ -714,14 +754,16 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,
* assign `nextStep` back to the caller's step counter so any subsequent
* numbered steps stay continuous.
*
- * The agent must drive the merge itself — `/do:pr` runs the Copilot 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.
+ * 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
+ * the wording — the merge step itself is reviewer-agnostic.
*/
-function buildPostPRMergeSteps(startStep) {
+function buildPostPRMergeSteps(startStep, { reviewer = DEFAULT_REVIEWER } = {}) {
+ const reviewerLabel = reviewer === DEFAULT_REVIEWER ? 'Copilot' : `\`${reviewer}\``;
const lines = [
- `${startStep}. **Merge the PR immediately when the Copilot 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 \`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.`,
' ```bash',
' gh pr merge "<PR_URL>" --squash --delete-branch',
' ```',
@@ -734,13 +776,17 @@ function buildPostPRMergeSteps(startStep) {
* 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 }) {
+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, reviewer = DEFAULT_REVIEWER }) {
const cmd = willOpenPR ? '/do:pr' : '/do:push';
+ const reviewerArg = willOpenPR && willReviewLoop && reviewer !== DEFAULT_REVIEWER ? ` --review-with ${reviewer}` : '';
const reviewSuffix = willOpenPR && willReviewLoop
- ? ' — after the PR opens, request a Copilot review (e.g. via `gh`).' : '';
+ ? (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.`)
+ : '';
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) : { lines: [], nextStep: 3 };
+ const merge = willOpenPR ? buildPostPRMergeSteps(3, { reviewer }) : { lines: [], nextStep: 3 };
const sentinelStep = merge.nextStep;
const quitStep = sentinelStep + 1;
@@ -749,7 +795,7 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
'When the task is complete, run these in order:',
'',
simplifyStep,
- `2. \`${cmd}\`${reviewSuffix}`,
+ `2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,
...merge.lines,
`${sentinelStep}. Write a short markdown summary (~5–15 lines) to the completion sentinel — PortOS polls this every 2s; without it the agent sits idle until a 3-minute fallback fires.`,
'',
@@ -778,15 +824,19 @@ 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 }) {
+function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = false, simplifyEnabled = false, reviewer = DEFAULT_REVIEWER }) {
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.`);
}
- lines.push(`${step++}. \`/do:pr\` — commits your changes, pushes the branch, opens a pull request against the default branch, and drives the Copilot review loop until clean.`);
- const merge = buildPostPRMergeSteps(step);
+ const reviewerArg = reviewer !== DEFAULT_REVIEWER ? ` --review-with ${reviewer}` : '';
+ const reviewerNote = reviewer === DEFAULT_REVIEWER
+ ? 'Copilot review loop'
+ : `\`${reviewer}\`-CLI review loop (\`--review-with ${reviewer}\`)`;
+ 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 });
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 cf1ac4640f..afa26c8e6c 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -284,6 +284,39 @@ 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/);
+ });
+
+ it('threads a non-default reviewer (claude) into the follow-up block via --review-with', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopPROwner: 'o',
+ reviewLoopPRRepo: 'r',
+ reviewLoopReviewer: 'claude',
+ sourceTaskId: 'task-src-2',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ 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/);
+ });
+
+ 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' } }),
+ '/r',
+ { branchName: 'feat', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: true });
+ expect(prompt).toMatch(/`\/do:pr --review-with gemini`/);
});
it('worktreeCommitGuidance: existing-branch wins over slashdo/PR — emits the review-fix push wording', () => {
diff --git a/server/services/agentState.js b/server/services/agentState.js
index bc2a5751fb..67bdf78e5b 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -22,3 +22,7 @@ export const setUseRunner = (val) => { useRunner = val; };
// Metadata booleans may arrive as true/'true' or false/'false' (JSON vs TASKS.md string round-trip)
export const isTruthyMeta = (value) => value === true || value === 'true';
export const isFalsyMeta = (value) => value === false || value === 'false';
+
+// Metadata strings may be absent, empty, or non-string (objects/numbers leak past `||` checks).
+// Returns `value` only when it's a non-empty string, otherwise `fallback`.
+export const metaStringOr = (value, fallback) => (typeof value === 'string' && value) ? value : fallback;
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index dd8e580694..9d4e87f69a 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -549,6 +549,37 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ // --- non-Copilot reviewer (--review-with claude/gemini/codex) ---
+
+ it('should NOT call the native GH Copilot reviewer API when reviewer is not "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',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
+ });
+
+ expect(git.requestCopilotReview).not.toHaveBeenCalled();
+ });
+
+ it('should still spawn the review-loop follow-up when a non-Copilot reviewer is selected', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/56' });
+ addTask.mockResolvedValue({ id: 'sys-rl-z' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, reviewer: '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.reviewLoopFollowUp).toBe(true);
+ });
+
// --- 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 fc7de197c3..9cd93007cf 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -2309,6 +2309,7 @@ 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;
if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;
if (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;
if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;