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
fix: run local review before manual PR creation (#5106)
[._.]/ Adam Eivy7e93f41d396d
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex a1cac900a3..d0bb9dd3c4 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -14,7 +14,7 @@ import { buildPrompt } from './promptService.js';import { getToolsSummaryForPrompt } from './tools.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isCliReviewer, resolveReviewerConfig } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, isCliReviewer, resolveReviewerConfig } 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';@@ -45,7 +45,7 @@ import {isPrBranchWorktree,worktreeCommitGuidance,} from './promptSections/completion.js';-import { buildReviewLoopFollowUpSection, isMergeOnlyFollowUp } from './promptSections/reviewLifecycle.js';+import { buildLocalReviewLoopSection, buildReviewLoopFollowUpSection, isMergeOnlyFollowUp } from './promptSections/reviewLifecycle.js';export {detectDomainSkillTemplate,@@ -796,6 +796,29 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetproviderId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,});const ownsPrWorkflow = inlineSection !== null;+ // Slashdo already partitions reviewers. Plain-git completion prompts need the+ // 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) || LOCAL_LLM_REVIEWERS.includes(reviewer);+ const localReviewSection = inlineSection === 'review-loop'+ ? buildLocalReviewLoopSection({+ taskId: task.id,+ branchName: worktreeInfo?.branchName || null,+ baseBranch: worktreeInfo?.baseBranch || null,+ localAgentLoopBody,+ localAgentLoopBodyPath,+ reviewers: lightReviewers,+ optionalReviewers: lightOptionalReviewers,+ reviewerMaxRounds: lightReviewerMaxRounds,+ reviewerModels: lightReviewerModels,+ reviewerEfforts: lightReviewerEfforts,+ reviewStopMode: lightReviewStopMode,+ reviewerApplies: lightReviewerApplies,+ })+ : '';+ const prSideReviewers = lightReviewers.filter(reviewer => !isLocalReviewer(reviewer));+ const runsPrSideReviewLoop = inlineSection === 'review-loop'+ && (prSideReviewers.length > 0 || lightReviewerUsernames.length > 0);const taskSections = [];const contractSections = [];@@ -919,10 +942,10 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetbaseBranch: worktreeInfo?.baseBranch || null,leavePrOpen: leavesPrForHuman(task),reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies,- forgeCli: resolvedForgeCli+ forgeCli: resolvedForgeCli, localReviewSection, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null}));} else {- contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli }));+ contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));}// The manual workflow's step 4 points here — it must follow the completion@@ -933,14 +956,14 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetcontractSections.push(buildInlineReviewLoopSection({taskId: task.id,branchName: worktreeInfo?.branchName || null,- runsReviewLoop: inlineSection === 'review-loop',+ runsReviewLoop: runsPrSideReviewLoop,leaveOpen: false,- localAgentLoopBody,- localAgentLoopBodyPath,+ localAgentLoopBody: null,+ localAgentLoopBodyPath: null,// Only the TUI completion workflow ends on a sentinel write; a CLI run// signals completion by exiting.writesSentinel: isTui,- reviewers: lightReviewers,+ reviewers: prSideReviewers,usernames: lightReviewerUsernames,optionalReviewers: lightOptionalReviewers,reviewerMaxRounds: lightReviewerMaxRounds,@@ -949,6 +972,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetreviewStopMode: lightReviewStopMode,reviewerApplies: lightReviewerApplies,forgeCli: resolvedForgeCli,+ workflowStep: localReviewSection ? 5 : 4,}));}diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex abbb091517..e4c9c14e27 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -832,17 +832,22 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/gh pr merge/);});- it('a slashdo-free OpenCode TUI drives its own PR, review loop, and merge', () => {+ it('runs slashdo-free local reviewers before GitHub PR creation, then keeps PR-side review after it', () => {// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push// would be uninvokable — but it runs `git`/`gh` and the reviewer CLIs fine,// so it owns the whole lifecycle in one session rather than handing off to a// `sys-rl-*` follow-up agent (#3733).const prompt = buildLightContextPrompt(- makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true } }),+ makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,- { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });+ {+ isTui: true,+ providerId: 'opencode-ollama-tui',+ providerCommand: 'opencode',+ localAgentLoopBody: 'RECIPE: codex --sandbox read-only review --base <base>',+ });expect(prompt).toMatch(/## Completion Workflow/);// No slashdo commands anywhere in the workflow.expect(prompt).not.toMatch(/`\/do:pr`/);@@ -850,12 +855,19 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/`\/simplify`/);// /simplify is a Claude built-in — OpenCode gets the inline equivalent.expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);- // Commit → push → PR → review loop → merge, all in this session.+ // Commit → local review → push → PR → PR-side review → merge, all in this session.expect(prompt).toMatch(/git commit -m/);+ expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);+ expect(prompt).toMatch(/RECIPE: codex --sandbox read-only review/);+ expect(prompt).toMatch(/git diff main\.\.\.HEAD/);expect(prompt).toMatch(/git push -u origin claim\/issue-1/);expect(prompt).toMatch(/PR_URL=\$\(gh pr create --base main --head claim\/issue-1/);expect(prompt).toMatch(/## Review Loop/);expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);+ expect(prompt.indexOf('### Local Review Before Opening the PR/MR')).toBeLessThan(prompt.indexOf('git push -u origin claim/issue-1'));+ expect(prompt.indexOf('git push -u origin claim/issue-1')).toBeLessThan(prompt.indexOf('## Review Loop'));+ // The post-PR section receives only Copilot, never the local codex reviewer.+ expect(prompt.slice(prompt.indexOf('## Review Loop'))).not.toMatch(/CLI Reviewer Procedure/);// PortOS no longer promises to do any of it.expect(prompt).not.toMatch(/PortOS will push the branch/);// Sentinel handshake still drives completion; never tell the agent to run /quit.@@ -864,19 +876,24 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);});- it('a slashdo-free GitLab TUI captures MR variables and keeps the lifecycle on glab', () => {+ it('runs local review before GitLab MR creation and leaves @ reviewers after it', () => {const prompt = buildLightContextPrompt(- makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['ollama'] } }),+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['ollama'], usernames: ['alice'] } }),'/r',{ branchName: 'claim/issue-4363', worktreePath: '/tmp/wt', baseBranch: 'main', forgeCli: 'glab' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });+ expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);+ expect(prompt).toMatch(/git diff main\.\.\.HEAD/);expect(prompt).toMatch(/PR_URL=\$\(glab mr create --source-branch claim\/issue-4363 --target-branch main/);expect(prompt).toMatch(/PR_NUMBER=\$\(glab mr view "\$PR_URL" --output json \| jq -r \.iid\)/);- expect(prompt).toMatch(/glab mr diff \$PR_NUMBER/);+ expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).toMatch(/request `@alice` as MR reviewer/);expect(prompt).toMatch(/glab mr merge "\$PR_NUMBER" --yes --remove-source-branch/);expect(prompt).toMatch(/glab mr view "\$PR_NUMBER"/);+ expect(prompt.indexOf('### Local Review Before Opening the PR/MR')).toBeLessThan(prompt.indexOf('glab mr create'));+ expect(prompt.indexOf('glab mr create')).toBeLessThan(prompt.indexOf('## Review Loop'));expect(prompt).not.toMatch(/gh pr (create|diff|merge|view|checks)/);});@@ -984,14 +1001,15 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/The system will clean up your worktree on exit/);});- it('a CLI inline review loop ends by exiting — a CLI run has no sentinel to write', () => {+ it('a CLI local-only review reaches the CI merge gate and exits without a sentinel', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: false, providerId: 'codex', providerCommand: 'codex' });- expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);+ expect(prompt).toMatch(/## Merge Gate/);expect(prompt).toMatch(/You are done — exit/);expect(prompt).not.toMatch(/write the completion sentinel — the run is not done/);});diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 423b3f2ea0..73e78cb37a 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -433,14 +433,14 @@ export function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail)* return 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, slashdoFree = false, ownsPrWorkflow = 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 }) {+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, ownsPrWorkflow = 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 = '', postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (slashdoFree) {// Plain `git`/`gh` instead of `/do:pr` — but still the whole lifecycle when// the session is a real coding harness (`ownsPrWorkflow`); the reviewer// procedure it needs is inlined in the Review Loop section that follows.- return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli, noChangeSuccess });+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli, noChangeSuccess, localReviewSection, postPrReview });}const cmd = willOpenPR ? '/do:pr' : '/do:push';// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out@@ -564,9 +564,9 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'* `ownsPrWorkflow: false` (lean mode) keeps the original handoff: commit and* stop, PortOS owns the post-exit push / PR / review / merge lifecycle.*/-function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false, forgeCli = 'gh', noChangeSuccess = false }) {+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);// `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the// leave-open exclusions — it is `inlinePrLifecycleSection() !== null` (see the// caller). Re-testing any of them here is how the two drifted apart before.@@ -598,6 +598,10 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETlet step = 3;if (drivesOwnPr) {+ if (localReviewSection) {+ lines.push(`${step++}. Complete the **Local Review Before Opening the PR/MR** section below. Commit any fixes it requires; a missing, timed-out, malformed, or inconclusive local review is UNSATISFIED, so do NOT push or open the PR/MR.`);+ lines.push('', localReviewSection, '');+ }lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli }));lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);} else if (willOpenPR) {@@ -673,7 +677,7 @@ export function inlinePrLifecycleSection(task, { providerType, providerId, provi*/export function buildInlineReviewLoopSection({taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,- reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, forgeCli = 'gh',+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, 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@@ -698,7 +702,7 @@ export function buildInlineReviewLoopSection({// exactly as the merge-only follow-up gets.reviewLoopMergeOnly: !runsReviewLoop,sourceTaskId: taskId || 'unknown',- }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli });+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli, inlineWorkflowStep: workflowStep });}/**@@ -711,9 +715,9 @@ export function buildInlineReviewLoopSection({* CLI providers fall through to the legacy commit-only block where PortOS* handles push+PR on exit.*/-export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, ownsPrWorkflow = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false }) {+export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, ownsPrWorkflow = 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 = '', postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);if (hasSlashdo && worktreeInfo && willOpenPR) {const lines = ['## Completion', ...(noChangeSuccess ? ['', NO_CHANGE_AUDIT_GUIDANCE, ''] : []), 'When finished, run these in order:'];let step = 1;@@ -765,6 +769,10 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti? `${step++}. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`: `${step++}. (simplify disabled — skip)`);lines.push(`${step++}. Stage only the files you changed (never \`git add -A\` / \`git add .\`) and commit with a conventional message (\`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations).`);+ if (localReviewSection) {+ lines.push(`${step++}. Complete the **Local Review Before Opening the PR/MR** section below. Commit any fixes it requires; a missing, timed-out, malformed, or inconclusive local review is UNSATISFIED, so do NOT push or open the PR/MR.`);+ lines.push('', localReviewSection, '');+ }lines.push(...buildManualPrCreateStep(step++, {branchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex aa62ce121d..b7ab25324f 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -55,7 +55,7 @@ export function isMergeOnlyFollowUp(metadata = {}) {* stay byte-identical so the two callers can't drift.* @returns {string}*/-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null } = {}) {+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null, localOnly = false, baseBranch = '<base-branch>', inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP } = {}) {// One parameter, not two: an `inline` boolean alongside it could disagree with// it, and the disagreement renders silently — `inline` with a blank exit step// emits a bare "6." and a truncated merge-gate hand-back.@@ -75,7 +75,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,return buildMergeFollowUpSection({prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,prHost: metadata.reviewLoopPRHost ?? '',- forgeCli: reviewForgeCli,+ forgeCli: reviewForgeCli, inlineWorkflowStep,});}// Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to@@ -191,7 +191,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// an agent whose reviewer binary was missing self-reviewed and merged anyway// — the exact regression this note blocks.const missingCliNote = hasCli- ? `**Missing reviewer CLI:** verify each reviewer's binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable. If a configured reviewer's binary genuinely is not installed, that reviewer is UNSATISFIED — do NOT substitute your own self-review and do NOT merge. Post a PR comment naming the missing command and exit.`+ ? `**Missing reviewer CLI:** verify each reviewer's binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable. If a configured reviewer's binary genuinely is not installed, that reviewer is UNSATISFIED — do NOT substitute your own self-review and do NOT ${localOnly ? 'push or open a PR/MR' : 'merge'}. ${localOnly ? 'Exit without opening the PR/MR.' : 'Post a PR comment naming the missing command and exit.'}`: '';// "multi" reflects the TOTAL number of review sources (keyed reviewers +// username reviewers) so the ordered per-reviewer loop wording kicks in as@@ -252,7 +252,9 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,...(localLlmPins.some(p => p.effort) ? ['effort: "…"'] : []),'diff: .'].join(', ');- const diffCommand = reviewForgeCli === 'glab'+ const diffCommand = localOnly+ ? `git diff ${baseBranch}...HEAD`+ : reviewForgeCli === 'glab'? `glab mr diff ${prNumber || '<MR_NUMBER>'}`: `gh pr diff ${prNumber || '<PR_NUMBER>'}`;const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it. Substitute the active reviewer name for \`<lmstudio|ollama>\`:@@ -280,13 +282,13 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lhasCopilot ? `**copilot**: ${copilotIsFirst? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)': 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,- hasCli ? `**${cliReviewerHeading}**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : null,+ hasCli ? `**${cliReviewerHeading}**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff ${baseBranch}...HEAD\`${localOnly ? '' : `; on GitHub \`gh pr diff ${prNumber || ''}\` also works`}).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : null,hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,].filter(Boolean).join(' ');// Name the BINARY, not the slug: `Invoke the \`antigravity\` CLI` sent a// follow-up agent hunting for a command that does not exist.- const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${reviewerPinNote}${cliProcedurePointer}`;+ const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff ${baseBranch}...HEAD\`${localOnly ? '' : `; on GitHub \`gh pr diff ${prNumber || ''}\` also works`}). Capture its findings as concrete issues to address.${reviewerPinNote}${cliProcedurePointer}`;// Resolved sequentially so a future reviewer kind only adds one branch// instead of deepening the nested ternary.let waitOrInvokeStep;@@ -311,7 +313,9 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// Inline runs opened the PR seconds ago inside their own completion workflow,// so nothing pre-requested anything — claiming otherwise would have the agent// poll forever for a Copilot review no one asked for.- const initialReviewState = inline+ const initialReviewState = localOnly+ ? `Run every configured local reviewer against the committed branch before any push or PR/MR creation.`+ : inline? 'Nothing has reviewed this PR yet — you must request/invoke each configured reviewer yourself against its diff.': (hasCopilot && copilotIsFirst)? 'The system has already requested the initial Copilot code review (Copilot leads the order).'@@ -330,7 +334,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l'```bash',`curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,'```',- 'A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can\'t dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),+ `A \`409\` (\`CHALLENGE_EXHAUSTED\` = the one challenge is spent, or \`CHALLENGE_BUDGET_EXHAUSTED\` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, ${localOnly ? 'stop without pushing or opening a PR/MR' : 'post a PR comment and stop'}. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → \`POST .../challenge/resolve\` with \`{"outcome":"upheld"}\` and continue to ${localOnly ? 'the PR/MR creation step' : 'merge'}; confirmed → fix it, or send \`{"outcome":"escalated"}\` to hand the dispute to the user.` + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),].join('\n');// Per-reviewer round caps. This prompt drives the loop in PROSE (it isn't// slashdo parsing a `~max=<n>` suffix), so a configured cap only binds if it's@@ -391,7 +395,11 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lconst exitStep = inline? `6. ${inlineExitStep}`: `6. Exit. Do **not** run \`/do:push\` or open a new PR${leaveOpen ? '' : ' — the merge handles everything'}. The system will clean up your worktree on exit.`;- const closingSteps = leaveOpen+ const closingSteps = localOnly+ ? [+ '4. When the local reviewer list is exhausted (or the stop mode triggers), return to the Completion Workflow and continue with the push and PR/MR creation step. Do NOT push or open the PR/MR before this local loop is clean.',+ ]+ : leaveOpen? ['4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.',// Forge-aware: `gh pr comment` fails outright on a GitLab MR URL.@@ -416,12 +424,14 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l].filter(Boolean);// Framing only — everything below it is identical for both callers.- const heading = inline ? '## Review Loop' : '## Review-Loop Follow-up (PRIMARY OBJECTIVE)';- const opening = inline- ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). ${initialReviewState} ${objective}`+ const heading = localOnly ? '### Local Review Before Opening the PR/MR' : (inline ? '## Review Loop' : '## Review-Loop Follow-up (PRIMARY OBJECTIVE)');+ const opening = localOnly+ ? `This runs as **step 3 of the Completion Workflow above**, against the committed branch \`${prBranch}\` and its base \`${baseBranch}\`. ${initialReviewState}`+ : 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). ${initialReviewState} ${objective}`: `A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}`;- if (verbose) {+ if (verbose && !localOnly) {return `${heading}${opening}@@ -452,7 +462,9 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do}// Compact light-path variant.- const compactOpening = inline+ const compactOpening = localOnly+ ? opening+ : inline? opening: `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`;return [@@ -463,11 +475,11 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do'','**Loop UNTIL all reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**',`1. ${waitOrInvokeStep}`,- '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),+ '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By)' + (localOnly ? ', then re-run the same local reviewer. Do NOT push or open a PR/MR yet.' : ', push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.')),'3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',...closingSteps,'',- '**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',+ `**Hard stop:** if a reviewer is not converged after 10 rounds, ${localOnly ? 'do NOT push or open a PR/MR; report the unresolved blocker and exit.' : 'post a PR comment summarising blockers and exit.'}`,repeatedCommentsNote,'',challengeProtocolNote,@@ -475,6 +487,30 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do].filter(Boolean).join('\n');}+/**+ * 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+ * pushed; forge-side reviewers remain in the post-PR section.+ */+export function buildLocalReviewLoopSection({+ taskId, branchName, baseBranch, localAgentLoopBody, localAgentLoopBodyPath = null,+ reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies,+}) {+ const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || LOCAL_LLM_REVIEWERS.includes(reviewer));+ if (!localReviewers.length) return '';+ return buildReviewLoopFollowUpSection({+ reviewLoopPRBranch: branchName || '<branch>',+ reviewLoopReviewers: localReviewers,+ reviewLoopOptionalReviewers: optionalReviewers,+ reviewLoopReviewerMaxRounds: reviewerMaxRounds,+ reviewLoopReviewerModels: reviewerModels,+ reviewLoopReviewerEfforts: reviewerEfforts,+ reviewLoopStopMode: reviewStopMode,+ reviewLoopReviewerApplies: reviewerApplies,+ sourceTaskId: taskId || 'unknown',+ }, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch: baseBranch || '<base-branch>' });+}+/*** The step that replaces the merge steps when a PR is a human's to land — a* JIRA-tracked task whose ticket is already "In Review" (see@@ -554,7 +590,7 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',* @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.* @returns {string}*/-function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null }) {+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null, inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP }) {const inline = inlineExitStep !== null;// PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed// `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify@@ -594,7 +630,7 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = 'return [inline ? '## Merge Gate' : '## Merge Follow-up (PRIMARY OBJECTIVE)',inline- ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR — land it yourself 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). **No code review was requested for this task, so nothing else will merge this PR — land it yourself once CI is green.**`: `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,'',...steps,