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

let the PRs tab choose who reviews, not just who runs the task

[._.]/ Adam Eivyac387b14a9fe
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsx
index 4035d159bf..596a5fee87 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx
@@ -1,19 +1,25 @@
import { useState, useEffect, useCallback, useMemo, useRef, useId } from 'react';
import { Link } from 'react-router';
import {
- AlertTriangle, Bot, CheckCircle2, ExternalLink, FileSearch, GitBranch, GitMerge,
- GitPullRequest, Loader2, RefreshCw, Rocket, ScanSearch, Search, ShieldAlert, User
+ AlertTriangle, Bot, CheckCircle2, ClipboardCheck, ExternalLink, FileSearch, GitBranch, GitMerge,
+ GitPullRequest, Info, Loader2, RefreshCw, Rocket, ScanSearch, Search, ShieldAlert, User
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import Banner from '../../ui/Banner';
+import CollapsibleSection from '../../ui/CollapsibleSection';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import Pill from '../../ui/Pill';
import toast from '../../ui/Toast';
import ProviderModelSelector from '../../ProviderModelSelector';
+import ReviewerPicker from '../../cos/ReviewerPicker';
+import { PR_REVIEW_MODES, PR_REVIEW_MODE_OPTIONS, DEFAULT_PR_REVIEW_MODE, prReviewModeOption, REVIEWER_LIST_OVERRIDE_KEYS } from '../../cos/constants';
import ScopeAdherenceCheck from '../ScopeAdherenceCheck';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';
import useProviderModels from '../../../hooks/useProviderModels';
+import useReviewerModelOptions from '../../../hooks/useReviewerModelOptions';
+import { CodeReviewDefaultsProvider, useCodeReviewDefaults } from '../../../hooks/useCodeReviewDefaults';
+import { reviewerModelsFromDefaults, reviewerEffortsFromDefaults } from '../../../lib/reviewerModels';
import { enabledProcessProviderFilter } from '../../../utils/providers';
import * as api from '../../../services/api';
import { timeAgo } from '../../../utils/formatters';
@@ -48,6 +54,22 @@ const actionStatusForTask = status => ({
// the action can run — absent means "always offered". `matches` is the
// LATE-BINDING rule: a click knows its PR number before the server has a task
// id, so a socket update is claimed by the row it names.
+//
+// `body` is what the click POSTs, built from the panel above the list. It is
+// per-kind because the three actions consume the panel differently, and that
+// difference is a real contract rather than a styling choice: `resolve` and
+// `doReview` are agents PortOS composes here, so they take the whole panel;
+// `review` hands its run to the `pr-reviewer` SCHEDULED task, whose providers
+// live on its own stages and whose review roster is that pipeline's, not this
+// panel's — so it takes only the provider pin, and only when the user opts in.
+//
+// `call` stays a lambda around each api function rather than a reference to it:
+// a reference is READ at module evaluation, and several suites that reach this
+// module transitively mock `services/api` with only the exports they use — so a
+// bare `call: api.resolveAppPullRequest` fails their import with "no export is
+// defined on the mock" before a single test runs.
+const wholePanelBody = ({ providerSettings, reviewSettings }) => ({ ...providerSettings, ...reviewSettings });
+
const ACTION_KINDS = {
resolve: {
label: 'Resolve & merge',
@@ -57,7 +79,8 @@ const ACTION_KINDS = {
// The only kind whose POST answers with a bare `task` rather than a record
// named after its field.
queued: result => result.task && { taskId: result.task.id, status: result.task.status },
- call: (appId, number, settings) => api.resolveAppPullRequest(appId, number, settings),
+ body: wholePanelBody,
+ call: (appId, number, body) => api.resolveAppPullRequest(appId, number, body),
title: (forgeLabel, number, appName) =>
`Start a CoS agent now to resolve and merge ${forgeLabel} request #${number} for ${appName}`,
matches: (task, appId, number) => task.metadata?.app === appId
@@ -71,8 +94,9 @@ const ACTION_KINDS = {
eligibleField: 'reviewEligible',
// The one action that follows its own saved stage providers unless the user
// explicitly opts the page-level pin in.
- call: (appId, number, settings, { overrideProvider }) =>
- api.reviewAppPullRequest(appId, number, overrideProvider ? settings : {}),
+ body: ({ providerSettings, applyRunWithToPrReview }) =>
+ (applyRunWithToPrReview ? providerSettings : {}),
+ call: (appId, number, body) => api.reviewAppPullRequest(appId, number, body),
title: (forgeLabel, number, appName) =>
`Run the pr-reviewer scheduled task against ${forgeLabel} request #${number} for ${appName}`,
matches: (task, appId, number) => task.metadata?.app === appId
@@ -85,7 +109,8 @@ const ACTION_KINDS = {
Icon: FileSearch,
field: 'doReviewAction',
eligibleField: 'doReviewEligible',
- call: (appId, number, settings) => api.doReviewAppPullRequest(appId, number, settings),
+ body: wholePanelBody,
+ call: (appId, number, body) => api.doReviewAppPullRequest(appId, number, body),
title: (forgeLabel, number, appName) =>
`Run the /do:review workflow against ${forgeLabel} request #${number} for ${appName} and post an inline review`,
// Shares `targetPullRequest` with the pr-reviewer match above — one
@@ -98,6 +123,79 @@ const ACTION_KINDS = {
};
const KIND_IDS = Object.keys(ACTION_KINDS);
+// The reviewer fields the run-settings panel may pin. `ReviewerPicker` emits a
+// partial against its baseline, and that partial can also carry the run flags
+// (`stopMode` / `reviewerApplies`) this panel deliberately does not offer — so
+// narrow it to the keys that actually change the resolved roster. That list is
+// `REVIEWER_LIST_OVERRIDE_KEYS` rather than a local copy: the server mirrors it
+// (`reviewerConfig.test.js` pins the two against each other), so a seventh
+// pinnable field reaches this filter with everything else instead of being
+// silently dropped on the way to the request. A partial with nothing left in it
+// is `null`: no override at all, which is what leaves the server resolving the
+// Code Review Defaults at spawn time.
+function pickReviewerOverride(next) {
+ const picked = Object.fromEntries(
+ REVIEWER_LIST_OVERRIDE_KEYS.filter(key => next?.[key] !== undefined).map(key => [key, next[key]]),
+ );
+ return Object.keys(picked).length ? picked : null;
+}
+
+/**
+ * The reviewer roster a delegated run uses, seeded from the install's Code
+ * Review Defaults and edited as a partial against them.
+ *
+ * Its own component, and its own `CodeReviewDefaultsProvider`, so that BOTH of
+ * its fetches are paid only by a user who opened the disclosure. That matters
+ * for one of them specifically: `useReviewerModelOptions` reads
+ * `/api/local-llm/status`, which is uncached and spawns `ollama --version` and
+ * `lms version` plus a forced LM Studio model list — a real cost to charge every
+ * visit to a tab whose common path is pressing Merge. The parent keeps it
+ * mounted once opened, so a second open costs nothing.
+ */
+function ReviewerOverrideBody({ override, onChange }) {
+ const codeReviewDefaults = useCodeReviewDefaults();
+ const reviewerModelOptions = useReviewerModelOptions();
+ // The defaults carry per-reviewer pins as `<reviewer>Model` / `<reviewer>Effort`
+ // scalars; the picker takes them as token-keyed maps.
+ const seeded = useMemo(() => ({
+ ...codeReviewDefaults,
+ reviewerModels: reviewerModelsFromDefaults(codeReviewDefaults),
+ reviewerEfforts: reviewerEffortsFromDefaults(codeReviewDefaults),
+ }), [codeReviewDefaults]);
+
+ return (
+ <>
+ <ReviewerPicker
+ {...seeded}
+ {...override}
+ defaults={seeded}
+ modelOptions={reviewerModelOptions}
+ showRunFlags={false}
+ onChange={next => onChange(pickReviewerOverride(next))}
+ />
+ <p className="text-xs text-gray-500">
+ Applies to Resolve &amp; merge and Do:Review. Left untouched, both resolve the install&apos;s Code Review Defaults when the agent starts.
+ </p>
+ {override && (
+ <button type="button" onClick={() => onChange(null)} className="text-xs text-port-accent hover:underline">
+ Use configured reviewers
+ </button>
+ )}
+ </>
+ );
+}
+
+// The defaults live in context, and this is the only consumer on the page — so
+// the provider is mounted with the picker rather than around the whole tab, which
+// is what keeps its fetch on the same lazy path as the model-options probe above.
+function ReviewerOverride(props) {
+ return (
+ <CodeReviewDefaultsProvider>
+ <ReviewerOverrideBody {...props} />
+ </CodeReviewDefaultsProvider>
+ );
+}
+
// The direct merge's methods, in the order the forges list them.
const MERGE_METHOD_LABELS = { merge: 'Merge commit', squash: 'Squash', rebase: 'Rebase' };
const DEFAULT_MERGE_METHOD = 'merge';
@@ -228,6 +326,7 @@ function actionRank(status) {
export default function PullRequestsTab({ appId, appName }) {
const searchId = useId();
const mergeId = useId();
+ const reviewModeId = useId();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
@@ -246,8 +345,8 @@ export default function PullRequestsTab({ appId, appName }) {
const [mergeMethod, setMergeMethod] = useState(DEFAULT_MERGE_METHOD);
const [deleteBranchOnMerge, setDeleteBranchOnMerge] = useState(true);
- // Resolve & merge defaults to the active provider. PR review follows its
- // saved stages unless the user explicitly enables the eligibility override.
+ // Resolve & merge and Do:Review default to the active provider. PR review
+ // follows its own scheduled stages unless the user explicitly opts this pin in.
// Auto remains available for server-side routing. Mirrors the Issues
// tab's "Run with" picker: a session convenience, never persisted.
const {
@@ -255,7 +354,31 @@ export default function PullRequestsTab({ appId, appName }) {
setSelectedProviderId, setSelectedModel
} = useProviderModels({ filter: enabledProcessProviderFilter, allowDefault: true, preselectDefaults: true, silent: true, withEffort: true });
const [effort, setEffort] = useState('');
- const [overrideReviewProvider, setOverrideReviewProvider] = useState(false);
+ const [applyRunWithToPrReview, setApplyRunWithToPrReview] = useState(false);
+
+ // WHO reviews, for the two actions PortOS composes here. `delegated` keeps the
+ // historical behavior (the agent orchestrates the install's reviewer roster);
+ // `self` collapses the review onto the Run with provider, which is the cheaper
+ // answer whenever that provider is already the model you wanted the review
+ // from. Session state, like everything else in this panel.
+ const [reviewMode, setReviewMode] = useState(DEFAULT_PR_REVIEW_MODE);
+ // What this run changes about the reviewer roster, as the PARTIAL the picker
+ // emits against its baseline — or `null` for "nothing, use whatever the
+ // install's Code Review Defaults resolve to". A partial rather than a seeded
+ // copy is what gates SENDING the fields: an untouched picker must leave the
+ // server reading the defaults at spawn time rather than freezing whatever this
+ // tab happened to render, and per-FIELD precedence then means pinning only the
+ // reviewers still takes the usernames and pins from the defaults. Editing a
+ // field back to its default drops it from the partial, so the override empties
+ // itself out the same way the reset button does.
+ const [reviewOverride, setReviewOverride] = useState(null);
+ // Whether the override picker has ever been opened. It owns two fetches — one
+ // of which probes the local-LLM backends and spawns `ollama`/`lms` — so it is
+ // mounted on the first open rather than with the tab, and then KEPT mounted so
+ // reopening does not pay for them again. See `ReviewerOverride` below.
+ const [overrideOpen, setOverrideOpen] = useState(false);
+ const [overrideMounted, setOverrideMounted] = useState(false);
+ const selfReview = reviewMode === PR_REVIEW_MODES.SELF;
// One writer for the whole `{ kind: { number: action } }` bag so the ref the
// socket handler reads and the state React renders can never disagree.
@@ -388,14 +511,23 @@ export default function PullRequestsTab({ appId, appName }) {
effort: effort || undefined,
};
+ // This run's review settings. The mode always rides along (the server needs an
+ // explicit answer, and its own default is `delegated` either way); the roster
+ // only does when the user actually edited the picker, and never under
+ // self-review, where there is no roster to override.
+ const reviewSettings = {
+ reviewMode,
+ ...(selfReview ? {} : (reviewOverride || {})),
+ };
+
// Every row action queues a CoS task and then tracks it identically: optimistic
// `queuing`, roll back on failure, and never let a stale response downgrade a
// status a socket update already advanced.
const queueAction = async (kind, pullRequest) => {
const { number } = pullRequest;
- const { verb, call } = ACTION_KINDS[kind];
+ const { verb, call, body } = ACTION_KINDS[kind];
setAction(kind, number, { status: 'queuing', taskId: null });
- const result = await call(appId, number, providerSettings, { overrideProvider: overrideReviewProvider })
+ const result = await call(appId, number, body({ providerSettings, reviewSettings, applyRunWithToPrReview }))
.catch(err => {
toast.error(err?.message || `Failed to queue an agent for #${number}`);
return null;
@@ -518,52 +650,108 @@ export default function PullRequestsTab({ appId, appName }) {
</button>
</div>
- <div className="px-3 py-2 text-xs text-gray-500 bg-port-card border border-port-border rounded-lg space-y-1">
+ {/* Reference text, not a control — collapsed by default so the run
+ settings and the request list both stay above the fold. It used to be
+ four permanently-expanded paragraphs, which pushed the first row off a
+ laptop screen for an explanation you read once. */}
+ <CollapsibleSection
+ icon={Info}
+ label="What each action does"
+ size="bar"
+ id="pull-request-action-help"
+ className="px-3 py-1 bg-port-card border border-port-border rounded-lg"
+ bodyClassName="pb-2 space-y-1 text-xs text-gray-500"
+ >
<p>
Merge lands the request on the forge immediately — no agent, no review, no model spend. Pick the merge method and whether to delete the source branch, then confirm. A long-lived source branch (a <span className="font-mono">main → release</span> request) is never deleted.
</p>
<p>
- Resolve and merge starts a PortOS agent right away to inspect feedback, fix the branch, wait for checks, and merge when the forge allows it. It uses the configured Code Review Defaults.
+ Resolve and merge starts a PortOS agent right away to inspect feedback, fix the branch, wait for checks, and merge when the forge allows it. It reviews the change under the Code review setting below.
</p>
{offersKind('review') && (
<p>
- PR review points the <span className="font-mono">pr-reviewer</span> scheduled task at this one request instead of letting it sweep every open contributor PR. It appears only on requests it can review — opened by someone else against the default branch — and uses the providers saved on its review stages. The security scan must pass before either review stage runs.
+ PR review points the <span className="font-mono">pr-reviewer</span> scheduled task at this one request instead of letting it sweep every open contributor PR. It appears only on requests it can review — opened by someone else against the default branch — and uses the providers saved on its review stages, so the Code review setting below does not apply to it. The security scan must pass before either review stage runs.
</p>
)}
{offersKind('doReview') && (
<p>
- Do:Review runs the <span className="font-mono">/do:review</span> workflow against one request with your Code Review Defaults and posts the findings as an inline review. It is review-only — nothing is committed, pushed, or merged — and it is offered on every open request, including the code-contributor PRs the pr-reviewer task skips.
+ Do:Review runs the <span className="font-mono">/do:review</span> workflow against one request and posts the findings as an inline review. It is review-only — nothing is committed, pushed, or merged — and it is offered on every open request, including the code-contributor PRs the pr-reviewer task skips.
</p>
)}
- </div>
+ </CollapsibleSection>
- <div className="flex flex-col sm:flex-row sm:items-center gap-2 px-3 py-2 bg-port-card border border-port-border rounded-lg">
- <span className="flex items-center gap-1.5 text-xs text-gray-500 uppercase tracking-wide shrink-0">
- <Bot size={14} /> Run with
- </span>
- <div className="flex-1">
- <ProviderModelSelector
- providers={providers}
- selectedProviderId={selectedProviderId}
- selectedModel={selectedModel}
- availableModels={availableModels}
- onProviderChange={(id) => { setSelectedProviderId(id); setEffort(''); }}
- onModelChange={setSelectedModel}
- effort={effort}
- onEffortChange={setEffort}
- emptyProviderOption="Auto (default)"
- emptyModelOption="Default model"
- compact
- highlightToolUse
- />
+ <div className="space-y-3 px-3 py-2 bg-port-card border border-port-border rounded-lg">
+ <div className="flex flex-col sm:flex-row sm:items-center gap-2">
+ <span className="flex items-center gap-1.5 text-xs text-gray-500 uppercase tracking-wide shrink-0">
+ <Bot size={14} /> Run with
+ </span>
+ <div className="flex-1">
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={(id) => { setSelectedProviderId(id); setEffort(''); }}
+ onModelChange={setSelectedModel}
+ effort={effort}
+ onEffortChange={setEffort}
+ emptyProviderOption="Auto (default)"
+ emptyModelOption="Default model"
+ compact
+ highlightToolUse
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-col sm:flex-row sm:items-center gap-2">
+ <label htmlFor={reviewModeId} className="flex items-center gap-1.5 text-xs text-gray-500 uppercase tracking-wide shrink-0">
+ <ClipboardCheck size={14} /> Code review
+ </label>
+ <div className="flex-1 flex flex-wrap items-center gap-2">
+ <select
+ id={reviewModeId}
+ value={reviewMode}
+ onChange={event => setReviewMode(event.target.value)}
+ className="px-2.5 py-1.5 bg-port-bg border border-port-border rounded-lg text-xs text-white focus:border-port-accent focus:outline-hidden"
+ >
+ {PR_REVIEW_MODE_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>{option.label}</option>
+ ))}
+ </select>
+ <span className="text-xs text-gray-500">{prReviewModeOption(reviewMode)?.description}</span>
+ </div>
</div>
- </div>
- <div className="text-xs text-gray-400">
- <input id="override-pr-review-provider" type="checkbox" checked={overrideReviewProvider}
- onChange={event => setOverrideReviewProvider(event.target.checked)} className="mr-2" />
- <label htmlFor="override-pr-review-provider">Use Run with for PR review eligibility</label>
- <p className="mt-1">Off by default to preserve your scheduled providers. The final code review keeps its own stage settings.</p>
+ {/* Only a delegated run HAS a roster, so the override is hidden — not
+ disabled — under self-review: a picker whose every edit is discarded
+ reads as a setting that is being ignored. */}
+ {!selfReview && (
+ <CollapsibleSection
+ label={`Reviewer override${reviewOverride ? ' (active)' : ''}`}
+ size="md"
+ id="pull-request-reviewer-override"
+ bodyClassName="pt-2 space-y-2"
+ open={overrideOpen}
+ onOpenChange={next => { setOverrideOpen(next); if (next) setOverrideMounted(true); }}
+ // Only after the first open: before that the body is unmounted (and
+ // its fetches unspent); after it, hiding rather than unmounting is
+ // what keeps a reopen from refetching.
+ keepMounted={overrideMounted}
+ >
+ {overrideMounted && <ReviewerOverride override={reviewOverride} onChange={setReviewOverride} />}
+ </CollapsibleSection>
+ )}
+
+ {offersKind('review') && (
+ <div className="text-xs text-gray-400">
+ <input id="apply-run-with-to-pr-review" type="checkbox" checked={applyRunWithToPrReview}
+ onChange={event => setApplyRunWithToPrReview(event.target.checked)} className="mr-2" />
+ <label htmlFor="apply-run-with-to-pr-review">Also run PR review on the Run with provider</label>
+ <p className="mt-1">
+ Off by default: PR review is a <span className="font-mono">pr-reviewer</span> run, and that task keeps the providers saved on its own stages. Tick this to point its scan and review stages at the provider chosen above instead. Resolve &amp; merge and Do:Review always use it.
+ </p>
+ </div>
+ )}
</div>
{error && (
diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
index f032f6a651..13d5b314ce 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
@@ -31,6 +31,10 @@ vi.mock('../../../services/api', () => ({
doReviewAppPullRequest: vi.fn(),
mergeAppPullRequest: vi.fn(),
getProviders: vi.fn(),
+ // The run-settings panel's reviewer override reads the install's Code Review
+ // Defaults for its seed and the reviewer Model column's options.
+ getCodeReviewDefaults: vi.fn(),
+ getLocalLlmStatus: vi.fn(),
}));
import * as api from '../../../services/api';
@@ -106,6 +110,11 @@ beforeEach(() => {
});
api.mergeAppPullRequest.mockResolvedValue({ number: 17, merged: true, method: 'merge', deletedBranch: true });
api.getProviders.mockResolvedValue({ activeProvider: '', providers: [] });
+ api.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['codex'], usernames: [], optionalReviewers: [], reviewerMaxRounds: {},
+ stopMode: 'all', reviewerApplies: false, installed: {},
+ });
+ api.getLocalLlmStatus.mockResolvedValue({ backends: {} });
});
afterEach(() => {
@@ -144,7 +153,7 @@ describe('PullRequestsTab', () => {
fireEvent.click(screen.getByRole('button', { name: /Resolve & merge/ }));
await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith(
- 'app-1', 17, { provider: 'claude', model: 'claude-opus-5', effort: undefined },
+ 'app-1', 17, { provider: 'claude', model: 'claude-opus-5', effort: undefined, reviewMode: 'delegated' },
));
});
@@ -168,7 +177,10 @@ describe('PullRequestsTab', () => {
));
});
- it('passes an explicitly enabled eligibility provider override', async () => {
+ // PR review hands its run to the `pr-reviewer` scheduled task, so it takes the
+ // provider pin only when the user opts in — and never the Code review setting,
+ // which governs the two actions PortOS composes here.
+ it('passes the Run with pin to PR review once the opt-in is ticked, and nothing else', async () => {
api.getProviders.mockResolvedValue({
providers: [{
id: 'claude', name: 'Claude', type: 'cli', enabled: true,
@@ -180,8 +192,9 @@ describe('PullRequestsTab', () => {
await screen.findByText('Fix the save path');
fireEvent.change(await screen.findByLabelText('Provider'), { target: { value: 'claude' } });
fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'claude-opus-5' } });
+ fireEvent.change(screen.getByLabelText('Code review'), { target: { value: 'self' } });
- fireEvent.click(screen.getByLabelText('Use Run with for PR review eligibility'));
+ fireEvent.click(screen.getByLabelText('Also run PR review on the Run with provider'));
fireEvent.click(screen.getByRole('button', { name: /PR review/ }));
await waitFor(() => expect(api.reviewAppPullRequest).toHaveBeenCalledWith(
@@ -194,7 +207,7 @@ describe('PullRequestsTab', () => {
fireEvent.click(await screen.findByRole('button', { name: /Resolve & merge/ }));
await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith(
- 'app-1', 17, { provider: undefined, model: undefined, effort: undefined },
+ 'app-1', 17, { provider: undefined, model: undefined, effort: undefined, reviewMode: 'delegated' },
));
expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();
});
@@ -407,7 +420,7 @@ describe('PullRequestsTab', () => {
fireEvent.click(screen.getByRole('button', { name: 'Do:Review' }));
await waitFor(() => expect(api.doReviewAppPullRequest).toHaveBeenCalledWith(
- 'app-1', 17, { provider: undefined, model: undefined, effort: undefined },
+ 'app-1', 17, { provider: undefined, model: undefined, effort: undefined, reviewMode: 'delegated' },
));
expect(await screen.findByRole('link', { name: /Do:Review: Queued/ })).toBeInTheDocument();
expect(toastMock.success).toHaveBeenCalledWith('Started an agent to run /do:review against GitHub #17');
@@ -454,7 +467,7 @@ describe('PullRequestsTab', () => {
expect(screen.queryByRole('button', { name: 'Retry PR review' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry Resolve & merge' }));
await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith(
- 'app-1', 17, { provider: undefined, model: undefined, effort: undefined },
+ 'app-1', 17, { provider: undefined, model: undefined, effort: undefined, reviewMode: 'delegated' },
));
expect(api.reviewAppPullRequest).not.toHaveBeenCalled();
expect(await screen.findByRole('link', { name: /Resolve & merge: Queued/ })).toBeInTheDocument();
@@ -559,4 +572,94 @@ describe('PullRequestsTab', () => {
expect(await screen.findByText('No open pull requests or merge requests.')).toBeInTheDocument();
});
+
+ // Four permanently-expanded paragraphs of reference text used to push the run
+ // settings and the first request off a laptop screen.
+ it('keeps the action explainer collapsed until asked for', async () => {
+ await renderTab();
+
+ const disclosure = await screen.findByRole('button', { name: /What each action does/ });
+ expect(disclosure).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByText(/Merge lands the request on the forge immediately/)).not.toBeInTheDocument();
+
+ fireEvent.click(disclosure);
+
+ expect(disclosure).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByText(/Merge lands the request on the forge immediately/)).toBeInTheDocument();
+ });
+
+ it('sends the self-review mode with the two actions PortOS composes itself', async () => {
+ await renderTab();
+ await screen.findByText('Fix the save path');
+
+ fireEvent.change(screen.getByLabelText('Code review'), { target: { value: 'self' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Resolve & merge' }));
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith(
+ 'app-1', 17, expect.objectContaining({ reviewMode: 'self' }),
+ ));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Do:Review' }));
+ await waitFor(() => expect(api.doReviewAppPullRequest).toHaveBeenCalledWith(
+ 'app-1', 17, expect.objectContaining({ reviewMode: 'self' }),
+ ));
+ });
+
+ // The roster only travels when the user actually edited it — an untouched
+ // picker must leave the server resolving the defaults at spawn time rather
+ // than freezing whatever this tab happened to render.
+ it('omits the reviewer roster while the picker is untouched', async () => {
+ await renderTab();
+ await screen.findByText('Fix the save path');
+
+ fireEvent.click(screen.getByRole('button', { name: /Reviewer override/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Resolve & merge' }));
+
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalled());
+ expect(api.resolveAppPullRequest.mock.calls[0][2]).not.toHaveProperty('reviewers');
+ });
+
+ // Dropping the seeded `codex` row is an edit, so the (now empty) roster has to
+ // be sent — otherwise the run silently reviews with the very default the user
+ // just removed.
+ it('sends an edited roster, including one edited down to empty', async () => {
+ await renderTab();
+ await screen.findByText('Fix the save path');
+
+ fireEvent.click(screen.getByRole('button', { name: /Reviewer override/ }));
+ fireEvent.click(await screen.findByRole('button', { name: /^Remove codex$/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'Resolve & merge' }));
+
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalled());
+ expect(api.resolveAppPullRequest.mock.calls[0][2]).toMatchObject({ reviewers: [] });
+ });
+
+ // The picker emits a partial against its baseline, so editing a field back to
+ // the default empties that partial — the override has to disappear with it,
+ // or the panel keeps claiming an override the run no longer has.
+ it('drops the override once every edit is undone', async () => {
+ await renderTab();
+ await screen.findByText('Fix the save path');
+
+ fireEvent.click(screen.getByRole('button', { name: /Reviewer override/ }));
+ fireEvent.click(await screen.findByRole('button', { name: /^Remove codex$/i }));
+ expect(screen.getByRole('button', { name: /Reviewer override \(active\)/ })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Codex$/ }));
+ expect(screen.getByRole('button', { name: /^Reviewer override$/ })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Resolve & merge' }));
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalled());
+ expect(api.resolveAppPullRequest.mock.calls[0][2]).not.toHaveProperty('reviewers');
+ });
+
+ // A picker whose every edit would be discarded reads as a setting being
+ // ignored, so self-review hides it rather than disabling it.
+ it('hides the reviewer override under self-review', async () => {
+ await renderTab();
+ await screen.findByText('Fix the save path');
+
+ expect(screen.getByRole('button', { name: /Reviewer override/ })).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText('Code review'), { target: { value: 'self' } });
+ expect(screen.queryByRole('button', { name: /Reviewer override/ })).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 59a5b1e41a..51615efa1a 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -19,6 +19,7 @@ import { normalizeReviewerSlug, REVIEWER_VALUES } from '../../lib/reviewerPins';
import { AVATAR_STYLE_LABELS } from '../../lib/avatarStyles';
import { inPlaceClipName } from '../../utils/animationClips';
import { getNavPageForPath, getPageNavTabs } from '../../../../server/lib/navManifest.js';
+import { PR_REVIEW_MODES, DEFAULT_PR_REVIEW_MODE } from '../../../../server/lib/prDisposition.js';
import { buildPageNavTabs } from '../../lib/pageNavTabs.js';
// Icon per tab id. The manifest (`tabGroup: 'cos'`) owns id/label/order — this
@@ -264,6 +265,27 @@ export const prCompletionOption = (value) => PR_COMPLETION_OPTIONS.find(option =
export const DEFAULT_PR_COMPLETION = 'review-then-merge';
+// WHO reviews a PR action's change — orthogonal to `PR_COMPLETION_OPTIONS`
+// above, which decides whether a review happens at all. The values come from
+// the server leaf that owns the vocabulary (it imports nothing, so reaching for
+// it costs the bundle nothing); only the UI copy lives here.
+export const PR_REVIEW_MODE_OPTIONS = [
+ {
+ value: PR_REVIEW_MODES.DELEGATED,
+ label: 'Delegated reviewers',
+ description: 'The agent orchestrates your Code Review Defaults roster as separate reviewer runs.',
+ },
+ {
+ value: PR_REVIEW_MODES.SELF,
+ label: 'Self-review only',
+ description: 'The Run with provider reviews the change itself — no child review agents.',
+ },
+];
+
+export const prReviewModeOption = (value) => PR_REVIEW_MODE_OPTIONS.find(option => option.value === value);
+
+export { PR_REVIEW_MODES, DEFAULT_PR_REVIEW_MODE };
+
// The policy a task falls back to when nothing pins `prCompletion` — mirrors the
// `resolvePrCompletion` fallback in server/lib/prDisposition.js (legacy
// `reviewLoop` records aside). Scheduled tasks inherit their app's
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 0d0ac83ae0..5ffc5f55b3 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -101,9 +101,13 @@ export const scoreAppScopeAdherence = (id, change, options = {}) =>
});
// Queue the shared review-loop follow-up for one freshly verified open PR/MR.
// The server, not the browser, owns the forge URL/branch and duplicate guard.
-// `settings` is the same provider/model/effort pin `createSlashdoTask` takes —
-// the Pull Requests tab's "Run with" picker — left blank to resolve the
-// install's active provider.
+// `settings` is the Pull Requests tab's run-settings panel: the same
+// provider/model/effort pin `createSlashdoTask` takes, plus this run's review
+// settings — `reviewMode` (`delegated` spawns the reviewer roster, `self` leaves
+// the review to the agent itself) and, for a delegated run the user overrode, the
+// same reviewer fields (`reviewers`, `usernames`, `optionalReviewers`,
+// `reviewerMaxRounds`, `reviewerModels`, `reviewerEfforts`). Left blank it
+// resolves the install's active provider and Code Review Defaults.
export const resolveAppPullRequest = (id, number, settings = {}, options = {}) =>
request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/resolve`, {
method: 'POST',
@@ -115,9 +119,11 @@ export const resolveAppPullRequest = (id, number, settings = {}, options = {}) =
// letting it pick from the app's whole external open set. The server owns the
// eligibility check (open, GitHub, opened by someone else) and the duplicate
// guard, so a refusal comes back as an explained error rather than a run that
-// silently reviews nothing. `settings` is the same provider/model/effort pin as
-// `resolveAppPullRequest` — the server still gates the resolved provider to the
-// pr-reviewer posture's eligible set.
+// silently reviews nothing. `settings` is the provider/model/effort pin ALONE —
+// the server still gates the resolved provider to the pr-reviewer posture's
+// eligible set. Deliberately not the review settings the other two take: this
+// queues a `pr-reviewer` run, whose reviewers come from that scheduled task's
+// own stages, so a `reviewMode` sent here would be a setting nothing applies.
export const reviewAppPullRequest = (id, number, settings = {}, options = {}) =>
request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/review`, {
method: 'POST',
@@ -125,11 +131,12 @@ export const reviewAppPullRequest = (id, number, settings = {}, options = {}) =>
silent: true,
...options,
});
-// Run the bundled `/do:review` workflow against ONE open GitHub PR with the
-// install's Code Review Defaults, review-only. Unlike `reviewAppPullRequest`
-// this is offered on every open GitHub request whoever opened it — `pr-reviewer`
-// covers untrusted contributors alone. `settings` is the same provider/model/
-// effort pin as `resolveAppPullRequest`.
+// Run the bundled `/do:review` workflow against ONE open GitHub PR, review-only.
+// Unlike `reviewAppPullRequest` this is offered on every open GitHub request
+// whoever opened it — `pr-reviewer` covers untrusted contributors alone.
+// `settings` is the same run-settings body `resolveAppPullRequest` takes, review
+// mode and reviewer override included; untouched, the run resolves the install's
+// Code Review Defaults when the prompt is built.
export const doReviewAppPullRequest = (id, number, settings = {}, options = {}) =>
request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/do-review`, {
method: 'POST',
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 2eaf1c18fa..18fe824b6a 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -13,7 +13,7 @@ import { emptyToUndefined, emptyToNull, providerRefFieldSchema, providerRefSchem
import { isPlainObject } from './objects.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { isValidSlashdoCommand } from './slashdoInvocation.js';
-import { PR_COMPLETION_VALUES } from './prDisposition.js';
+import { PR_COMPLETION_VALUES, PR_REVIEW_MODE_VALUES } from './prDisposition.js';
import { QUEUEABLE_IMAGE_MODES } from './generationModes.js';
import { PUBLIC_REVIEW_EXECUTION_PROFILES } from './agentExecutionProfiles.js';
import { ORCHESTRATION_MODES, ORCHESTRATION_ROLES } from './orchestrationProfile.js';
@@ -1056,15 +1056,39 @@ export const slashdoTaskSchema = createCosTaskSchema
issueAuthorFilter: z.enum(ISSUE_AUTHOR_FILTERS).optional(),
});
-// POST /api/apps/:id/pull-requests/:number/resolve|review — the Pull Requests
-// tab's "Run with" picker (mirrors the Issues tab's same picker). PICKED
-// from createCosTaskSchema so the provider/model/effort vocabulary and its
-// preprocessors stay identical to every other manual dispatch surface. Every
-// field is optional — an untouched picker resolves the install's active
-// provider, same as the bare button always did.
+// The Pull Requests tab's "Run with" picker (mirrors the Issues tab's same
+// picker). PICKED from createCosTaskSchema so the provider/model/effort
+// vocabulary and its preprocessors stay identical to every other manual dispatch
+// surface. Every field is optional — an untouched picker resolves the install's
+// active provider, same as the bare button always did.
+//
+// This is the WHOLE body of `POST …/pull-requests/:number/review`, and
+// deliberately so: that route queues a `pr-reviewer` run, whose reviewers come
+// from that scheduled task's own stages, so review settings sent there would be
+// a request the server accepts and nothing applies.
export const pullRequestProviderOverrideSchema = createCosTaskSchema
.pick({ model: true, provider: true, effort: true });
+// …and the body of `/resolve` and `/do-review`, the two actions PortOS composes
+// itself: the same provider pin plus this run's review settings.
+//
+// `reviewMode` is the one field with no counterpart on the task schema: it is a
+// property of how THIS action composes its review, not of the queued task's own
+// settings, and each route translates it into that route's own vocabulary (a
+// self-review marker on the follow-up for `/resolve`, `--review-with none` for
+// `/do-review`). The reviewer fields beside it are the ordinary per-run override,
+// resolved over the install's Code Review Defaults.
+export const pullRequestRunSettingsSchema = pullRequestProviderOverrideSchema
+ .extend(createCosTaskSchema
+ .pick({
+ reviewers: true, usernames: true, optionalReviewers: true,
+ reviewerMaxRounds: true, reviewerModels: true, reviewerEfforts: true,
+ })
+ .shape)
+ .extend({
+ reviewMode: z.enum(PR_REVIEW_MODE_VALUES).optional(),
+ });
+
// POST /api/cos/agents/:id/resume — the resume dialog's edits for a paused
// agent's next run. PICKED from createCosTaskSchema for the same reason
// slashdoTaskSchema is: one vocabulary and one set of preprocessors for the
diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.js
index 5d6c055b89..7cdb550f6f 100644
--- a/server/lib/prDisposition.js
+++ b/server/lib/prDisposition.js
@@ -29,6 +29,47 @@ export const PR_COMPLETION_VALUES = Object.freeze(Object.values(PR_COMPLETIONS))
const PR_COMPLETION_SET = new Set(PR_COMPLETION_VALUES);
+/**
+ * WHO performs the code review an action triggers — orthogonal to
+ * `PR_COMPLETIONS` above, which decides whether a review happens at all.
+ *
+ * - `delegated` — the historical shape. The agent running the action is an
+ * ORCHESTRATOR: it spawns the install's Code Review Defaults roster (or a
+ * per-run override) as separate reviewer processes, collects their findings,
+ * and applies them. Several models, several invocations, the most coverage.
+ * - `self` — one agent. The provider the action runs on reviews the change
+ * itself and no reviewer CLI is spawned. Cheaper and faster, and the right
+ * answer when the top-level provider is already the model you wanted the
+ * review from; the orchestration layer was pure overhead in that case.
+ *
+ * Deliberately a mode rather than "an empty reviewer roster": an empty roster
+ * already means *no review at all* (`spawnReviewLoopFollowUp`'s merge-only
+ * path), and collapsing "nobody reviews this" into "I review this myself" would
+ * make the two indistinguishable at every layer downstream.
+ *
+ * Lives here, beside `PR_COMPLETIONS`, because both halves of the PR lifecycle
+ * read it: the routes that queue an action and the prompt sections that tell the
+ * agent what it is responsible for. This module imports nothing, so the client
+ * mirrors the vocabulary by importing it rather than restating it.
+ */
+export const PR_REVIEW_MODES = Object.freeze({
+ DELEGATED: 'delegated',
+ SELF: 'self',
+});
+
+export const PR_REVIEW_MODE_VALUES = Object.freeze(Object.values(PR_REVIEW_MODES));
+
+/** What an action runs under when the caller names no mode. */
+export const DEFAULT_PR_REVIEW_MODE = PR_REVIEW_MODES.DELEGATED;
+
+/**
+ * True when this run's review is the running agent's own job. Written as a
+ * predicate so a caller never compares against the string literal — the two
+ * spellings that matter (`'self'` and "not delegated") would otherwise drift
+ * apart the first time a third mode appears.
+ */
+export const isSelfReviewMode = (mode) => mode === PR_REVIEW_MODES.SELF;
+
/**
* Resolve a task's PR completion policy without migrating stored task data.
*
diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.js
index 3120bcb594..4c5ec667f1 100644
--- a/server/routes/apps/pullRequests.js
+++ b/server/routes/apps/pullRequests.js
@@ -19,14 +19,21 @@
* `pr-reviewer` covers untrusted contributors alone. `/merge` is the one that
* queues nothing and spends nothing: the forge's own merge button, for a change
* the user has already read.
+ *
+ * That split is why the two agent routes PortOS composes itself (`/resolve`,
+ * `/do-review`) take `pullRequestRunSettingsSchema` — the provider pin PLUS this
+ * run's review settings — while `/review` takes the provider pin alone: its run
+ * is a `pr-reviewer` task whose reviewers come from that scheduled task's own
+ * stages, so a review setting sent there would be one the server accepts and
+ * nothing applies.
*/
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { pullRequestProviderOverrideSchema } from '../../lib/cosValidation.js';
+import { pullRequestProviderOverrideSchema, pullRequestRunSettingsSchema, reviewerConfigMetadata } from '../../lib/cosValidation.js';
import { claimSafeReviewers, normalizeReviewers, validateRequest } from '../../lib/validation.js';
-import { PR_COMPLETIONS } from '../../lib/prDisposition.js';
+import { PR_COMPLETIONS, isSelfReviewMode } from '../../lib/prDisposition.js';
import { isTruthyMeta } from '../../services/agentState.js';
import { resolveReviewLoopOptions } from '../../services/codeReview.js';
import { getAllTasks } from '../../services/cos.js';
@@ -267,8 +274,11 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (r
const { number } = validateRequest(pullRequestParamsSchema, req.params);
// Optional provider/model/effort pin from the tab's "Run with" picker — left
// blank, the follow-up resolves the install's active provider exactly as it
- // always did.
- const { provider, model, effort } = validateRequest(pullRequestProviderOverrideSchema, req.body || {});
+ // always did — plus this run's review settings (mode, and any reviewer
+ // override layered over the install's Code Review Defaults).
+ const runSettings = validateRequest(pullRequestRunSettingsSchema, req.body || {});
+ const { provider, model, effort } = runSettings;
+ const selfReview = isSelfReviewMode(runSettings.reviewMode);
const { result, tasks } = await listWithActionState(app);
throwForgeReadError(result);
@@ -299,10 +309,18 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (r
return;
}
- // Code Review Defaults are the one source for the installed review roster.
+ // Code Review Defaults are the one source for the installed review roster, and
+ // this run's own reviewer override (when the panel supplied one) layers over
+ // them with the same task-over-default precedence every other dispatch surface
+ // uses — `resolveReviewLoopOptions` takes the override in the metadata slot.
// `claimSafeReviewers` removes forge-side Copilot and supplies PortOS's
// unattended coding-review fallback when the defaults contain only Copilot.
- const reviewOptions = await resolveReviewLoopOptions({}, {
+ //
+ // Resolved even under self-review, and handed over intact: emptying the roster
+ // is `spawnReviewLoopFollowUp`'s job, not this route's (see its `selfReview`
+ // contract), and the stop-mode / applies fields alongside it are not roster
+ // fields at all.
+ const reviewOptions = await resolveReviewLoopOptions(reviewerConfigMetadata(runSettings), {
normalize: normalizeReviewers,
isTruthyMeta,
});
@@ -345,6 +363,7 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (r
...reviewOptions,
reviewers,
optionalReviewers,
+ selfReview,
// This button IS the user's approval — start the agent now instead of leaving
// the follow-up as a pending system task the autonomous dequeue only picks up
// while CoS auto-run is in `execute` and under its daily budget (which is why
@@ -520,8 +539,12 @@ router.post('/:id/pull-requests/:number/do-review', loadApp, asyncHandler(async
const { number } = validateRequest(pullRequestParamsSchema, req.params);
// Optional provider/model/effort pin from the tab's "Run with" picker, applied
// exactly as /resolve applies it: this is a directly user-triggered agent run,
- // not a scheduled task with saved stage providers.
- const { provider, model, effort } = validateRequest(pullRequestProviderOverrideSchema, req.body || {});
+ // not a scheduled task with saved stage providers. The review settings ride
+ // along the same way — `/do:review` resolves its own roster at prompt-build
+ // time, so both the mode and any reviewer override are handed to the task
+ // rather than rendered into a flag here.
+ const runSettings = validateRequest(pullRequestRunSettingsSchema, req.body || {});
+ const { provider, model, effort } = runSettings;
// Deliberately NOT `listWithActionState`: that annotates every row with all
// four action fields, and its `resolveReviewEligibility` spends a `gh repo
// view`, a `gh api user`, and one collaborator-permission call per distinct PR
@@ -578,6 +601,8 @@ router.post('/:id/pull-requests/:number/do-review', loadApp, asyncHandler(async
provider,
model,
effort,
+ selfReview: isSelfReviewMode(runSettings.reviewMode),
+ reviewerConfig: reviewerConfigMetadata(runSettings),
});
if (!queued.task) {
throw new ServerError('Could not queue the pull-request review agent', {
diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.js
index 91cf4a4eec..0ed9637d5b 100644
--- a/server/routes/apps/pullRequests.test.js
+++ b/server/routes/apps/pullRequests.test.js
@@ -185,6 +185,53 @@ describe('app pull-request routes', () => {
}));
});
+ // The panel's reviewer override rides the same task-over-default resolver
+ // every other dispatch surface uses, so the run reviews with what the user
+ // picked instead of the install-wide Code Review Defaults.
+ it('layers a per-run reviewer override over the Code Review Defaults', async () => {
+ resolveReviewLoopOptions.mockResolvedValue({
+ reviewers: ['claude'], usernames: ['octocat'], optionalReviewers: ['claude'],
+ reviewerMaxRounds: { claude: 2 }, reviewStopMode: 'all', reviewerApplies: false,
+ reviewerModels: null, reviewerEfforts: null,
+ });
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve')
+ .send({ reviewers: ['claude'], usernames: ['octocat'], optionalReviewers: ['claude'], reviewerMaxRounds: { claude: 2 } });
+
+ expect(response.status).toBe(202);
+ expect(resolveReviewLoopOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ reviewers: ['claude'], usernames: ['octocat'] }),
+ expect.anything(),
+ );
+ expect(spawnReviewLoopFollowUp).toHaveBeenCalledWith(expect.objectContaining({
+ reviewers: ['claude'],
+ usernames: ['octocat'],
+ optionalReviewers: ['claude'],
+ selfReview: false,
+ }));
+ });
+
+ // The route hands the mode over and leaves the roster alone — emptying it is
+ // `spawnReviewLoopFollowUp`'s contract, so a second caller adopting the mode
+ // gets the same behavior without re-deriving it.
+ it('passes the self-review mode to the follow-up without pre-emptying the roster', async () => {
+ resolveReviewLoopOptions.mockResolvedValue({
+ reviewers: ['codex', 'claude'], usernames: ['octocat'], optionalReviewers: ['claude'],
+ reviewerMaxRounds: {}, reviewStopMode: 'all', reviewerApplies: false,
+ reviewerModels: null, reviewerEfforts: null,
+ });
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve')
+ .send({ reviewMode: 'self' });
+
+ expect(response.status).toBe(202);
+ expect(spawnReviewLoopFollowUp).toHaveBeenCalledWith(expect.objectContaining({
+ selfReview: true,
+ reviewers: ['codex', 'claude'],
+ usernames: ['octocat'],
+ }));
+ });
+
it('leaves the follow-up task unpinned when no provider override is sent', async () => {
const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');
@@ -544,6 +591,11 @@ describe('app pull-request routes', () => {
provider: undefined,
model: undefined,
effort: undefined,
+ // An untouched run-settings panel: delegated review with no roster
+ // override, which is what leaves the prompt layer reading the install's
+ // Code Review Defaults at spawn time.
+ selfReview: false,
+ reviewerConfig: {},
});
});
@@ -558,6 +610,20 @@ describe('app pull-request routes', () => {
}));
});
+ it('threads the review mode and reviewer override into the /do:review task', async () => {
+ const response = await request(app)
+ .post('/api/apps/app-001/pull-requests/17/do-review')
+ .send({ reviewMode: 'self', reviewers: ['codex'] });
+
+ expect(response.status).toBe(202);
+ // The roster still travels: the service is what decides self-review has no
+ // roster to apply, so the route must not pre-empt that decision here.
+ expect(spawnPrDoReviewTask).toHaveBeenCalledWith(expect.objectContaining({
+ selfReview: true,
+ reviewerConfig: expect.objectContaining({ reviewers: ['codex'] }),
+ }));
+ });
+
it('refuses /do:review on a GitLab forge instead of burning a run on slashdo aborting', async () => {
listAppPullRequests.mockResolvedValue({ ...listResult(), forge: 'gitlab', tracker: 'gitlab' });
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index a405c88e18..8e8970461d 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -918,13 +918,21 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }
* automatic dequeue and force-spawns the task instead (same path
* as that Run now button), reporting the outcome as `dispatch`.
*
+ * `selfReview` says the follow-up agent is the reviewer: it EMPTIES the roster
+ * (reviewers, usernames and the `~opt` set alike) and then marks the resulting
+ * no-roster run as one that still owes the change a review. That distinction is
+ * the whole point — an empty roster has always meant "nothing reviews this, just
+ * land it on green CI", and that stays what it means without this flag.
+ * Deliberately ignored on a `merge-on-green` run, where the caller asked for no
+ * review at all rather than for an undelegated one.
+ *
* Returns the follow-up task, or — when an equivalent follow-up was already
* queued — that existing task with `duplicate: true`. `dispatch: 'immediate'`
* additionally stamps `dispatch: { started, reason }` so the caller can say
* whether an agent actually started or the task is still waiting (no slots,
* daemon stopped, …) rather than guessing.
*/
-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, forkHead = null, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, dispatch = 'queue' }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, forkHead = null, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, selfReview = false, dispatch = 'queue' }) {
if (!prUrl || !prBranch) return null;
if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN) return null;
@@ -936,30 +944,49 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// misreading it as non-GitHub would strip the only reviewer and silently
// downgrade the run to merge-only.
const isNonGithubForge = !!parsedPr?.host && detectForgeCli(parsedPr.host) !== 'gh';
+ // Self-review empties the roster HERE rather than at each caller. "The agent
+ // reviews it itself" and "these reviewers review it" are mutually exclusive, so
+ // whoever holds the flag has to hold the emptying too — and the non-obvious
+ // half is the usernames: a single `@login` inherited from the Code Review
+ // Defaults keeps the roster non-empty and quietly puts the run back on the
+ // delegated path the caller opted out of. One owner, so a second caller adopting
+ // the mode cannot rediscover that the hard way.
+ //
// An EXPLICITLY empty list means "no review was requested" and must stay empty —
// normalizeReviewers' `[copilot]` default would otherwise resurrect a reviewer.
- const reviewerList = (Array.isArray(reviewers) && reviewers.length === 0) ? [] : normalizeReviewers({ reviewers });
+ const reviewerList = (selfReview || (Array.isArray(reviewers) && reviewers.length === 0))
+ ? []
+ : normalizeReviewers({ reviewers });
const effectiveReviewers = prioritizeToolFreeReviewers(
isNonGithubForge ? reviewerList.filter(r => r !== DEFAULT_REVIEWER) : reviewerList
);
// GitHub reviewer usernames are forge-agnostic requested reviewers, so they are
// NOT stripped on a non-GitHub forge — a username reviewer alone can drive the
// loop even when copilot was dropped.
- const effectiveUsernames = normalizeReviewUsernames(usernames);
+ const effectiveUsernames = selfReview ? [] : normalizeReviewUsernames(usernames);
// Non-blocking (`~opt`) marker set — forge-agnostic, threaded verbatim so the
// follow-up's `--review-with` marks the same reviewers optional.
- const effectiveOptionalReviewers = normalizeOptionalReviewers(optionalReviewers) || [];
+ const effectiveOptionalReviewers = selfReview ? [] : (normalizeOptionalReviewers(optionalReviewers) || []);
// Per-reviewer iteration caps (`~max=<n>`) — forge-agnostic, threaded verbatim
// so the follow-up's `--review-with` carries the same budgets. Entries for
// reviewers that were stripped are inert (the emitter only marks tokens it
// actually emits), so no narrowing is needed here.
const effectiveReviewerMaxRounds = normalizeReviewerMaxRounds(reviewerMaxRounds) || {};
- // Merge-on-green deliberately skips every reviewer. A legacy review loop
- // whose GitHub-only reviewer vanishes on another forge retains its prior
- // merge-only fallback instead of leaving an orphaned PR.
- const mergeOnly = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN
- || (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE
- && effectiveReviewers.length === 0 && effectiveUsernames.length === 0);
+ // A review WAS asked for, but nothing is left to perform it — a legacy review
+ // loop whose GitHub-only reviewer vanished on another forge (which retains its
+ // prior merge-only fallback rather than leaving an orphaned PR), or a caller
+ // that deliberately resolved no roster. Named rather than inlined into
+ // `mergeOnly`, because the self-review branch below is exactly this case and
+ // re-deriving it by conjunction reads as a condition that might contradict it.
+ const noRosterMerge = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE
+ && effectiveReviewers.length === 0 && effectiveUsernames.length === 0;
+ // Merge-on-green deliberately skips every reviewer.
+ const mergeOnly = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN || noRosterMerge;
+ // The follow-up reviews the change ITSELF before the CI gate. Only meaningful
+ // on the no-roster path — with reviewers configured the review loop already
+ // runs — and never on a `merge-on-green` run, where the caller asked for no
+ // review at all rather than for an undelegated one.
+ const selfReviewMerge = selfReview && noRosterMerge;
// ...and with nothing to review AND nothing to merge there is no follow-up at
// all (a JIRA-tracked task whose reviewers were all stripped). The caller
// normally catches this; the guard keeps the invariant local to this function.
@@ -989,7 +1016,9 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// One place that names the mode, so the title, the log line, and the warning
// can't drift apart as the two follow-up kinds evolve.
const kind = mergeOnly
- ? { title: 'Merge', label: 'merge', reviewers: 'merge on green CI, no review' }
+ ? (selfReviewMerge
+ ? { title: 'Self-Review & Merge', label: 'self-review-merge', reviewers: 'self-review, no delegated reviewer' }
+ : { title: 'Merge', label: 'merge', reviewers: 'merge on green CI, no review' })
: { title: 'Review Loop', label: 'review-loop', reviewers: [...effectiveReviewers, ...effectiveUsernames.map(u => `@${u}`)].join(', ') };
// Inherit the source task's provider/model/effort pins. A follow-up runs a
@@ -1045,6 +1074,11 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
reviewLoopFollowUp: true,
// Merge-only run: no reviewers, the prompt is a CI-gate-and-merge procedure.
reviewLoopMergeOnly: mergeOnly,
+ // …and, on that same path, whether the agent owes the change its OWN
+ // review first. Read by `buildMergeFollowUpSection`, which is why it sits
+ // beside the flag that selects that section rather than in the roster keys
+ // below — there is no roster in this mode.
+ reviewLoopSelfReview: selfReviewMerge,
// Review, but do NOT merge — the PR is a human's to land (JIRA hand-off).
reviewLoopLeaveOpen: leaveOpen,
reviewLoopPRUrl: prUrl,
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 6dc3df918e..bef7969d7d 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1688,6 +1688,51 @@ describe('spawnReviewLoopFollowUp', () => {
expect(addTask).toHaveBeenCalledTimes(1);
});
+ // The invariant lives here, not at the callers: "the agent reviews it itself"
+ // and "these reviewers review it" are mutually exclusive, and the non-obvious
+ // half is the usernames — one inherited `@login` keeps the roster non-empty
+ // and quietly puts the run back on the delegated path.
+ it('empties the whole roster under self-review and marks the run self-reviewing', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws',
+ reviewers: ['codex', 'claude'], usernames: ['octocat'], optionalReviewers: ['claude'],
+ selfReview: true,
+ });
+
+ expect(result.metadata.reviewLoopReviewers).toEqual([]);
+ expect(result.metadata.reviewLoopReviewerUsernames).toEqual([]);
+ expect(result.metadata.reviewLoopOptionalReviewers).toEqual([]);
+ expect(result.metadata.reviewLoopMergeOnly).toBe(true);
+ expect(result.metadata.reviewLoopSelfReview).toBe(true);
+ });
+
+ // An empty roster has always meant "nothing reviews this, land it on green
+ // CI". Only the flag distinguishes that from "I am the reviewer" — collapsing
+ // the two would land a self-review run's change unread.
+ it('leaves a plain no-roster follow-up unmarked', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws',
+ reviewers: [], usernames: [],
+ });
+
+ expect(result.metadata.reviewLoopMergeOnly).toBe(true);
+ expect(result.metadata.reviewLoopSelfReview).toBe(false);
+ });
+
+ // `merge-on-green` is a request for NO review, not for an undelegated one.
+ it('ignores the self-review flag on a merge-on-green run', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws',
+ prCompletion: 'merge-on-green', selfReview: true,
+ });
+
+ expect(result.metadata.reviewLoopMergeOnly).toBe(true);
+ expect(result.metadata.reviewLoopSelfReview).toBe(false);
+ });
+
it('should default priority to MEDIUM when originalTask omits it', async () => {
await spawnReviewLoopFollowUp({
originalAgentId: 'agent-1',
diff --git a/server/services/prDoReviewTask.js b/server/services/prDoReviewTask.js
index 2a5a070598..4b8ace4f1f 100644
--- a/server/services/prDoReviewTask.js
+++ b/server/services/prDoReviewTask.js
@@ -29,7 +29,17 @@
* `--review-with` at queue time instead would take slashdo's precedence-1
* path, which makes task-level reviewer pins unreachable, suppresses the
* per-reviewer effort note, and freezes a roster that may sit in the queue
- * while the defaults change.
+ * while the defaults change. A per-run reviewer OVERRIDE is therefore
+ * persisted as task metadata (`reviewerConfig`), not flattened into a flag —
+ * it then wins over the defaults through that same resolver.
+ *
+ * **Self-review is the one exception**, and deliberately so. It is not a
+ * roster at all but slashdo's own documented opt-out, so it has to ride the
+ * invocation: `--review-with none` sets `REVIEW_AGENTS=[]` with no fallback,
+ * which leaves the host CLI's own self-review as the whole review. Because it
+ * IS precedence-1, `resolveSlashdoReviewContract` recognizes it and prunes
+ * every delegated reviewer loop out of the prompt — the pruning and the run
+ * stay in agreement, which is exactly what that precedence exists to protect.
* - **No contributor prose enters the prompt.** The context names the PR
* number and URL; the title, body, and diff stay on the forge, where the
* workflow reads them as the untrusted data the prompt says they are.
@@ -58,13 +68,17 @@ export const isDoReviewTask = (metadata) => metadata?.slashdoCommand === DO_REVI
* `/do:review` body the prompt builder inlines; this says which request, and
* that the request is evidence rather than instruction.
*/
-function renderContext({ number, url, repoLabel }) {
+function renderContext({ number, url, repoLabel, selfReview }) {
return [
`Review pull request #${number} in ${repoLabel} (${url}) and publish the result as a review on that pull request.`,
'',
UNTRUSTED_PULL_REQUEST_NOTICE,
'',
'This run is review-only. The invocation carries `--no-apply`: publish findings as an inline review and do not commit, push, check the branch out, or merge. Landing the PR is a separate action the user triggers themselves.',
+ ...(selfReview ? [
+ '',
+ 'The invocation also carries `--review-with none`: YOU are the reviewer. Do not spawn, shell out to, or request any other review agent — your own pass is the whole review, so read the diff with the care you would otherwise delegate.',
+ ] : []),
].join('\n');
}
@@ -90,9 +104,18 @@ function renderContext({ number, url, repoLabel }) {
* @param {string} [params.provider] - "Run with" provider pin
* @param {string} [params.model] - "Run with" model pin
* @param {string} [params.effort] - "Run with" reasoning-effort pin
+ * @param {boolean} [params.selfReview] - run with no delegated reviewers, so the
+ * provider above is the only thing that reads the diff (`--review-with none`)
+ * @param {Object} [params.reviewerConfig] - already-sanitized reviewer override
+ * (`reviewerConfigMetadata`) persisted for the prompt layer to resolve over
+ * the install's Code Review Defaults. Ignored under `selfReview`, which has no
+ * roster to override.
* @returns {Promise<{task: Object|null, duplicate: boolean, dispatch: {started: boolean, reason: string|null}}>}
*/
-export async function spawnPrDoReviewTask({ app, pullRequest, repoFullName = '', provider, model, effort } = {}) {
+export async function spawnPrDoReviewTask({
+ app, pullRequest, repoFullName = '', provider, model, effort,
+ selfReview = false, reviewerConfig = null,
+} = {}) {
const { addTask, forceSpawnTask } = await import('./cos.js');
const { number, url } = pullRequest;
const appLabel = String(app.name || app.id).replace(/\s+/g, ' ').trim();
@@ -102,12 +125,20 @@ export async function spawnPrDoReviewTask({ app, pullRequest, repoFullName = '',
description: `Review PR #${number} for ${appLabel}`,
app: app.id,
priority: 'HIGH',
- context: renderContext({ number, url, repoLabel }),
+ context: renderContext({ number, url, repoLabel, selfReview }),
slashdoCommand: DO_REVIEW_COMMAND,
// The URL is what puts slashdo into PR mode; `--no-apply` is the one flag
- // this button owns. Everything about reviewers is left to the prompt layer.
- slashdoArgs: `${url} --no-apply`,
+ // this button always owns. `--review-with none` joins it only for a
+ // self-review run — see the module doc for why that one review setting has
+ // to ride the invocation while a roster override rides the metadata.
+ slashdoArgs: `${url} --no-apply${selfReview ? ' --review-with none' : ''}`,
provider, model, effort,
+ // The per-run reviewer override, spread as top-level task fields so
+ // `buildTaskMetadata` normalizes each one exactly as it does for every other
+ // dispatch surface. Absent under self-review and absent when the panel was
+ // left untouched — either way the prompt layer falls back to the install's
+ // Code Review Defaults, which is the behavior this button always had.
+ ...(selfReview ? {} : (reviewerConfig || {})),
// The catalog's own posture for `review` (no worktree, no PR, no simplify,
// a clean tree IS the success shape), read rather than restated so a catalog
// change reaches this surface too.
diff --git a/server/services/prDoReviewTask.test.js b/server/services/prDoReviewTask.test.js
index 1eb252eb9b..c9b63686a4 100644
--- a/server/services/prDoReviewTask.test.js
+++ b/server/services/prDoReviewTask.test.js
@@ -37,6 +37,10 @@ describe('spawnPrDoReviewTask', () => {
// pins unreachable and freeze the roster at click time. `promptSections/
// slashdo.js` resolves it from Code Review Defaults when the prompt is built.
expect(task.slashdoArgs).toBe('https://github.com/acme/widget/pull/17 --no-apply');
+ // …and nothing about the roster or the reviewer is pinned onto the task
+ // either, so the default run is exactly the one this button always queued.
+ expect(task).not.toHaveProperty('reviewers');
+ expect(task.context).not.toContain('YOU are the reviewer');
});
it('forces a posture that cannot switch the app\'s live checkout to the PR branch', async () => {
@@ -96,6 +100,47 @@ describe('spawnPrDoReviewTask', () => {
expect(result).toMatchObject({ duplicate: true, dispatch: { started: false } });
expect(forceSpawnTask).not.toHaveBeenCalled();
});
+
+ // A per-run roster is persisted as task metadata so the prompt layer resolves
+ // it OVER the Code Review Defaults. Rendering it as `--review-with` here would
+ // take slashdo's precedence-1 path and freeze the roster at click time.
+ it('persists a reviewer override as task fields rather than as a flag', async () => {
+ await queue({ reviewerConfig: { reviewers: ['codex'], reviewerModels: { codex: 'gpt-5.6-sol' } } });
+
+ const task = queuedTask();
+ expect(task).toMatchObject({ reviewers: ['codex'], reviewerModels: { codex: 'gpt-5.6-sol' } });
+ expect(task.slashdoArgs).not.toContain('--review-with');
+ });
+
+ // The one review setting that MUST ride the invocation: `none` is slashdo's
+ // own opt-out, and being precedence-1 is what lets the prompt builder prune
+ // every delegated reviewer loop and still describe the run accurately.
+ it('opts out of delegated reviewers with --review-with none under self-review', async () => {
+ await queue({ selfReview: true });
+
+ const task = queuedTask();
+ expect(task.slashdoArgs).toBe('https://github.com/acme/widget/pull/17 --no-apply --review-with none');
+ expect(task.context).toContain('YOU are the reviewer');
+ });
+
+ // Self-review has no roster, so an override that arrived alongside it would be
+ // a reviewer list the run then refuses to use — a task record that disagrees
+ // with the prompt built from it.
+ it('drops a reviewer override under self-review instead of persisting a roster it will not use', async () => {
+ await queue({ selfReview: true, reviewerConfig: { reviewers: ['codex'] } });
+
+ const task = queuedTask();
+ expect(task).not.toHaveProperty('reviewers');
+ });
+
+ it('leaves the invocation and the roster alone for an untouched delegated run', async () => {
+ await queue();
+
+ const task = queuedTask();
+ expect(task.slashdoArgs).toBe('https://github.com/acme/widget/pull/17 --no-apply');
+ expect(task).not.toHaveProperty('reviewers');
+ expect(task.context).not.toContain('YOU are the reviewer');
+ });
});
describe('isDoReviewTask', () => {
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 441180237a..2644e3d607 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -31,6 +31,21 @@ export function isMergeOnlyFollowUp(metadata = {}) {
return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';
}
+/**
+ * True when a no-roster follow-up still owes the change a review — the agent's
+ * OWN, because the user chose self-review over delegating to reviewer CLIs.
+ *
+ * A refinement of `isMergeOnlyFollowUp`, not an alternative to it: the section
+ * is the same CI-gate-and-merge procedure, with a review step in front and the
+ * "do NOT start a code review" instructions inverted. Same string tolerance as
+ * every other follow-up flag, for the same reason — task metadata round-trips
+ * through the markdown task file.
+ */
+export function isSelfReviewFollowUp(metadata = {}) {
+ return isMergeOnlyFollowUp(metadata)
+ && (metadata?.reviewLoopSelfReview === true || metadata?.reviewLoopSelfReview === 'true');
+}
+
/**
* Adapt slashdo's local-agent recipe for the pre-PR half of a manual workflow.
* The normal recipe pushes after each reviewer pass so a later PR-side reviewer
@@ -717,6 +732,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
return buildMergeFollowUpSection({
prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,
mergeGateForge: forge.mergeGateForge, inlineWorkflowStep, localReviewers: localPhaseReviewerList, localReviewRequired: localPhaseReviewRequired,
+ selfReview: isSelfReviewFollowUp(metadata),
});
}
const phase = resolveReviewPhase({
@@ -1055,21 +1071,75 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
* Loop off, or copilot-only on a non-GitHub forge). Nothing else will touch the
* PR, so the merge gate is CI alone (`buildCiMergeGateSteps`).
*
+ * `selfReview` is the same procedure for the other reason a follow-up has no
+ * roster: the user chose self-review, so the agent reviews the change itself
+ * before the CI gate instead of delegating to reviewer CLIs. It is one flag
+ * rather than a fourth phase in `resolveReviewPhase` because every step below is
+ * unchanged — only who reads the diff differs. What that costs is that several
+ * sentences have to flip together, which is why they are a per-reason record
+ * (`REVIEW_MODES`) rather than a ternary apiece.
+ *
* @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.
* @returns {string}
*/
-function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, mergeGateForge = 'github', inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localReviewers = [], localReviewRequired = false }) {
+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, mergeGateForge = 'github', inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localReviewers = [], localReviewRequired = false, selfReview = false }) {
const inline = inlineExitStep !== null;
const hasLocalReview = Array.isArray(localReviewers) && localReviewers.length > 0;
- const localReviewLabel = hasLocalReview
- ? `The pre-PR local review for ${localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')} has completed; no PR-side code reviewer is configured. The merge gate still re-runs that local review after any conflict rebase${localReviewRequired ? '; a `review-blocked` result leaves the PR/MR open until the required review completes' : ''}.`
- : 'No code review was requested for this task, so nothing else will merge this PR';
+ // WHY this follow-up has no roster, decided once. Every sentence that differs
+ // between the three reasons reads from the record below rather than re-testing
+ // the discriminant, so a fourth reason is one entry instead of four scattered
+ // ternaries that can disagree about what the run is responsible for.
+ //
+ // `exitNote` is the only field with two spellings, and deliberately: the
+ // standalone exit sentence is a CLAUSE inside a longer sentence, and the
+ // no-review case truncates there rather than lowercasing its own `inline`
+ // form, so neither survives being derived from the other.
+ const REVIEW_MODES = {
+ // The user declined to DELEGATE, not to review. `steps` runs before the CI
+ // gate so its fixes are part of what CI then verifies; reviewing after a
+ // green run would either re-open the gate or land unreviewed code. Spelled
+ // out rather than delegated to a slashdo body because this agent has no
+ // reviewer to invoke — there is no invocation recipe to inline, only a
+ // standard to hold itself to.
+ self: {
+ headingPrefix: 'Self-Review & ',
+ label: () => 'No delegated reviewer is configured for this PR — you are its reviewer, and once you have reviewed it nothing else will',
+ objective: inline ? 'Review it yourself, then land it once CI is green.' : 'Your job is to review it yourself and then land it once CI is green.',
+ exitNote: inline
+ ? 'Do NOT delegate a second code review to another agent or CLI — your own pass above is the whole review.'
+ : 'do NOT delegate a second code review to another agent or CLI — your own pass above is the whole review; ',
+ steps: [
+ '1. **Review the change yourself, before the CI gate.** Read the full diff this PR proposes (`gh pr diff` against its head, or `git diff <base>...HEAD` in the checkout) and review it as a reviewer would: correctness bugs first, then contract, compatibility and data-safety breaks, then reuse and simplification. Review this change and directly affected contracts only — report material issues with concrete wrong outcomes, and skip repository-wide audits, style preferences, speculation, and nits.',
+ '2. **Fix what you found, on this branch.** Commit the fixes (`fix:` prefix, no Co-Authored-By) and push before the gate below, so CI verifies the reviewed state rather than the state you reviewed. If a finding needs a product decision you cannot make, leave the PR open and say so in your completion summary instead of merging past it.',
+ ],
+ },
+ // A pre-PR local phase already reviewed; only the PR-SIDE roster is empty.
+ local: {
+ headingPrefix: '',
+ label: () => `The pre-PR local review for ${localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')} has completed; no PR-side code reviewer is configured. The merge gate still re-runs that local review after any conflict rebase${localReviewRequired ? '; a \`review-blocked\` result leaves the PR/MR open until the required review completes' : ''}.`,
+ objective: inline ? 'Land it yourself once CI is green.' : 'Your job is to land it once CI is green.',
+ exitNote: inline
+ ? 'Do NOT start a second PR-side code review — the pre-PR local review is the only configured review.'
+ : 'do NOT start a second PR-side code review — the pre-PR local review is the only configured review; ',
+ steps: [],
+ },
+ // Review Loop off, or every configured reviewer stripped: nothing reviews.
+ none: {
+ headingPrefix: '',
+ label: () => 'No code review was requested for this task, so nothing else will merge this PR',
+ objective: inline ? 'Land it yourself once CI is green.' : 'Your job is to land it once CI is green.',
+ exitNote: inline ? 'Do NOT start a code review — none is configured for this task.' : 'do NOT start a code review — ',
+ steps: [],
+ },
+ };
+ const mode = REVIEW_MODES[selfReview ? 'self' : hasLocalReview ? 'local' : 'none'];
+
// PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed
// `gh` commands. The caller resolved that once — its override first, the
// persisted PR host only as the fallback — and hands the answer down here.
// This arm used to re-derive it from the host for a non-inline gate, which
// told a self-managed GitLab run to land its MR with `gh pr merge` (#6846).
- const gate = buildCiMergeGateSteps(1, {
+ const gate = buildCiMergeGateSteps(mode.steps.length + 1, {
prRef: `"${prUrl}"`,
mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',
forge: mergeGateForge,
@@ -1080,10 +1150,11 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
alreadyMergedHint: inline ? '' : undefined,
});
const steps = [
+ ...mode.steps,
...gate.lines,
inline
- ? `${gate.nextStep}. ${inlineExitStep} ${hasLocalReview ? 'Do NOT start a second PR-side code review — the pre-PR local review is the only configured review.' : 'Do NOT start a code review — none is configured for this task.'}`
- : `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and ${hasLocalReview ? 'do NOT start a second PR-side code review — the pre-PR local review is the only configured review; ' : 'do NOT start a code review — '}landing this PR is the whole job.`,
+ ? `${gate.nextStep}. ${inlineExitStep} ${mode.exitNote}`
+ : `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and ${mode.exitNote}landing this PR is the whole job.`,
];
const prDetails = verbose ? [
'',
@@ -1096,10 +1167,10 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
].filter(Boolean) : [];
return [
- inline ? '## Merge Gate' : '## Merge Follow-up (PRIMARY OBJECTIVE)',
+ `## ${mode.headingPrefix}Merge ${inline ? 'Gate' : 'Follow-up (PRIMARY OBJECTIVE)'}`,
inline
- ? `This runs as **step ${inlineWorkflowStep} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **${localReviewLabel} Land it yourself once CI is green.**`
- : `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **${localReviewLabel} Your job is to land it once CI is green.**`,
+ ? `This runs as **step ${inlineWorkflowStep} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **${mode.label()} ${mode.objective}**`
+ : `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **${mode.label()} ${mode.objective}**`,
'',
...steps,
'',
diff --git a/server/services/promptSections/reviewLifecycleMatrix.test.js b/server/services/promptSections/reviewLifecycleMatrix.test.js
index cb5be124f3..426d12120b 100644
--- a/server/services/promptSections/reviewLifecycleMatrix.test.js
+++ b/server/services/promptSections/reviewLifecycleMatrix.test.js
@@ -379,3 +379,73 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with their
expect(section).not.toContain('glab mr merge');
});
});
+
+/**
+ * Self-review is the third reason a follow-up has no reviewer roster, and the
+ * only one where the agent still owes the change a review. It shares the
+ * merge-only section, so the failure mode is a prompt that reads like the other
+ * two: an agent told "no code review was requested" lands the branch unread,
+ * which is the opposite of what the user asked for by choosing self-review.
+ */
+describe('buildReviewLoopFollowUpSection — self-review follow-up', () => {
+ const selfReview = (over = {}, opts = {}) => buildReviewLoopFollowUpSection(
+ fixture({ reviewLoopMergeOnly: true, reviewLoopSelfReview: true, ...over }),
+ { verbose: false, ...opts },
+ );
+
+ it('asks the agent to review the change before the CI gate, and renumbers the gate around it', () => {
+ const section = selfReview();
+
+ expect(section).toContain('## Self-Review & Merge Follow-up (PRIMARY OBJECTIVE)');
+ expect(section).toContain('1. **Review the change yourself, before the CI gate.**');
+ expect(section).toContain('2. **Fix what you found, on this branch.**');
+ // The CI gate's four steps start after the two review steps rather than at 1.
+ expect(section).toContain('3. **Wait for CI to finish**');
+ expect(section).toContain('6. **Confirm the merge before exiting**');
+ // …and its merge command is untouched: only who reads the diff changed.
+ expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');
+ });
+
+ it('never tells a self-reviewing agent that no review was requested', () => {
+ const section = selfReview();
+
+ expect(section).toContain('you are its reviewer');
+ expect(section).not.toContain('No code review was requested for this task');
+ expect(section).not.toContain('do NOT start a code review');
+ expect(section).toContain('do NOT delegate a second code review');
+ });
+
+ it('leaves a plain merge-only follow-up unchanged', () => {
+ const section = buildReviewLoopFollowUpSection(
+ fixture({ reviewLoopMergeOnly: true }),
+ { verbose: false },
+ );
+
+ expect(section).toContain('## Merge Follow-up (PRIMARY OBJECTIVE)');
+ expect(section).toContain('No code review was requested for this task');
+ expect(section).toContain('1. **Wait for CI to finish**');
+ expect(section).not.toContain('Review the change yourself');
+ });
+
+ // The marker round-trips through the markdown task file as a string, exactly
+ // like every other follow-up flag.
+ it('accepts the string form the task file round-trips', () => {
+ const section = selfReview({ reviewLoopMergeOnly: 'true', reviewLoopSelfReview: 'true' });
+ expect(section).toContain('## Self-Review & Merge Follow-up (PRIMARY OBJECTIVE)');
+ });
+
+ // A self-review marker is meaningless without the no-roster path that selects
+ // this section — a run with reviewers configured already reviews.
+ it('ignores the marker when a reviewer roster is configured', () => {
+ const section = buildReviewLoopFollowUpSection(fixture({ reviewLoopSelfReview: true }), { verbose: false });
+ expect(section).not.toContain('Self-Review & Merge');
+ });
+
+ it('renders the inline arm as a self-review gate', () => {
+ const section = selfReview({}, { inlineExitStep: INLINE_EXIT_STEP });
+
+ expect(section).toContain('## Self-Review & Merge Gate');
+ expect(section).toContain('Review it yourself, then land it once CI is green.');
+ expect(section).toContain('Do NOT delegate a second code review');
+ });
+});