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: preserve managed worktrees until explicit cleanup (#12133)

Adam Eivy52ba0c954600
diff --git a/AGENTS.md b/AGENTS.md
index c43c5e44e6..be82c39651 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -258,7 +258,7 @@ This policy governs code comments, not user-facing guides or product copy.
- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.
- **Before pushing**: inspect branch/upstream and working-tree state, preserve unrelated changes, and commit the intended work. Fetch the workflow's intended base explicitly for comparison; a feature branch's tracking branch is not necessarily the default branch. Integrate it only when needed under the merge policy below. Run `npm run pregate` on the resulting commits, then push. Re-run it after any subsequent rebase; do not blindly pull with autostash.
- **Merge ready branches without chasing `main`.** A branch that is behind the default branch may merge when it is conflict-free, required checks pass for its current head, and configured reviews are satisfied. Default-branch movement alone does not invalidate those results or require a rebase, branch update, or another CI run. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk (including semantic overlap without textual conflicts); after changing the head, rerun affected validation and required reviews/checks. Keep implementation, review, and CI concurrent; hold repository merge admission only for the final live-state check, merge attempt, and readback, releasing it before recovery or further CI waits. Never bypass required checks or confuse a queued merge with `MERGED`. This policy overrides mandatory base-sync instructions in delegated slashdo workflows.
-- **Finish authorized merges and teardown before reporting success.** When merge is authorized, finish review and required checks, merge, and verify the merge completed. Archive unique content, including untracked and ignored files, before deleting a checkout. Recheck live ownership, release only this task's locks on its completed work, remove its worktree, and delete its explicitly named local branch; never infer the branch to delete from its upstream. Preserve other owners' locks and explicit manual handoffs. If work must remain, name its owner, blocker, and next step in the handoff.
+- **Finish authorized merges and teardown before reporting success.** When merge is authorized, finish review and required checks, merge, and verify the merge completed. Managed GitHub merges never pass `--delete-branch` to `gh pr merge`, including method fallbacks: it can remove another linked checkout before preservation. Pin every attempt to the CI-verified head, verify remote `MERGED`, and release merge admission before cleanup. Archive unique content, including untracked and ignored files, and verify preservation before deleting a checkout. Delete only the authorized exact remote ref with an expected-head lease; an advanced ref or archive failure leaves the checkout/ref intact with a tracked handoff. Recheck live ownership, release only this task's locks on its completed work, remove its worktree, and delete its explicitly named local branch; never infer the branch to delete from its upstream. Preserve other owners' locks and explicit manual handoffs. If work must remain, name its owner, blocker, and next step in the handoff.
- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.
- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json` through an immediately-merged pull request; with no local evidence it commits nothing and says so.
- **Versioning**: `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.
diff --git a/server/lib/README.md b/server/lib/README.md
index 598b383a11..ffd1b75f90 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -732,7 +732,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` / `merge-handoff-queued` / `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` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
+| `mergeGateContract.js` | `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `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` / `merge-handoff-queued` / `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` or a pending-merge receipt (`mergeHandoffQueued`). 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`. |
| `recoveryMergeTarget.js` | `repositoryCleanupMergeTarget(task)` → the `{ url, branch }` parent PR a repository-cleanup recovery was filed to land, or null (#12251). A claimed target only: merge admission also requires the completed parent's server-written backlink to that exact task, branch and PR. |
diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.js
index 5a91b2f112..9fc2fbd067 100644
--- a/server/lib/mergeGateContract.js
+++ b/server/lib/mergeGateContract.js
@@ -113,7 +113,7 @@ 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: use the verified PortOS pending-merge handoff (or, outside merge admission, the 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.',
+ 'Work through the Merge Gate steps from your original instructions now: use the verified PortOS pending-merge handoff (or, outside merge admission, the GitHub auto-merge handoff) when eligible, otherwise watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>`, 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');
}
@@ -138,3 +138,13 @@ export function hasHealthyAutoMergeRequest(pr, now = Date.now()) {
export function buildAutoMergeHandoffInstructions(prRef) {
return `**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read \`gh pr checks ${prRef} --required --json name,state\` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable \`gh pr merge ${prRef} --auto --merge --match-head-commit <published-head>\`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If unavailable, rejected, or unverified, follow the normal CI/merge gate below; failed checks require a real fix.`;
}
+
+/** Shared preservation ordering for every managed checkout delivery prompt. */
+export const MANAGED_WORKTREE_CLEANUP_CONTRACT = `**Managed-worktree preservation and explicit cleanup:** Merge commands must preserve local checkouts and branches on every GitHub CLI version; do not ask gh to delete branches at merge time. Keep every merge-method attempt pinned to the CI-verified head. The parent owns merge admission for swarm children too. First verify remote state is exactly MERGED, then release any owned merge-admission lease and require released:true. Only afterwards begin cleanup.
+Recheck live claim/worktree ownership, the exact checkout path and holder branch, the exact local branch tip, and the exact remote head ref on its verified remote. Limit all mutations to this task's allowlisted branch and checkout; refuse the default branch. A late unpublished commit or any changed ownership/ref invalidates cleanup: keep the checkout and refs intact and leave a tracked handoff. A missing remote ref (including repository auto-deletion) proves neither local preservation nor archive completion; a failed lookup is not proof of absence.
+Inventory and preserve ALL unique tracked, untracked AND ignored content outside the checkout, including test results and scratch artifacts; do not follow dependency symlinks into shared installations. Verify the archive manifest and copied bytes before removal, and recheck ownership, local tip and inventory again after archiving. Archive failure or an ownership/ref/inventory change keeps the checkout and branch intact; record the owner, blocker and next step in the owning tracker. Never infer preservation from a clean git status.
+After those proofs, when this workflow owns remote cleanup, delete an existing remote head only with an exact-ref compare-and-delete: \`git push --force-with-lease=refs/heads/<branch>:<verified-head> <verified-remote> :refs/heads/<branch>\`. A lease rejection preserves the advanced ref and stops cleanup. Verify that exact remote ref is absent. Then remove only the authorized worktree and ancestry-gate the explicitly named local branch with \`git branch -d <branch>\`; never force local branch deletion. Do not checkout or pull the default branch. A refusal leaves the surviving checkout/ref for reconciliation. Managed review/completion agents that hand teardown to PortOS must leave the local checkout and branch intact for that owner to apply these same gates.`;
+
+
+/** Review/completion agents hand teardown to PortOS rather than removing it. */
+export const MANAGED_WORKTREE_COMPLETION_HANDOFF = '**Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.';
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 296bf67665..879acd85be 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -484,7 +484,9 @@ describe('generic own-PR delivery merges inside repository admission (#11435)',
expect(prompt).toContain('/api/cos/merge-admission');
expect(prompt).toContain('agent-1');
expect(prompt).toContain('--match-head-commit <sha>');
- expect(prompt).toMatch(/gh pr merge "[^"]+" --merge --delete-branch/);
+ expect(prompt).not.toContain('--delete-branch');
+ expect(prompt).toContain('Archive failure');
+ expect(prompt).toMatch(/gh pr merge "[^"]+" --merge --match-head-commit <verified-head>/);
// Read before the workflow whose TUI form ends on the sentinel write.
expect(prompt.indexOf(ADMISSION)).toBeLessThan(prompt.search(/^## Completion/m));
// A saved slashdo merge default must not land the PR outside the lease.
@@ -1073,7 +1075,7 @@ describe('buildLightContextPrompt', () => {
// "no checks reported" is ambiguous on a just-opened PR — merging on it races CI.
expect(prompt).toMatch(/AMBIGUOUS/);
expect(prompt).toMatch(/gh workflow list/);
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);
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');
@@ -1354,13 +1356,13 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toContain('do NOT post a PR/MR comment saying the review was unavailable or inconclusive');
expect(prompt).toMatch(/PR_URL=\$\(gh pr create --base main --head "\$PR_HEAD"/);
expect(prompt).toMatch(/## Review Loop/);
- expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --match-head-commit <verified-head>/);
expect(prompt).toContain('LOCAL_PHASE_START_SHA');
expect(prompt).toContain('Cross-phase stop-mode gate');
expect(prompt).toContain('`all` always runs the PR-side reviewers.');
expect(prompt.indexOf('### Local Review Before Opening the PR/MR')).toBeLessThan(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"'));
expect(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"')).toBeLessThan(prompt.indexOf('## Review Loop'));
- expect(prompt.indexOf('Required local-review merge gate')).toBeLessThan(prompt.indexOf('gh pr merge "$PR_URL" --merge --delete-branch'));
+ expect(prompt.indexOf('Required local-review merge gate')).toBeLessThan(prompt.indexOf('gh pr merge "$PR_URL" --merge --match-head-commit <verified-head>'));
// The post-PR section receives only Copilot, never the local codex reviewer.
expect(prompt.slice(prompt.indexOf('## Review Loop'))).not.toMatch(/CLI Reviewer Procedure/);
// PortOS no longer promises to do any of it.
@@ -1575,7 +1577,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/## Merge Gate/);
expect(prompt).not.toMatch(/## Review Loop/);
expect(prompt).toMatch(/gh pr checks/);
- expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --match-head-commit <verified-head>/);
expect(prompt).not.toMatch(/PortOS will push the branch/);
});
@@ -1742,7 +1744,9 @@ describe('buildLightContextPrompt', () => {
// 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);
+ // #12133 adds the managed-worktree preservation handoff to the merge gate;
+ // the ceiling stays well below the 40KB recipe.
+ expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(33_000);
});
it('quotes a hostile branch ref inert in the PR-create command line', () => {
@@ -1945,7 +1949,7 @@ describe('buildLightContextPrompt', () => {
// After /do:pr drives the Copilot review loop clean, the agent must
// 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).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);
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');
@@ -1964,7 +1968,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/Copilot review loop/i);
// No review loop means nothing else merges the PR — the agent gates on CI.
expect(prompt).toMatch(/gh pr checks "<PR_URL>" --watch --fail-fast/);
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).not.toMatch(/review loop reports/);
});
@@ -1978,7 +1982,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/`\/do:pr`/);
expect(prompt).not.toMatch(/`\/simplify`/);
// Merge guidance still applies when /simplify is skipped.
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>/);
});
it('tells Claude Code CLI to commit only (no /do:push) when PortOS merges the worktree branch back', () => {
@@ -2086,7 +2090,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toContain('--match-head-commit <sha>');
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/);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);
// 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');
@@ -2127,7 +2131,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/## Review-Loop Follow-up/);
// CI is the gate, and the merge command matches the review-loop contract.
expect(prompt).toMatch(/gh pr checks "https:\/\/github\.com\/o\/r\/pull\/9" --watch --fail-fast/);
- expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);
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');
@@ -2178,7 +2182,7 @@ describe('buildLightContextPrompt', () => {
}}),
'/r',
{ branchName: 'b', worktreePath: '/tmp/wt' });
- expect(prompt).toMatch(/gh pr merge "https:\/\/github\.example\.com\/o\/r\/pull\/7" --merge --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.example\.com\/o\/r\/pull\/7" --merge --match-head-commit <verified-head>/);
expect(prompt).not.toMatch(/glab (?:issue|mr) /);
});
@@ -2938,8 +2942,8 @@ describe('buildAgentPrompt — provider type routing', () => {
{ branchName: 'b', worktreePath: '/tmp/wt' },
{ providerType: 'api' });
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/);
+ // Merge command must be present, exactly with --merge --match-head-commit <verified-head>.
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --match-head-commit <verified-head>/);
// 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');
@@ -3217,7 +3221,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {
const FIXTURE_GLOBAL_CLAUDE_MD = [
'# Example Global Instructions',
'',
- '- When CI is green, land it with `gh pr merge <url> --merge --delete-branch`.',
+ '- When CI is green, land it with `gh pr merge <url> --merge --match-head-commit <verified-head>`.',
'- Commit and push your changes before you stop.',
].join('\n');
@@ -3376,7 +3380,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {
// to do work — the task metadata asks for a PR, and discardWorktree must
// still win. Remove the discardWorktree arm and this prompt falls through to
// buildTuiCompletionSection, which renders `gh pr merge … --merge
- // --delete-branch`. (The `openPR: false` sibling above never reaches that
+ // --match-head-commit <verified-head>`. (The `openPR: false` sibling above never reaches that
// line at all, which is why its /gh pr merge/ check can't carry this.)
const prTask = makeTask({ metadata: { discardWorktree: true, useWorktree: true, openPR: true, simplify: true } });
const prompt = buildLightContextPrompt(prTask, '/r', wt, { isTui: true });
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index e5f1f4a798..3c59c1898d 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -373,7 +373,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,
* A map rather than a switch with a `default`, so a new code cannot ship without
* one — `repoStateExpectations.test.js` asserts the two key sets match.
* `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
+ * caveats a hand-written line loses: preserve the linked checkout (gh can implicitly delete a
* branch checked out elsewhere), retry `--squash`/`--rebase` on "not allowed",
* verify the GitHub auto-merge handoff, or remove the worktree after merging
* before deleting the branch.
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 350ad9d3da..f92edec5ea 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1,3 +1,4 @@
+import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
/**
* Branch & PR Reconciler — deterministic core (Tier 1).
*
@@ -1864,8 +1865,8 @@ export const driveToMerge = (pr) => [
`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\`.`,
- '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.'
+ `Once every required check is green AND the PR is MERGEABLE, merge without implicit local teardown: \`gh pr merge ${pr} --merge --match-head-commit <verified-head>\`. On a disallowed method retry with \`gh pr merge ${pr} --squash --match-head-commit <verified-head>\`, then \`gh pr merge ${pr} --rebase --match-head-commit <verified-head>\`. Never \`--auto\`: a queued merge outlives this run.`,
+ MANAGED_WORKTREE_CLEANUP_CONTRACT,
].join(' ');
/**
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index b00a42fcad..c002756476 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -1985,7 +1985,7 @@ describe('filterActionable', () => {
describe('desiredEndState', () => {
it('tells IN_REVIEW to merge only when autoMerge is on', () => {
- expect(desiredEndState('IN_REVIEW', {})).toContain('gh pr merge <num> --merge --delete-branch');
+ expect(desiredEndState('IN_REVIEW', {})).toContain('gh pr merge <num> --merge --match-head-commit <verified-head>');
expect(desiredEndState('IN_REVIEW', { autoMerge: false })).toContain('Do NOT merge');
});
@@ -2044,7 +2044,7 @@ describe('desiredEndState', () => {
expect(instruction).toContain('Do not merely inventory unfinished work');
expect(instruction).toContain('exceptional blocked outcome');
expect(instruction).toContain('/do:pr --no-merge');
- expect(instruction).toContain('gh pr merge <num> --merge --delete-branch');
+ expect(instruction).toContain('gh pr merge <num> --merge --match-head-commit <verified-head>');
});
it('tells NEEDS_PR to finish incomplete work instead of leaving it for another run', () => {
@@ -2071,7 +2071,7 @@ describe('desiredEndState', () => {
// IN_REVIEW, contradicting driveToMerge's own "opening the PR is NOT the end
// state" principle.
it('tells CONFLICTED to merge only when autoMerge is on', () => {
- expect(desiredEndState('CONFLICTED', {})).toContain('gh pr merge <num> --merge --delete-branch');
+ expect(desiredEndState('CONFLICTED', {})).toContain('gh pr merge <num> --merge --match-head-commit <verified-head>');
expect(desiredEndState('CONFLICTED', { autoMerge: false })).toContain('Do NOT merge');
expect(desiredEndState('CONFLICTED', { autoMerge: false })).not.toContain('gh pr merge');
});
@@ -2082,7 +2082,7 @@ describe('desiredEndState', () => {
it('drives NEEDS_PR past the PR to a merge when autoMerge is on', () => {
const instruction = desiredEndState('NEEDS_PR', {});
expect(instruction).toContain('gh pr checks <num> --required');
- expect(instruction).toContain('gh pr merge <num> --merge --delete-branch');
+ expect(instruction).toContain('gh pr merge <num> --merge --match-head-commit <verified-head>');
expect(instruction).toContain('NOT the end state');
});
@@ -2115,19 +2115,20 @@ describe('desiredEndState', () => {
// branch-reconcile runs against ANY managed app; a repo that disallows merge
// commits would strand the branch on a hardcoded `--merge`.
- it('gives the merge a method fallback and keeps it out of the branch worktree', () => {
+ it('pins every method fallback and preserves the worktree through archive checks', () => {
const instruction = desiredEndState('IN_REVIEW', {});
- expect(instruction).toContain('`--squash`');
- expect(instruction).toContain('`--rebase`');
- expect(instruction).toContain('NOT from inside the branch\'s worktree');
+ expect(instruction).toContain('--squash --match-head-commit <verified-head>');
+ expect(instruction).toContain('--rebase --match-head-commit <verified-head>');
+ expect(instruction).not.toContain('--delete-branch');
+ expect(instruction).toContain('Archive failure');
// Worktree first, then the branch — the delete fails while it's checked out.
- expect(instruction).toContain('remove the branch\'s worktree first, then delete the local branch');
+ expect(instruction).toContain('Then remove only the authorized worktree and ancestry-gate');
});
it('names the real PR number when the branch already has one', () => {
const instruction = desiredEndState('IN_REVIEW', {}, { prNumber: 42 });
expect(instruction).toContain('gh pr checks 42 --required');
- expect(instruction).toContain('gh pr merge 42 --merge --delete-branch');
+ expect(instruction).toContain('gh pr merge 42 --merge --match-head-commit <verified-head>');
expect(instruction).not.toContain('<num>');
});
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index 34c6ade670..cfe80a9bb0 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -433,7 +433,7 @@ describe('mode is honored identically from schedule, manual run, and quota burn'
}, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });
expect(prompt).toContain('gh pr create');
expect(prompt).toContain('## Merge Gate');
- expect(prompt).toContain('--merge --delete-branch');
+ expect(prompt).toContain('--merge --match-head-commit <verified-head>');
expect(prompt).not.toContain('PortOS will merge it back after completion');
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 26d187eb4a..78ea3e9abd 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -1,3 +1,4 @@
+import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
import { FORGE_MAINTENANCE_VERSION } from '../lib/forgeMaintenanceTasks.js';
/**
* CoS Task Pre-Step Blocks
@@ -289,6 +290,8 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}
## Phase C — Serialize only the merge instant (orchestrator, after all agents finish)
Bring every ready ${pr} to a CI-verified head CONCURRENTLY, without merge admission: re-sync each onto the latest default branch, run pregate, push, and gate on **required** CI on that exact head (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next). Then merge them ONE AT A TIME: for each green ${pr}, the parent orchestrator acquires the repository merge admission described in the Claim Workflow Handoff, re-reads the ${pr}, merges with \`${mergeCmd} ${mergePin}\` when the forge still reports it mergeable, and releases its own lease immediately (outcome merged). A ${pr} the forge no longer reports mergeable releases with outcome resync and goes back through the concurrent sync/pregate/CI step outside the lease; a base that moved while the ${pr} stays mergeable needs no resync. After all merges, run Phase 7 cleanup once per merged worktree.
+${forgeKey === 'gh' ? MANAGED_WORKTREE_CLEANUP_CONTRACT : ''}
+
**Then — orchestrator only, ALWAYS, even though swarm work ships via ${pr}s with no working-tree change — write the completion sentinel** described in the **Completion Workflow** section below (write it at the EXACT sentinel path that section gives you — the filename carries your agent id — with a short run summary of the issues claimed + their ${pr}s + merge outcomes). Skip the \`/simplify\` and push/${pr} steps of that workflow (each fan-out agent already ran them), but the sentinel write is NOT optional: it is the ONLY signal that marks this CoS task complete and hands the orchestrator's summary back. A swarm run that ends without the sentinel leaves the task hanging as if it never finished.
Everything not covered above (claim mechanics, branch naming, verify/skip rules, implement conventions, ${pr} body, review loop) is exactly the single-issue flow documented below.
diff --git a/server/services/managedMergePreservation.test.js b/server/services/managedMergePreservation.test.js
new file mode 100644
index 0000000000..852355b1ce
--- /dev/null
+++ b/server/services/managedMergePreservation.test.js
@@ -0,0 +1,134 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { writeFile, readFile, access } from 'node:fs/promises';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { makeGitSandbox, destroyGitSandbox } from '../lib/gitTestRepo.js';
+import { execGit } from '../lib/execGit.js';
+import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';
+import { buildCiMergeGateSteps } from './promptSections/reviewLifecycle.js';
+import { driveToMerge } from './branchReconcile.js';
+import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
+import { resolveSwarmBlock } from './cosTaskPreStepBlocks.js';
+
+let sandbox;
+afterEach(async () => {
+ if (sandbox) await destroyGitSandbox(sandbox.scratch);
+ sandbox = null;
+});
+
+it('pins every managed GitHub merge attempt and defers removal until preservation', () => {
+ const rendered = [
+ ...['plan-task', 'plan-task-claim', 'claim-issue'].map(key => DEFAULT_TASK_PROMPTS[key]),
+ driveToMerge('42'),
+ resolveSwarmBlock('claim-issue', 2),
+ ];
+ for (const text of rendered) {
+ const commands = text.match(/gh pr merge[^\n`]+/g);
+ expect(commands?.length).toBeGreaterThan(0);
+ for (const command of commands) {
+ expect(command).not.toContain('--delete-branch');
+ expect(command).toContain('--match-head-commit');
+ }
+ const proofOrder = ['remote state is exactly MERGED', 'require released:true', 'Recheck live claim/worktree ownership', 'Inventory and preserve ALL', 'Verify the archive manifest', 'exact-ref compare-and-delete', 'git branch -d'];
+ const positions = proofOrder.map(marker => text.indexOf(marker, text.indexOf('**Managed-worktree')));
+ expect(positions.every(at => at >= 0)).toBe(true);
+ expect(positions).toEqual([...positions].sort((a, b) => a - b));
+ expect(text).toContain('Archive failure or an ownership/ref/inventory change keeps the checkout and branch intact');
+ }
+});
+
+// Exercise the emitted shell with a synthetic gh that models the linked-checkout
+// teardown of CLI 2.102.0. No forge or host repository is touched. The renderer
+// assertions above remain platform-independent; shell execution needs bash.
+describe.skipIf(process.platform === 'win32')('managed merge shell preservation (#12133)', () => {
+ it.each([false, true])('retains ignored artifacts and a late unpublished commit=%s through merge fallbacks', async (lateCommit) => {
+ sandbox = await makeGitSandbox({ origin: true });
+ const { scratch, repo, origin } = sandbox;
+ const branch = 'claim/issue-42';
+ const checkout = join(scratch, 'claim');
+ await execGit(['worktree', 'add', '-b', branch, checkout, 'main'], repo);
+ await writeFile(join(checkout, '.gitignore'), 'ignored-results.json\n');
+ await execGit(['add', '.gitignore'], checkout);
+ await execGit(['commit', '-m', 'reviewed change'], checkout);
+ const verifiedHead = (await execGit(['rev-parse', 'HEAD'], checkout)).stdout.trim();
+ await execGit(['push', 'origin', branch], checkout);
+ const sentinel = join(checkout, 'ignored-results.json');
+ await writeFile(sentinel, 'unique test evidence');
+ expect((await execGit(['status', '--porcelain'], checkout)).stdout).toBe('');
+ if (lateCommit) {
+ await writeFile(join(checkout, 'late.txt'), 'unpublished work');
+ await execGit(['add', 'late.txt'], checkout);
+ await execGit(['commit', '-m', 'late unpublished change'], checkout);
+ }
+ const localHead = (await execGit(['rev-parse', 'HEAD'], checkout)).stdout.trim();
+ const calls = join(scratch, 'calls');
+ const state = join(scratch, 'state');
+ await writeFile(state, 'OPEN');
+ // Use a shell function rather than a PATH binary so the fake cannot leak
+ // into another concurrent test or invoke the installed gh accidentally.
+ const fakeGh = `
+ gh() {
+ if [ "$2" = view ]; then
+ case "$*" in
+ *--json\\ url*) printf '%s' 'https://github.com/example/repo/pull/42' ;;
+ *) cat "$MERGE_STATE" ;;
+ esac
+ return
+ fi
+ printf '%s\\n' "$*" >> "$MERGE_CALLS"
+ case "$*" in *--match-head-commit\\ "$CI_VERIFIED_HEAD"*) ;; *) return 99 ;; esac
+ case "$*" in *--rebase*) ;; *) return 1 ;; esac
+ git --git-dir="$FAKE_ORIGIN" update-ref refs/heads/main "$CI_VERIFIED_HEAD" || return
+ case "$*" in
+ *--delete-branch*)
+ git worktree remove --force "$CLAIM_CHECKOUT" || return
+ git update-ref -d refs/heads/claim/issue-42 || return ;;
+ esac
+ printf '%s' MERGED > "$MERGE_STATE"
+ }
+ `;
+ const prompt = DEFAULT_TASK_PROMPTS['claim-issue'];
+ const mergeBlock = prompt.slice(prompt.indexOf(' # CI_VERIFIED_HEAD'), prompt.indexOf(' ```', prompt.indexOf(' # CI_VERIFIED_HEAD')));
+ execFileSync('bash', ['-eu', '-c', `${fakeGh}\n${mergeBlock}`], {
+ cwd: repo,
+ env: { ...process.env, CI_VERIFIED_HEAD: verifiedHead, MERGE_STATE: state, MERGE_CALLS: calls, FAKE_ORIGIN: origin, CLAIM_CHECKOUT: checkout },
+ });
+ expect(await readFile(state, 'utf8')).toBe('MERGED');
+ expect((await readFile(calls, 'utf8')).trim().split('\n')).toHaveLength(3);
+ expect(await readFile(sentinel, 'utf8')).toBe('unique test evidence');
+ expect((await execGit(['rev-parse', branch], repo)).stdout.trim()).toBe(localHead);
+ await access(join(checkout, '.git'));
+ if (lateCommit) expect(await readFile(join(checkout, 'late.txt'), 'utf8')).toBe('unpublished work');
+ });
+});
+
+
+it('the rendered remote compare-and-delete refuses a newly advanced branch', async () => {
+ sandbox = await makeGitSandbox({ origin: true });
+ const { repo, origin } = sandbox;
+ const branch = 'claim/issue-42';
+ await execGit(['checkout', '-b', branch], repo);
+ const verifiedHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
+ await execGit(['push', 'origin', branch], repo);
+ await writeFile(join(repo, 'late.txt'), 'another writer advanced the ref');
+ await execGit(['add', 'late.txt'], repo);
+ await execGit(['commit', '-m', 'late remote work'], repo);
+ const advancedHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
+ await execGit(['push', 'origin', branch], repo);
+ const command = MANAGED_WORKTREE_CLEANUP_CONTRACT.match(/`(git push[^`]+)`/)[1]
+ .replaceAll('<branch>', branch).replaceAll('<verified-head>', verifiedHead).replaceAll('<verified-remote>', 'origin');
+ const result = await execGit(command.split(' ').slice(1), repo, { ignoreExitCode: true });
+ expect(result.exitCode).not.toBe(0);
+ expect((await execGit(['--git-dir', origin, 'rev-parse', `refs/heads/${branch}`], repo)).stdout.trim()).toBe(advancedHead);
+});
+
+
+it('completion merges preserve the checkout for the PortOS cleanup owner', () => {
+ const text = buildCiMergeGateSteps(1, { prRef: '42' }).lines.join('\n');
+ expect(text).not.toContain('--delete-branch');
+ expect(text).toContain('--match-head-commit <verified-head>');
+ expect(text).toContain('Leave local teardown to PortOS');
+ expect(text).toContain('Archive failure or changed ownership/refs preserves the checkout and branch');
+ expect(text).toContain('unique tracked, untracked and ignored bytes');
+ expect(text).toContain('compare-and-delete only the exact ref at the CI-verified head');
+});
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 2b04c279ac..0489c1871f 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
@@ -28,13 +28,14 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but an unresolved accepted finding or rejection, failed build/test, or push failure still blocks.
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 0f513dae56..fe49f6663a 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
@@ -33,13 +33,14 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
index d35ee49003..022b1cabfe 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
@@ -15,13 +15,14 @@ A previous agent finished task **task-example** and opened **PR https://github.c
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
**Hard stop:** if a reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit.
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 ad3eb06c95..d352c427dd 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
@@ -38,13 +38,14 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.
**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, post a PR comment summarising blockers and exit. An optional reviewer may end with an inconclusive result without blocking, but an unresolved accepted finding or rejection, failed build/test, or push failure still blocks.
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 2c2d8f2590..c972fcd7a1 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
@@ -43,13 +43,14 @@ Only an `ok: true` response with a validated `clean` or `findings` verdict and a
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+6. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ (Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
7. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
8. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
index 7718d8f7d4..b3011b2c0a 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt
@@ -4,12 +4,13 @@ A previous agent finished the work for source task **task-example** and opened *
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
4. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
5. Exit. Do NOT run `/do:push`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
index d89d227217..6a0158b63e 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-inline-gh.txt
@@ -4,12 +4,13 @@ This runs as **step 4 of the Completion Workflow above**, against the PR you jus
**GitHub auto-merge handoff (before waiting for CI):** If this run requires repository merge admission, do not enable GitHub auto-merge: a deferred GitHub merge cannot honor the local lease. Use the normal in-session CI wait and immediate admission-gated merge below. The remaining handoff applies only to workflows explicitly outside local admission. 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. Read `gh pr checks "https://github.com/example-org/example-repo/pull/42" --required --json name,state` and compare with every outstanding check in the workflow's CI gate: every such check must be enforced by GitHub. Missing/unknown required-check policy or any outstanding unenforced check means wait for all workflow checks and use the normal immediate merge gate. Only then enable `gh pr merge "https://github.com/example-org/example-repo/pull/42" --auto --merge --match-head-commit <published-head>`. 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. A verified pending handoff is successful only outside local admission: 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 eligible handoff overrides later in-session CI waits and MERGED-only completion instructions, including delegated slashdo workflows. If 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:
+3. **Merge** with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed — 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
+ gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>
```
- **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Verify deletion of this merged task's exact remote head branch (read `gh pr view "https://github.com/example-org/example-repo/pull/42" --json headRefName -q .headRefName`, then query that exact `refs/heads/<headRefName>` on its verified remote with `git ls-remote --heads`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with `git push <verified-remote> --delete <headRefName>`, never another branch or a local worktree. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
- If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, keeping `--delete-branch`.
+ **Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.
+ **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state`. If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.
+ If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed`) and merge with an allowed method instead — `--squash` first, else `--rebase`, retaining `--match-head-commit <verified-head>` on every attempt.
4. **Confirm the merge before exiting**: `gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.
5. Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR. Do NOT start a code review — none is configured for this task.
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index f1a6cf0154..e648d72460 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -627,12 +627,13 @@ export function buildMergeAdmissionSection(agentId) {
'```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.',
'Inside the lease, re-read the PR (head SHA, merge state, required check rollup; on GitHub `gh pr view --json headRefOid,mergeStateStatus,statusCheckRollup`):',
- '- If the head still equals the CI-verified head, every required check is green on it, and the forge reports the PR mergeable (`CLEAN`, or `UNSTABLE`/`HAS_HOOKS` with every required check green): check admission (replace TOKEN with the returned token; require admitted:true), then merge pinned to the CI-verified head — add `--match-head-commit <sha>` (GitLab: `--sha <sha>`) to every merge-method attempt your workflow lists; this pin is the one addition to a merge command that says to use exactly its flags. A base that moved while the PR stays `CLEAN` does NOT require a resync or fresh CI: the forge’s own merge check is authoritative, and post-merge default-branch CI catches semantic conflicts between two individually green PRs.',
+ '- If the head still equals the CI-verified head, every required check is green on it, and the forge reports the PR mergeable (`CLEAN`, or `UNSTABLE`/`HAS_HOOKS` with every required check green): check admission (replace TOKEN with the returned token; require admitted:true), then merge pinned to the CI-verified head — add `--match-head-commit <sha>` (GitLab: `--sha <sha>`) to every merge-method attempt your workflow lists; replace any verified-head placeholder with that SHA and retain the pin on every fallback. Managed GitHub merges must preserve local checkouts and branches; this overrides delegated merge instructions that request implicit branch deletion. A base that moved while the PR stays `CLEAN` does NOT require a resync or fresh CI: the forge’s own merge check is authoritative, and post-merge default-branch CI catches semantic conflicts between two individually green PRs.',
'```bash', command('check', { token: 'TOKEN' }), '```',
'- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.',
'Verify the remote state is exactly MERGED, then release with outcome merged before worktree cleanup. On a recorded failure or leave-open handoff, release with outcome leave-open. Require released:true; report a failed release without deleting or overwriting ownership state:',
'```bash', command('release', { token: 'TOKEN', outcome: 'merged' }), '```',
'The server voids an agent lease 5 minutes after acquisition and lets another run reclaim it. A check refused with lease-expired or lease-owner-mismatch means stop: do not merge on that token; acquire again and repeat the re-read. Never bypass CI, infer success from absent checks, merge without the head pin, or treat auto-merge/queued as MERGED. Admission coordinates participating runs on this install only; manual merges and other installs can still move the base, which the forge’s merge state already reflects.',
+ 'After lease release, follow the managed-worktree preservation contract in the delivery steps: fresh ownership/ref checks and a verified archive of unique tracked, untracked and ignored content precede explicit allowlisted cleanup. Preserve the checkout/ref on any failure; remote auto-deletion never proves archive completion.',
'A completed child, empty cwd process list or CI wait is not proof that the parent has stopped. Only the server may recover a lease, after verifying its registered owner completed or its hold deadline passed.',
].join('\n');
}
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index 86c4229bda..f26cf083da 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -25,7 +25,7 @@ describe('review-enabled completion merge gate', () => {
expect(section).toContain('4. **Wait for CI to finish**');
expect(section).toContain('gh pr checks "<PR_URL>" --watch --fail-fast --interval 30');
expect(section).toContain('repeat the configured review loop for `copilot` against the new HEAD');
- expect(section).toContain('gh pr merge "<PR_URL>" --merge --delete-branch');
+ expect(section).toContain('gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>');
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');
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 672410b628..5ca9332df0 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -1,3 +1,4 @@
+import { MANAGED_WORKTREE_COMPLETION_HANDOFF } from '../../lib/mergeGateContract.js';
/**
* Review-loop, CI-gate, and merge prompt sections.
*/
@@ -163,7 +164,7 @@ function resolveReviewForge(reviewForgeCli, { prUrl = '', prNumber = '', prOwner
// coordinates were persisted.
mergeEquivalentLine: glab
? null
- : (prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null),
+ : (prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --match-head-commit <verified-head>\`.)` : null),
commentCmd: glab
? `\`glab mr note ${mrRef} --message "<summary>"\``
: `\`gh pr comment "${prUrl}" --body "<summary>"\``,
@@ -1073,8 +1074,8 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea
* run. Callers derive this with `detectForgeCli` — a GitHub Enterprise host is
* `github`, not "not github.com". `unknown` (the agent's own completion
* workflow, which runs before the PR exists) emits both, commented.
- * @param {boolean} [opts.deleteBranch=true] - whether the merge command also
- * deletes the head branch. False for a PR whose head lives in a CONTRIBUTOR's
+ * @param {boolean} [opts.deleteBranch=true] - whether explicit post-merge cleanup
+ * may delete the remote head branch. False for a PR whose head lives in a CONTRIBUTOR's
* fork: PortOS may have push rights there (`maintainerCanModify`) without it
* being our call to delete someone else's branch.
* @param {string[]} [opts.reviewRecheckReviewers=[]] - configured reviewers
@@ -1087,7 +1088,6 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
const gh = forge !== 'gitlab';
const glab = forge !== 'github';
const both = gh && glab;
- const ghDelete = deleteBranch ? ' --delete-branch' : '';
const glabDelete = deleteBranch ? ' --remove-source-branch' : '';
const localReviewNames = Array.isArray(localReviewers) && localReviewers.length
? localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')
@@ -1128,17 +1128,18 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
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, ${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:`,
+ `${startStep + 2}. **Merge** ${gh ? 'with these flags, replacing <verified-head> with the exact head whose required CI and configured reviews passed' : '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,
+ gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --match-head-commit <verified-head>` : null,
// `glab mr merge` takes an MR IID or source branch — a URL is not accepted.
glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${mrRef} --yes${glabDelete}` : null,
' ```',
mergeEquivalentLine,
+ gh ? ` ${MANAGED_WORKTREE_COMPLETION_HANDOFF}${deleteBranch ? '' : ' This workflow does not own remote branch deletion; leave the remote head intact.'}` : null,
// Not every repo allows merge commits; a repo restricted to squash/rebase
// rejects `--merge` outright, which would leave the PR open forever.
- gh ? ` **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with \`gh pr view ${prRef} --json state -q .state\`. If it returns \`MERGED\`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one.${deleteBranch ? ` Verify deletion of this merged task's exact remote head branch (read \`gh pr view ${prRef} --json headRefName -q .headRefName\`, then query that exact \`refs/heads/<headRefName>\` on its verified remote with \`git ls-remote --heads\`); a failed lookup is not proof of absence. If it still exists, retry remote deletion only for that verified task branch with \`git push <verified-remote> --delete <headRefName>\`, never another branch or a local worktree.` : ''} Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.` : null,
- gh ? ` If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (\`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed\`) and merge with an allowed method instead — \`--squash\` first, else \`--rebase\`${deleteBranch ? ', keeping \`--delete-branch\`' : ''}.` : null,
+ gh ? ` **Merge-command failure recovery:** If the CLI exits nonzero, first read the remote PR state with \`gh pr view ${prRef} --json state -q .state\`. If it returns \`MERGED\`, publication succeeded even when the CLI failed during local cleanup (for example, because the primary checkout already owns the default branch). Do not retry a successful merge. Leave the active managed local worktree and its branch to PortOS cleanup; never checkout the default branch to satisfy CLI cleanup, remove another worktree, alter its registration, or discard dirty work. Continue to the completion sentinel when this workflow requires one. Only while the PR is still unmerged may you investigate merge blockers or try an allowed merge-method fallback; a failed state lookup is inconclusive, never success.` : null,
+ gh ? ` If the PR is still unmerged and the command was rejected because this repo disallows merge commits, re-check what it allows (\`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed\`) and merge with an allowed method instead — \`--squash\` first, else \`--rebase\`, retaining \`--match-head-commit <verified-head>\` on every attempt.` : null,
`${startStep + 3}. **Confirm the merge before exiting**: ${stateCmd}. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.`,
].filter(Boolean);
return { lines, nextStep: startStep + 4 };
diff --git a/server/services/promptSections/reviewLifecycleMatrix.test.js b/server/services/promptSections/reviewLifecycleMatrix.test.js
index 699fe4e636..249d180d2a 100644
--- a/server/services/promptSections/reviewLifecycleMatrix.test.js
+++ b/server/services/promptSections/reviewLifecycleMatrix.test.js
@@ -269,7 +269,7 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with their
expect(section).toContain('**Required local-review merge gate:**');
expect(section).toContain('4. **Wait for CI to finish**');
expect(section).toContain('never merge on checks that were expected but never appeared');
- expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');
+ expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>');
expect(section).toContain('repeat the configured review loop for `ollama`, `copilot`, `codex`, `@example-user` against the new HEAD');
expect(section).toContain(`8. ${INLINE_EXIT_STEP}`);
expect(section).not.toContain('6. Exit. Do **not** run `/do:push`');
@@ -284,15 +284,16 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with their
expect(section).toContain('on GitHub `gh pr diff 42` also works');
expect(section).toContain(`gh pr diff 42 | jq -Rs '{ backend:`);
expect(section).toContain('4. **Wait for CI to finish**');
- expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');
- expect(section).toContain('(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --delete-branch`.)');
+ expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>');
+ expect(section).toContain('(Equivalent: `gh pr merge 42 --repo example-org/example-repo --merge --match-head-commit <verified-head>`.)');
expect(section).toContain('`gh pr view "https://github.com/example-org/example-repo/pull/42" --json state -q .state` must return `MERGED`');
expect(section).toContain('If it returns `MERGED`, publication succeeded even when the CLI failed during local cleanup');
expect(section).toContain('Do not retry a successful merge');
expect(section).toContain('Leave the active managed local worktree and its branch to PortOS cleanup');
expect(section).toContain('never checkout the default branch');
- expect(section).toContain('a failed lookup is not proof of absence');
- expect(section).toContain('retry remote deletion only for that verified task branch');
+ expect(section).toContain('Remote auto-deletion proves no archive');
+ expect(section).toContain('compare-and-delete only the exact ref at the CI-verified head');
+ expect(section).toContain('Leave local teardown to PortOS');
expect(section).toContain('Only while the PR is still unmerged');
expect(section).toContain('a failed state lookup is inconclusive, never success');
expect(section).toContain('8. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything.');
@@ -404,7 +405,7 @@ describe('buildReviewLoopFollowUpSection — load-bearing lines stay with their
fixture({ reviewLoopMergeOnly: true }),
{ verbose: false },
);
- expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');
+ expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>');
expect(section).not.toContain('glab mr merge');
});
});
@@ -432,7 +433,7 @@ describe('buildReviewLoopFollowUpSection — self-review follow-up', () => {
expect(section).toContain('3. **Wait for CI to finish**');
expect(section).toContain('6. **Confirm the merge before exiting**');
// …and its merge command is untouched: only who reads the diff changed.
- expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --delete-branch');
+ expect(section).toContain('gh pr merge "https://github.com/example-org/example-repo/pull/42" --merge --match-head-commit <verified-head>');
});
it('never tells a self-reviewing agent that no review was requested', () => {
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index a4ea1b51b7..c46f49a568 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -298,14 +298,17 @@ describe('taskPromptDefaults integrity snapshot', () => {
});
it('claim workflows avoid Copilot and require verified remote merge state before cleanup', () => {
- for (const key of ['plan-task', 'claim-issue']) {
+ for (const key of ['plan-task', 'plan-task-claim', 'claim-issue']) {
const prompt = DEFAULT_TASK_PROMPTS[key];
expect(prompt.toLowerCase()).not.toContain('copilot');
expect(prompt).not.toMatch(/^\s*gh pr merge[^\n]*--auto/m);
expect(prompt).toContain('--json state -q .state');
expect(prompt).toContain('[ "$STATE" = "MERGED" ]');
- expect(prompt).toContain('--squash --delete-branch');
- expect(prompt).toContain('--rebase --delete-branch');
+ expect(prompt).toContain('--squash --match-head-commit "$CI_VERIFIED_HEAD"');
+ expect(prompt).not.toContain('--delete-branch');
+ expect(prompt).toContain('Archive failure');
+ expect(prompt).toContain('untracked AND ignored');
+ expect(prompt).toContain('--rebase --match-head-commit "$CI_VERIFIED_HEAD"');
expect(prompt).toContain('Never force-delete with `-D`');
}
@@ -330,7 +333,7 @@ describe('taskPromptDefaults integrity snapshot', () => {
const current = DEFAULT_TASK_PROMPTS['plan-task'];
const claimFlow = DEFAULT_TASK_PROMPTS['plan-task-claim'];
- expect(PROMPT_VERSIONS['plan-task']).toBe(21);
+ expect(PROMPT_VERSIONS['plan-task']).toBe(22);
expect(current).not.toContain('## Phase 6 — Review locally');
expect(current).not.toContain('{reviewers}');
expect(current).not.toContain('LOCAL reviewers');
@@ -948,7 +951,7 @@ describe('taskPromptDefaults integrity snapshot', () => {
it('claim-issue v25 leaves the same volunteer-claim state the issue-watcher leaves', () => {
const current = DEFAULT_TASK_PROMPTS['claim-issue'];
- expect(PROMPT_VERSIONS['claim-issue']).toBe(41);
+ expect(PROMPT_VERSIONS['claim-issue']).toBe(42);
expect(current).toContain('**a volunteer claim IS a claim**');
for (const command of formatVolunteerClaimCommands('"${CANDIDATE}"')) {
expect(current).toContain(command);
@@ -975,7 +978,7 @@ describe('taskPromptDefaults integrity snapshot', () => {
);
it('publishes claim work when a required local review is unavailable, but leaves it unmerged and silent', () => {
- const cases = [['claim-issue', 41], ['claim-issue-gitlab', 37], ['claim-issue-jira', 24]];
+ const cases = [['claim-issue', 42], ['claim-issue-gitlab', 37], ['claim-issue-jira', 24]];
for (const [key, version] of cases) {
const current = DEFAULT_TASK_PROMPTS[key];
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index ffc614346f..372999fab6 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -12,7 +12,7 @@
"better-test-quality": "8e305f986e9c9066da5db2aee76fc024",
"branch-cleanup": "8fdeb4acc2749816a47ca318b6602721",
"branch-reconcile": "90acf7a56c0de2147cf7463ba338a099",
- "claim-issue": "cea12f4209a3f20ebe1a5ad8cc7b38b5",
+ "claim-issue": "2ca300b6dc35b8e73bc2d0908e87168e",
"claim-issue-gitlab": "29f025187d20a8583292bb53bb974c06",
"claim-issue-jira": "d0df766dd9ef326c8578efe2953af13e",
"code-quality": "175fab48fc713b71b4f0574b7cc5fe0b",
@@ -41,8 +41,8 @@
"observability": "243e58bcfae2759f82caf3ff6c8fc9c5",
"performance": "4f8ddada54d7c6f31b7fb35aeb0f29db",
"plan-feature": "7f859397ff16889ffc0cf5a8ba6bddab",
- "plan-task": "5dd527c47e736094949c4605cfb2d973",
- "plan-task-claim": "7b87285534fc52cc99fa676ecf6939ba",
+ "plan-task": "2f3de862cf9962e684202b9312b78292",
+ "plan-task-claim": "796baac684589dec9a170c42e6df951a",
"pr-reviewer": "de9c295018df7c403a722a9ac2e780af",
"pr-reviewer-eligibility": "a5652f7bcb7e2e50b1cfb9a54a6fabe0",
"pr-reviewer-review": "511b26a376439cc6cb268a736897fefd",
@@ -77,7 +77,7 @@
"better-structural-drift": 2,
"better-test-quality": 2,
"branch-reconcile": 8,
- "claim-issue": 41,
+ "claim-issue": 42,
"claim-issue-gitlab": 37,
"claim-issue-jira": 24,
"code-quality": 6,
@@ -106,7 +106,7 @@
"observability": 2,
"performance": 6,
"plan-feature": 6,
- "plan-task": 21,
+ "plan-task": 22,
"pr-reviewer": 5,
"pr-watcher": 2,
"privacy": 2,
@@ -219,7 +219,8 @@
"77be383966232f8115454e15237c31b7",
"2663933c28056e0e23caf42acb1b41d0",
"9e51f8f382774585728c2c642e88539b",
- "34557a99689bd2e089b0e1e634ce1ff3"
+ "34557a99689bd2e089b0e1e634ce1ff3",
+ "cea12f4209a3f20ebe1a5ad8cc7b38b5"
],
"claim-issue-gitlab": [
"fae92c45c89c65455930b4b06a1b88c4",
@@ -421,7 +422,8 @@
"2012a0da54bdbf441911a0eed05f0cb1",
"910802d67f3b5a785f068f4d90178543",
"b85fe92999aa4ee4a8910320457c4242",
- "8a53a518714cc4029d751fdad92f9b05"
+ "8a53a518714cc4029d751fdad92f9b05",
+ "5dd527c47e736094949c4605cfb2d973"
],
"pr-reviewer": [
"679680b3b382aeb6786df01c4d1a90c6",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 80a9a211d0..27a571f576 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -10,6 +10,7 @@
*/
// PORTOS_API_URL is interpolated into the jira-status-report default prompt below.
+import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../../lib/mergeGateContract.js';
import { APP_LAUNCH_VIDEO_PROMPT } from './appLaunchVideo.js';
import { CONTRIBUTION_SECURITY_POLICY } from '../../lib/contributionSecurityPolicy.js';
import { PORTOS_API_URL } from '../../lib/portosUrls.js';
@@ -2850,11 +2851,14 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop
3. **Wait for required CI before merging.** Run \`gh pr checks <num> --required --watch --fail-fast\` — REQUIRED checks only, so optional jobs cannot stall the merge. If a required check stays red, comment on the PR naming the failure, remove only the worktree, and leave the branch and PR for reconciliation.
4. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:
\`\`\`bash
+ # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.
+ # Re-read the forge head and checks, and check merge admission before each attempt.
+ : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"
PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch
- gh pr merge "$PR_URL" --merge --delete-branch || {
+ gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {
[ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \
- gh pr merge "$PR_URL" --squash --delete-branch || \
- gh pr merge "$PR_URL" --rebase --delete-branch
+ gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || \
+ gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"
}
STATE=$(gh pr view "$PR_URL" --json state -q .state)
[ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }
@@ -2865,7 +2869,9 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop
This phase runs only after the PR was merged via Phase 6. If you exited via Phase 3b instead, you already did the 3b-specific cleanup — do NOT also run Phase 7.
-From the **source repo** (cd back to {repoPath} first; you are currently inside the worktree):
+${MANAGED_WORKTREE_CLEANUP_CONTRACT}
+
+From the **source repo**, only after the preservation and ownership gates above succeed (cd back to {repoPath} first; you are currently inside the worktree):
\`\`\`bash
cd {repoPath}
@@ -3032,9 +3038,12 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split the
6. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:
\`\`\`bash
+ # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.
+ # Re-read the forge head and checks, and check merge admission before each attempt.
+ : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"
PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch
- gh pr merge "$PR_URL" --merge --delete-branch || {
- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --delete-branch || gh pr merge "$PR_URL" --rebase --delete-branch
+ gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {
+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"
}
STATE=$(gh pr view "$PR_URL" --json state -q .state)
[ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }
@@ -3045,7 +3054,9 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split the
This phase runs only after the PR was merged via Phase 6. If you exited via Phase 3b instead, you already did the 3b-specific cleanup — do NOT also run Phase 7.
-From the **source repo** (cd back to {repoPath} first; you are currently inside the worktree):
+${MANAGED_WORKTREE_CLEANUP_CONTRACT}
+
+From the **source repo**, only after the preservation and ownership gates above succeed (cd back to {repoPath} first; you are currently inside the worktree):
\`\`\`bash
cd {repoPath}
@@ -3293,11 +3304,14 @@ Every local reviewer's fixes are already committed, so the PR opens against fini
4. **Let required CI finish and go green** — \`gh pr checks <pr-number> --required --watch --fail-fast\` (scope the wait to REQUIRED checks so an optional job can't stall a merge branch protection would allow). A red required check is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.
5. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:
\`\`\`bash
+ # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.
+ # Re-read the forge head and checks, and check merge admission before each attempt.
+ : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"
PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch
- gh pr merge "$PR_URL" --merge --delete-branch || {
+ gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {
[ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \
- gh pr merge "$PR_URL" --squash --delete-branch || \
- gh pr merge "$PR_URL" --rebase --delete-branch
+ gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || \
+ gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"
}
STATE=$(gh pr view "$PR_URL" --json state -q .state)
[ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }
@@ -3306,7 +3320,11 @@ Every local reviewer's fixes are already committed, so the PR opens against fini
## Phase 7 — Clean up (post-merge ONLY)
-This phase runs only after the PR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):
+This phase runs only after the PR merged via Phase 6.
+
+${MANAGED_WORKTREE_CLEANUP_CONTRACT}
+
+From the **source repo**, only after the preservation and ownership gates above succeed (cd back to {repoPath} first):
\`\`\`bash
cd {repoPath}
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index c4baf4d7ea..aef69f9515 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -111,7 +111,7 @@ export const PROMPT_VERSIONS = {
// Code review isolation is a preference; supported headless reviewers remain usable.
// v39 (claim-issue) / v35 (gitlab) / v22 (jira): an optional reviewer (~opt) failure/timeout/provider error never sets review-blocked and does not prevent merge.
// Revalidate current need and project alignment before claims, contributor handoff or epic splits.
-PROMPT_VERSIONS['claim-issue'] = 41;
+PROMPT_VERSIONS['claim-issue'] = 42; // Preserve managed checkouts through merge until explicit verified cleanup (#12133).
PROMPT_VERSIONS['claim-issue-gitlab'] = 37;
// Accepted review findings require resolution regardless of severity.
PROMPT_VERSIONS['claim-issue-jira'] = 24;
@@ -129,3 +129,6 @@ PROMPT_VERSIONS['claim-issue-jira'] = 24;
// moves past this anchor — forcing whoever bumps the prompt to re-confirm the default still
// matches the prompt's behavior and then advance this anchor in the same change. See issue #734.
export const REFERENCE_WATCH_AUDITED_VERSION = 4;
+
+// Managed GitHub merges preserve linked checkouts on every method fallback (#12133).
+PROMPT_VERSIONS['plan-task'] = 22;