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: gate manual PRs on local review
[._.]/ Adam Eivy977245ba1c03
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 40be19287e..6cf07dd6fa 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -803,6 +803,12 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// 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 localReviewers = lightReviewers.filter(isLocalReviewer);+ const localReviewRequired = localReviewers.some(reviewer => !lightOptionalReviewers.includes(reviewer));+ const reviewerPositions = [+ ...lightReviewers.map((reviewer, position) => ({ reviewer, position })),+ ...lightReviewerUsernames.map((username, index) => ({ reviewer: `@${username}`, position: lightReviewers.length + index })),+ ];const localReviewSection = inlineSection === 'review-loop'? buildLocalReviewLoopSection({taskId: task.id,@@ -817,11 +823,14 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetreviewerEfforts: lightReviewerEfforts,reviewStopMode: lightReviewStopMode,reviewerApplies: lightReviewerApplies,+ reviewerPositions,}): '';const prSideReviewers = lightReviewers.filter(reviewer => !isLocalReviewer(reviewer));const runsPrSideReviewLoop = inlineSection === 'review-loop'&& (prSideReviewers.length > 0 || lightReviewerUsernames.length > 0);+ const localPhaseCanShortCircuit = localReviewSection !== ''+ && runsPrSideReviewLoop;const taskSections = [];const contractSections = [];@@ -945,10 +954,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, localReviewSection, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null+ forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, 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, localReviewSection, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));+ 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, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));}// The manual workflow's step 4 points here — it must follow the completion@@ -974,6 +983,9 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetreviewerEfforts: lightReviewerEfforts,reviewStopMode: lightReviewStopMode,reviewerApplies: lightReviewerApplies,+ localPhaseReviewers: localReviewers,+ localPhaseCanShortCircuit,+ reviewerPositions,forgeCli: resolvedForgeCli,workflowStep: localReviewSection ? 5 : 4,}));diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex eada19b234..9132bc805a 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -860,13 +860,31 @@ describe('buildLightContextPrompt', () => {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(/git diff origin\/main\.\.\.HEAD/);+ expect(prompt).toMatch(/BRANCH=claim\/issue-1/);+ expect(prompt).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');+ expect(prompt).toContain('git config --get "branch.${BRANCH}.pushRemote"');+ expect(prompt).toContain('git config --get remote.pushDefault');+ expect(prompt).toContain('git fetch "$PUBLISH_REMOTE" "+refs/heads/$BRANCH:refs/remotes/$PUBLISH_REMOTE/$BRANCH"');+ expect(prompt).toContain('PUBLISH_REMOTE="$PUSH_REMOTE"');+ expect(prompt).toContain('git merge-base --is-ancestor "$REMOTE_BRANCH_SHA" HEAD');+ expect(prompt).toContain('publish_reviewed_branch -u "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"');+ expect(prompt).toContain('publish_reviewed_branch --force-with-lease="refs/heads/$BRANCH:$REMOTE_BRANCH_SHA" -u "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"');+ expect(prompt).toContain('PUBLISH_ERROR="publish failed; refusing PR/MR"');+ expect(prompt).toContain('publish_reviewed_branch() { git push "$@" || { echo "$PUBLISH_ERROR" >&2; exit 1; }; }');+ expect(prompt).toContain('PUSH_OWNER=$(gh repo view "$(git remote get-url --push "$PUSH_REMOTE"');+ expect(prompt).toContain('[ -n "$PUSH_OWNER" ] || { echo "Missing PR head owner; refusing PR" >&2; exit 1; }');+ expect(prompt).toContain('PR_HEAD="$PUSH_OWNER:$BRANCH"');+ expect(prompt).toContain('portos-local-review-baseline');+ expect(prompt).toContain('refusing to overwrite them');+ expect(prompt).toMatch(/PR_URL=\$\(gh pr create --base main --head "\$PR_HEAD"/);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'));+ expect(prompt).toContain('LOCAL_PHASE_START_SHA');+ expect(prompt).toContain('Cross-phase stop-mode gate');+ expect(prompt).toContain('`all` always runs the PR-side reviewers.');+ expect(prompt.indexOf('### Local Review Before Opening the PR/MR')).toBeLessThan(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"'));+ expect(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"')).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.@@ -877,6 +895,67 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);});+ it.each(['on-clean', 'on-findings'])('carries the %s stop mode across the local and PR-side phases', (reviewStopMode) => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'], reviewStopMode } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });++ expect(prompt).toContain(`\`${reviewStopMode}\` skips the PR-side reviewers only when the local phase actually satisfied that stop condition`);+ expect(prompt).toContain('LOCAL_STOP_TRIGGERED=true');+ expect(prompt).toContain('git rev-parse --git-path portos-local-review-state');+ expect(prompt).toContain('. "$LOCAL_REVIEW_STATE_FILE"');+ expect(prompt).toContain('The original order places every local reviewer before every PR-side reviewer.');+ expect(prompt).toContain('skip the PR-side phase and record the configured stop-mode short-circuit as `partial`');+ expect(prompt).toContain('including when that verdict came from the final local reviewer');+ });++ it.each(['on-clean', 'on-findings'])('runs every PR-side reviewer for an interleaved %s order', (reviewStopMode) => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['copilot', 'codex'], reviewStopMode } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });++ expect(prompt).toContain('Cross-phase stop-mode gate');+ expect(prompt).toContain('Cross-phase stop-mode skip disabled');+ expect(prompt).toContain('Always run every PR-side reviewer');+ expect(prompt).not.toContain('skip the PR-side phase and record the configured stop-mode short-circuit');+ expect(prompt.slice(prompt.indexOf('## Review Loop'))).toContain('copilot');+ });++ it.each(['on-clean', 'on-findings'])('disables cross-phase skipping for an interleaved %s order', (reviewStopMode) => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot', 'ollama'], reviewStopMode } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });++ expect(prompt).toContain('`codex`=0, `copilot`=1, `ollama`=2');+ expect(prompt).toContain('`LOCAL_STOP_INDEX` to that triggering local reviewer\'s position');+ expect(prompt).toContain('Cross-phase stop-mode skip disabled');+ expect(prompt).toContain('run every PR-side reviewer in this phase');+ });++ it('keeps an optional local reviewer non-blocking when its verdict is inconclusive', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'], optionalReviewers: ['codex'] } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });++ expect(prompt).toContain('All local reviewers are optional, so missing/inconclusive results');+ expect(prompt).toContain('Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive');+ expect(prompt).toContain('missing/malformed/no-verdict result from one of them is non-blocking');+ expect(prompt).toContain('`codex` still run and their findings must still be fixed');+ expect(prompt).not.toContain('a missing, timed-out, malformed, or inconclusive local review is UNSATISFIED');+ });+it('defers the local CLI recipe push until after the local review gate', () => {const localRecipe = ['### Maintained local recipe',@@ -897,14 +976,17 @@ describe('buildLightContextPrompt', () => {localAgentLoopBody: localRecipe,});const localStart = prompt.indexOf('### Local Review Before Opening the PR/MR');- const prPush = prompt.indexOf('git push -u origin claim/issue-1');+ const prPush = prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');const localSection = prompt.slice(localStart, prPush);expect(localStart).toBeGreaterThanOrEqual(0);expect(prPush).toBeGreaterThan(localStart);expect(localSection).toContain('Keep verified changes local');- expect(localSection).not.toMatch(/^\s*(?:git pull --rebase --autostash && )?git push\b/m);- expect(localSection).not.toContain('git push origin');+ const recipeStart = localSection.indexOf('### Maintained local recipe');+ const recipeEnd = localSection.indexOf('\n\n4. Push', recipeStart);+ const renderedLocalRecipe = localSection.slice(recipeStart, recipeEnd);+ expect(renderedLocalRecipe).not.toMatch(/^\s*(?:git pull --rebase --autostash && )?git push\b/m);+ expect(renderedLocalRecipe).not.toContain('git push origin');});it('keeps reviewer-applies local fixes off the remote branch', () => {@@ -915,7 +997,7 @@ describe('buildLightContextPrompt', () => {isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });const localStart = prompt.indexOf('### Local Review Before Opening the PR/MR');- const prPush = prompt.indexOf('git push -u origin claim/issue-1');+ const prPush = prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');const localSection = prompt.slice(localStart, prPush);expect(localSection).toContain('keep fixes committed locally');@@ -931,8 +1013,8 @@ describe('buildLightContextPrompt', () => {isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });- expect(prompt).toContain("git diff 'release; echo bad'...HEAD");- expect(prompt).not.toContain('git diff release; echo bad...HEAD');+ expect(prompt).toContain("git diff 'origin/release; echo bad'...HEAD");+ expect(prompt).not.toContain('git diff origin/release; echo bad...HEAD');});it('runs local review before GitLab MR creation and leaves @ reviewers after it', () => {@@ -944,7 +1026,7 @@ describe('buildLightContextPrompt', () => {{ 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(/git diff origin\/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(/## Review Loop/);@@ -1018,8 +1100,8 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/`\/do:push`/);// Plain git/gh equivalent of the whole slashdo workflow (#3733).expect(prompt).toMatch(/git commit -m/);- expect(prompt).toMatch(/git push -u origin claim\/x/);- expect(prompt).toMatch(/gh pr create --base main --head claim\/x/);+ expect(prompt).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');+ expect(prompt).toMatch(/gh pr create --base main --head "\$PR_HEAD"/);expect(prompt).toMatch(/## Review Loop/);expect(prompt).not.toMatch(/PortOS will push the branch/);expect(prompt).toMatch(/\.agent-done/);@@ -1070,6 +1152,9 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);expect(prompt).toMatch(/## Merge Gate/);expect(prompt).toMatch(/You are done — exit/);+ expect(prompt).toContain('repeat the pre-PR local review phase');+ expect(prompt).toContain('the pre-PR local review is the only configured review');+ expect(prompt).not.toContain('No code review was requested for this task');expect(prompt).not.toMatch(/write the completion sentinel — the run is not done/);});@@ -1123,8 +1208,9 @@ describe('buildLightContextPrompt', () => {{ branchName: 'weird;rm -rf /', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });- expect(prompt).toMatch(/git push -u origin 'weird;rm -rf \/'/);- expect(prompt).toMatch(/gh pr create --base main --head 'weird;rm -rf \/'/);+ expect(prompt).toMatch(/BRANCH='weird;rm -rf \/'/);+ expect(prompt).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');+ expect(prompt).toMatch(/gh pr create --base main --head "\$PR_HEAD"/);// Never bare — that would be a command substitution waiting to happen.expect(prompt).not.toMatch(/origin weird;rm/);});@@ -1136,7 +1222,8 @@ describe('buildLightContextPrompt', () => {{ branchName: 'cos/task-1/agent-2', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });- expect(readable).toMatch(/git push -u origin cos\/task-1\/agent-2/);+ expect(readable).toMatch(/BRANCH=cos\/task-1\/agent-2/);+ expect(readable).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');const noBase = buildLightContextPrompt(makeTask({ metadata: { openPR: true } }),@@ -1144,7 +1231,9 @@ describe('buildLightContextPrompt', () => {{ branchName: 'b', worktreePath: '/tmp/wt' },isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });- expect(noBase).toMatch(/gh pr create --base <base-branch> --head b/);+ expect(noBase).toMatch(/git remote set-head origin --auto/);+ expect(noBase).toMatch(/BASE_BRANCH=\$\(git symbolic-ref --short refs\/remotes\/origin\/HEAD/);+ expect(noBase).toMatch(/gh pr create --base "\$BASE_BRANCH" --head "\$PR_HEAD"/);});it('a path-configured claude binary under a custom provider id gets the slashdo workflow', () => {@@ -2695,13 +2784,13 @@ describe('buildReviewLoopFollowUpSection — CLI reviewer procedure inlining', (});}- it('fails the local reviewer command when its JSON response has no findings', () => {+ it('records a no-verdict local reviewer result when its JSON response has no findings', () => {const out = buildReviewLoopFollowUpSection({ ...baseMeta, reviewLoopReviewers: ['ollama'] },{ verbose: false, localAgentLoopBody: null });expect(out).toMatch(/Local reviewer failed:/);- expect(out).toMatch(/STATUS=cli-error[^]*exit 1/);+ expect(out).toMatch(/STATUS=no-verdict[^]*exit 1/);});it('does NOT inline the procedure for a copilot-only loop', () => {diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 73e78cb37a..12772499c3 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -421,6 +421,18 @@ export function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail)];}+/**+ * Keep the manual pre-PR gate aligned with the review loop's `~opt` contract.+ * Defaulting to required preserves the fail-closed behavior for direct callers+ * that provide a local section without its reviewer metadata.+ */+function localReviewCompletionInstruction(localReviewRequired = true) {+ if (!localReviewRequired) {+ return 'Complete the **Local Review Before Opening the PR/MR** section below. All local reviewers are optional, so missing/inconclusive results (including skipped, timeout, malformed, or no-verdict) may continue. Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive; use `partial` only for a qualifying stop, never raw statuses. Hard errors, failed build/test, rejection, or unpushed fixes block. Still run each reviewer and fix its findings.';+ }+ return 'Complete the **Local Review Before Opening the PR/MR** section below. Commit its fixes. A missing/timed-out/malformed/inconclusive REQUIRED review blocks publication; an OPTIONAL inconclusive result may continue. Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive; use `partial` only for a qualifying stop, never raw statuses. Hard errors, failed build/test, rejection, or unpushed fixes block.';+}+/*** TUI completion-workflow block. The TUI owns its own commit → push → PR* pipeline via slashdo commands and signals "done" with a sentinel file.@@ -433,14 +445,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, localReviewSection = '', postPrReview = null }) {+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 = '', localReviewRequired = true, 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, localReviewSection, postPrReview });+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli, noChangeSuccess, localReviewSection, localReviewRequired, postPrReview });}const cmd = willOpenPR ? '/do:pr' : '/do:push';// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out@@ -522,18 +534,72 @@ function promptRef(ref, fallback) {* inline review-loop and merge-gate sections address the PR by those names —* they are rendered before the PR exists, so a literal URL is impossible.*/-function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh' }) {+function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh', localReviewStateRequired = false }) {const branch = promptRef(branchName, '<branch>');- const base = promptRef(baseBranch, '<base-branch>');+ const hasBaseBranch = typeof baseBranch === 'string' && baseBranch && baseBranch !== '<base-branch>';+ const base = hasBaseBranch ? promptRef(baseBranch, '<base-branch>') : '"$BASE_BRANCH"';const gitlab = forgeCli === 'glab';return [- `${step}. Push the branch and open the pull request yourself, capturing its URL and number — the section below addresses the PR by these shell variables:`,+ `${step}. Publish the branch and open the pull request yourself, capturing its URL and number:`,'',' ```bash',- ` git push -u origin ${branch}`,+ ...(hasBaseBranch ? [] : [+ ' if ! git fetch origin; then echo "Unable to fetch origin while resolving the default branch" >&2; exit 1; fi',+ ' if ! git remote set-head origin --auto; then echo "Unable to resolve origin/HEAD while resolving the default branch" >&2; exit 1; fi',+ ' BASE_BRANCH=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed \'s#^origin/##\')',+ ' if [ -z "$BASE_BRANCH" ]; then echo "Unable to resolve the repository default branch" >&2; exit 1; fi',+ ]),+ ...(localReviewStateRequired ? [+ ' LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"',+ ' if [ ! -s "$LOCAL_REVIEW_STATE_FILE" ]; then echo "Local review state is missing; refusing to publish an unverified branch" >&2; exit 1; fi',+ ' . "$LOCAL_REVIEW_STATE_FILE"',+ ' LOCAL_REVIEW_BASELINE_FILE="$(git rev-parse --git-path portos-local-review-baseline)"',+ ' if [ ! -s "$LOCAL_REVIEW_BASELINE_FILE" ]; then echo "Local review publication baseline is missing; refusing to publish" >&2; exit 1; fi',+ ' LOCAL_PRE_REBASE_REMOTE=$(grep -m1 "^LOCAL_PRE_REBASE_REMOTE=" "$LOCAL_REVIEW_BASELINE_FILE" | cut -d= -f2-)',+ ' LOCAL_PRE_REBASE_HEAD_SHA=$(grep -m1 "^LOCAL_PRE_REBASE_HEAD_SHA=" "$LOCAL_REVIEW_BASELINE_FILE" | cut -d= -f2-)',+ ' LOCAL_PRE_REBASE_REMOTE_SHA=$(grep -m1 "^LOCAL_PRE_REBASE_REMOTE_SHA=" "$LOCAL_REVIEW_BASELINE_FILE" | cut -d= -f2-)',+ ' if [ -z "$LOCAL_PRE_REBASE_REMOTE" ] || [ -z "$LOCAL_PRE_REBASE_HEAD_SHA" ]; then echo "Local review publication baseline is invalid; refusing to publish" >&2; exit 1; fi',+ ' CURRENT_HEAD_SHA=$(git rev-parse HEAD)',+ ' case "$LOCAL_OVERALL_STATUS" in clean|partial) ;; *) echo "Local review did not finish with an acceptable status; refusing to publish" >&2; exit 1 ;; esac',+ ' if [ "$LOCAL_REVIEWED_HEAD_SHA" != "$CURRENT_HEAD_SHA" ]; then echo "Local review covered $LOCAL_REVIEWED_HEAD_SHA, but HEAD is $CURRENT_HEAD_SHA; refusing to publish an unreviewed branch" >&2; exit 1; fi',+ ] : []),+ ` BRANCH=${branch}`,+ ' PUSH_REMOTE=$(git config --get "branch.${BRANCH}.pushRemote")',+ ' PUSH_REMOTE_SOURCE=branch.pushRemote',+ ' if [ -z "$PUSH_REMOTE" ] || [ "$PUSH_REMOTE" = "." ]; then PUSH_REMOTE=$(git config --get remote.pushDefault); PUSH_REMOTE_SOURCE=remote.pushDefault; fi',+ ' if [ -z "$PUSH_REMOTE" ] || [ "$PUSH_REMOTE" = "." ]; then PUSH_REMOTE=$(git config --get "branch.${BRANCH}.remote"); PUSH_REMOTE_SOURCE=branch.remote; fi',+ ' if [ -z "$PUSH_REMOTE" ] || [ "$PUSH_REMOTE" = "." ]; then PUSH_REMOTE=origin; PUSH_REMOTE_SOURCE=default; fi',+ ' PUSH_REF=$(git config --get "branch.${BRANCH}.merge")',+ ' PUBLISH_ERROR="publish failed; refusing PR/MR"',+ ' publish_reviewed_branch() { git push "$@" || { echo "$PUBLISH_ERROR" >&2; exit 1; }; }',+ ' if [ "$PUSH_REMOTE_SOURCE" = "branch.remote" ] && [ -n "$PUSH_REF" ]; then',+ ' if [ "$PUSH_REF" != "refs/heads/$BRANCH" ] && [ "$PUSH_REF" != "$BRANCH" ]; then echo "Configured upstream $PUSH_REMOTE/$PUSH_REF does not name $BRANCH; refusing to publish" >&2; exit 1; fi',+ ' fi',+ ' if git ls-remote --exit-code --heads "$PUSH_REMOTE" "$BRANCH" >/dev/null 2>&1; then',+ ' PUBLISH_REMOTE="$PUSH_REMOTE"',+ ' else',+ ' publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"',+ ' PUBLISH_REMOTE=',+ ' fi',+ ' if [ -n "$PUBLISH_REMOTE" ]; then',+ ' if ! git fetch "$PUBLISH_REMOTE" "+refs/heads/$BRANCH:refs/remotes/$PUBLISH_REMOTE/$BRANCH"; then echo "Unable to fetch the remote branch before publishing" >&2; exit 1; fi',+ ' REMOTE_BRANCH_SHA=$(git rev-parse "refs/remotes/$PUBLISH_REMOTE/$BRANCH" 2>/dev/null) || { echo "Unable to read the remote branch before publishing" >&2; exit 1; }',+ ' if git merge-base --is-ancestor "$REMOTE_BRANCH_SHA" HEAD; then',+ ' if [ -n "$PUSH_REF" ]; then publish_reviewed_branch "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"; else publish_reviewed_branch -u "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"; fi',+ ' elif [ "$PUBLISH_REMOTE" = "${LOCAL_PRE_REBASE_REMOTE:-}" ] && [ "$REMOTE_BRANCH_SHA" = "${LOCAL_PRE_REBASE_REMOTE_SHA:-}" ] && [ -n "${LOCAL_PRE_REBASE_HEAD_SHA:-}" ] && git merge-base --is-ancestor "$REMOTE_BRANCH_SHA" "$LOCAL_PRE_REBASE_HEAD_SHA" ]; then',+ ' if [ -n "$PUSH_REF" ]; then publish_reviewed_branch --force-with-lease="refs/heads/$BRANCH:$REMOTE_BRANCH_SHA" "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"; else publish_reviewed_branch --force-with-lease="refs/heads/$BRANCH:$REMOTE_BRANCH_SHA" -u "$PUBLISH_REMOTE" "HEAD:refs/heads/$BRANCH"; fi',+ ' else',+ ' echo "Remote $PUBLISH_REMOTE/$BRANCH contains commits not in HEAD, or changed during synchronization; refusing to overwrite them" >&2; exit 1',+ ' fi',+ ' fi',+ ...(gitlab ? [] : [+ ' PUSH_OWNER=$(gh repo view "$(git remote get-url --push "$PUSH_REMOTE" 2>/dev/null)" --json owner -q .owner.login 2>/dev/null) || { echo "Unable to resolve PR head; refusing PR" >&2; exit 1; }',+ ' [ -n "$PUSH_OWNER" ] || { echo "Missing PR head owner; refusing PR" >&2; exit 1; }',+ ' PR_HEAD="$PUSH_OWNER:$BRANCH"',+ ]),gitlab? ` PR_URL=$(glab mr create --source-branch ${branch} --target-branch ${base} --title "<conventional title>" --description "<description>" | grep -Eo 'https?://[^[:space:]]+' | tail -n 1)`- : ` PR_URL=$(gh pr create --base ${base} --head ${branch} --title "<conventional title>" --body "<description>")`,+ : ' PR_URL=$(gh pr create --base ' + base + ' --head "$PR_HEAD" --title "<conventional title>" --body "<description>")',gitlab? ' PR_NUMBER=$(glab mr view "$PR_URL" --output json | jq -r .iid)': ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',@@ -564,7 +630,7 @@ 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, localReviewSection = '', postPrReview = null }) {+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false, 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);// `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the@@ -599,10 +665,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(`${step++}. ${localReviewCompletionInstruction(localReviewRequired)}`);lines.push('', localReviewSection, '');}- lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli }));+ lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli, localReviewStateRequired: Boolean(localReviewSection) }));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) {const handoff = policyLeavesOpen@@ -677,7 +743,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', workflowStep,+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, localPhaseReviewers = [], localPhaseCanShortCircuit = 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@@ -702,7 +768,7 @@ export function buildInlineReviewLoopSection({// exactly as the merge-only follow-up gets.reviewLoopMergeOnly: !runsReviewLoop,sourceTaskId: taskId || 'unknown',- }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli, inlineWorkflowStep: workflowStep });+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli, inlineWorkflowStep: workflowStep, localPhaseReviewers, localPhaseCanShortCircuit, reviewerPositions });}/**@@ -715,7 +781,7 @@ 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, localReviewSection = '', postPrReview = null }) {+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 = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);if (hasSlashdo && worktreeInfo && willOpenPR) {@@ -770,13 +836,14 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti: `${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(`${step++}. ${localReviewCompletionInstruction(localReviewRequired)}`);lines.push('', localReviewSection, '');}lines.push(...buildManualPrCreateStep(step++, {branchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,forgeCli,+ localReviewStateRequired: Boolean(localReviewSection),}));lines.push(`${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR.`);return lines.join('\n');diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex 4b4563ae4f..dc12c62947 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -43,6 +43,12 @@ export function prepareLocalReviewLoopBody(body) {);}+function remoteReviewBaseRef(baseBranch) {+ if (typeof baseBranch !== 'string' || !baseBranch || baseBranch === '<base-branch>') return 'origin/HEAD';+ if (baseBranch.startsWith('origin/') || baseBranch.startsWith('refs/remotes/origin/')) return baseBranch;+ return `origin/${baseBranch}`;+}+/*** Build the **review-loop follow-up** section — the instructions for the* agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix@@ -71,8 +77,13 @@ export function prepareLocalReviewLoopBody(body) {* passes this; a follow-up agent, whose whole job is the loop, still inlines.* @param {boolean} [opts.localOnly=false] - Render the pre-PR local-review half* of a manual workflow, deferring pushes and PR/MR creation to the caller.- * @param {string} [opts.baseBranch='<base-branch>'] - Base ref used by local- * review diff commands when `localOnly` is set.+ * @param {string} [opts.baseBranch='origin/HEAD'] - Base ref used by local+ * review diff commands when `localOnly` is set. `origin/HEAD` resolves the+ * repository's actual default branch for adopted worktrees whose worktree+ * metadata deliberately has no base branch.+ * @param {Array<{reviewer: string, position: number}>} [opts.reviewerPositions=[]]+ * Complete configured reviewer order, used to carry stop-mode state across+ * the pre-PR and post-PR phases.* @param {number} [opts.inlineWorkflowStep=INLINE_REVIEW_LOOP_STEP] - Completion* workflow step referenced by an inline review or merge-gate section.* @param {boolean} [opts.inline=false] - Emit the SAME loop for an agent that@@ -81,9 +92,13 @@ export function prepareLocalReviewLoopBody(body) {* the heading and opening sentence, and the fact that nothing pre-requested a* Copilot review. The loop body, notes, merge command, and MERGED verification* stay byte-identical so the two callers can't drift.+ * @param {string[]} [opts.localPhaseReviewers=[]] - Reviewers completed in the+ * pre-PR local phase before this inline PR-side phase.+ * @param {boolean} [opts.localPhaseCanShortCircuit=false] - Whether the local+ * phase is allowed to satisfy the configured stop mode for this phase too.* @returns {string}*/-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 } = {}) {+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null, localOnly = false, baseBranch = '<base-branch>', reviewerPositions = [], inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localPhaseReviewers = [], localPhaseCanShortCircuit = false } = {}) {// 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.@@ -94,7 +109,14 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const prOwner = metadata.reviewLoopPROwner ?? '';const prRepo = metadata.reviewLoopPRRepo ?? '';const sourceTaskId = metadata.sourceTaskId || 'unknown';- const renderedBaseBranch = localOnly ? shellQuote(baseBranch) : baseBranch;+ const localPhaseReviewerList = Array.isArray(localPhaseReviewers) ? localPhaseReviewers : [];+ const localBaseRef = localOnly ? remoteReviewBaseRef(baseBranch) : baseBranch;+ const renderedBaseBranch = localOnly ? shellQuote(localBaseRef) : baseBranch;+ const configuredReviewerPositions = (Array.isArray(reviewerPositions) ? reviewerPositions : [])+ .filter(entry => entry && typeof entry.reviewer === 'string' && Number.isInteger(entry.position));+ const reviewerPositionLabel = configuredReviewerPositions.length+ ? configuredReviewerPositions.map(({ reviewer, position }) => `\`${reviewer}\`=${position}`).join(', ')+ : '';const preparedLocalAgentLoopBody = localOnly? prepareLocalReviewLoopBody(localAgentLoopBody): localAgentLoopBody;@@ -107,7 +129,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,return buildMergeFollowUpSection({prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,prHost: metadata.reviewLoopPRHost ?? '',- forgeCli: reviewForgeCli, inlineWorkflowStep,+ forgeCli: reviewForgeCli, inlineWorkflowStep, localReviewers: localPhaseReviewerList,});}// Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to@@ -219,11 +241,23 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const cliBinaryNote = cliBinaryAliases.length? ` Reviewer slug → command: ${cliBinaryAliases.join('; ')}.`: '';- // A configured reviewer that cannot run is NOT a clean review. Without this,- // an agent whose reviewer binary was missing self-reviewed and merged anyway- // — the exact regression this note blocks.+ const isOptionalReviewer = reviewer => optionalReviewers.some(optional => optional.toLowerCase() === reviewer.toLowerCase());+ const requiredCliBinaries = cliBinaries.filter(reviewer => !isOptionalReviewer(reviewer.slug));+ const optionalCliBinaries = cliBinaries.filter(reviewer => isOptionalReviewer(reviewer.slug));+ // A required reviewer that cannot run is NOT a clean review. Optional+ // reviewers have an explicit non-blocking contract for an inconclusive+ // precondition such as a missing binary, but that does not authorize a+ // self-review substitution.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 ${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.'}`+ ? [+ `**Missing reviewer CLI:** verify each configured binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable.`,+ requiredCliBinaries.length+ ? `If a required reviewer binary is genuinely missing (${requiredCliBinaries.map(c => `\`${c.binary}\``).join(' / ')}), 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.'}`+ : '',+ optionalCliBinaries.length+ ? `A missing optional reviewer binary (${optionalCliBinaries.map(c => `\`${c.binary}\``).join(' / ')}) is an inconclusive optional result and does not block ${localOnly ? 'the push or PR/MR creation' : 'the merge'}; record it and continue without substituting a self-review.`+ : '',+ ].filter(Boolean).join(' '): '';// "multi" reflects the TOTAL number of review sources (keyed reviewers +// username reviewers) so the ordered per-reviewer loop wording kicks in as@@ -238,6 +272,13 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,...reviewers.map(r => `\`${r}\``),...usernames.map(u => `\`@${u}\``),].join(' → ');+ const optionalConfiguredReviewers = [+ ...reviewers.filter(isOptionalReviewer).map(reviewer => `\`${reviewer}\``),+ ...usernames.filter(username => isOptionalReviewer(`@${username}`)).map(username => `\`@${username}\``),+ ];+ const optionalReviewNote = optionalConfiguredReviewers.length+ ? `**Optional reviewers (~opt):** ${optionalConfiguredReviewers.join(', ')} still run and their findings must still be fixed, but a timeout, skipped/incomplete pass, or missing/malformed/no-verdict result from one of them is non-blocking. A hard reviewer error, failed build/test, rejection, or push failure still blocks.`+ : '';const equivArgs = buildReviewWithArgs(reviewers, { stopMode, reviewerApplies, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels: reviewerModelMap });const equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';@@ -292,10 +333,24 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,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>\`:\`\`\`bashREVIEW_RESPONSE=$(mktemp)-${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- > "$REVIEW_RESPONSE"+HTTP_STATUS=$(${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {+ echo "Local reviewer failed: request transport error" >&2+ STATUS=cli-error+ exit 1+}+if [ "$HTTP_STATUS" -ge 400 ] 2>/dev/null; then+ echo "Local reviewer failed: HTTP $HTTP_STATUS $(jq -r '.error // "request failed"' "$REVIEW_RESPONSE" 2>/dev/null)" >&2+ STATUS=cli-error+ exit 1+fi+if jq -e '.error | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" >/dev/null 2>&1; then+ echo "Local reviewer failed: $(jq -r '.error' "$REVIEW_RESPONSE")" >&2+ STATUS=cli-error+ exit 1+fiif ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; thenecho "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2- STATUS=cli-error # Never treat an absent or malformed response as clean.+ STATUS=no-verdict # Never treat an absent or malformed response as clean.exit 1elsecat "\${REVIEW_RESPONSE}.findings"@@ -325,7 +380,8 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// instead of deepening the nested ternary.let waitOrInvokeStep;if (multi) waitOrInvokeStep = `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`;- else if (hasCopilot) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';+ else if (hasCopilot && copilotIsFirst) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';+ else if (hasCopilot) waitOrInvokeStep = 'Request a Copilot review when you reach its turn, then wait for it to complete (poll every 5–15s, max 5 minutes per round).';else if (hasLocalLlm) waitOrInvokeStep = localLlmInvocation;else if (hasCli) waitOrInvokeStep = singleCliInvocation;else waitOrInvokeStep = `To obtain a review, ${githubUsersInvocation}`;@@ -335,6 +391,43 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l: stopMode === 'on-clean'? '**Stop mode (on-clean):** stop after the FIRST reviewer that reports zero findings; skip the remaining reviewers.': (multi ? '**Stop mode (all):** run every reviewer in the list, in order, before merging.' : '');+ const localPhaseReviewerNames = [...new Set(localPhaseReviewerList)];+ const prSideReviewerNames = [...reviewers, ...usernames.map(username => `@${username}`)];+ const reviewerPositionMap = new Map(configuredReviewerPositions.map(({ reviewer, position }) => [reviewer, position]));+ const localPhasePositions = localPhaseReviewerNames.map(reviewer => reviewerPositionMap.get(reviewer));+ const prSidePositions = prSideReviewerNames.map(reviewer => reviewerPositionMap.get(reviewer));+ // Cross-phase short-circuiting is safe only when the user's original ordered+ // reviewer list already placed every local reviewer before every PR-side one.+ // If the list was interleaved, a PR-side reviewer can add fixes after the local+ // trigger; skipping a later PR-side reviewer would then leave those fixes+ // unreviewed. This mirrors lib/slashdo/commands/do/pr.md's fail-closed gate.+ const crossPhaseOrderingAllowsSkip = localPhaseReviewerNames.length > 0+ && prSideReviewerNames.length > 0+ && localPhasePositions.every(Number.isInteger)+ && prSidePositions.every(Number.isInteger)+ && Math.max(...localPhasePositions) < Math.min(...prSidePositions);+ const crossPhaseStopModeNote = (!localOnly && inline && localPhaseCanShortCircuit && localPhaseReviewerList.length)+ ? [+ '**Cross-phase stop-mode gate:** the local reviewers ran before this PR-side phase, so decide the configured stop mode across both phases before requesting any reviewer listed here.',+ 'The local phase persisted `LOCAL_PHASE_START_SHA`, `LOCAL_OVERALL_STATUS`, `LOCAL_STOP_TRIGGERED`, `LOCAL_STOP_INDEX`, `LOCAL_STOP_REVIEW_COMMITS`, `LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)`, and `LOCAL_REVIEWED_HEAD_SHA` in the worktree-private Git state file. Shell variables do not survive between agent commands, so at the start of this phase, in the same shell call that makes the skip decision, run `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if `[ ! -s "$LOCAL_REVIEW_STATE_FILE" ]`, then load it with `. "$LOCAL_REVIEW_STATE_FILE"`. If `LOCAL_REVIEWED_HEAD_SHA` does not equal `$(git rev-parse HEAD)`, do not skip any PR-side reviewer. Use the loaded values rather than treating the PR-side list as a fresh stop-mode scope.',+ crossPhaseOrderingAllowsSkip+ ? (reviewerPositionLabel+ ? `Configured reviewer positions are zero-based: ${reviewerPositionLabel}. The original order places every local reviewer before every PR-side reviewer.`+ : 'The original order places every local reviewer before every PR-side reviewer.')+ : '**Cross-phase stop-mode skip disabled:** the configured reviewer order is interleaved, or its positions are unavailable. Always run every PR-side reviewer so fixes made after a local trigger receive review.',+ '`all` always runs the PR-side reviewers.',+ crossPhaseOrderingAllowsSkip+ ? '`on-clean` skips the PR-side reviewers only when the local phase actually satisfied that stop condition: `LOCAL_OVERALL_STATUS=partial` from a stop-mode short-circuit, or `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS=0` and `LOCAL_STOP_TRIGGERED=true`.'+ : '`on-clean` always runs every PR-side reviewer here because cross-phase skipping is disabled for this order.',+ crossPhaseOrderingAllowsSkip+ ? '`on-findings` skips the PR-side reviewers only when the local phase actually satisfied that stop condition: `LOCAL_OVERALL_STATUS=partial` from a stop-mode short-circuit, or `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS>0` and `LOCAL_STOP_TRIGGERED=true`.'+ : '`on-findings` always runs every PR-side reviewer here because cross-phase skipping is disabled for this order.',+ 'An inconclusive or dirty local result does not satisfy a stop condition; a required local result still blocks the PR workflow, while an optional inconclusive result may continue but must never trigger this skip.',+ crossPhaseOrderingAllowsSkip+ ? 'When the local phase satisfies the stop condition, skip the PR-side phase and record the configured stop-mode short-circuit as `partial`; otherwise run this PR-side list normally. If the stop index or triggering reviewer commit count is missing or invalid, run every PR-side reviewer.'+ : 'Even when the local phase satisfies the stop condition, run every PR-side reviewer in this phase, then record the configured stop-mode result; do not skip reviewers across an interleaved phase boundary.',+ ].join('\n')+ : '';const applyNote = hasCli? (reviewerApplies@@ -349,8 +442,18 @@ 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 hasExplicitLocalBase = typeof baseBranch === 'string' && baseBranch && baseBranch !== '<base-branch>';+ const localBasePreparation = hasExplicitLocalBase+ ? '`git fetch origin`'+ : '`git fetch origin`, then run `git remote set-head origin --auto` to resolve the repository default branch';+ const renderedLocalBranch = localOnly ? shellQuote(prBranch || '<branch>') : '';const initialReviewState = localOnly- ? `Run every configured local reviewer against the committed branch before any push or PR/MR creation.`+ ? [+ `Before the first local reviewer, run ${localBasePreparation}. Set \`BRANCH=${renderedLocalBranch}\`; resolve \`LOCAL_PRE_REBASE_REMOTE\` from \`branch.$BRANCH.pushRemote\`, then \`remote.pushDefault\`, then \`branch.$BRANCH.remote\`, using \`origin\` if empty or \`.\`. Capture \`LOCAL_PRE_REBASE_HEAD_SHA=$(git rev-parse HEAD)\` and \`LOCAL_PRE_REBASE_REMOTE_SHA=$(git ls-remote --exit-code --heads "$LOCAL_PRE_REBASE_REMOTE" "$BRANCH" 2>/dev/null | awk 'NR == 1 {print $1}')\`. Immediately write all three to \`LOCAL_REVIEW_BASELINE_FILE="$(git rev-parse --git-path portos-local-review-baseline)"\` with \`printf 'LOCAL_PRE_REBASE_REMOTE=%s\\nLOCAL_PRE_REBASE_HEAD_SHA=%s\\nLOCAL_PRE_REBASE_REMOTE_SHA=%s\\n' "$LOCAL_PRE_REBASE_REMOTE" "$LOCAL_PRE_REBASE_HEAD_SHA" "$LOCAL_PRE_REBASE_REMOTE_SHA" > "$LOCAL_REVIEW_BASELINE_FILE"\`; abort if the write fails.`,+ `Rebase onto the current remote base with \`git rebase ${renderedBaseBranch}\`. Fetch/base-resolution failure or conflicts block publication; on conflict run \`git rebase --abort 2>/dev/null || true\` before stopping.`,+ `After synchronization, set \`LOCAL_PHASE_START_SHA=$(git rev-parse HEAD)\`; reset and initialize worktree-private \`LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"\` with \`printf 'LOCAL_PHASE_START_SHA=%s\\nLOCAL_OVERALL_STATUS=incomplete\\nLOCAL_STOP_TRIGGERED=false\\nLOCAL_STOP_INDEX=-1\\nLOCAL_STOP_REVIEW_COMMITS=-1\\nLOCAL_PHASE_COMMITS=0\\nLOCAL_REVIEWED_HEAD_SHA=\\n' "$LOCAL_PHASE_START_SHA" > "$LOCAL_REVIEW_STATE_FILE"\`. Abort if reset/initialization fails.`,+ `Before each local reviewer, record \`LOCAL_REVIEWER_START_SHA=$(git rev-parse HEAD)\`; after its loop compute \`LOCAL_REVIEWER_COMMITS=$(git rev-list "$LOCAL_REVIEWER_START_SHA..HEAD" --count)\`. On a qualifying stop, set \`LOCAL_STOP_REVIEW_COMMITS=$LOCAL_REVIEWER_COMMITS\`. Run every local reviewer before publication, then persist the aggregate and stop result.`+ ].join(' '): inline? 'Nothing has reviewed this PR yet — you must request/invoke each configured reviewer yourself against its diff.': (hasCopilot && copilotIsFirst)@@ -384,7 +487,13 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l? `**Round caps (~max):** stop these reviewers after their budget even if findings remain, then advance: ${maxRoundsEntries.join(', ')}. Spending a configured budget is a SUCCESS, not a failure — do not block the merge on it. Reviewers not listed keep the default cap below.`: '';- const extraNotes = [stopModeNote, applyNote, maxRoundsNote, missingCliNote].filter(Boolean);+ const localRebaseConflictNote = localOnly+ ? '**Rebase conflict gate:** on conflicts, run `git rebase --abort 2>/dev/null || true`; do NOT publish a conflicted or half-rebased worktree.'+ : '';+ const localStatePersistenceNote = localOnly+ ? '**State persistence:** shell calls do not share variables. Reload state before each reviewer, preserve it while persisting `LOCAL_REVIEWER_START_SHA`; reload before commit/stop calculations and the final aggregate. Any read/write failure blocks publication.'+ : '';+ const extraNotes = [crossPhaseStopModeNote, stopModeNote, applyNote, maxRoundsNote, missingCliNote, optionalReviewNote, localRebaseConflictNote, localStatePersistenceNote].filter(Boolean);// Inline slashdo's local-agent review loop when a spawnable CLI reviewer is// configured. This is the maintained, precise recipe — exact per-CLI headless@@ -408,7 +517,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// already carrying the real task, and pasting 40KB of reviewer recipe up front// to be read at step 4 is the wrong place to spend that context.const localOnlyProcedureNote = localOnly- ? '**Pre-PR local-review rule:** keep every reviewer fix committed locally. Do NOT push or open a PR/MR from this procedure; the outer Completion Workflow performs the push after every local reviewer is clean.\n\n'+ ? '**Pre-PR rule:** keep reviewer fixes committed locally. Do NOT push or open a PR/MR here; the outer workflow publishes after local review.\n\n': '';const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\n${localOnlyProcedureNote}Drive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n`;//@@ -436,9 +545,12 @@ 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 localStopIndexNote = reviewerPositionLabel+ ? ` The configured reviewer positions are zero-based: ${reviewerPositionLabel}. When a qualifying verdict triggers the configured stop condition, set \`LOCAL_STOP_TRIGGERED=true\` and \`LOCAL_STOP_INDEX\` to that triggering local reviewer's position; when the list exhausts without a qualifying stop or a result is inconclusive, set \`LOCAL_STOP_TRIGGERED=false\` and \`LOCAL_STOP_INDEX=-1\`.`+ : ' Set `LOCAL_STOP_INDEX=-1` whenever no qualifying stop condition fired.';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.',+ `4. When the local reviewer list is exhausted (or the stop mode triggers), record \`LOCAL_OVERALL_STATUS\`. Set \`LOCAL_STOP_TRIGGERED=true\` when the configured stop condition actually fired on a qualifying verdict, including when that verdict came from the final local reviewer; set it false only for list exhaustion without a qualifying stop or for an inconclusive result.${localStopIndexNote} Compute \`LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)\`; if a qualifying stop fired, retain the triggering reviewer's \`LOCAL_REVIEWER_COMMITS\` as \`LOCAL_STOP_REVIEW_COMMITS\`, otherwise set \`LOCAL_STOP_REVIEW_COMMITS=-1\`. Record \`LOCAL_REVIEWED_HEAD_SHA=$(git rev-parse HEAD)\`. Persist all phase state for later shell calls in the worktree-private Git state file: \`LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"\`; then run \`printf 'LOCAL_PHASE_START_SHA=%s\\nLOCAL_OVERALL_STATUS=%s\\nLOCAL_STOP_TRIGGERED=%s\\nLOCAL_STOP_INDEX=%s\\nLOCAL_STOP_REVIEW_COMMITS=%s\\nLOCAL_PHASE_COMMITS=%s\\nLOCAL_REVIEWED_HEAD_SHA=%s\\n' "$LOCAL_PHASE_START_SHA" "$LOCAL_OVERALL_STATUS" "$LOCAL_STOP_TRIGGERED" "$LOCAL_STOP_INDEX" "$LOCAL_STOP_REVIEW_COMMITS" "$LOCAL_PHASE_COMMITS" "$LOCAL_REVIEWED_HEAD_SHA" > "$LOCAL_REVIEW_STATE_FILE"\`. If that write fails, do NOT push or open the PR/MR. For a final-reviewer stop, follow the same phase-level gate below: \`on-clean\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS=0\`, while \`on-findings\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS>0\`; a \`partial\` status is already a qualifying stop. Return to the Completion Workflow and continue with the push and PR/MR creation step when all executed required reviewers are clean and optional reviewers are clean or inconclusive, or when \`LOCAL_OVERALL_STATUS=partial\` records a qualifying configured stop-mode short-circuit that intentionally skipped later reviewers. Do NOT push or open the PR/MR before this local phase is complete.`,]: leaveOpen? [@@ -508,19 +620,25 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do: 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.'}`;+ const loopCompletionText = optionalConfiguredReviewers.length+ ? 'all required reviewers are satisfied and optional reviewers are satisfied or explicitly inconclusive (or the stop mode triggers)'+ : 'all configured reviewers are satisfied (or the stop mode triggers)';+ const hardStopNote = optionalConfiguredReviewers.length+ ? `**Hard stop:** if a required reviewer's loop 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.'} An optional reviewer may end with an inconclusive result without blocking, but a hard error, failed build/test, rejection, or push failure still blocks.`+ : `**Hard stop:** if a reviewer's loop 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.'}`;return [heading,compactOpening,`**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,...extraNotes,'',- '**Loop UNTIL all reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**',+ `**Loop UNTIL ${loopCompletionText}, 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)' + (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, ${localOnly ? 'do NOT push or open a PR/MR; report the unresolved blocker and exit.' : 'post a PR comment summarising blockers and exit.'}`,+ hardStopNote,repeatedCommentsNote,'',challengeProtocolNote,@@ -535,7 +653,7 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do*/export function buildLocalReviewLoopSection({taskId, branchName, baseBranch, localAgentLoopBody, localAgentLoopBodyPath = null,- reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies,+ reviewers, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, reviewerPositions = [],}) {const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || LOCAL_LLM_REVIEWERS.includes(reviewer));if (!localReviewers.length) return '';@@ -549,7 +667,7 @@ export function buildLocalReviewLoopSection({reviewLoopStopMode: reviewStopMode,reviewLoopReviewerApplies: reviewerApplies,sourceTaskId: taskId || 'unknown',- }, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch: baseBranch || '<base-branch>' });+ }, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch, reviewerPositions });}/**@@ -592,10 +710,19 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea* workflow, which runs before the PR exists) emits both, commented.* @returns {{lines: string[], nextStep: number}}*/-export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)' }) {+export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [] }) {const gh = forge !== 'gitlab';const glab = forge !== 'github';const both = gh && glab;+ const localReviewNames = Array.isArray(localReviewers) && localReviewers.length+ ? localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')+ : '';+ const localReviewAfterCodeFix = localReviewNames+ ? ` If a CI fix changes code, repeat the pre-PR local review phase for ${localReviewNames} against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.`+ : '';+ const localReviewRecheck = localReviewNames+ ? ` After that rebase, repeat the pre-PR local review phase for ${localReviewNames} against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging.`+ : '';const checksCmd = gh? `\`gh pr checks ${prRef} --watch --fail-fast --interval 30\`${glab ? ' (GitLab: `glab ci status`)' : ''}`: '`glab ci status`';@@ -606,8 +733,9 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',? `\`gh pr view ${prRef} --json state -q .state\` must return \`MERGED\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` must show it merged)' : ''}`: `\`glab mr view ${mrRef}\` must show it merged`;const lines = [+ localReviewAfterCodeFix ? `**Code-changing CI fix gate:**${localReviewAfterCodeFix}` : null,`${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,- `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, \`git push --force-with-lease\`, and re-check.`,+ `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent,${localReviewRecheck} re-run the tests, \`git push --force-with-lease\`, and re-check.`,`${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged${alreadyMergedHint}, skip to the next step:`,' ```bash',gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,@@ -631,8 +759,12 @@ 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, inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP }) {+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null, inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localReviewers = [] }) {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.`+ : 'No code review was requested for this task, so nothing else will merge this PR';// PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed// `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify// with the shared detector — a GitHub Enterprise host is still `gh`, which a@@ -648,6 +780,7 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = 'forge: inline? (normalizeForgeCli(forgeCli) === 'glab' ? 'gitlab' : 'github'): (detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github'),+ localReviewers,// An inline run reached this gate through plain `git`/`gh` — it never ran// `/do:pr`, so a saved slashdo merge default can't have landed the PR for it.alreadyMergedHint: inline ? '' : undefined,@@ -655,8 +788,8 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = 'const steps = [...gate.lines,inline- ? `${gate.nextStep}. ${inlineExitStep} 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 do NOT start a code review — landing this PR is the whole job.`,+ ? `${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.`,];const prDetails = verbose ? ['',@@ -671,8 +804,8 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = 'return [inline ? '## Merge Gate' : '## Merge 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). **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.**`,+ ? `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.**`,'',...steps,'',