Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: pass reviewer configuration to prompt builders as one reviewPolicy (#9156)
[._.]/ Adam Eivya41255f5120b
diff --git a/server/lib/README.md b/server/lib/README.mdindex 32ff6f0a5c..7be40c1cc4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -200,7 +200,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. `parseAntigravityModelList(stdout)` parses `agy models` rows — accepts both the modern `<id>\t<Label>` shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's `internal/antigravity.js`; used by both the provider-catalog refresh and Image Gen's agy model picker). `isAntigravityModelId(id)` is the same id shape as a bare predicate, for spawn sites building an `agy --model` argv from a value no route schema bounded. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. || `llmText.js` | Pure LLM-output text helpers — `stripCodeFences` (unfence a model reply) and `parseLLMJSON` (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration. || `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `services/promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |-| `reviewerConfig.js` | Review-Loop reviewer vocabulary (split out of `cosValidation.js`, #5702; Zod-free): the reviewer roster + aliases (`REVIEWER_VALUES` / `REVIEWER_ALIASES` / `DEFAULT_REVIEWER`), the local-LLM / PortOS-only / model-capable / effort-selectable subsets, the slug→CLI-binary map (`REVIEWER_CLI_BINARIES`, `isCliReviewer`, `reviewerCliBinary`), the keyed model/effort/max-rounds pin normalizers + resolvers (`normalizeReviewers`, `normalizeReviewerModels`, `normalizeReviewerEfforts`, `resolveReviewerGroup` — task reviewer overrides fall back through system tiers when paused, `resolveReviewerConfig`, `resolveClaimReviewerConfig`, `KEYED_REVIEWER_PINS`), the override-key rosters that say when a task has pinned its own reviewers (`REVIEWER_OVERRIDE_KEYS` — everything the picker writes and its reset clears; `REVIEWER_LIST_OVERRIDE_KEYS` / `hasReviewerOverride` — only the keys that can change the resolved LIST), and the emitters that render a reviewer set into slashdo argv (`buildReviewWithArgs` — which emits `--reviewer-applies` only alongside an `APPLY_CAPABLE_REVIEWERS` slug, the reviewers slashdo lets edit the tree, `buildReviewersCsv`) and into agent-prompt notes (`buildReviewerPinNote`, `buildReviewerEffortNote`). Re-exported flat by `cosValidation.js`, so existing `validation.js` imports keep resolving. Provider-backed identities use `provider:<id>` (`isProviderReviewer`, `isReviewer`, `isToolFreeReviewer`) and additive `providerModels` defaults; legacy scalar pins stay compatible. `REVIEWER_CONFIG_FAULT_CODES` / `isReviewerConfigFault` name the refusals a caller fixes by changing configuration (no model, missing/disabled provider, missing CLI command or unsupported explicitly restricted transport) rather than by retrying, so a reviewer that can never answer is not mistaken for a transient outage. |+| `reviewerConfig.js` | Review-Loop reviewer vocabulary (split out of `cosValidation.js`, #5702; Zod-free): the reviewer roster + aliases (`REVIEWER_VALUES` / `REVIEWER_ALIASES` / `DEFAULT_REVIEWER`), the local-LLM / PortOS-only / model-capable / effort-selectable subsets, the slug→CLI-binary map (`REVIEWER_CLI_BINARIES`, `isCliReviewer`, `reviewerCliBinary`), the keyed model/effort/max-rounds pin normalizers + resolvers (`normalizeReviewers`, `normalizeReviewerModels`, `normalizeReviewerEfforts`, `resolveReviewerGroup` — task reviewer overrides fall back through system tiers when paused, `resolveReviewerConfig`, `resolveReviewPolicy` — the whole reviewer config plus stop-mode and the public-forge `reviewerApplies` clamp as ONE frozen `reviewPolicy` the prompt builders take, `resolveClaimReviewerConfig`, `KEYED_REVIEWER_PINS`), the override-key rosters that say when a task has pinned its own reviewers (`REVIEWER_OVERRIDE_KEYS` — everything the picker writes and its reset clears; `REVIEWER_LIST_OVERRIDE_KEYS` / `hasReviewerOverride` — only the keys that can change the resolved LIST), and the emitters that render a reviewer set into slashdo argv (`buildReviewWithArgs` — which emits `--reviewer-applies` only alongside an `APPLY_CAPABLE_REVIEWERS` slug, the reviewers slashdo lets edit the tree, `buildReviewersCsv`) and into agent-prompt notes (`buildReviewerPinNote`, `buildReviewerEffortNote`). Re-exported flat by `cosValidation.js`, so existing `validation.js` imports keep resolving. Provider-backed identities use `provider:<id>` (`isProviderReviewer`, `isReviewer`, `isToolFreeReviewer`) and additive `providerModels` defaults; legacy scalar pins stay compatible. `REVIEWER_CONFIG_FAULT_CODES` / `isReviewerConfigFault` name the refusals a caller fixes by changing configuration (no model, missing/disabled provider, missing CLI command or unsupported explicitly restricted transport) rather than by retrying, so a reviewer that can never answer is not mistaken for a transient outage. || `reviewerHealth.js` | Dependency-free `activeReviewerGroupIndex` (shared runtime/editor pause selection), reviewer configuration-fault vocabulary and `reviewerAccessFailureCode`, which recognizes explicit structured OpenCode access refusals without treating generic HTTP or transport failures as permanent faults. || `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, gatewayKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key a gateway-backed wrapper inherits from the API record of its own gateway id unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. || `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). |diff --git a/server/lib/reviewerConfig.js b/server/lib/reviewerConfig.jsindex f40496df9b..255e336bb2 100644--- a/server/lib/reviewerConfig.js+++ b/server/lib/reviewerConfig.js@@ -11,6 +11,7 @@* This module must stay Zod-free — it is pure reviewer domain vocabulary.*/import { isPlainObject } from './objects.js';+import { isTruthyMeta } from './metadataFlags.js';import { EFFORT_LEVELS, effortLevelsForProvider, buildEffortArgs, foldCursorEffortIntoModel, splitAntigravityModel } from './providerModels.js';import { ANTIGRAVITY_COMMAND } from './antigravity.js';import { CURSOR_COMMAND } from './cursor.js';@@ -846,6 +847,39 @@ export function resolveReviewerConfig(metadata, codeReviewDefaults, defaultRevie};}+/**+ * `resolveReviewerConfig` plus the two run flags the prompt builders need — the+ * complete reviewer configuration as ONE frozen value, so a prompt builder takes+ * `reviewPolicy` instead of eight parameters and a ninth knob is added here, not+ * at every call site.+ *+ * - `forgeReviewerUsernames` — the forge logins (`@user` review tokens) requested+ * as PR/MR reviewers; the bare `usernames` of `resolveReviewerConfig`.+ * - `reviewStopMode` — task over Code Review Defaults over `DEFAULT_REVIEW_STOP_MODE`.+ * - `reviewerApplies` — the `--reviewer-applies` flag. `crossesPublicForge` clamps+ * it to `false`: a PR/MR review reads contributor-controlled public content, so+ * its reviewer stays review-only and the orchestrating agent applies the fixes.+ *+ * @param {Object|undefined} metadata - task metadata+ * @param {Object|null|undefined} codeReviewDefaults+ * @param {string[]|null|undefined} defaultReviewers+ * @param {Object} [opts]+ * @param {boolean} [opts.crossesPublicForge=false] - the run opens a PR/MR or is a+ * review-loop follow-up over one+ */+export function resolveReviewPolicy(metadata, codeReviewDefaults, defaultReviewers, { crossesPublicForge = false } = {}) {+ const { usernames, ...config } = resolveReviewerConfig(metadata, codeReviewDefaults, defaultReviewers);+ const configuredReviewerApplies = metadata?.reviewerApplies !== undefined+ ? isTruthyMeta(metadata.reviewerApplies)+ : (codeReviewDefaults?.reviewerApplies === true);+ return Object.freeze({+ ...config,+ forgeReviewerUsernames: usernames,+ reviewStopMode: metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE,+ reviewerApplies: crossesPublicForge ? false : configuredReviewerApplies+ });+}+/** The reviewer a claim flow falls back to when its resolved list is unusable. */const CLAIM_REVIEWER_FALLBACK = ['codex'];diff --git a/server/lib/reviewerConfig.test.js b/server/lib/reviewerConfig.test.jsindex 3e67c2149a..eea9bb7107 100644--- a/server/lib/reviewerConfig.test.js+++ b/server/lib/reviewerConfig.test.js@@ -32,6 +32,7 @@ import {claimSafeReviewers,prioritizeToolFreeReviewers,resolveReviewerConfig,+ resolveReviewPolicy,resolveClaimReviewerConfig,reviewerTokenSlug,reviewerModelFlag,@@ -1031,3 +1032,24 @@ describe('REVIEW_UNAVAILABLE_REPORTING_NOTE', () => {expect(REVIEW_UNAVAILABLE_REPORTING_NOTE).toContain('do NOT post a PR/MR comment');});});++describe('resolveReviewPolicy', () => {+ const defaults = { stopMode: 'on-clean', reviewerApplies: true, usernames: ['alice'] };++ it('bundles the roster with stop-mode and reviewer-applies, task over defaults', () => {+ const policy = resolveReviewPolicy({ reviewers: ['codex'], reviewStopMode: 'on-findings', reviewerApplies: 'false' }, defaults, null);+ expect(policy).toMatchObject({ reviewers: ['codex'], forgeReviewerUsernames: ['alice'], reviewStopMode: 'on-findings', reviewerApplies: false });+ const fromDefaults = resolveReviewPolicy({ reviewers: ['codex'] }, defaults, null);+ expect(fromDefaults).toMatchObject({ reviewStopMode: 'on-clean', reviewerApplies: true });+ expect(resolveReviewPolicy({ reviewers: ['codex'] }, null, null).reviewStopMode).toBe(DEFAULT_REVIEW_STOP_MODE);+ });++ it('clamps reviewerApplies off when the run crosses the public forge, even if configured on', () => {+ const policy = resolveReviewPolicy({ reviewers: ['codex'], reviewerApplies: true }, defaults, null, { crossesPublicForge: true });+ expect(policy.reviewerApplies).toBe(false);+ });++ it('is frozen so one builder cannot mutate the value another reads', () => {+ expect(Object.isFrozen(resolveReviewPolicy({ reviewers: ['codex'] }, null, null))).toBe(true);+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex fa99139e9d..160fbf4744 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -13,7 +13,7 @@ import { getToolsSummaryForPrompt } from './tools.js';import { isTruthyMeta } from '../lib/metadataFlags.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isToolFreeReviewer, isCliReviewer, hasRequiredReviewer, resolveReviewerConfig } from '../lib/validation.js';+import { DEFAULT_REVIEWER, isToolFreeReviewer, isCliReviewer, hasRequiredReviewer, resolveReviewerConfig, resolveReviewPolicy } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { doneSentinelName } from '../lib/agentSentinel.js';import { canTypeSlashCommands, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';@@ -495,21 +495,9 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// a task pinning no reviewer config would silently drop the configured gating// reviewers / stop-mode / reviewer-applies here while the non-PR-owning CLI// follow-up path honored them — same defaults, different gating by provider.- const {- reviewers: taskReviewers,- usernames: taskReviewerUsernames,- optionalReviewers: taskOptionalReviewers,- reviewerMaxRounds: taskReviewerMaxRounds,- reviewerModels: taskReviewerModels,- reviewerEfforts: taskReviewerEfforts- } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);- const taskReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;- const configuredTaskReviewerApplies = task.metadata?.reviewerApplies !== undefined- ? isTruthyMeta(task.metadata?.reviewerApplies)- : (codeReviewDefaults?.reviewerApplies === true);- // A PR/MR review consumes public contributor-controlled content. Its reviewer- // must stay review-only; the orchestrating agent validates and applies fixes.- const taskReviewerApplies = willOpenPR ? false : configuredTaskReviewerApplies;+ // A PR/MR review consumes public contributor-controlled content, so opening a+ // PR clamps `reviewerApplies` off (the policy documents the rule).+ const reviewPolicy = resolveReviewPolicy(task.metadata, codeReviewDefaults, defaultReviewers, { crossesPublicForge: willOpenPR });// TUI completion section — delegate to the shared light-path builder so// both prompt paths emit byte-identical workflows. (Background: TUI owns@@ -585,14 +573,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';baseBranch: worktreeInfo?.baseBranch || null,sentinelPath,leavePrOpen: leavesPrForHuman(task),- reviewers: taskReviewers,- usernames: taskReviewerUsernames,- optionalReviewers: taskOptionalReviewers,- reviewerMaxRounds: taskReviewerMaxRounds,- reviewerModels: taskReviewerModels,- reviewerEfforts: taskReviewerEfforts,- reviewStopMode: taskReviewStopMode,- reviewerApplies: taskReviewerApplies+ reviewPolicy});// Which completion section this mode gets. A mode with no entry renders@@ -624,7 +605,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';toolsSection, planningContextSection,} = await buildFullPathOptionalSections({task, workspaceDir, agentId, worktreeInfo, isTui, prCompletion, willOpenPR,- taskReviewers, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,+ reviewPolicy, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,skipDevContext,});@@ -703,7 +684,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an*/async function buildFullPathOptionalSections({task, workspaceDir, agentId, worktreeInfo, isTui, prCompletion, willOpenPR,- taskReviewers, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,+ reviewPolicy, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,skipDevContext,}) {// Build review loop section if enabled. The agent itself does NOT open the PR@@ -717,9 +698,9 @@ async function buildFullPathOptionalSections({// review inline — the system-side post-exit handler never fires for TUI.const reviewLoopSection = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE && willOpenPR && !isTui ? `## Code Review-After your task completes, the system will spawn a follow-up agent that runs the review-and-fix loop until all configured reviewers are satisfied, then merges the PR. The follow-up uses **${taskReviewers.join(' → ')}** (in order). ${taskReviewers[0] === DEFAULT_REVIEWER+After your task completes, the system will spawn a follow-up agent that runs the review-and-fix loop until all configured reviewers are satisfied, then merges the PR. The follow-up uses **${reviewPolicy.reviewers.join(' → ')}** (in order). ${reviewPolicy.reviewers[0] === DEFAULT_REVIEWER? 'Copilot leads the list, so for GitHub PRs the system pre-requests its initial review automatically (skipped on GitLab MRs and other non-GitHub forges); the follow-up then drives the rest of the chain.'- : taskReviewers.includes(DEFAULT_REVIEWER)+ : reviewPolicy.reviewers.includes(DEFAULT_REVIEWER)? 'The follow-up invokes the CLI reviewers itself and requests Copilot at its turn (Copilot is GitHub-only, so it is skipped on non-GitHub forges).': 'The follow-up agent will invoke the configured CLI reviewers directly to critique the PR diff, then iterate on their feedback.'} You do not need to open the PR, trigger the review, or address feedback yourself — focus on producing high-quality, well-tested code so the review passes go cleanly.` : '';@@ -945,23 +926,9 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t// [--reviewer-applies]`. All five fields fall back to the defaults with// task-over-default precedence (see the matching block in buildAgentPrompt and// resolveReviewLoopOptions) — not just the reviewer list.- const {- reviewers: lightReviewers,- usernames: lightReviewerUsernames,- optionalReviewers: lightOptionalReviewers,- reviewerMaxRounds: lightReviewerMaxRounds,- reviewerModels: lightReviewerModels,- reviewerEfforts: lightReviewerEfforts- } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);- const lightReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;- const configuredLightReviewerApplies = task.metadata?.reviewerApplies !== undefined- ? isTruthyMeta(task.metadata?.reviewerApplies)- : (codeReviewDefaults?.reviewerApplies === true);// Inline PR/MR lifecycles and review-loop follow-ups cross the public-forge- // boundary. Preserve reviewer-applies only for non-public local review work.- const lightReviewerApplies = (willOpenPR || isReviewLoopFollowUp)- ? false- : configuredLightReviewerApplies;+ // boundary; `reviewerApplies` survives only for non-public local review work.+ const reviewPolicy = resolveReviewPolicy(task.metadata, codeReviewDefaults, defaultReviewers, { crossesPublicForge: willOpenPR || isReviewLoopFollowUp });const resolvedForgeCli = manualForgeCli(forgeCli, worktreeInfo);// Can this session TYPE a Claude Code slash command (`/do:pr`, `/do:push`,// `/simplify`)? One predicate, both prompt paths (#3114): `canTypeSlashCommands`@@ -1001,11 +968,11 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t// same split spelled out: local CLIs/local LLMs inspect the committed branch// before it is public; Copilot and @login reviewers can only run after a PR.const isLocalReviewer = reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer);- const localReviewers = lightReviewers.filter(isLocalReviewer);- const localReviewRequired = hasRequiredReviewer(localReviewers, lightOptionalReviewers);+ const localReviewers = reviewPolicy.reviewers.filter(isLocalReviewer);+ const localReviewRequired = hasRequiredReviewer(localReviewers, reviewPolicy.optionalReviewers);const reviewerPositions = [- ...lightReviewers.map((reviewer, position) => ({ reviewer, position })),- ...lightReviewerUsernames.map((username, index) => ({ reviewer: `@${username}`, position: lightReviewers.length + index })),+ ...reviewPolicy.reviewers.map((reviewer, position) => ({ reviewer, position })),+ ...reviewPolicy.forgeReviewerUsernames.map((username, index) => ({ reviewer: `@${username}`, position: reviewPolicy.reviewers.length + index })),];const localReviewSection = inlineSection === 'review-loop'? buildLocalReviewLoopSection({@@ -1014,19 +981,16 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = tbaseBranch: worktreeInfo?.baseBranch || null,localAgentLoopBody,localAgentLoopBodyPath,- reviewers: lightReviewers,- optionalReviewers: lightOptionalReviewers,- reviewerMaxRounds: lightReviewerMaxRounds,- reviewerModels: lightReviewerModels,- reviewerEfforts: lightReviewerEfforts,- reviewStopMode: lightReviewStopMode,- reviewerApplies: lightReviewerApplies,+ reviewPolicy,reviewerPositions,}): '';- const prSideReviewers = lightReviewers.filter(reviewer => !isLocalReviewer(reviewer));+ // The post-PR section renders only the reviewers that need an open PR (the+ // local ones already ran pre-PR); every other knob is the shared policy's.+ const prSideReviewers = reviewPolicy.reviewers.filter(reviewer => !isLocalReviewer(reviewer));+ const prSidePolicy = Object.freeze({ ...reviewPolicy, reviewers: prSideReviewers });const runsPrSideReviewLoop = inlineSection === 'review-loop'- && (prSideReviewers.length > 0 || lightReviewerUsernames.length > 0);+ && (prSideReviewers.length > 0 || reviewPolicy.forgeReviewerUsernames.length > 0);const localPhaseCanShortCircuit = localReviewSection !== ''&& runsPrSideReviewLoop;@@ -1098,10 +1062,10 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = tbranchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,leavePrOpen: leavesPrForHuman(task),- reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies,+ reviewPolicy,forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null}));- const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, mode: completionMode, canTypeSlashCommands: canTypeSlash, rendersInlinePrLifecycle, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null }));+ const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, mode: completionMode, canTypeSlashCommands: canTypeSlash, rendersInlinePrLifecycle, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewPolicy, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null }));({[COMPLETION_MODES.TOOL_FREE]: () => contractSections.push(buildToolFreeReasoningCompletionSection()),@@ -1153,14 +1117,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t// Only the TUI completion workflow ends on a sentinel write; a CLI run// signals completion by exiting.writesSentinel: isTui,- reviewers: prSideReviewers,- usernames: lightReviewerUsernames,- optionalReviewers: lightOptionalReviewers,- reviewerMaxRounds: lightReviewerMaxRounds,- reviewerModels: lightReviewerModels,- reviewerEfforts: lightReviewerEfforts,- reviewStopMode: lightReviewStopMode,- reviewerApplies: lightReviewerApplies,+ reviewPolicy: prSidePolicy,localPhaseReviewers: localReviewers,localPhaseCanShortCircuit,localPhaseReviewRequired: localReviewSection ? localReviewRequired : false,diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 3ec969b0a9..c0ff079974 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -2,7 +2,7 @@* Completion workflow, worktree, and sentinel prompt sections.*/-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isCliReviewer, isToolFreeReviewer, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';+import { DEFAULT_REVIEWER, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isCliReviewer, isToolFreeReviewer, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';import { isAuditTaskType } from '../../lib/auditCatalog.js';import { resolveTaskHookType } from '../taskTypeHooks.js';import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';@@ -11,7 +11,7 @@ import { shellQuote } from '../../lib/shellQuote.js';import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib/prDisposition.js';import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';-import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';+import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, reviewPolicyToLoopMetadata, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';import { isTruthyMeta } from '../../lib/metadataFlags.js';export const NO_CHANGE_AUDIT_GUIDANCE = 'This audit may legitimately conclude that no change is needed. First verify the data this audit owns against authoritative sources. If the audited data is current, leave the worktree clean and do not run the commit, push, PR, or review steps below; write the completion sentinel when this provider uses one, or exit without committing when it does not. If a change is needed, continue through the normal workflow below.';@@ -659,7 +659,9 @@ export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommand* `prCompletion` selects the review gate or CI-only merge gate. Leave-open* callers do not invoke this helper.*/-function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, forgeCli = 'gh' } = {}) {+function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewPolicy, forgeCli = 'gh' }) {+ const { reviewers, optionalReviewers, reviewStopMode } = reviewPolicy;+ const usernames = normalizeReviewUsernames(reviewPolicy.forgeReviewerUsernames);const mergeGateForge = forgeCli === 'glab' ? 'gitlab' : 'github';// No review loop → CI is the whole gate, so emit the shared CI procedure that// the manual-TUI workflow and the merge follow-up agent also use. The PR URL@@ -725,11 +727,12 @@ function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW* Resolve the review-loop invocation shared by buildTuiCompletionSection and* buildCliCompletionSection: the normalized reviewer usernames, the* `--review-with ...` argument text, and the effort-pin note. Both callers- * used to re-derive this identical trio from the same 8-field reviewer-config- * bundle independently.+ * used to re-derive this identical trio from the same reviewer policy+ * independently.*/-function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies }) {- const reviewUsernames = normalizeReviewUsernames(usernames);+function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewPolicy }) {+ const { reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies } = reviewPolicy;+ const reviewUsernames = normalizeReviewUsernames(reviewPolicy.forgeReviewerUsernames);const reviewArgs = willOpenPR? (runsReviewLoop ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts }) : '--review-with none'): '';@@ -794,7 +797,7 @@ function localReviewCompletionInstruction(localReviewRequired = true) {* this IS a Claude session, so `/simplify` and `/do:pr` are both safe to emit* without a second provider check.*/-export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, rendersInlinePrLifecycle = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, rendersInlinePrLifecycle = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (mode === COMPLETION_MODES.TUI_SLASHDO_FREE) {@@ -807,7 +810,8 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out// when the task's Review Loop control is off so that default cannot start a// Copilot (or other external) review unexpectedly.- const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewPolicy });+ const { reviewers } = reviewPolicy;// A saved slashdo `merge: true` default would otherwise merge a PR that must// stay open — dropping our own merge steps isn't enough, `/do:pr` has to be// told not to merge (see lib/prDisposition.js).@@ -840,7 +844,7 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE// alone when it doesn't (nothing else merges a no-review-loop PR). The one// exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)- ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode, forgeCli })+ ? buildPostPRMergeSteps(3, { prCompletion, reviewPolicy, forgeCli }): { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };const sentinelStep = merge.nextStep;@@ -1148,7 +1152,7 @@ export function inlinePrLifecycleSection(task, opts) {*/export function buildInlineReviewLoopSection({taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,- reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, localPhaseReviewers = [], localPhaseCanShortCircuit = false, localPhaseReviewRequired = false, reviewerPositions = [], forgeCli = 'gh', workflowStep,+ reviewPolicy, localPhaseReviewers = [], localPhaseCanShortCircuit = false, localPhaseReviewRequired = false, reviewerPositions = [], forgeCli = 'gh', workflowStep,}) {// Where control goes after the merge. A TUI run still owes PortOS its// `.agent-done` sentinel — telling it to "exit" here is how a finished merge@@ -1160,14 +1164,7 @@ export function buildInlineReviewLoopSection({reviewLoopPRUrl: '$PR_URL',reviewLoopPRNumber: '$PR_NUMBER',reviewLoopPRBranch: branchName || '<branch>',- reviewLoopReviewers: reviewers,- reviewLoopReviewerUsernames: usernames,- reviewLoopOptionalReviewers: optionalReviewers,- reviewLoopReviewerMaxRounds: reviewerMaxRounds,- reviewLoopReviewerModels: reviewerModels,- reviewLoopReviewerEfforts: reviewerEfforts,- reviewLoopStopMode: reviewStopMode,- reviewLoopReviewerApplies: reviewerApplies,+ ...reviewPolicyToLoopMetadata(reviewPolicy),reviewLoopLeaveOpen: leaveOpen,// No reviewer configured ⇒ the merge-gate variant (CI is the whole gate),// exactly as the merge-only follow-up gets.@@ -1190,7 +1187,7 @@ export function buildInlineReviewLoopSection({* (`lib/agentCompletionMode.js`) rather than re-testing `worktreeInfo` /* `willOpenPR` — the caller already resolved those into `mode`.*/-export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, simplifyEnabled = false, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);if (canTypeSlashCommands && mode === COMPLETION_MODES.WORKTREE_NO_PUSH) {@@ -1199,7 +1196,8 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletiif (simplifyEnabled) {lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);}- const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewPolicy });+ const { reviewers } = reviewPolicy;// `--no-merge` overrides a saved slashdo `merge: true` default, which would// otherwise merge a PR this task must leave open (see lib/prDisposition.js).const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');@@ -1221,7 +1219,7 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletiif (leavePrOpen || policyLeavesOpen) {lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));} else {- const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode, forgeCli });+ const merge = buildPostPRMergeSteps(step, { prCompletion, reviewPolicy, forgeCli });lines.push(...merge.lines);}return lines.join('\n');diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsindex f595eb5ea4..ba3721d6e1 100644--- a/server/services/promptSections/completion.test.js+++ b/server/services/promptSections/completion.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';import { PR_COMPLETIONS } from '../../lib/prDisposition.js';+import { resolveReviewPolicy } from '../../lib/reviewerConfig.js';import { buildTuiCompletionSection } from './completion.js';const render = (forgeCli = 'gh', reviewers = ['copilot']) => buildTuiCompletionSection({@@ -9,7 +10,7 @@ const render = (forgeCli = 'gh', reviewers = ['copilot']) => buildTuiCompletionSsimplifyEnabled: false,sentinelPath: '/tmp/example-agent-done',mode: COMPLETION_MODES.TUI,- reviewers,+ reviewPolicy: resolveReviewPolicy({ reviewers }, null, null),forgeCli,});diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex ce68f124be..e701ebe54c 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -993,6 +993,25 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do].filter(Boolean).join('\n');}+/**+ * A `reviewPolicy` (see `resolveReviewPolicy`) as the persisted `reviewLoop*`+ * metadata keys `buildReviewLoopFollowUpSection` reads. The keys are stored on+ * follow-up tasks and read by other installs, so they keep their names; this is+ * the one place a policy field maps onto one.+ */+export function reviewPolicyToLoopMetadata(reviewPolicy) {+ return {+ reviewLoopReviewers: reviewPolicy.reviewers,+ reviewLoopReviewerUsernames: reviewPolicy.forgeReviewerUsernames,+ reviewLoopOptionalReviewers: reviewPolicy.optionalReviewers,+ reviewLoopReviewerMaxRounds: reviewPolicy.reviewerMaxRounds,+ reviewLoopReviewerModels: reviewPolicy.reviewerModels,+ reviewLoopReviewerEfforts: reviewPolicy.reviewerEfforts,+ reviewLoopStopMode: reviewPolicy.reviewStopMode,+ reviewLoopReviewerApplies: reviewPolicy.reviewerApplies,+ };+}+/*** Build the local half of an inline review workflow. Local CLIs and local LLMs* can inspect the worktree directly, so they must finish before the branch is@@ -1000,20 +1019,16 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do*/export function buildLocalReviewLoopSection({taskId, branchName, baseBranch, localAgentLoopBody, localAgentLoopBodyPath = null,- reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, reviewerPositions = [],+ reviewPolicy, reviewerPositions = [],}) {- const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer));+ const localReviewers = reviewPolicy.reviewers.filter(reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer));if (!localReviewers.length) return '';- const localReviewRequired = hasRequiredReviewer(localReviewers, optionalReviewers);+ const localReviewRequired = hasRequiredReviewer(localReviewers, reviewPolicy.optionalReviewers);+ // The pre-PR phase reviews only the local reviewers; forge logins can act only+ // once a PR exists, so they are left to the post-PR section.return buildReviewLoopFollowUpSection({reviewLoopPRBranch: branchName || '<branch>',- reviewLoopReviewers: localReviewers,- reviewLoopOptionalReviewers: optionalReviewers,- reviewLoopReviewerMaxRounds: reviewerMaxRounds,- reviewLoopReviewerModels: reviewerModels,- reviewLoopReviewerEfforts: reviewerEfforts,- reviewLoopStopMode: reviewStopMode,- reviewLoopReviewerApplies: reviewerApplies,+ ...reviewPolicyToLoopMetadata({ ...reviewPolicy, reviewers: localReviewers, forgeReviewerUsernames: [] }),sourceTaskId: taskId || 'unknown',}, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch, reviewerPositions, localPhaseReviewRequired: localReviewRequired });}