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

fix: verify auto-merge handoffs and preserve recovery work

[._.]/ Adam Eivy97cd7315f0f7
diff --git a/server/lib/README.md b/server/lib/README.md
index 031c3f6604..8c85769c0b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -731,7 +731,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` / `resolveStepEffort` (spec rung → role default → run effort; an unsupported rung is an error, never a silent downgrade). |
| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. |
| `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |
-| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. Live `autoMergeEnabled` evidence accepts a terminal handoff without calling it merged. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
+| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` evidence. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
| `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. |
| `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |
| `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. |
diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.js
index 98fa503209..39c8863351 100644
--- a/server/lib/mergeGateContract.js
+++ b/server/lib/mergeGateContract.js
@@ -114,7 +114,23 @@ export function buildMergeGateReprompt(prUrl) {
].join('\n');
}
+// A queued handoff is temporary ownership, not an indefinite exemption from
+// recovery. Unknown check shapes and hour-old requests fail closed.
+export function hasHealthyAutoMergeRequest(pr, now = Date.now()) {
+ const enabledAt = Date.parse(pr?.autoMergeRequest?.enabledAt);
+ if (pr?.state !== 'OPEN' || pr.isDraft !== false || !Number.isFinite(enabledAt)
+ || enabledAt > now || now - enabledAt >= 60 * 60 * 1000
+ || !Array.isArray(pr.statusCheckRollup) || pr.statusCheckRollup.length === 0) return false;
+ return pr.statusCheckRollup.every(check => {
+ if (check?.__typename === 'StatusContext') return ['SUCCESS', 'PENDING', 'EXPECTED'].includes(check.state);
+ if (check?.__typename !== 'CheckRun') return false;
+ return check.status === 'COMPLETED'
+ ? ['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(check.conclusion)
+ : ['QUEUED', 'IN_PROGRESS', 'REQUESTED', 'WAITING', 'PENDING'].includes(check.status);
+ });
+}
+
/** Shared GitHub handoff contract for inline, review-follow-up and recovery prompts. */
export function buildAutoMergeHandoffInstructions(prRef) {
- return `**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect \`gh pr view ${prRef} --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision\` and \`gh api repos/{owner}/{repo}\` (use the PR's BASE repository). If that repository has \`allow_auto_merge: true\`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with \`gh pr merge ${prRef} --auto --merge --match-head-commit <published-head>\`. Use \`--squash\` or \`--rebase\` instead only when the repository disallows merge commits. Never use \`--admin\`, change branch protection, or enable repository auto-merge settings. Read back \`gh pr view ${prRef} --json state,headRefOid,autoMergeRequest\`: require the same published head and OPEN with a non-null \`autoMergeRequest.enabledAt\`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.`;
+ return `**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect \`gh pr view ${prRef} --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision\` and \`gh api repos/{owner}/{repo}\` (the PR's BASE repository). Require \`allow_auto_merge: true\`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before \`gh pr merge ${prRef} --auto --merge --match-head-commit <published-head>\`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use \`--squash\` or \`--rebase\` only if merge commits are disallowed. Never use \`--admin\`, change branch protection, or enable repository auto-merge settings. Read back \`gh pr view ${prRef} --json state,headRefOid,autoMergeRequest\`: require the same published head and OPEN with a non-null \`autoMergeRequest.enabledAt\`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.`;
}
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 2848f132db..011ab05913 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -204,13 +204,27 @@ describe('verifyAgentRepoState — divergent runs', () => {
localBranch(true);
hasBranchMergeEvidence.mockResolvedValue(false);
listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled: true });
+ execGit.mockImplementation(async (args) => ({ exitCode: 0, stdout: args[0] === 'rev-parse' ? 'abc123\n' : '' }));
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled: true, headRefOid: 'abc123' });
const result = await run();
expect(result.issues).toEqual([]);
expect(result.observed).toMatchObject({ prState: 'OPEN', autoMergeEnabled: true });
expect(addTask).not.toHaveBeenCalled();
});
+ it.each([
+ ['failed CI', false, 'abc123'],
+ ['unpublished local head', true, 'different-head'],
+ ])('retains recovery for an auto-merge request with %s', async (_name, autoMergeEnabled, headRefOid) => {
+ localBranch(true);
+ hasBranchMergeEvidence.mockResolvedValue(false);
+ execGit.mockImplementation(async (args) => ({ exitCode: 0, stdout: args[0] === 'rev-parse' ? 'abc123\n' : '' }));
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled, headRefOid });
+ const result = await run();
+ expect(result.issues.map(issue => issue.code)).toContain(REPO_STATE_ISSUES.PR_UNMERGED);
+ expect(addTask).toHaveBeenCalled();
+ });
+
it('reports an unmerged PR the agent left open', async () => {
localBranch(true);
hasBranchMergeEvidence.mockResolvedValue(false);
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 74bfc796da..59366fe028 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -550,8 +550,10 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
if (skipMerge) {
const pr = await import('./prProbe.js').then(({ probePrForBranch }) =>
probePrForBranch(sourceWorkspace, worktreeBranch)).catch(() => null);
- if (pr?.readable && pr.prState === 'OPEN' && pr.autoMergeEnabled === true) {
- emitLog('info', `🌳 Preserving pending GitHub auto-merge worktree for ${agentId}`, { agentId, branchName: worktreeBranch });
+ if (pr?.readable && pr.prState === 'OPEN') {
+ // Failed CI or unpublished commits need recovery, which still needs this
+ // branch. Only a healthy handoff suppresses the post-cleanup audit.
+ emitLog('info', `🌳 Preserving ${pr.autoMergeEnabled === true ? 'pending GitHub auto-merge' : 'unmerged PR recovery'} worktree for ${agentId}`, { agentId, branchName: worktreeBranch });
return;
}
}
diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
index f16f9b9a43..808099922f 100644
--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js
+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
@@ -35,7 +35,7 @@ vi.mock('./worktreeManager.js', () => ({
removeWorktree: vi.fn().mockResolvedValue({ removed: true, warnings: [] }),
classifyWorktreeDirt: vi.fn().mockReturnValue({ clean: true }),
}));
-vi.mock('./prProbe.js', () => ({ probePrForBranch: vi.fn().mockResolvedValue({ readable: true, prState: 'OPEN' }) }));
+vi.mock('./prProbe.js', () => ({ probePrForBranch: vi.fn().mockResolvedValue({ readable: true, prState: 'MERGED' }) }));
vi.mock('./agentRepoStateVerification.js', () => ({
verifyAgentRepoState: vi.fn().mockResolvedValue({ verified: true, issues: [] }),
}));
@@ -60,7 +60,7 @@ const auditRan = () => vi.waitFor(() => expect(verifyAgentRepoState).toHaveBeenC
beforeEach(() => {
vi.clearAllMocks();
- probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN' });
+ probePrForBranch.mockResolvedValue({ readable: true, prState: 'MERGED' });
// A non-worktree agent makes the cleanup itself a no-op, so these exercise the
// wrapper's hook rather than the teardown.
getAgent.mockResolvedValue({ metadata: { isWorktree: false } });
@@ -163,6 +163,15 @@ describe('cleanupAgentWorktree → repo-state audit', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it('preserves an unhealthy handoff for the repo-state recovery audit', async () => {
+ getAgent.mockResolvedValue(worktreeAgent);
+ probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN' });
+ const warnings = await cleanupAgentWorktree('agent-1', true, { skipMerge: true, originalTask: { id: 'task-1', metadata: { openPR: true } } });
+ expect(warnings).toEqual([]);
+ expect(removeWorktree).not.toHaveBeenCalled();
+ await auditRan();
+ });
+
it('returns the cleanup warnings unchanged, and survives an audit that throws', async () => {
// The audit is an observer. A failure in it must never swallow the warnings
// the caller uses to notify the user and spawn a merge recovery task.
diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.js
index a03ccb16c6..852617cf59 100644
--- a/server/services/github.ghHealth.test.js
+++ b/server/services/github.ghHealth.test.js
@@ -260,13 +260,31 @@ describe('findPullRequestForBranch (#3358)', () => {
});
it.each([
- [false, { enabledAt: '2026-10-18T00:00:00Z' }, true],
- [true, { enabledAt: '2026-10-18T00:00:00Z' }, false],
- [false, null, false],
- [false, {}, false],
- ])('reads auto-merge evidence for draft=%s request=%j', async (isDraft, autoMergeRequest, autoMergeEnabled) => {
- spawnMock.mockImplementation(() => ghChild({ stdout: JSON.stringify([{ number: 7, state: 'OPEN', isDraft, autoMergeRequest }]) }));
- await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ autoMergeEnabled });
+ ['pending', { __typename: 'CheckRun', status: 'IN_PROGRESS' }, true],
+ ['successful', { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'SUCCESS' }, true],
+ ['failed', { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'FAILURE' }, false],
+ ['cancelled', { __typename: 'CheckRun', status: 'COMPLETED', conclusion: 'CANCELLED' }, false],
+ ['legacy pending', { __typename: 'StatusContext', state: 'PENDING' }, true],
+ ['legacy error', { __typename: 'StatusContext', state: 'ERROR' }, false],
+ ['unknown', {}, false],
+ ])('classifies a %s auto-merge handoff from live CI', async (_name, check, autoMergeEnabled) => {
+ const pr = { number: 7, state: 'OPEN', isDraft: false, headRefOid: 'published-head',
+ autoMergeRequest: { enabledAt: new Date().toISOString() }, statusCheckRollup: [check] };
+ spawnMock.mockImplementation(() => ghChild({ stdout: JSON.stringify([pr]) }));
+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ autoMergeEnabled, headRefOid: 'published-head' });
+ });
+
+ it.each(['draft', 'missing request', 'malformed date', 'stalled', 'missing checks', 'empty checks'])('rejects a %s auto-merge handoff', async (kind) => {
+ const pr = { number: 7, state: 'OPEN', isDraft: kind === 'draft',
+ autoMergeRequest: { enabledAt: new Date().toISOString() },
+ statusCheckRollup: [{ __typename: 'CheckRun', status: 'IN_PROGRESS' }] };
+ if (kind === 'missing request') pr.autoMergeRequest = null;
+ if (kind === 'malformed date') pr.autoMergeRequest.enabledAt = 'invalid';
+ if (kind === 'stalled') pr.autoMergeRequest.enabledAt = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+ if (kind === 'missing checks') delete pr.statusCheckRollup;
+ if (kind === 'empty checks') pr.statusCheckRollup = [];
+ spawnMock.mockImplementation(() => ghChild({ stdout: JSON.stringify([pr]) }));
+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ autoMergeEnabled: false });
});
it('reports `none` for an ANSWERED empty list', async () => {
diff --git a/server/services/github.js b/server/services/github.js
index 08a0a0213e..72a84b3472 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -1,3 +1,4 @@
+import { hasHealthyAutoMergeRequest } from '../lib/mergeGateContract.js';
import { spawn } from '../lib/childProcess.js';
import { isHostShuttingDown } from '../lib/hostShutdown.js';
import { join } from 'path';
@@ -849,7 +850,7 @@ export async function ensureForgeReachable(label, { hostname = null, env = null
export async function findPullRequestForBranch(branch, { cwd = null, env = null, includeDraft = false } = {}) {
if (!branch) return { status: 'unavailable', number: null, url: null, detail: 'no branch name' };
const raw = await execGh(
- ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,body,state,isDraft,autoMergeRequest'],
+ ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,body,state,isDraft,autoMergeRequest,headRefOid,statusCheckRollup'],
DEFAULT_EXEC_GH_TIMEOUT_MS,
{ cwd, env }
).catch(err => err);
@@ -864,7 +865,7 @@ export async function findPullRequestForBranch(branch, { cwd = null, env = null,
}
const pr = parsed[0];
if (!pr) return { status: 'none', number: null, url: null, detail: null };
- return { status: 'found', number: pr.number ?? null, url: pr.url || null, body: typeof pr.body === 'string' ? pr.body : null, detail: pr.state || null, autoMergeEnabled: pr.state === 'OPEN' && pr.isDraft === false && typeof pr.autoMergeRequest?.enabledAt === 'string' && !!pr.autoMergeRequest.enabledAt, ...(includeDraft ? { isDraft: pr.isDraft === true } : {}) };
+ return { status: 'found', number: pr.number ?? null, url: pr.url || null, body: typeof pr.body === 'string' ? pr.body : null, detail: pr.state || null, headRefOid: typeof pr.headRefOid === 'string' ? pr.headRefOid : null, autoMergeEnabled: hasHealthyAutoMergeRequest(pr), ...(includeDraft ? { isDraft: pr.isDraft === true } : {}) };
}
/**
diff --git a/server/services/prProbe.js b/server/services/prProbe.js
index 4d7a5a7590..2eb29cb2d1 100644
--- a/server/services/prProbe.js
+++ b/server/services/prProbe.js
@@ -8,6 +8,7 @@
*/
import * as git from './git.js';
+import { execGit } from '../lib/execGit.js';
// `resolveForgeForRepo` spawns `git remote get-url` + `gh auth status` + `gh
// auth token` with no internal timeout, so a stalled `gh` (network / keychain
@@ -60,6 +61,11 @@ export async function probePrForBranch(sourceWorkspace, branchName, resolvedForg
// `none` is a real answer, not a gap — callers that need "the agent never
// opened one" distinguished from "we couldn't ask" read `readable` for that.
if (found.status !== 'found') return { prState: null, prUrl: null, prNumber: null, cli, readable: true };
+ // A remote handoff cannot cover local commits the agent never published.
+ const localHead = cli === 'gh' && found.autoMergeEnabled === true
+ ? await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace)
+ .then(result => result.exitCode === 0 ? result.stdout.trim() : null).catch(() => null)
+ : null;
return {
prState: found.detail ? String(found.detail).toUpperCase() : null,
prUrl: found.url || null,
@@ -69,7 +75,7 @@ export async function probePrForBranch(sourceWorkspace, branchName, resolvedForg
prNumber: found.number ?? null,
cli,
readable: !!found.detail,
- ...(cli === 'gh' && found.autoMergeEnabled === true ? { autoMergeEnabled: true } : {}),
+ ...(cli === 'gh' && found.autoMergeEnabled === true && localHead && localHead === found.headRefOid ? { autoMergeEnabled: true } : {}),
};
}
diff --git a/server/services/prProbe.test.js b/server/services/prProbe.test.js
index 338db90817..43ae66306e 100644
--- a/server/services/prProbe.test.js
+++ b/server/services/prProbe.test.js
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));
+
vi.mock('./git.js', () => ({
resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),
}));
@@ -11,6 +13,7 @@ vi.mock('./gitlab.js', () => ({
findMergeRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),
}));
+import { execGit } from '../lib/execGit.js';
import { resolveForgeForRepo } from './git.js';
import { findPullRequestForBranch, getPullRequestState } from './github.js';
import { findMergeRequestForBranch } from './gitlab.js';
@@ -18,6 +21,7 @@ import { probeChangeRequestState, probePrForBranch } from './prProbe.js';
beforeEach(() => {
vi.clearAllMocks();
+ execGit.mockResolvedValue({ exitCode: 0, stdout: 'published-head\n' });
resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: null });
findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });
findMergeRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });
@@ -36,10 +40,21 @@ describe('probePrForBranch', () => {
});
it('propagates GitHub-confirmed pending auto-merge without claiming MERGED', async () => {
- findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', autoMergeEnabled: true });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', autoMergeEnabled: true, headRefOid: 'published-head' });
expect(await probePrForBranch('/repo', 'my-branch')).toMatchObject({ prState: 'OPEN', readable: true, autoMergeEnabled: true });
});
+ it.each([
+ ['unpublished commits', { exitCode: 0, stdout: 'local-only-head\n' }],
+ ['missing local branch', { exitCode: 1, stdout: '' }],
+ ['unreadable local head', null],
+ ])('refuses a remote auto-merge handoff with %s', async (_name, local) => {
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', autoMergeEnabled: true, headRefOid: 'published-head' });
+ if (local) execGit.mockResolvedValue(local);
+ else execGit.mockRejectedValue(new Error('unreadable'));
+ expect(await probePrForBranch('/repo', 'my-branch')).not.toHaveProperty('autoMergeEnabled', true);
+ });
+
it('uppercases whatever case the forge returned for prState', async () => {
findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1, detail: 'open' });
const result = await probePrForBranch('/repo', 'my-branch');
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
index b55a61fbb5..88be1d5407 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
@@ -25,7 +25,7 @@ fi
Only an `ok: true` response with a validated `clean` or `findings` verdict and a successfully extracted `.findings` value is 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.
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
index 0e857b370e..aa0d4327d4 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
@@ -30,7 +30,7 @@ fi
Only an `ok: true` response with a validated `clean` or `findings` verdict and a successfully extracted `.findings` value is 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.
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
index 5b90de8a45..e13102e455 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
@@ -12,7 +12,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
1. 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.
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
index eac0e6a036..05802d72fc 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
@@ -35,7 +35,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
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.
**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.
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
index 840461d9e1..fd25b70447 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
@@ -40,7 +40,7 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
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.
**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.
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
index ef2ef72980..510fa68841 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
@@ -1,7 +1,7 @@
## Merge Follow-up (PRIMARY OBJECTIVE)
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.**
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged (a saved `/do:pr` default can merge it for you), skip to the next step:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
index bf27f79581..fc448007f5 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
@@ -1,7 +1,7 @@
## Merge Gate
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.**
-**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (use the PR's BASE repository). If that repository has `allow_auto_merge: true`, the PR is ready (not draft), conflict-free, reviews are satisfied, no check has failed, and CI is queued or running on that same head, enable GitHub auto-merge with `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Use `--squash` or `--rebase` instead only when the repository disallows merge commits. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. A command's exit status alone is not proof. Verified auto-merge is a successful terminal HANDOFF: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim the work landed. This handoff overrides subsequent in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces its required checks/reviews at the later merge instant, so this handoff does not acquire or hold local merge admission. If auto-merge is unavailable, rejected, or cannot be verified, follow the normal CI/merge gate below; failed checks still require a real fix.
+**GitHub auto-merge handoff (before waiting for CI):** After local validation and all configured reviews pass on the published head, inspect `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,isDraft,headRefOid,mergeable,statusCheckRollup,reviewDecision` and `gh api repos/{owner}/{repo}` (the PR's BASE repository). Require `allow_auto_merge: true`, a ready/non-draft conflict-free PR, satisfied reviews, no failed checks, and CI queued or running on that head. The next command can merge immediately: acquire repository merge admission with a valid token, re-read that same head and checks, and check admission immediately before `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. Follow the Repository merge admission acquire/check/release procedure; if unavailable or no registered parent identity was supplied, leave the PR open. Use `--squash` or `--rebase` only if merge commits are disallowed. Never use `--admin`, change branch protection, or enable repository auto-merge settings. Read back `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state,headRefOid,autoMergeRequest`: require the same published head and OPEN with a non-null `autoMergeRequest.enabledAt`, or confirm MERGED. Exit status alone is not proof. Release with outcome merged if MERGED, otherwise leave-open for a pending handoff or failure; require released:true. Never hold admission while waiting for CI. A verified pending handoff is successful: report the PR URL and head, explicitly say auto-merge enabled with CI pending, write the completion sentinel if required, and stop without waiting for MERGED. Preserve the unmerged branch; do not close its issue or claim it landed. This handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. GitHub enforces required checks/reviews at the later merge instant. If auto-merge is unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.
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.** A conflict-free branch may merge behind the base when required checks pass for its current head and configured reviews are satisfied. Base movement alone does not require rebasing or restarting CI. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after any resulting head change, rerun affected validation and required reviews/checks. 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, unless the verified GitHub auto-merge handoff above already completed this run. If it is already merged, skip to the next step:
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index f8d2b504eb..040838d177 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -600,7 +600,7 @@ export function buildMergeAdmissionSection(agentId) {
return [
'## Repository merge admission',
'Admission serializes only the merge instant. The parent orchestrator (never a fan-out child) completes publication, validation, configured reviews and required CI on its own head WITHOUT admission — other runs and every PR in a swarm do this concurrently. Never hold admission while syncing, running pregate, pushing or waiting for CI/reviews. Do not chase the default branch: rebase only for an actual conflict, an enforced up-to-date branch policy, or evidenced integration risk (inspect semantic overlap as well as textual conflicts). This overrides mandatory base-sync instructions in delegated slashdo workflows.',
- 'GitHub exception: the Merge Gate permits a verified auto-merge handoff after local validation and configured reviews pass while CI is pending. GitHub owns that later merge instant; do not acquire local admission for the handoff, and do not call it MERGED. The immediate merge path below still requires green CI and admission.',
+ 'GitHub exception: the Merge Gate permits a verified auto-merge handoff after local validation and configured reviews pass while CI is pending. The auto-merge command can also merge immediately: acquire admission around that command and its readback, then release with outcome merged for MERGED or leave-open for a pending handoff; do not call a pending handoff MERGED. For this pending-CI exception, re-read the same published head, require no failed checks and satisfied configured reviews, and check admission immediately before the command; release without waiting for CI. The immediate merge path below still requires green CI and admission.',
'Once required CI is green on the exact head you pushed (record that SHA as the CI-verified head) and configured reviews are satisfied, acquire admission. Require a parsed JSON response with admitted:true and a nonempty token; retain that token privately for check/release:',
'```bash', command('acquire'), '```',
'If an acquire/check refusal names lease-head-changed, release your token with outcome resync before acquiring again. If admitted:false with retryable:false, release any owned token with outcome leave-open, stop retrying, report the reason and message, and leave the PR/worktree intact. Otherwise, if admitted:false, report the reason and wait retryAfterMs (5 seconds), with a progress update at least every minute. Retry for at most 10 minutes, then record a leave-open outcome and finish with the PR (and any claim) intact. A refusal is never a reason to merge without admission. An HTTP/auth/transport error, unreadable JSON, or missing admission is a refusal, never permission to proceed. Do not modify another owner’s branch, checkout or lease.',
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index c19a711754..e6d5da10c0 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -25,6 +25,8 @@ describe('review-enabled completion merge gate', () => {
expect(section.indexOf('GitHub auto-merge handoff')).toBeLessThan(section.indexOf('4. **Wait for CI to finish**'));
expect(section).toContain('allow_auto_merge: true');
expect(section).toContain('autoMergeRequest.enabledAt');
+ expect(section).toContain('check admission immediately before');
+ expect(section).toContain('Release with outcome merged if MERGED, otherwise leave-open');
expect(section).toContain('all configured reviews pass');
expect(section).toContain('8. Write a short markdown summary');
});