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: require current-head CI before review-enabled merges (#7930)
[._.]/ Adam Eivy1a0cff844735
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex d51f4eb3db..391eef55c3 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1342,8 +1342,8 @@ describe('buildLightContextPrompt', () => {expect(prompt).toContain('do NOT post a PR/MR comment saying the review was unavailable or inconclusive');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).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)/);@@ -2038,7 +2038,7 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/--review-with ollama~opt,codex,@alice --review-stop-on-findings/);expect(prompt).not.toMatch(/--reviewer-applies/);// `codex` and `@alice` are still blocking, so the skip list stays whole.- expect(prompt).toContain('Skip the merge if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');+ expect(prompt).toContain('skip the gate if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');expect(prompt).not.toContain('Every configured reviewer is optional (`~opt`)');});@@ -2061,7 +2061,7 @@ describe('buildLightContextPrompt', () => {isTruthyMeta,{ isTui: true, defaultReviewers: codeReviewDefaults.reviewers, codeReviewDefaults });// The skip list is NOT relaxed — a surviving `inconclusive` still blocks.- expect(prompt).toContain('Skip the merge if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');+ expect(prompt).toContain('skip the gate if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');expect(prompt).toContain('Every configured reviewer is optional (`~opt`), so a reviewer that timed out or returned no verdict does NOT make the loop inconclusive');expect(prompt).toContain('An `inconclusive` that still appears despite that is a real blocker (fixes committed but not pushed), and stands.');});@@ -2075,7 +2075,7 @@ describe('buildLightContextPrompt', () => {{ branchName: 'b', worktreePath: '/tmp/wt' },isTruthyMeta,{ isTui: true });- expect(prompt).toContain('Skip the merge if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');+ expect(prompt).toContain('skip the gate if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');expect(prompt).not.toContain('Every configured reviewer is optional (`~opt`)');});@@ -2424,7 +2424,8 @@ describe('buildLightContextPrompt', () => {{ branchName: 'feat', worktreePath: '/tmp/wt' },isTruthyMeta,{ isTui: true });- expect(prompt).not.toMatch(/`partial`/);+ expect(prompt).toContain('reports `clean` (or `too-large`)');+ expect(prompt).not.toContain('reports `clean`, `partial`');});it('tells the follow-up to request Copilot at its turn when copilot does NOT lead the list', () => {diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txtindex f71cac7edc..07f8b88464 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt@@ -24,14 +24,16 @@ fiOnly a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch```(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the PR is actually merged before exiting: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it returns `OPEN` or `CLOSED`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is `MERGED`.-6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.+ If that is rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.+7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but a substantive rejection, failed build/test, or push failure still blocks.**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txtindex ba707baa1d..9ecbf50db6 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt@@ -29,14 +29,16 @@ fiOnly a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch```(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the PR is actually merged before exiting: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it returns `OPEN` or `CLOSED`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is `MERGED`.-6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.+ If that is rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.+7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txtindex 5e325d03c9..96d996cd43 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt@@ -24,13 +24,14 @@ fiOnly a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+4. **Wait for CI to finish**: `glab ci status`. "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 (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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bash- glab mr merge "42" --yes --remove-source-branch+ glab mr merge 42 --yes --remove-source-branch```- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the MR is actually merged before exiting: `glab mr view "42"` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.-6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.+7. **Confirm the merge before exiting**: `glab mr view 42` must show it merged. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a MR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but a substantive rejection, failed build/test, or push failure still blocks.**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txtindex c366c1a0ca..b53edeb3fd 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt@@ -29,13 +29,14 @@ fiOnly a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON object (`jq -Rs '{ backend: "ollama", model: "…", timeoutMs: 1800000, diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+4. **Wait for CI to finish**: `glab ci status`. "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 (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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bash- glab mr merge "42" --yes --remove-source-branch+ glab mr merge 42 --yes --remove-source-branch```- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the MR is actually merged before exiting: `glab mr view "42"` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.-6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.+7. **Confirm the merge before exiting**: `glab mr view 42` must show it merged. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a MR comment summarising the unresolved blockers and exit. Do not loop indefinitely.diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txtindex 4065e825d7..9b4fe07b74 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt@@ -12,14 +12,16 @@ A previous agent finished task **task-example** and opened **PR https://github.c1. For EACH reviewer in order — `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: wait for the initial Copilot review the system already pre-requested (Copilot leads the list) (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, repeat the configured review loop for `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch```(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the PR is actually merged before exiting: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it returns `OPEN` or `CLOSED`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is `MERGED`.-6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.+ If that is rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.+7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**Hard stop:** if a reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit.**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txtindex dc64522576..99a7e213b3 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt@@ -33,14 +33,17 @@ Only a successfully extracted `.findings` value is the review text; treat it lik2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.+4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch```(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the PR is actually merged before exiting: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it returns `OPEN` or `CLOSED`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is `MERGED`.-6. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.+ If that is rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.+7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but a substantive rejection, failed build/test, or push failure still blocks.**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txtindex 34ac55b3eb..f1324180b7 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt@@ -38,14 +38,17 @@ Only a successfully extracted `.findings` value is the review text; treat it lik2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.+4. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch```(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the PR is actually merged before exiting: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it returns `OPEN` or `CLOSED`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is `MERGED`.-6. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.+ If that is rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.+7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txtindex e38d11cf9a..9c56d5bda6 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt@@ -33,13 +33,15 @@ Only a successfully extracted `.findings` value is the review text; treat it lik2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.+4. **Wait for CI to finish**: `glab ci status`. "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 (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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bash- glab mr merge "42" --yes --remove-source-branch+ glab mr merge 42 --yes --remove-source-branch```- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the MR is actually merged before exiting: `glab mr view "42"` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.-6. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.+7. **Confirm the merge before exiting**: `glab mr view 42` must show it merged. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a MR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but a substantive rejection, failed build/test, or push failure still blocks.**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txtindex 34ecef16e1..751b00efe9 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt@@ -38,13 +38,15 @@ Only a successfully extracted `.findings` value is the review text; treat it lik2. Fix EVERY finding from the review in this worktree, including non-blocking findings and nits; run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and resolve ALL review threads from that review, including non-blocking findings and nits.3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published, so leave it open and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Report the pending review in your run summary — do NOT post a PR/MR comment saying the review was unavailable or inconclusive. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):+**Code-changing CI fix gate:** If a CI fix changes code, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.+4. **Wait for CI to finish**: `glab ci status`. "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 (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.+5. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. If the CI fix changes code, repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `git fetch origin`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, after that rebase, repeat the pre-PR local review phase for `mtplx` against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging; repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code; re-run the tests, `git push --force-with-lease`, and re-check.+6. **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, skip to the next step:```bash- glab mr merge "42" --yes --remove-source-branch+ glab mr merge 42 --yes --remove-source-branch```- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-5. Confirm the MR is actually merged before exiting: `glab mr view "42"` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.-6. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.+7. **Confirm the merge before exiting**: `glab mr view 42` must show it merged. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.+8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a MR comment summarising the unresolved blockers and exit. Do not loop indefinitely.diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txtindex 0bba9d2c7c..2b867f04cb 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt@@ -2,7 +2,7 @@A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **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.**1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.-2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), 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 `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `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.+2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `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.3. **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 (a saved `/do:pr` default can merge it for you), skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branchdiff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txtindex 7d4e5f3bc0..a87e43cf87 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt@@ -2,7 +2,7 @@A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **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.**1. **Wait for CI to finish**: `glab ci status`. "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 (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.-2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`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 `glab mr view 42` shows a conflict with the target branch, `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.+2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `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.3. **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 (a saved `/do:pr` default can merge it for you), skip to the next step:```bashglab mr merge 42 --yes --remove-source-branchdiff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txtindex 410fb82dfa..edb3f3b158 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt@@ -2,7 +2,7 @@This runs as **step 4 of the Completion Workflow above**, against the PR you just opened on `feature/example` (`https://github.com/example-org/example-repo/pull/42` / `42` 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.**1. **Wait for CI to finish**: `gh pr checks "https://github.com/example-org/example-repo/pull/42" --watch --fail-fast --interval 30`. "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 workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check 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.-2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), 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 `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `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.+2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`gh run view --log-failed`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `gh pr view "https://github.com/example-org/example-repo/pull/42" --json mergeable -q .mergeable` reports `CONFLICTING`, `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.3. **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, skip to the next step:```bashgh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branchdiff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-glab.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-glab.txtindex 464630897e..13977e8909 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-glab.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-glab.txt@@ -2,7 +2,7 @@This runs as **step 4 of the Completion Workflow above**, against the PR you just opened on `feature/example` (`https://github.com/example-org/example-repo/pull/42` / `42` 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.**1. **Wait for CI to finish**: `glab ci status`. "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 (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.-2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`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 `glab mr view 42` shows a conflict with the target branch, `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.+2. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (`glab ci trace`), fix the cause here, run the project's tests, commit (`fix:` prefix, no Co-Authored-By), push. Then go back to the previous step — cap this at 5 rounds. If `glab mr view 42` shows a conflict with the target branch, `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.3. **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, skip to the next step:```bashglab mr merge 42 --yes --remove-source-branchdiff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex d75c2473d5..2c29deb99a 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -2,7 +2,7 @@* Completion workflow, worktree, and sentinel prompt sections.*/-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isCliReviewer, isToolFreeReviewer, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';import { isAuditTaskType } from '../../lib/auditCatalog.js';import { resolveTaskHookType } from '../taskTypeHooks.js';import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';@@ -603,7 +603,8 @@ export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommand* `prCompletion` selects the review gate or CI-only merge gate. Leave-open* callers do not invoke this helper.*/-function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {+function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, forgeCli = 'gh' } = {}) {+ const mergeGateForge = forgeCli === 'glab' ? 'gitlab' : 'github';// No review loop → CI is the whole gate, so emit the shared CI procedure that// the manual-TUI workflow and the merge follow-up agent also use. The PR URL// isn't known when this prompt is written, hence the placeholder.@@ -643,14 +644,25 @@ function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEWconst optionalMergeNote = allReviewersOptional? ' Every configured reviewer is optional (`~opt`), so a reviewer that timed out or returned no verdict does NOT make the loop inconclusive and is never your reason to skip the merge — the loop already excluded it. An `inconclusive` that still appears despite that is a real blocker (fixes committed but not pushed), and stands.': '';+ const localReviewers = reviewers.filter(reviewer => isCliReviewer(reviewer) || isToolFreeReviewer(reviewer));+ const localReviewRequired = hasRequiredReviewer(localReviewers, optionalReviewers);+ const reviewNames = [+ ...reviewers.filter(reviewer => !localReviewers.includes(reviewer)),+ ...usernames.map(username => `@${username}`),+ ];+ const gate = buildCiMergeGateSteps(startStep + 1, {+ prRef: '"<PR_URL>"',+ forge: mergeGateForge,+ alreadyMergedHint: '',+ localReviewers,+ localReviewRequired,+ reviewRecheckReviewers: reviewNames,+ });const lines = [- `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, \`review-blocked\`, or \`guardrail\`; leave the PR open for human follow-up. ${REVIEW_UNAVAILABLE_REPORTING_NOTE}${optionalMergeNote}`,- ' ```bash',- ' gh pr merge "<PR_URL>" --merge --delete-branch',- ' ```',- `${startStep + 1}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection), fix, and retry. Do NOT exit until state is \`MERGED\` (or you have explicitly decided not to merge per the rule above).`+ `${startStep}. **Enter the CI merge gate only when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\`, then follow the current-head CI gate below. Do not merge directly from a review verdict; skip the gate if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, \`review-blocked\`, or \`guardrail\` and leave the PR open for human follow-up. ${REVIEW_UNAVAILABLE_REPORTING_NOTE}${optionalMergeNote}`,+ ...gate.lines,];- return { lines, nextStep: startStep + 2 };+ return { lines, nextStep: gate.nextStep };}/**@@ -772,7 +784,7 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE// alone when it doesn't (nothing else merges a no-review-loop PR). The one// exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)- ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode })+ ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode, forgeCli }): { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };const sentinelStep = merge.nextStep;@@ -1154,7 +1166,7 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletiif (leavePrOpen || policyLeavesOpen) {lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));} else {- const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode });+ const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, optionalReviewers, reviewStopMode, forgeCli });lines.push(...merge.lines);}return lines.join('\n');diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsnew file mode 100644index 0000000000..f595eb5ea4--- /dev/null+++ b/server/services/promptSections/completion.test.js@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';+import { PR_COMPLETIONS } from '../../lib/prDisposition.js';+import { buildTuiCompletionSection } from './completion.js';++const render = (forgeCli = 'gh', reviewers = ['copilot']) => buildTuiCompletionSection({+ willOpenPR: true,+ prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,+ simplifyEnabled: false,+ sentinelPath: '/tmp/example-agent-done',+ mode: COMPLETION_MODES.TUI,+ reviewers,+ forgeCli,+});++describe('review-enabled completion merge gate', () => {+ it('waits for current-head CI and re-runs review after a changed head', () => {+ const section = render();++ expect(section).toContain('4. **Wait for CI to finish**');+ expect(section).toContain('gh pr checks "<PR_URL>" --watch --fail-fast --interval 30');+ expect(section).toContain('repeat the configured review loop for `copilot` against the new HEAD');+ expect(section).toContain('gh pr merge "<PR_URL>" --merge --delete-branch');+ expect(section.indexOf('4. **Wait for CI to finish**')).toBeLessThan(section.indexOf('gh pr merge'));+ expect(section).toContain('8. Write a short markdown summary');+ });++ it('uses GitLab CI and merge commands when the completion forge is GitLab', () => {+ const section = render('glab');++ expect(section).toContain('4. **Wait for CI to finish**: `glab ci status`');+ expect(section).toContain('glab mr merge <MR_NUMBER> --yes --remove-source-branch');+ expect(section).not.toContain('gh pr merge');+ });++ it('keeps required local-review state fail-closed before CI or merge', () => {+ const section = render('gh', ['codex']);++ expect(section).toContain('**Required local-review merge gate:**');+ expect(section).toContain('If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path');+ });+});diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex a38e7bc9e7..36571a4998 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -154,18 +154,14 @@ function resolveReviewForge(reviewForgeCli, { prUrl = '', prNumber = '', prOwnerreturn {noun: glab ? 'MR' : 'PR',mergeGateForge: glab ? 'gitlab' : 'github',+ ciPrRef: prUrl ? `"${prUrl}"` : '"<PR_URL>"',+ ciMrRef: `${mrRef}`,diffCmd: glab ? `glab mr diff ${mrRef}` : `gh pr diff ${prRef}`,- mergeCommandLine: glab- ? ` glab mr merge "${mrRef}" --yes --remove-source-branch`- : ` gh pr merge "${prUrl}" --merge --delete-branch`,// The `--repo` form is a GitHub convenience only, and only when the PR// coordinates were persisted.mergeEquivalentLine: glab? null: (prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null),- confirmMergedStep: glab- ? `5. Confirm the MR is actually merged before exiting: \`glab mr view "${mrRef}"\` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.`- : `5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.`,commentCmd: glab? `\`glab mr note ${mrRef} --message "<summary>"\``: `\`gh pr comment "${prUrl}" --body "<summary>"\``,@@ -463,12 +459,12 @@ function buildCrossPhaseStopModeNote({ localPhaseReviewers, prSideReviewerNames,}/**- * Steps 4-6 for both PR-side phases. A `leaveOpen` run reviews and comments;+ * Steps 4-8 for both PR-side phases. A `leaveOpen` run reviews and comments;* every other run merges and verifies the MERGED state. Identical for the* inline and standalone follow-up phases apart from the exit step and the* inline-only local-review merge guard, which is why both read this one builder.*/-function buildPrSideClosingSteps({ leaveOpen, exitStep, mergeGuard = '', forge }) {+function buildPrSideClosingSteps({ leaveOpen, exitStep, mergeGuard = '', forge, reviewRecheckReviewers = [], localReviewers = [], localReviewRequired = false }) {if (leaveOpen) {return ['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.',@@ -477,16 +473,25 @@ function buildPrSideClosingSteps({ leaveOpen, exitStep, mergeGuard = '', forge }exitStep,];}+ const gate = buildCiMergeGateSteps(4, {+ prRef: forge.ciPrRef,+ mrRef: forge.ciMrRef,+ forge: forge.mergeGateForge,+ alreadyMergedHint: '',+ reviewRecheckReviewers,+ mergeEquivalentLine: forge.mergeEquivalentLine,+ // `mergeGuard` is the inline phase's existing local-review state check. It+ // has the same fail-closed predicate but the handoff text must return to+ // the enclosing completion workflow, so avoid rendering the generic guard+ // twice here.+ localReviewers,+ localReviewRequired: Boolean(localReviewRequired && !mergeGuard),+ });+ const numberedExitStep = exitStep.replace(/^\d+\./, `${gate.nextStep}.`);return [mergeGuard,- `4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):`,- ' ```bash',- forge.mergeCommandLine,- ' ```',- forge.mergeEquivalentLine,- ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',- forge.confirmMergedStep,- exitStep,+ ...gate.lines,+ numberedExitStep,].filter(Boolean);}@@ -609,7 +614,12 @@ function buildInlinePhaseTexts({ inlineExitStep, inlineWorkflowStep, leaveOpen,canPreRequestCopilot: false,opening,compactOpening: opening,- closingSteps: ({ forge }) => buildPrSideClosingSteps({ leaveOpen, exitStep, mergeGuard, forge }),+ closingSteps: ({ forge, prSideReviewerNames }) => buildPrSideClosingSteps({+ leaveOpen, exitStep, mergeGuard, forge,+ reviewRecheckReviewers: prSideReviewerNames,+ localReviewers: localPhaseReviewers,+ localReviewRequired: localPhaseReviewRequired,+ }),crossPhaseNote: ({ prSideReviewerNames, configuredReviewerPositions, reviewerPositionLabel }) => ((localPhaseCanShortCircuit && localPhaseReviewers.length)? buildCrossPhaseStopModeNote({ localPhaseReviewers, prSideReviewerNames, configuredReviewerPositions, reviewerPositionLabel })@@ -640,7 +650,9 @@ function buildFollowUpPhaseTexts({ leaveOpen, baseBranch, prBranch, prUrl, prNumcanPreRequestCopilot: true,opening: ctx => `A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState(ctx)} ${objective}`,compactOpening: ctx => `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState(ctx)} ${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.'}`,- closingSteps: ({ forge }) => buildPrSideClosingSteps({ leaveOpen, exitStep, forge }),+ closingSteps: ({ forge, prSideReviewerNames }) => buildPrSideClosingSteps({+ leaveOpen, exitStep, forge, reviewRecheckReviewers: prSideReviewerNames,+ }),};}@@ -1047,9 +1059,13 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea* deletes the head branch. False for a PR whose head lives in a CONTRIBUTOR's* fork: PortOS may have push rights there (`maintainerCanModify`) without it* being our call to delete someone else's branch.+ * @param {string[]} [opts.reviewRecheckReviewers=[]] - configured reviewers+ * whose clean verdict must be repeated when a CI fix or rebase changes HEAD.+ * @param {string|null} [opts.mergeEquivalentLine=null] - optional equivalent+ * forge command to show beside the primary merge command.* @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)', localReviewers = [], localReviewRequired = false, deleteBranch = true }) {+export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [], localReviewRequired = false, reviewRecheckReviewers = [], mergeEquivalentLine = null, deleteBranch = true }) {const gh = forge !== 'gitlab';const glab = forge !== 'github';const both = gh && glab;@@ -1064,9 +1080,21 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',const localReviewMergeGuard = localReviewRequired && localReviewNames? localReviewBlockedMergeGuard(): '';- 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 reviewRecheckNames = Array.isArray(reviewRecheckReviewers)+ ? reviewRecheckReviewers.filter(Boolean).map(reviewer => `\`${reviewer}\``).join(', ')+ : '';+ const reviewRecheckAfterCodeFix = reviewRecheckNames+ ? ` If the CI fix changes code, repeat the configured review loop for ${reviewRecheckNames} against the new HEAD before returning to the CI wait; an earlier clean verdict does not cover changed code.`: '';+ const rebaseReviewNotes = [+ 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`+ : '',+ reviewRecheckNames+ ? `repeat the configured review loop for ${reviewRecheckNames} against the rebased HEAD before re-checking CI; an earlier clean verdict does not cover changed code`+ : '',+ ].filter(Boolean);+ const rebaseReviewSuffix = rebaseReviewNotes.length ? ` ${rebaseReviewNotes.join('; ')};` : '';const checksCmd = gh? `\`gh pr checks ${prRef} --watch --fail-fast --interval 30\`${glab ? ' (GitLab: `glab ci status`)' : ''}`: '`glab ci status`';@@ -1080,13 +1108,14 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',localReviewMergeGuard || null,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,${localReviewRecheck} 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.${reviewRecheckAfterCodeFix} Then 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,${rebaseReviewSuffix} 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${ghDelete}` : null,// `glab mr merge` takes an MR IID or source branch — a URL is not accepted.glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${mrRef} --yes${glabDelete}` : null,' ```',+ mergeEquivalentLine,// Not every repo allows merge commits; a repo restricted to squash/rebase// rejects `--merge` outright, which would leave the PR open forever.gh ? ` If that is rejected because this repo disallows merge commits, re-check what it allows (\`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed\`) and merge with an allowed method instead — \`--squash\` first, else \`--rebase\`${deleteBranch ? ', keeping \`--delete-branch\`' : ''}.` : null,diff --git a/server/services/promptSections/reviewLifecycleMatrix.test.js b/server/services/promptSections/reviewLifecycleMatrix.test.jsindex 00039f0b5e..ee0e44cef4 100644--- a/server/services/promptSections/reviewLifecycleMatrix.test.js+++ b/server/services/promptSections/reviewLifecycleMatrix.test.js@@ -252,8 +252,11 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with theirexpect(section).toContain('Nothing has reviewed this PR yet');expect(section).toContain('**Cross-phase stop-mode gate:**');expect(section).toContain('**Required local-review merge gate:**');+ expect(section).toContain('4. **Wait for CI to finish**');+ expect(section).toContain('never merge on checks that were expected but never appeared');expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');- expect(section).toContain(`6. ${INLINE_EXIT_STEP}`);+ expect(section).toContain('repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD');+ expect(section).toContain(`8. ${INLINE_EXIT_STEP}`);expect(section).not.toContain('6. Exit. Do **not** run `/do:push`');expect(section).not.toContain('### Local Review Before Opening the PR/MR');});@@ -265,10 +268,11 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with theirexpect(section).toContain('Drive the review-and-fix loop to completion and merge.');expect(section).toContain('on GitHub `gh pr diff 42` also works');expect(section).toContain(`gh pr diff 42 | jq -Rs '{ backend:`);+ expect(section).toContain('4. **Wait for CI to finish**');expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');expect(section).toContain('(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)');expect(section).toContain('`gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`');- expect(section).toContain('6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything.');+ expect(section).toContain('8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything.');expect(section).not.toContain('**Cross-phase stop-mode gate:**');expect(section).not.toContain('Do NOT push or open a PR/MR');});@@ -288,8 +292,8 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with theirconst section = render(CELL('followUp', 'glab', false, false));expect(section).toContain(`glab mr diff 42 | jq -Rs '{ backend:`);- expect(section).toContain('glab mr merge "42" --yes --remove-source-branch');- expect(section).toContain('`glab mr view "42"` must show it merged');+ expect(section).toContain('glab mr merge 42 --yes --remove-source-branch');+ expect(section).toContain('`glab mr view 42` must show it merged');expect(section).toContain('request `@example-user` as MR reviewer using the GitLab project UI or API');expect(section).not.toContain('gh pr merge');expect(section).not.toContain('gh pr view');@@ -354,8 +358,8 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with theirconst merging = hostGlab({}, {});expect(merging).toContain(`glab mr diff 42 | jq -Rs '{ backend:`);- expect(merging).toContain('glab mr merge "42" --yes --remove-source-branch');- expect(merging).toContain('`glab mr view "42"` must show it merged');+ expect(merging).toContain('glab mr merge 42 --yes --remove-source-branch');+ expect(merging).toContain('`glab mr view 42` must show it merged');expect(merging).toContain('request `@example-user` as MR reviewer using the GitLab project UI or API');expect(merging).not.toContain('gh pr merge');expect(merging).not.toContain('gh pr view');