Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

merge CoS PRs on green CI when no review loop is configured

[._.]/ Adam Eivy25ae2324aecb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a64c8eb646..c15c6108c0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -146,6 +146,7 @@
## Changed
+- **A CoS task that opens a PR without a Review Loop now merges it once CI is green, instead of leaving it open forever** — "Review Loop off" was being treated as "nobody merges this": the agent's completion workflow only got merge instructions when a reviewer was configured, and PortOS's own post-exit PR path only spawned a follow-up when there was a review to run. So every no-review-loop task ended with an orphaned PR and a leaked branch someone had to notice and merge by hand. The merge now always happens — gated on the review verdict when a loop is configured, on CI alone when it isn't: wait for the checks, fix a failing check or a base conflict, merge with a real merge commit, and verify the PR actually reached `MERGED` before exiting. Where PortOS opens the PR itself after the agent exits, it spawns a merge follow-up agent that does the same. **What to know:** scheduled task types that open a PR without a reviewer (`feature-ideas`, `do-replan`, `jira-sprint-manager`, `refresh-local-llm-catalog`) now land on the default branch on green CI rather than queueing a PR for you — turn on Review Loop for those if you want a reviewer first. A PR is still left open, with the reason stated, when CI stays red after a genuine fix attempt or a conflict needs a human decision. Fixed alongside: a copilot-only Review Loop on a **GitLab** MR used to spawn no follow-up at all (Copilot is GitHub-only) and orphaned the MR — it now degrades to the same merge-on-green-CI follow-up, with `glab` commands instead of `gh`.
- **[issue-2833] Decompose the ~1000-line `spawnTuiAgent()`** — extract the output buffering/spooling pipeline into `agentTuiSpawning/outputSpooler.js` and the failure-analysis + worktree-inspection helpers into `agentTuiSpawning/finalizeHelpers.js`, leaving `spawnTuiAgent` as a thinner orchestrator. No behavior change to spawn/timeout/completion semantics; adds unit coverage for both extracted modules.
- Route client `localStorage` access through the `safeStorage` helpers (Layout, MorseTrainer, calendar persisted-state, MoodBoard reference strip, VoiceWidget, WorkEditor, Tribe) — several sites previously threw uncaught in Safari private mode instead of degrading gracefully.
- Replace inline `new Promise(r => setTimeout(r, …))` delays with the shared `sleep(ms)` helper across nine server modules.
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 7574597032..d6a531c398 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -684,7 +684,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent disabled:opacity-40"
/>
<GitPullRequest size={14} className="text-blue-400" />
- <span className={`text-sm ${formData.defaultUseWorktree ? 'text-white' : 'text-gray-600'}`} title="When checked, agents open a PR to the default branch. When unchecked with worktree enabled, agents auto-merge to the default branch on completion.">Default to Open PR for new tasks</span>
+ <span className={`text-sm ${formData.defaultUseWorktree ? 'text-white' : 'text-gray-600'}`} title="When checked, agents open a PR to the default branch and merge it once it passes — the review loop if one is configured, CI alone if not. When unchecked with worktree enabled, agents merge the branch directly on completion.">Default to Open PR for new tasks</span>
</label>
</div>
)}
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 1682b6e544..d43b270ad2 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -161,9 +161,9 @@ export const STATE_MESSAGES = {
// Agent option toggles for task metadata (useWorktree, openPR, simplify, reviewLoop)
export const AGENT_OPTIONS = [
{ field: 'useWorktree', label: 'Worktree', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch. If unchecked, commits directly to the default branch.' },
- { field: 'openPR', label: 'Open PR', shortLabel: 'PR', description: 'Open a pull request to the default branch (implies worktree). If unchecked with worktree enabled, auto-merges to the default branch on completion.' },
+ { field: 'openPR', label: 'Open PR', shortLabel: 'PR', description: 'Open a pull request to the default branch (implies worktree). The PR is merged once it passes — the review loop when one is configured, CI alone when it is not. If unchecked with worktree enabled, auto-merges to the default branch on completion.' },
{ field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' },
- { field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'After the agent opens a PR during its run, keep iterating on review feedback until checks pass. Only applies when Open PR is not enabled (manual PR creation by agent).' }
+ { field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'Run the configured reviewers against the PR and keep iterating on their feedback until they are satisfied, then merge. Needs Open PR — with it off, the PR is merged on green CI with no review.' }
];
// Reviewer choices for the Review Loop. `copilot` requests a GitHub Copilot
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 6e874ac8d8..94bea157d2 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -293,6 +293,19 @@ export function reconcileSplitContext(task) {
return { ...task, description: context, metadata: restMeta };
}
+/**
+ * True when a follow-up task is a **merge-only** run: it has a PR to land but no
+ * reviewer to run (Review Loop off, or every configured reviewer was stripped —
+ * e.g. copilot on a GitLab MR). Tolerates the string `'true'` because task
+ * metadata round-trips through JSON/forms like every other CoS flag.
+ *
+ * Used both to pick the prompt section and to skip preloading the reviewer-only
+ * slashdo bodies (`/do:rpr`, the local-agent review loop) that section ignores.
+ */
+function isMergeOnlyFollowUp(metadata = {}) {
+ return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';
+}
+
/**
* Build the **review-loop follow-up** section — the instructions for the
* agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix
@@ -324,6 +337,15 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const prOwner = metadata.reviewLoopPROwner ?? '';
const prRepo = metadata.reviewLoopPRRepo ?? '';
const sourceTaskId = metadata.sourceTaskId || 'unknown';
+ // Merge-only follow-up (Review Loop off): no reviewer to wait on or invoke —
+ // the whole job is CI-gate → fix → merge. Branch before any reviewer defaulting
+ // below, which would otherwise resolve the empty list back to `[copilot]`.
+ if (isMergeOnlyFollowUp(metadata)) {
+ return buildMergeFollowUpSection({
+ prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose,
+ prHost: metadata.reviewLoopPRHost ?? '',
+ });
+ }
// Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to
// the review flow after the keyed reviewers.
const usernames = normalizeReviewUsernames(metadata.reviewLoopReviewerUsernames);
@@ -533,6 +555,100 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
].filter(Boolean).join('\n');
}
+/**
+ * The CI-gated merge procedure, in numbered steps starting at `startStep`.
+ *
+ * This is the single definition of "no reviewer is configured, so CI is the
+ * merge gate" — shared by every flow that reaches it: the agent's own completion
+ * workflow (slashdo TUI + Claude Code CLI via `buildPostPRMergeSteps`), the
+ * manual/OpenCode TUI workflow, and the merge follow-up agent PortOS spawns when
+ * it opened the PR itself. They differ only in how the PR is addressed and
+ * whether GitLab commands are offered, so those are parameters rather than three
+ * hand-written copies that drift.
+ *
+ * Ends on the same merge command + MERGED verification as the review-loop
+ * contract (`buildReviewLoopFollowUpSection`): a true merge commit keeps the
+ * branch tip in the base branch's history, which is what lets automated worktree
+ * cleanup prove the branch landed.
+ *
+ * @param {number} startStep - number of the first emitted step.
+ * @param {Object} opts
+ * @param {string} opts.prRef - how to address the PR in commands, already
+ * quoted: the `"<PR_URL>"` placeholder before the PR exists, or the real URL.
+ * @param {'github'|'gitlab'|'unknown'} [opts.forge] - which CLI to name. PortOS
+ * opens GitLab MRs too (`git.createPR` falls back to `glab`), so a follow-up
+ * whose PR host is known non-GitHub must not be handed `gh` commands it can't
+ * run. `unknown` (the agent's own completion workflow, which runs before the
+ * PR exists) emits both, commented.
+ * @returns {{lines: string[], nextStep: number}}
+ */
+function buildCiMergeGateSteps(startStep, { prRef, forge = 'github' }) {
+ const gh = forge !== 'gitlab';
+ const glab = forge !== 'github';
+ const both = gh && glab;
+ const checksCmd = gh
+ ? `\`gh pr checks ${prRef} --watch --fail-fast --interval 30\`${glab ? ' (GitLab: `glab ci status`)' : ''}`
+ : '`glab ci status`';
+ const mergeableCmd = gh
+ ? `\`gh pr view ${prRef} --json mergeable -q .mergeable\` reports \`CONFLICTING\``
+ : 'the MR reports a conflict with its target branch';
+ const stateCmd = gh
+ ? `\`gh pr view ${prRef} --json state -q .state\` must return \`MERGED\``
+ : '`glab mr view` must show it merged';
+ const lines = [
+ `${startStep}. **Wait for CI to finish**: ${checksCmd}. A repo with no checks configured reports "no checks reported" — treat that as green.`,
+ `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (\`gh run view --log-failed\` on GitHub), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, \`git push --force-with-lease\`, and re-check.`,
+ `${startStep + 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 (a saved \`/do:pr\` default can merge it for you), skip to the next step:`,
+ ' ```bash',
+ gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,
+ glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${both ? '"<MR_URL>"' : prRef} --yes --remove-source-branch` : null,
+ ' ```',
+ `${startStep + 3}. **Confirm the merge before exiting**: ${stateCmd}. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open ONLY if CI stays red after a genuine fix attempt, or a conflict needs a human decision — and say so explicitly in your completion summary.`,
+ ].filter(Boolean);
+ return { lines, nextStep: startStep + 4 };
+}
+
+/**
+ * Build the **merge follow-up** section — the instructions for the agent
+ * `spawnReviewLoopFollowUp` spawns when no reviewer survived resolution (Review
+ * Loop off, or copilot-only on a non-GitHub forge). Nothing else will touch the
+ * PR, so the merge gate is CI alone (`buildCiMergeGateSteps`).
+ *
+ * @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.
+ * @returns {string}
+ */
+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false }) {
+ // PortOS opens GitLab MRs via `glab` too, so a non-GitHub host must not be
+ // handed `gh` commands (the host is persisted by spawnReviewLoopFollowUp).
+ const gate = buildCiMergeGateSteps(1, {
+ prRef: `"${prUrl}"`,
+ forge: (prHost && prHost !== 'github.com') ? 'gitlab' : 'github',
+ });
+ const steps = [
+ ...gate.lines,
+ `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.`,
+ ];
+ const prDetails = verbose ? [
+ '',
+ 'PR Details:',
+ `- **URL**: ${prUrl}`,
+ `- **Branch**: \`${prBranch}\``,
+ prNumber !== '' ? `- **Number**: ${prNumber}` : null,
+ prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : null,
+ `- **Source task**: ${sourceTaskId}`,
+ ].filter(Boolean) : [];
+
+ return [
+ '## Merge Follow-up (PRIMARY OBJECTIVE)',
+ `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,
+ '',
+ ...steps,
+ '',
+ '**Hard stop:** if CI is still red after 5 fix rounds, or a conflict needs a product decision you can\'t make, post a PR comment summarising exactly what is blocking the merge and exit with the PR left open. Do not force a merge over red CI.',
+ ...prDetails,
+ ].join('\n');
+}
+
/**
* Build the single "## Guidelines" completion-handoff bullet for the full
* (api) prompt path. Mirrors the helper pattern the light path already uses
@@ -581,7 +697,7 @@ export function buildCompletionGuidelineBullet({
if (worktreeInfo && willOpenPR) {
const reviewSuffix = willReviewLoop
? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'
- : '';
+ : ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';
return `On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`;
}
if (worktreeInfo) {
@@ -723,8 +839,12 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// Preload slashdo's local-agent review-loop recipe once for review-loop
// follow-up tasks; both the light/TUI path (via lightOptions) and the full
// path (the verbose builder below) reuse this single value to inline the exact
- // CLI-reviewer invocation. Cheap + cached; only read for follow-ups.
- const localAgentLoopBody = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)
+ // CLI-reviewer invocation. Cheap + cached; only read for follow-ups — and not
+ // for a merge-only follow-up, which has no reviewer to invoke and renders a
+ // section that ignores this body entirely.
+ const needsReviewerRecipes = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)
+ && !isMergeOnlyFollowUp(task.metadata || {});
+ const localAgentLoopBody = needsReviewerRecipes
? await loadSlashdoLib('local-agent-review-loop').catch(() => null)
: null;
@@ -888,7 +1008,9 @@ After your task completes, the system will spawn a follow-up agent that runs the
const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
let reviewLoopFollowUpSection = '';
if (isReviewLoopFollowUp) {
- const rprBody = await loadSlashdoFile('rpr').catch(() => null);
+ // `/do:rpr` is the Copilot/@github comment-resolution procedure — a merge-only
+ // follow-up has no review to resolve, so skip the ~35KB read for it.
+ const rprBody = needsReviewerRecipes ? await loadSlashdoFile('rpr').catch(() => null) : null;
// localAgentLoopBody (the CLI-reviewer recipe) was already preloaded at the
// top of buildAgentPrompt under the same reviewLoopFollowUp guard — reuse it
// rather than re-reading the lib a second time.
@@ -1274,8 +1396,26 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,
* leaks. Mirrors the merge contract in the review-loop follow-up section so
* both agent flows converge on the same final state. `reviewers` only colors
* the wording — the merge step itself is reviewer-agnostic.
+ *
+ * With `willReviewLoop: false` the same two steps are emitted, but the merge
+ * gate is CI instead of a review verdict: nothing else will ever merge that PR
+ * (no review-loop follow-up is spawned), so "no reviewer configured" must mean
+ * "merge it yourself once the checks pass", not "leave it open forever".
*/
-function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {
+function buildPostPRMergeSteps(startStep, { willReviewLoop = true, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {
+ // 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.
+ if (!willReviewLoop) {
+ const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown' });
+ return {
+ lines: [
+ ' **No review loop is configured for this task, so nothing and nobody else will merge this PR** — `/do:pr` opens it and exits. Capture the PR URL it printed, then:',
+ ...gate.lines,
+ ],
+ nextStep: gate.nextStep
+ };
+ }
// Trailing space when present so the sentence reads "the Copilot review loop"
// (lone copilot, no usernames) or "the review loop" (multi/CLI/username) —
// never "the the review loop".
@@ -1309,9 +1449,10 @@ function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, usern
*/
function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
if (slashdoFree) {
- // The manual path never auto-merges (it opens the PR for review), so it
- // doesn't need willReviewLoop — the review gate holds unconditionally.
- return buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinelPath, branchName, baseBranch });
+ // The manual path can't drive the reviewer CLIs, so with a review loop
+ // configured it opens the PR and stops. Without one, no reviewer and no
+ // follow-up is coming — it merges on green CI like every other flow.
+ return buildManualTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, branchName, baseBranch });
}
const cmd = willOpenPR ? '/do:pr' : '/do:push';
const reviewUsernames = normalizeReviewUsernames(usernames);
@@ -1337,8 +1478,10 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
? (canRunSimplifyCommand ? '1. `/simplify`' : `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`)
: '1. (simplify disabled — skip)';
const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';
- const merge = willOpenPR && willReviewLoop
- ? buildPostPRMergeSteps(3, { reviewers, usernames: reviewUsernames, reviewStopMode })
+ // A PR always gets merge steps — gated on the review verdict when a loop runs,
+ // on CI alone when it doesn't (nothing else merges a no-review-loop PR).
+ const merge = willOpenPR
+ ? buildPostPRMergeSteps(3, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode })
: { lines: [], nextStep: 3 };
const sentinelStep = merge.nextStep;
@@ -1373,14 +1516,21 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
*
* PortOS forces `openPR:false, skipMerge:true` on TUI worktree cleanup (see
* agentTuiSpawning.js), so nothing happens after the agent exits — the agent owns
- * the push and the PR itself. It opens the PR/MR for review but does NOT merge:
+ * the push and the PR itself.
+ *
+ * With a review loop configured (`willReviewLoop`), it opens the PR/MR and stops:
* this provider can't drive the reviewer CLIs (no slashdo `/do:pr` review loop)
- * and PortOS runs no post-exit review for a TUI, so auto-merging would ship
- * unreviewed work. A configured reviewer / human reviews and merges. Forge-aware
- * (GitHub `gh` + GitLab `glab`) to match the slashdo path; refs are shell-quoted
- * because a git ref can legally contain shell metacharacters.
+ * and PortOS runs no post-exit review for a TUI, so merging here would ship work
+ * the user asked to have reviewed. With the review loop OFF there is no reviewer
+ * and no follow-up coming, so leaving it open just leaks the PR — the agent
+ * merges it once CI is green, matching every other no-review-loop flow.
+ *
+ * Forge-aware (GitHub `gh` + GitLab `glab`) to match the slashdo path; refs are
+ * shell-quoted because a git ref can legally contain shell metacharacters.
*/
-function buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null }) {
+// `willReviewLoop` defaults to the conservative side (same as buildPostPRMergeSteps):
+// an omitted flag leaves the PR open for review rather than merging unreviewed work.
+function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null }) {
const branchRef = shellQuote(branchName || 'HEAD');
// Pin the PR base to the worktree's base branch when known, so the forge CLI
// doesn't guess (and a fork install targets the intended branch). `--fill`
@@ -1412,14 +1562,23 @@ function buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinel
let step = 4;
if (willOpenPR) {
+ const openNote = willReviewLoop
+ ? '**Leave it open for review — do NOT merge it yourself.** This provider can\'t run the reviewer loop, and PortOS won\'t merge it for a TUI task, so a configured reviewer or a human reviews and merges it.'
+ : 'No review loop is configured for this task, so you merge it yourself in the next step — nothing else will.';
lines.push(
- `${step++}. Open a pull/merge request against the base branch using the CLI for this repo's forge (check \`git remote -v\`), and capture the URL it prints. **Leave it open for review — do NOT merge it yourself.** This provider can't run the reviewer loop, and PortOS won't merge it for a TUI task, so a configured reviewer or a human reviews and merges it.`,
+ `${step++}. Open a pull/merge request against the base branch using the CLI for this repo's forge (check \`git remote -v\`), and capture the URL it prints. ${openNote}`,
'',
' ```bash',
` # GitHub: gh pr create --fill${ghBaseArg}`,
` # GitLab: glab mr create --fill${glabBaseArg}`,
' ```',
);
+ if (!willReviewLoop) {
+ // Same CI-gate procedure the slashdo workflow and the merge follow-up use.
+ const gate = buildCiMergeGateSteps(step, { prRef: '"<PR_URL>"', forge: 'unknown' });
+ lines.push(...gate.lines);
+ step = gate.nextStep;
+ }
}
lines.push(
@@ -1469,11 +1628,9 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop =
: `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)
: 'with external review disabled.';
lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);
- const merge = willReviewLoop
- ? buildPostPRMergeSteps(step, { reviewers, usernames: reviewUsernames, reviewStopMode })
- : { lines: [], nextStep: step };
+ // Merge steps always follow — review-gated with a loop, CI-gated without one.
+ const merge = buildPostPRMergeSteps(step, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode });
lines.push(...merge.lines);
- step = merge.nextStep;
return lines.join('\n');
}
if (hasSlashdo && worktreeInfo) {
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 62add8a6e8..05aa156dd0 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -323,10 +323,14 @@ describe('buildLightContextPrompt', () => {
// poll). The prompt only mentions /quit to tell the agent NOT to run it.
expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);
expect(prompt).toMatch(/NOT run `\/quit`/);
- // Without a Review Loop the task opens the PR for human follow-up and
- // must not be told to auto-merge based on a review outcome.
- expect(prompt).not.toMatch(/gh pr merge/);
- expect(prompt).not.toMatch(/gh pr view "<PR_URL>" --json state/);
+ // Without a Review Loop nothing else will ever merge this PR, so the agent
+ // merges it itself — gated on CI instead of on a review verdict.
+ expect(prompt).toMatch(/gh pr checks "<PR_URL>" --watch --fail-fast/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
+ expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
+ // ...and the gate is CI, not a review-loop status.
+ expect(prompt).not.toMatch(/review loop reports/);
});
it('TUI simplify step is provider-aware — non-Claude TUI (codex-tui) gets the inline equivalent, not /simplify', () => {
@@ -352,13 +356,14 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/gh pr merge/);
});
- it('emits a slashdo-free, forge-aware Completion Workflow for an OpenCode TUI + openPR (opens PR, no auto-merge)', () => {
+ it('emits a slashdo-free, forge-aware Completion Workflow for an OpenCode TUI + openPR + Review Loop (opens PR, no auto-merge)', () => {
// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push
// would be uninvokable. The agent commits, pushes, opens the PR/MR for review,
- // and writes the sentinel with plain git + the forge CLI. It must NOT auto-merge
- // (it can't run the reviewer loop and PortOS runs no post-exit review for a TUI).
+ // and writes the sentinel with plain git + the forge CLI. With a Review Loop
+ // configured it must NOT auto-merge (it can't run the reviewer loop and PortOS
+ // runs no post-exit review for a TUI).
const prompt = buildLightContextPrompt(
- makeTask({ metadata: { simplify: true, openPR: true } }),
+ makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true } }),
'/r',
{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },
isTruthyMeta,
@@ -386,6 +391,23 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);
});
+ it('OpenCode TUI + openPR WITHOUT a Review Loop merges on green CI (forge-aware)', () => {
+ // No reviewer and no PortOS follow-up is coming for a TUI task, so leaving the
+ // PR open would leak it — the agent gates on CI and merges itself.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { simplify: true, openPR: true } }),
+ '/r',
+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },
+ isTruthyMeta,
+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });
+ expect(prompt).toMatch(/gh pr create --fill --base main/);
+ expect(prompt).toMatch(/gh pr checks "<PR_URL>" --watch --fail-fast/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).toMatch(/glab mr merge "<MR_URL>" --yes --remove-source-branch/);
+ expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
+ expect(prompt).not.toMatch(/do NOT merge it yourself/);
+ });
+
it('OpenCode TUI without openPR pushes the branch but opens no PR', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: { openPR: false } }),
@@ -478,7 +500,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/MERGED/);
});
- it('disables external review and omits merge guidance for Claude Code CLI when Review Loop is off', () => {
+ it('disables external review but merges on green CI for Claude Code CLI when Review Loop is off', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: { openPR: true, simplify: false } }),
'/r',
@@ -488,8 +510,11 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/`\/do:pr --review-with none`/);
expect(prompt).toMatch(/external review disabled/i);
expect(prompt).not.toMatch(/Copilot review loop/i);
- expect(prompt).not.toMatch(/gh pr merge/);
- expect(prompt).not.toMatch(/gh pr view "<PR_URL>" --json state/);
+ // No review loop means nothing else merges the PR — the agent gates on CI.
+ expect(prompt).toMatch(/gh pr checks "<PR_URL>" --watch --fail-fast/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
+ expect(prompt).not.toMatch(/review loop reports/);
});
it('skips /simplify in the slashdo Completion block when simplify is disabled', () => {
@@ -576,6 +601,61 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/challenge\/resolve/);
});
+ it('renders a merge-only follow-up block (no reviewers) when reviewLoopMergeOnly is set', () => {
+ // Review Loop off: PortOS opened the PR and spawned this follow-up purely to
+ // land it. The block must gate on CI, never invoke or wait for a reviewer.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopMergeOnly: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopPROwner: 'o',
+ reviewLoopPRRepo: 'r',
+ reviewLoopReviewers: [],
+ sourceTaskId: 'task-src-2',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/## Merge Follow-up/);
+ expect(prompt).not.toMatch(/## Review-Loop Follow-up/);
+ // CI is the gate, and the merge command matches the review-loop contract.
+ expect(prompt).toMatch(/gh pr checks "https:\/\/github\.com\/o\/r\/pull\/9" --watch --fail-fast/);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
+ expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);
+ expect(prompt).toMatch(/MERGED/);
+ // No reviewer defaulting may leak back in (normalizeReviewers would say copilot).
+ expect(prompt).not.toMatch(/copilot/i);
+ expect(prompt).not.toMatch(/Reviewers \(in order\)/);
+ expect(prompt).not.toMatch(/--review-with/);
+ });
+
+ it('a merge-only follow-up on a GitLab MR gets glab commands, not gh', () => {
+ // PortOS opens MRs via glab too, so a gh-only procedure would fail on the
+ // first command after a full agent spawn.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopMergeOnly: true,
+ reviewLoopPRUrl: 'https://gitlab.com/g/p/-/merge_requests/5',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 5,
+ reviewLoopPRHost: 'gitlab.com',
+ sourceTaskId: 'task-src-3',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/## Merge Follow-up/);
+ expect(prompt).toMatch(/glab mr merge "https:\/\/gitlab\.com\/g\/p\/-\/merge_requests\/5" --yes --remove-source-branch/);
+ expect(prompt).toMatch(/glab ci status/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/gh pr checks/);
+ });
+
it('threads a non-default reviewer (claude) into the follow-up block via --review-with', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: {
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index d47bc0fdee..d7acbb01b4 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -168,25 +168,29 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
// at copilot's turn (so a failed pre-request or copilot-only config still gets a
// review pass) and invokes the CLI reviewers itself. The only reviewer dropped is
// copilot on a non-GitHub forge, handled centrally in spawnReviewLoopFollowUp.
- const canSpawnFollowUp = shouldRequestCopilot && reviewerList.length > 0;
- if (canSpawnFollowUp) {
- await spawnReviewLoopFollowUp({
- originalAgentId: agentId,
- originalTask,
- prUrl: prResult.url,
- prBranch: worktreeBranch,
- sourceWorkspace,
- reviewers: reviewerList,
- usernames,
- optionalReviewers,
- reviewStopMode,
- reviewerApplies,
- reviewerModels
- }).catch(err => {
- emitLog('warn', `🤖 Failed to spawn review-loop follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
- warnings.push(`Review-loop follow-up spawn failed for ${prResult.url}: ${err.message}`);
- });
- }
+ //
+ // A follow-up is ALWAYS spawned for a PR PortOS opened, because something has
+ // to land it. `spawnReviewLoopFollowUp` picks the mode from what actually
+ // survives reviewer resolution: reviewers left → review-then-merge; none left
+ // (Review Loop off, or copilot-only on a non-GitHub forge) → merge on green CI.
+ // Deciding it there rather than here is what keeps a stripped reviewer list
+ // from silently producing an orphaned PR.
+ await spawnReviewLoopFollowUp({
+ originalAgentId: agentId,
+ originalTask,
+ prUrl: prResult.url,
+ prBranch: worktreeBranch,
+ sourceWorkspace,
+ reviewers: shouldRequestCopilot ? reviewerList : [],
+ usernames: shouldRequestCopilot ? usernames : [],
+ optionalReviewers: shouldRequestCopilot ? optionalReviewers : [],
+ reviewStopMode,
+ reviewerApplies,
+ reviewerModels
+ }).catch(err => {
+ emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
+ warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);
+ });
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
@@ -231,10 +235,17 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
* runs each in order — invoking the CLI reviewers itself and requesting Copilot at
* its turn — honoring `reviewStopMode` (`all`/`on-findings`/`on-clean`) and
* `reviewerApplies`. Copilot is GitHub-only, so it is stripped here on non-GitHub
- * forges; if that empties the list AND no `usernames` are configured, no follow-up
- * is spawned. `usernames` are arbitrary GitHub reviewer usernames the follow-up
+ * forges. `usernames` are arbitrary GitHub reviewer usernames the follow-up
* requests as PR reviewers to gate the merge — forge-agnostic, so never stripped.
*
+ * **Mode is derived, not passed.** When nothing survives reviewer resolution —
+ * the task's Review Loop was off (caller passes an explicitly empty list), or
+ * copilot was the only reviewer and this is a GitLab MR — the follow-up runs in
+ * **merge-only** mode: no review, just land the PR (wait for CI, fix a failing
+ * check or a conflict, merge). Deriving it here means there is no combination
+ * that spawns nothing and leaves the PR open forever, which is what used to
+ * happen both with the Review Loop off and with copilot-only on GitLab.
+ *
* The follow-up task uses an isolated worktree attached to the existing PR
* branch (via createWorktree's `existingBranch` option) so it can fix-and-push
* without trampling concurrent agents.
@@ -245,10 +256,11 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
const parsedPr = git.parsePullRequestUrl(prUrl);
// Copilot is GitHub-only; CLI-based reviewers (claude/antigravity/codex/grok) work on any
// forge because the agent invokes the CLI directly. On a non-GitHub forge, drop
- // copilot from the list — if nothing's left (and no username reviewers), there's
- // no review to run.
+ // copilot from the list.
const isNonGithubForge = parsedPr && parsedPr.host && parsedPr.host !== 'github.com';
- const reviewerList = normalizeReviewers({ reviewers });
+ // An EXPLICITLY empty list means "no review was requested" and must stay empty —
+ // normalizeReviewers' `[copilot]` default would otherwise resurrect a reviewer.
+ const reviewerList = (Array.isArray(reviewers) && reviewers.length === 0) ? [] : normalizeReviewers({ reviewers });
const effectiveReviewers = isNonGithubForge ? reviewerList.filter(r => r !== DEFAULT_REVIEWER) : reviewerList;
// GitHub reviewer usernames are forge-agnostic requested reviewers, so they are
// NOT stripped on a non-GitHub forge — a username reviewer alone can drive the
@@ -257,7 +269,8 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// Non-blocking (`~opt`) marker set — forge-agnostic, threaded verbatim so the
// follow-up's `--review-with` marks the same reviewers optional.
const effectiveOptionalReviewers = normalizeOptionalReviewers(optionalReviewers) || [];
- if (effectiveReviewers.length === 0 && effectiveUsernames.length === 0) return null;
+ // Nothing left to review → this follow-up's only job is to land the PR.
+ const mergeOnly = effectiveReviewers.length === 0 && effectiveUsernames.length === 0;
// Reviewer-keyed CLI model map, narrowed to the model-capable reviewers actually
// in this loop's list (e.g. `{ codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }`); the
@@ -268,10 +281,16 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
if (MODEL_CAPABLE_CLI_REVIEWERS.includes(r) && reviewerModels?.[r]) narrowedReviewerModels[r] = reviewerModels[r];
}
+ // One place that names the mode, so the title, the log line, and the warning
+ // can't drift apart as the two follow-up kinds evolve.
+ const kind = mergeOnly
+ ? { title: 'Merge', label: 'merge', reviewers: 'merge on green CI, no review' }
+ : { title: 'Review Loop', label: 'review-loop', reviewers: [...effectiveReviewers, ...effectiveUsernames.map(u => `@${u}`)].join(', ') };
+
const appId = originalTask?.metadata?.app || null;
const sourceTaskDesc = originalTask?.description || 'CoS automated task';
const firstLine = sourceTaskDesc.split(/[\r\n]/).find(l => l.trim()) || sourceTaskDesc;
- const followUpTitle = `[Review Loop] ${firstLine.trim().substring(0, 80)} (${prUrl})`;
+ const followUpTitle = `[${kind.title}] ${firstLine.trim().substring(0, 80)} (${prUrl})`;
const followUpTaskId = `sys-rl-${Date.now().toString(36)}`;
const followUpTask = {
@@ -293,6 +312,8 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
simplify: false,
// Marker flags consumed by the agent prompt + completion handler
reviewLoopFollowUp: true,
+ // Merge-only run: no reviewers, the prompt is a CI-gate-and-merge procedure.
+ reviewLoopMergeOnly: mergeOnly,
reviewLoopPRUrl: prUrl,
reviewLoopPRBranch: prBranch,
reviewLoopPRNumber: parsedPr?.number ?? null,
@@ -325,8 +346,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
};
await addTask(followUpTask, 'internal', { raw: true });
- const reviewLoopLabel = [...effectiveReviewers, ...effectiveUsernames.map(u => `@${u}`)].join(', ');
- emitLog('info', `🔁 Spawned review-loop follow-up task ${followUpTaskId} (${reviewLoopLabel}) for PR ${prUrl}`, {
+ emitLog('info', `🔁 Spawned ${kind.label} follow-up task ${followUpTaskId} (${kind.reviewers}) for PR ${prUrl}`, {
taskId: followUpTaskId, prUrl, prBranch, sourceAgentId: originalAgentId, sourceTaskId: originalTask?.id
});
return followUpTask;
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index c1be4f1e50..b8d23ca71d 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -535,23 +535,31 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(removeWorktree).toHaveBeenCalled();
});
- it('should NOT spawn a review-loop follow-up on non-GitHub forges (Copilot is GitHub-only)', async () => {
+ it('spawns a merge-only follow-up on non-GitHub forges when copilot was the only reviewer', async () => {
+ // Copilot can't review a GitLab MR, so the review loop has nothing to run — but
+ // the MR still has to land, so the follow-up degrades to merge-only rather than
+ // not spawning (which left the MR open with no owner).
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://gitlab.com/group/proj/-/merge_requests/12' });
git.requestCopilotReview.mockResolvedValue({ success: true, skipped: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-gl' });
await cleanupAgentWorktree('agent-1', true, {
openPR: true, requestCopilotReview: true, description: 'X',
originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
});
- expect(addTask).not.toHaveBeenCalled();
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask.mock.calls[0][0].metadata.reviewLoopMergeOnly).toBe(true);
expect(removeWorktree).toHaveBeenCalled();
});
- it('should NOT spawn a review-loop follow-up when requestCopilotReview is false', async () => {
+ it('spawns a MERGE-ONLY follow-up (no reviewers) when requestCopilotReview is false', async () => {
+ // Review Loop off: PortOS opened this PR and nothing else would ever merge it,
+ // so the follow-up runs in merge-only mode — CI gate, then merge.
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/44' });
+ addTask.mockResolvedValue({ id: 'sys-rl-m' });
await cleanupAgentWorktree('agent-1', true, {
openPR: true, requestCopilotReview: false, description: 'X',
@@ -559,7 +567,16 @@ describe('cleanupAgentWorktree - openPR path', () => {
});
expect(git.requestCopilotReview).not.toHaveBeenCalled();
- expect(addTask).not.toHaveBeenCalled();
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopMergeOnly).toBe(true);
+ // No reviewer may be defaulted back in — this PR was never meant to be reviewed.
+ expect(followUp.metadata.reviewLoopReviewers).toEqual([]);
+ expect(followUp.metadata.reviewLoopReviewerUsernames).toEqual([]);
+ expect(followUp.description).toMatch(/^\[Merge\]/);
+ // Still attaches to the PR branch so it can fix a failing check before merging.
+ expect(followUp.metadata.existingBranch).toBe('cos/task-abc123');
+ expect(removeWorktree).toHaveBeenCalled();
});
// --- non-Copilot reviewer (--review-with claude/antigravity/codex) ---
@@ -757,13 +774,16 @@ describe('spawnReviewLoopFollowUp', () => {
expect(addTask).not.toHaveBeenCalled();
});
- it('should skip spawning for GitLab MR URLs (Copilot is GitHub-only)', async () => {
+ it('falls back to a merge-only follow-up for GitLab MRs when copilot was the only reviewer', async () => {
+ // Copilot is GitHub-only, so nothing survives reviewer resolution here. Spawning
+ // nothing used to leave the MR open forever — the follow-up now just lands it.
const result = await spawnReviewLoopFollowUp({
originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
prUrl: 'https://gitlab.com/group/proj/-/merge_requests/5', prBranch: 'feat/x', sourceWorkspace: '/ws'
});
- expect(result).toBeNull();
- expect(addTask).not.toHaveBeenCalled();
+ expect(result.metadata.reviewLoopMergeOnly).toBe(true);
+ expect(result.metadata.reviewLoopReviewers).toEqual([]);
+ expect(addTask).toHaveBeenCalledTimes(1);
});
it('should default priority to MEDIUM when originalTask omits it', async () => {