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

feat: complete agent runs with verified GitHub auto-merge handoffs

Adam Eivyd8ed64041092
diff --git a/server/lib/README.md b/server/lib/README.md
index 3120005b55..031c3f6604 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, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. 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. 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`. |
| `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 bdb9d4f8d8..98fa503209 100644
--- a/server/lib/mergeGateContract.js
+++ b/server/lib/mergeGateContract.js
@@ -77,6 +77,8 @@ export function summaryStatesLeaveOpen(summary) {
* one that's CLOSED rather than merged). Either way there is nothing here
* to act on: finalize normally and let the post-teardown audit
* (`agentRepoStateVerification.js`) be the backstop, as today.
+ * - `auto-merge-enabled` — GitHub confirms a pending handoff; finalize without
+ * claiming it has merged.
* - `leave-open-stated` — the agent said, in its own words, that it is
* deliberately leaving the PR open; that is a correct terminal state.
* - `needs-reprompt` — the PR is open and the summary names no blocker: send
@@ -85,12 +87,13 @@ export function summaryStatesLeaveOpen(summary) {
* @param {object} params
* @param {{prState: string|null, readable: boolean}|null} params.prProbe
* @param {string|null|undefined} params.summary
- * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'needs-reprompt'}
+ * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'auto-merge-enabled'|'needs-reprompt'}
*/
export function resolveMergeGateVerdict({ prProbe, summary }) {
if (!prProbe || prProbe.readable === false) return 'no-pr-action';
if (prProbe.prState === 'MERGED') return 'merged';
if (prProbe.prState !== 'OPEN') return 'no-pr-action';
+ if (prProbe.autoMergeEnabled === true) return 'auto-merge-enabled';
if (summaryStatesLeaveOpen(summary)) return 'leave-open-stated';
return 'needs-reprompt';
}
@@ -106,7 +109,12 @@ export function resolveMergeGateVerdict({ prProbe, summary }) {
export function buildMergeGateReprompt(prUrl) {
return [
`Your Merge Gate is not finished: ${prUrl} is still OPEN and your last summary did not say you were leaving it open.`,
- 'Work through the Merge Gate steps from your original instructions now: watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --delete-branch`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.',
+ 'Work through the Merge Gate steps from your original instructions now: use the verified GitHub auto-merge handoff when eligible, otherwise watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --delete-branch`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.',
'If it truly cannot merge (a required check is red after a genuine fix attempt, or there is a conflict only a human can resolve), say so explicitly and leave it open.',
].join('\n');
}
+
+/** 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.`;
+}
diff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.js
index 72d6e57b2f..c5968193d0 100644
--- a/server/lib/mergeGateContract.test.js
+++ b/server/lib/mergeGateContract.test.js
@@ -82,6 +82,11 @@ describe('resolveMergeGateVerdict', () => {
})).toBe('leave-open-stated');
});
+ it('accepts live auto-merge evidence even without a handoff summary', () => {
+ expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true, autoMergeEnabled: true }, summary })).toBe('auto-merge-enabled');
+ expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true }, summary: 'Auto-merge enabled.' })).toBe('needs-reprompt');
+ });
+
it('is "needs-reprompt" when the PR is open and no blocker is stated', () => {
expect(resolveMergeGateVerdict({
prProbe: { prState: 'OPEN', readable: true }, summary,
diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.js
index 5e41cf8938..66d72375ac 100644
--- a/server/lib/repoStateExpectations.js
+++ b/server/lib/repoStateExpectations.js
@@ -150,6 +150,8 @@ export function resolveRepoStateExpectation({
export function classifyRepoStateIssues(expectation, observed = {}) {
if (!expectation?.verify) return [];
const branch = observed.branchName || 'the agent branch';
+ // GitHub owns a verified pending merge; retaining its branch is intentional.
+ if (observed.prState === 'OPEN' && observed.autoMergeEnabled === true) return [];
const branchShouldBeGone = !expectation.staysOpen;
const issues = [];
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 9630543593..acfd735733 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -1060,7 +1060,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/AMBIGUOUS/);
expect(prompt).toMatch(/gh workflow list/);
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 merge[^`\n]*--auto --merge --match-head-commit <published-head>/);
+ expect(prompt).toContain('autoMergeRequest.enabledAt');
+ expect(prompt).toContain('allow_auto_merge: true');
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).toContain('If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup');
expect(prompt).toContain('Continue to the completion sentinel when this workflow requires one');
@@ -1723,7 +1725,10 @@ describe('buildLightContextPrompt', () => {
// Keep bounded headroom for that safety prose while the explicit recipe
// omission above and this ceiling still reject inlining the 40KB recipe.
// #11435 adds the repository merge admission contract to own-PR runs.
- expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(30_000);
+ // The verified auto-merge handoff adds ~1.7KB of required policy. Keep
+ // the staging ceiling below the 40KB recipe and retain its explicit
+ // absence assertion above; this allowance covers only the new contract.
+ expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(32_000);
});
it('quotes a hostile branch ref inert in the PR-create command line', () => {
@@ -1927,7 +1932,9 @@ describe('buildLightContextPrompt', () => {
// merge and verify — without these steps the PR sits open after the
// agent exits (the original "agent abandoned the PR" bug).
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 merge[^`\n]*--auto --merge --match-head-commit <published-head>/);
+ expect(prompt).toContain('autoMergeRequest.enabledAt');
+ expect(prompt).toContain('allow_auto_merge: true');
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).toMatch(/MERGED/);
});
@@ -2066,10 +2073,11 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toContain('/api/cos/merge-admission');
expect(prompt).toMatch(/task-src-1/);
expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
- // --auto must NOT appear inside any `gh pr merge` invocation — it defers
- // the merge and the PR sits open after the agent exits.
- expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
- // Agent must verify the PR is actually merged before exiting.
+ // Pending CI may finish with a GitHub-confirmed auto-merge handoff.
+ expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);
+ expect(prompt).toContain('autoMergeRequest.enabledAt');
+ expect(prompt).toContain('allow_auto_merge: true');
+ // The immediate-merge fallback still verifies MERGED.
expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);
expect(prompt).toMatch(/MERGED/);
expect(prompt).not.toMatch(/## Completion Workflow/);
@@ -2106,7 +2114,9 @@ describe('buildLightContextPrompt', () => {
// 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 merge[^`\n]*--auto --merge --match-head-commit <published-head>/);
+ expect(prompt).toContain('autoMergeRequest.enabledAt');
+ expect(prompt).toContain('allow_auto_merge: true');
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).
@@ -2892,7 +2902,7 @@ describe('buildAgentPrompt — provider type routing', () => {
});
});
- it('full-context (api) review-loop follow-up emits merge command WITHOUT --auto and includes MERGED verification', async () => {
+ it('full-context (api) review-loop follow-up offers verified auto-merge and immediate-merge fallback', async () => {
// Regression for Copilot feedback on PR #260: the merge-without-auto +
// MERGED-state verification instructions live in BOTH the light and full
// prompt paths, and we lock them in for the full path here so the two
@@ -2916,10 +2926,11 @@ describe('buildAgentPrompt — provider type routing', () => {
expect(prompt).toMatch(/## Review-Loop Follow-up/);
// Merge command must be present, exactly with --merge --delete-branch.
expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
- // --auto must NOT appear inside any `gh pr merge` invocation — it defers
- // the merge and the PR sits open after the agent exits.
- expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
- // Agent must verify the PR is actually merged before exiting.
+ // Pending CI may finish with a GitHub-confirmed auto-merge handoff.
+ expect(prompt).toMatch(/gh pr merge[^`\n]*--auto --merge --match-head-commit <published-head>/);
+ expect(prompt).toContain('autoMergeRequest.enabledAt');
+ expect(prompt).toContain('allow_auto_merge: true');
+ // The immediate-merge fallback still verifies MERGED.
expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state -q \.state/);
expect(prompt).toMatch(/MERGED/);
// The generic completion guidance must not contradict the follow-up section:
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index b4a402f3f6..3e14eada0e 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -220,6 +220,7 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc
remoteBranchPresent,
branchMerged,
prState: pr.prState,
+ autoMergeEnabled: pr.autoMergeEnabled === true,
prUrl: pr.prUrl,
prNumber: pr.prNumber,
forgeCli: pr.cli,
@@ -309,7 +310,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,
emitLog('info', `🔎 Repo state only partly readable for ${agentId} (${branchName}) — could not check: ${observed.unreadable.join(', ')}`, { agentId, branchName });
return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_INCOMPLETE, issues: [], observed, recoveryTaskId: null };
}
- emitLog('info', `🔎 Agent branch ${branchName} verified clean for ${agentId}`, { agentId, branchName });
+ emitLog('info', `🔎 Agent branch ${branchName} ${observed.autoMergeEnabled ? 'verified pending GitHub auto-merge' : 'verified clean'} for ${agentId}`, { agentId, branchName });
return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
}
@@ -373,7 +374,8 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,
* `PR_UNMERGED` delegates to branch-reconcile's `driveToMerge`, which carries the
* caveats a hand-written line loses: merge from the repo ROOT (gh cannot delete a
* branch checked out elsewhere), retry `--squash`/`--rebase` on "not allowed",
- * never `--auto`, and remove the worktree before deleting the branch.
+ * verify the GitHub auto-merge handoff, or remove the worktree after merging
+ * before deleting the branch.
*/
export const REPO_STATE_REMEDIATIONS = Object.freeze({
[REPO_STATE_ISSUES.WORKTREE_PRESENT]: ({ worktreePath }) =>
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 9c2a0a4c2e..2848f132db 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -200,6 +200,17 @@ describe('verifyAgentRepoState — divergent runs', () => {
expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.WORKTREE_PRESENT]);
});
+ it('does not file recovery against GitHub-confirmed auto-merge while its branch survives', async () => {
+ 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 });
+ const result = await run();
+ expect(result.issues).toEqual([]);
+ expect(result.observed).toMatchObject({ prState: 'OPEN', autoMergeEnabled: true });
+ expect(addTask).not.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 71becf7b9b..74bfc796da 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -541,12 +541,20 @@ async function queueWorktreeMerge({ agentId, worktreeBranch, originalTask, descr
return queuedDeterministicMerge;
}
-async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranch, warnings }, disposition) {
+async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranch, warnings, skipMerge }, disposition) {
// Default: auto-merge on success, just cleanup on failure.
// Review-loop follow-up agents pass skipMerge: true because gh pr merge already
// handled the merge upstream — re-merging the worktree branch into the local
// source workspace would duplicate the squashed commits.
const shouldMerge = disposition.merge;
+ 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 });
+ return;
+ }
+ }
emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${shouldMerge})`, {
agentId, branchName: worktreeBranch, merge: shouldMerge
});
diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
index 807e5feeab..f16f9b9a43 100644
--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js
+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
@@ -35,10 +35,12 @@ 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('./agentRepoStateVerification.js', () => ({
verifyAgentRepoState: vi.fn().mockResolvedValue({ verified: true, issues: [] }),
}));
+import { probePrForBranch } from './prProbe.js';
import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
import { verifyAgentRepoState } from './agentRepoStateVerification.js';
import { getAgent, getAgentRecord, addTask } from './cos.js';
@@ -58,6 +60,7 @@ const auditRan = () => vi.waitFor(() => expect(verifyAgentRepoState).toHaveBeenC
beforeEach(() => {
vi.clearAllMocks();
+ probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN' });
// 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 } });
@@ -151,6 +154,15 @@ describe('cleanupAgentWorktree → repo-state audit', () => {
expect(order).toEqual(['removeWorktree', 'audit']);
});
+ it('preserves a GitHub-confirmed pending auto-merge without cleanup warnings', async () => {
+ getAgent.mockResolvedValue(worktreeAgent);
+ probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN', autoMergeEnabled: true });
+ const warnings = await cleanupAgentWorktree('agent-1', true, { skipMerge: true, originalTask: { id: 'task-1', metadata: { openPR: true } } });
+ expect(warnings).toEqual([]);
+ expect(removeWorktree).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
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/branchReconcile.js b/server/services/branchReconcile.js
index d6e31c7b4c..5cf822c244 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -22,6 +22,7 @@
* is reported, never touched.
*/
+import { buildAutoMergeHandoffInstructions } from '../lib/mergeGateContract.js';
import { stat } from 'node:fs/promises';
import { join } from 'node:path';
import { isHostShuttingDown } from '../lib/hostShutdown.js';
@@ -1827,27 +1828,21 @@ const supersessionGate = ({ collisionPaths = [], behind } = {}) => {
// recovery followed by fresh validation on the resulting head.
const verifyGate = 'Fetch the default branch for comparison before opening or updating a PR; inspect semantic overlap and supersession. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk. Base movement alone does not require a rebase or another CI run; this overrides mandatory base-sync instructions in delegated slashdo workflows. Run the test suites for the workspaces the diff touches (`cd server && npm test`, `cd client && npm test`) plus lint, and read the result. After changing the head, rerun affected validation and required reviews/checks. If anything fails, fix it on the branch and re-run; if you cannot get it green, stop and report which suite fails and why. Never push a branch whose tests you have not seen pass.';
-// The terminal state of an auto-mergeable branch is MERGED — not "PR opened",
-// not "PR green and waiting". Every drive-to-merge instruction ends with this
-// tail so the agent waits CI out IN-SESSION instead of handing back an open PR
-// (the miss that left a green, MERGEABLE PR sitting open after a NEEDS_PR run:
-// the agent opened it and signaled done 51s later). GitHub-native `--auto` is
-// deliberately not the answer on its own — the agent exits the moment it
-// finishes, so a queued auto-merge that later goes red has nobody left to fix
-// it, and the branch silently stays in-flight until the next recheck.
-//
+// A verified GitHub auto-merge handoff can finish the run before CI drains.
+// Immediate merges still require the current-head CI and ownership gates.
// `pr` is the PR's number when the branch already has one, else the `<num>`
// placeholder the agent fills in after opening it.
// Exported so the per-agent repo-state audit (services/agentRepoStateVerification.js)
// hands a recovery agent the SAME merge procedure, rather than re-authoring a
// `gh pr merge` line that loses these caveats.
export const driveToMerge = (pr) => [
+ buildAutoMergeHandoffInstructions(pr),
'Opening (or approving) the PR is NOT the end state — a green PR left open is still an unfinished branch that this task will simply re-drive on its next run.',
'A conflict-free branch with passing current-head required checks and satisfied configured reviews may merge behind the default branch. Base movement alone does not require rebasing or restarting CI.',
`Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s so the run stays observable while CI is pending. Budget 15 minutes for the run; past that, leave the PR open and report that CI was still pending.`,
'If a required check FAILS, fix it on the branch, push, and re-poll (max 3 rounds); if it is still red after that, leave the PR open and report exactly which check failed.',
'Record the exact local branch head whose checks and configured reviews passed as <verified-head>; immediately before merging, repeat the ownership/policy Recheck and require the forge PR head to equal that same head. If either changed, stop and revalidate. Every merge attempt, including a method retry, must retain --match-head-commit <verified-head>.',
- `Once every required check is green AND the PR is MERGEABLE, merge it — from the repo root, NOT from inside the branch's worktree (\`gh\` can't delete a branch that is checked out elsewhere): \`gh pr merge ${pr} --merge --delete-branch --match-head-commit <verified-head>\`. Repos differ in which methods they allow, so on a "not allowed" error retry with \`--squash\`, then \`--rebase\`. Never \`--auto\`: a queued auto-merge outlives this run, so a check that goes red afterward has nobody left to fix it.`,
+ `Once every required check is green AND the PR is MERGEABLE, merge it — from the repo root, NOT from inside the branch's worktree (\`gh\` can't delete a branch that is checked out elsewhere): \`gh pr merge ${pr} --merge --delete-branch --match-head-commit <verified-head>\`. Repos differ in which methods they allow, so on a "not allowed" error retry with \`--squash\`, then \`--rebase\`.`,
'After the merge, remove the branch\'s worktree first, then delete the local branch — the delete fails while a worktree still has it checked out.'
].join(' ');
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 0199bf8b1c..b00a42fcad 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -2104,11 +2104,12 @@ describe('desiredEndState', () => {
}
});
- it('makes both merge-bound states wait for CI in-session and forbid queued auto-merge', () => {
+ it('offers verified auto-merge before the fallback CI wait in both merge-bound states', () => {
for (const state of ['NEEDS_PR', 'IN_REVIEW']) {
const instruction = desiredEndState(state, {});
expect(instruction).toContain('gh pr checks <num> --required');
- expect(instruction).toContain('Never `--auto`');
+ expect(instruction).toContain('--auto --merge --match-head-commit <published-head>');
+ expect(instruction).toContain('autoMergeRequest.enabledAt');
}
});
diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.js
index 64877b3e74..a03ccb16c6 100644
--- a/server/services/github.ghHealth.test.js
+++ b/server/services/github.ghHealth.test.js
@@ -259,6 +259,16 @@ describe('findPullRequestForBranch (#3358)', () => {
await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'found', number: 7, body: 'Closes #1' });
});
+ 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 });
+ });
+
it('reports `none` for an ANSWERED empty list', async () => {
spawnMock.mockImplementation(() => ghChild({ stdout: '[]' }));
await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'none', number: null });
diff --git a/server/services/github.js b/server/services/github.js
index 3b10f1e623..08a0a0213e 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -849,7 +849,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', includeDraft ? 'number,url,body,state,isDraft' : 'number,url,body,state'],
+ ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,body,state,isDraft,autoMergeRequest'],
DEFAULT_EXEC_GH_TIMEOUT_MS,
{ cwd, env }
).catch(err => err);
@@ -864,7 +864,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, ...(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, autoMergeEnabled: pr.state === 'OPEN' && pr.isDraft === false && typeof pr.autoMergeRequest?.enabledAt === 'string' && !!pr.autoMergeRequest.enabledAt, ...(includeDraft ? { isDraft: pr.isDraft === true } : {}) };
}
/**
diff --git a/server/services/prProbe.js b/server/services/prProbe.js
index 9ecb2a9340..4d7a5a7590 100644
--- a/server/services/prProbe.js
+++ b/server/services/prProbe.js
@@ -69,6 +69,7 @@ export async function probePrForBranch(sourceWorkspace, branchName, resolvedForg
prNumber: found.number ?? null,
cli,
readable: !!found.detail,
+ ...(cli === 'gh' && found.autoMergeEnabled === true ? { autoMergeEnabled: true } : {}),
};
}
diff --git a/server/services/prProbe.test.js b/server/services/prProbe.test.js
index 18e0bb1593..338db90817 100644
--- a/server/services/prProbe.test.js
+++ b/server/services/prProbe.test.js
@@ -35,6 +35,11 @@ describe('probePrForBranch', () => {
expect(result).toEqual({ prState: 'MERGED', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true });
});
+ it('propagates GitHub-confirmed pending auto-merge without claiming MERGED', async () => {
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', autoMergeEnabled: true });
+ expect(await probePrForBranch('/repo', 'my-branch')).toMatchObject({ prState: 'OPEN', readable: true, 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 063840262b..b55a61fbb5 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
@@ -25,9 +25,10 @@ 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
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 c5038abea7..0e857b370e 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
@@ -30,9 +30,10 @@ 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
index 7a8bae5526..5b90de8a45 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
@@ -12,9 +12,10 @@ 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
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 92b7bad91d..eac0e6a036 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
@@ -35,9 +35,10 @@ 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
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 56f66e9216..840461d9e1 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
@@ -40,9 +40,10 @@ 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
index 2bb3cf63cf..ef2ef72980 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
@@ -1,9 +1,10 @@
## 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.
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, 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:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
index ac63631191..bf27f79581 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
@@ -1,9 +1,10 @@
## 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.
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, and any merge-deferral flag leaves the PR open after you exit. If it is already merged, skip to the next step:
+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:
```bash
gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch
```
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index df0b647e55..f8d2b504eb 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -2,6 +2,7 @@
* Completion workflow, worktree, and sentinel prompt sections.
*/
+import { buildAutoMergeHandoffInstructions } from '../../lib/mergeGateContract.js';
import { DEFAULT_REVIEWER, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isCliReviewer, isToolFreeReviewer, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/reviewerConfig.js';
import { isAuditTaskType } from '../../lib/auditCatalog.js';
import { resolveTaskHookType } from '../taskTypeHooks.js';
@@ -599,6 +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.',
'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.',
@@ -621,7 +623,7 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
...(resumeOverride ? [resumeOverride, ''] : []),
...(pin ? [pin, ''] : []),
buildClaimOwnershipSection(agentId), '',
- ...(!leavePrOpen ? [buildMergeAdmissionSection(agentId), ''] : []),
+ ...(!leavePrOpen ? [buildAutoMergeHandoffInstructions('"<PR_URL>"'), '', buildMergeAdmissionSection(agentId), ''] : []),
'## Claim Workflow Handoff',
...(leavePrOpen ? [
'PR completion policy: LEAVE OPEN for further human review. This overrides any merge, auto-merge, issue-close, or merged-branch cleanup instruction in the claim prompt and delegated slashdo commands. Do not pass --merge, enable auto-merge, merge the PR/MR, or close the issue/ticket.',
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index b7f1a82960..c19a711754 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -22,7 +22,10 @@ describe('review-enabled completion merge gate', () => {
expect(section).toContain('gh pr checks "<PR_URL>" --watch --fail-fast --interval 30');
expect(section).toContain('repeat the configured review loop for `copilot` against the new HEAD');
expect(section).toContain('gh pr merge "<PR_URL>" --merge --delete-branch');
- expect(section.indexOf('4. **Wait for CI to finish**')).toBeLessThan(section.indexOf('gh pr merge'));
+ expect(section.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('all configured reviews pass');
expect(section).toContain('8. Write a short markdown summary');
});
@@ -65,7 +68,7 @@ describe('claim parent merge admission instructions', () => {
expect(prompt).toContain('Authorization: Bearer');
expect(prompt).toContain('never a fan-out child');
// Ordering: CI-verified head → acquire → final PR re-read → pinned merge.
- const order = ['WITHOUT admission', 'Once required CI is green', '"action":"acquire"', 'Inside the lease, re-read the PR', '--match-head-commit'];
+ const order = ['WITHOUT admission', 'Once required CI is green', '"action":"acquire"', 'Inside the lease, re-read the PR', 'then merge pinned to the CI-verified head'];
const positions = order.map((marker) => prompt.indexOf(marker));
expect(positions.every((at) => at >= 0)).toBe(true);
expect(positions).toEqual([...positions].sort((x, y) => x - y));
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 0b91b35a5b..672410b628 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -2,6 +2,7 @@
* Review-loop, CI-gate, and merge prompt sections.
*/
+import { buildAutoMergeHandoffInstructions } from '../../lib/mergeGateContract.js';
import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isOptionalReviewer, isToolFreeReviewer, isProviderReviewer, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, reviewerModelFlag, resolveKeyedReviewers, buildReviewWithArgs, prioritizeToolFreeReviewers } from '../../lib/reviewerConfig.js';
import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';
import { detectForgeCli } from '../../lib/gitForge.js';
@@ -1124,9 +1125,10 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
const lines = [
localReviewMergeGuard || null,
localReviewAfterCodeFix ? `**Code-changing CI fix gate:**${localReviewAfterCodeFix}` : null,
+ gh ? buildAutoMergeHandoffInstructions(prRef) : null,
`${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,
`${startStep + 1}. **Clear whatever blocks the merge, then re-check.** 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 ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push.${reviewRecheckAfterCodeFix} Then go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent,${rebaseReviewSuffix} re-run the tests, \`git push --force-with-lease\`, and re-check.`,
- `${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged${alreadyMergedHint}, skip to the next step:`,
+ `${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, ${gh ? 'unless the verified GitHub auto-merge handoff above already completed this run' : 'and any merge-deferral flag leaves the PR open after you exit'}. If it is already merged${alreadyMergedHint}, skip to the next step:`,
' ```bash',
gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge${ghDelete}` : null,
// `glab mr merge` takes an MR IID or source branch — a URL is not accepted.