Skip to content

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

feat: let agents hand pending CI to the merge coordinator and stop (#12247)

[._.]/ Adam Eivyd158ed342732
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index c609a6492e..f068eb6a8a 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -108,6 +108,24 @@ check or conflict does the same; an unreadable binding never merges and is
handed to the operator by notification; a PR that never settles times out to a
notification as before.
+The merge-admission prompt section offers this handoff to every participant
+before its CI wait. When a local review round returns clean, the run records
+`REVIEW_HEAD=$(git rev-parse HEAD)` beside `REVIEW_STATUS` (one line, replacing
+any earlier one); a later commit means that head was not reviewed. On
+`queued: true` with a receipt for its head, the run stops: it does not wait for
+CI, merge, enable auto-merge, close the issue or remove its branch or worktree,
+and it reports the PR as handed off and not yet merged. Any other answer keeps
+the run on the in-session CI wait and admission-gated merge.
+
+A receipt is a pending end state. `probePrForBranch` reports
+`mergeHandoffQueued` only when the queue holds a binding for that PR, branch and
+the published local head, so the merge-gate check finalizes without a nudge
+(`merge-handoff-queued`), worktree cleanup keeps the branch, and the repo-state
+audit treats the queued entry as the branch's owner. The receipt starts one
+immediate sweep of the app, which merges a head whose CI already settled
+without waiting for the 30-minute timer and spends no tick budget. Overlapping
+sweeps of one app (timer, task generator, receipt) join a single pass.
+
Leases extend the existing machine-local CoS runtime ownership in
`data/cos/state.json`, under its existing write queue; there is no new store,
seed, migration, or federation payload. Admission waits at most 15 seconds to
diff --git a/server/lib/README.md b/server/lib/README.md
index adfdccc210..12d1703ad4 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` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` evidence. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
+| `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`. |
| `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. |
| `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |
| `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. |
diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.js
index 3a7ea95cbf..5a91b2f112 100644
--- a/server/lib/mergeGateContract.js
+++ b/server/lib/mergeGateContract.js
@@ -79,21 +79,25 @@ export function summaryStatesLeaveOpen(summary) {
* (`agentRepoStateVerification.js`) be the backstop, as today.
* - `auto-merge-enabled` — GitHub confirms a pending handoff; finalize without
* claiming it has merged.
+ * - `merge-handoff-queued` — the server's pending-merge coordinator holds a
+ * verified receipt for the published head (#12247); finalize without claiming
+ * it has merged. The branch is the coordinator's until it merges or recovers.
* - `leave-open-stated` — the agent said, in its own words, that it is
* deliberately leaving the PR open; that is a correct terminal state.
* - `needs-reprompt` — the PR is open and the summary names no blocker: send
* one corrective re-prompt.
*
* @param {object} params
- * @param {{prState: string|null, readable: boolean}|null} params.prProbe
+ * @param {{prState: string|null, readable: boolean, autoMergeEnabled?: boolean, mergeHandoffQueued?: boolean}|null} params.prProbe
* @param {string|null|undefined} params.summary
- * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'auto-merge-enabled'|'needs-reprompt'}
+ * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'auto-merge-enabled'|'merge-handoff-queued'|'needs-reprompt'}
*/
export function resolveMergeGateVerdict({ prProbe, summary }) {
if (!prProbe || prProbe.readable === false) return 'no-pr-action';
if (prProbe.prState === 'MERGED') return 'merged';
if (prProbe.prState !== 'OPEN') return 'no-pr-action';
if (prProbe.autoMergeEnabled === true) return 'auto-merge-enabled';
+ if (prProbe.mergeHandoffQueued === true) return 'merge-handoff-queued';
if (summaryStatesLeaveOpen(summary)) return 'leave-open-stated';
return 'needs-reprompt';
}
@@ -109,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 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 --delete-branch`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.',
'If it truly cannot merge (a required check is red after a genuine fix attempt, or there is a conflict only a human can resolve), say so explicitly and leave it open.',
].join('\n');
}
diff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.js
index c5968193d0..d09a904c6d 100644
--- a/server/lib/mergeGateContract.test.js
+++ b/server/lib/mergeGateContract.test.js
@@ -87,6 +87,11 @@ describe('resolveMergeGateVerdict', () => {
expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true }, summary: 'Auto-merge enabled.' })).toBe('needs-reprompt');
});
+ it('accepts a verified pending-merge receipt, never the summary alone, as a pending end state', () => {
+ expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true, mergeHandoffQueued: true }, summary })).toBe('merge-handoff-queued');
+ expect(resolveMergeGateVerdict({ prProbe: { prState: 'OPEN', readable: true }, summary: 'Handed to the PortOS pending-merge coordinator.' })).toBe('needs-reprompt');
+ });
+
it('is "needs-reprompt" when the PR is open and no blocker is stated', () => {
expect(resolveMergeGateVerdict({
prProbe: { prState: 'OPEN', readable: true }, summary,
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 1754eaa89c..ee52a6e778 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -541,6 +541,11 @@ async function queueWorktreeMerge({ agentId, worktreeBranch, originalTask, descr
return queuedDeterministicMerge;
}
+// A healthy handoff owns the branch until it merges (#12247); anything else
+// open or unreadable is preserved for recovery.
+const preservedPrState = (pr) => (pr?.mergeHandoffQueued === true ? 'pending-merge handoff'
+ : pr?.autoMergeEnabled === true ? 'pending GitHub auto-merge' : 'unconfirmed PR recovery');
+
async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranch, warnings, skipMerge }, disposition) {
// Default: auto-merge on success, just cleanup on failure.
// Review-loop follow-up agents pass skipMerge: true because gh pr merge already
@@ -553,7 +558,7 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
if (!pr?.readable || (pr.prState && pr.prState !== 'MERGED')) {
// Failed/unreadable CI or unpublished commits need recovery, which needs this
// branch. Only a healthy handoff suppresses the post-cleanup audit.
- emitLog('info', `🌳 Preserving ${pr?.autoMergeEnabled === true ? 'pending GitHub auto-merge' : 'unconfirmed PR recovery'} worktree for ${agentId}`, { agentId, branchName: worktreeBranch });
+ emitLog('info', `🌳 Preserving ${preservedPrState(pr)} worktree for ${agentId}`, { agentId, branchName: worktreeBranch });
return;
}
}
diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.js
index 3fd02b70f6..906cb0ccf9 100644
--- a/server/services/cosMergeHandoff.js
+++ b/server/services/cosMergeHandoff.js
@@ -144,7 +144,7 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat
id: randomUUID(), appId: app.id, prUrl, prNumber: pr.number, headSha: head, repository,
queuedAt: new Date().toISOString(),
};
- const { queuePendingMerge } = await import('./prWatcher.js');
+ const { queuePendingMerge, sweepPendingMergeApp } = await import('./prWatcher.js');
const queued = await queuePendingMerge(app.id, {
prUrl, prNumber: pr.number, prBranch: view.headRefName, sourceAgentId: agentId,
sourceTask: {
@@ -167,5 +167,33 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat
});
if (!queued) return refuse('queue-write-failed');
console.log(`🤝 PR #${pr.number} handed to the pending-merge coordinator at ${head.slice(0, 12)} by ${agentId}`);
+ // Detached: the receipt must not wait on forge reads, and the 30-minute timer
+ // still owns the entry if this pass finds CI pending or fails.
+ sweepPendingMergeApp(app.id);
return { queued: true, receipt };
}
+
+/**
+ * Does the pending-merge queue hold a verified handoff of exactly this PR head?
+ * Completion and cleanup read it as a pending end state (#12247): the branch is
+ * the coordinator's until it merges or recovers. False on anything unreadable,
+ * so a missed receipt degrades to the ordinary open-PR handling.
+ *
+ * @param {{ prUrl: string, prBranch: string, headSha: string }} target
+ * @returns {Promise<boolean>}
+ */
+export async function hasQueuedMergeHandoff({ prUrl, prBranch, headSha }) {
+ const head = String(headSha || '').toLowerCase();
+ const target = prIdentity(prUrl);
+ if (!target || !prBranch || !SHA_PATTERN.test(head)) return false;
+ const [{ getActiveApps }, { readPendingMergePrs }] = await Promise.all([import('./apps.js'), import('./prWatcher.js')]);
+ const apps = await getActiveApps().catch(() => []);
+ return apps.some((app) => readPendingMergePrs(app).some((entry) => entry?.prBranch === prBranch
+ && prIdentity(entry.prUrl) === target && isPlainObject(entry.handoff) && entry.handoff.headSha === head));
+}
+
+// Forge URLs differ in case and trailing segments; the PR they name does not.
+function prIdentity(url) {
+ const pr = parsePullRequestUrl(url);
+ return pr ? `${pr.host}/${pr.owner}/${pr.repo}#${pr.number}`.toLowerCase() : null;
+}
diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.js
index 3ec54d6e31..f55910fb5e 100644
--- a/server/services/cosMergeHandoff.test.js
+++ b/server/services/cosMergeHandoff.test.js
@@ -57,7 +57,7 @@ vi.mock('./notifications.js', () => ({
const followUpMock = vi.fn(async () => ({ id: 'follow-up-1' }));
vi.mock('./agentWorktreeCleanup.js', () => ({ spawnReviewLoopFollowUp: (...args) => followUpMock(...args) }));
-import { handoffPendingMerge } from './cosMergeHandoff.js';
+import { handoffPendingMerge, hasQueuedMergeHandoff } from './cosMergeHandoff.js';
import { processPendingMergePrs, readPendingMergePrs } from './prWatcher.js';
import { claimMergeAdmission } from './cosMergeAdmission.js';
@@ -71,6 +71,14 @@ const claimAgent = (id, branch) => ({
});
const handoff = (overrides = {}) => handoffPendingMerge({ agentId: 'agent-1', prUrl: PR_URL, headSha: HEAD, worktreePath: workspace, ...overrides });
const pending = () => readPendingMergePrs(f.apps.get('app1'));
+// A receipt starts an immediate sweep; joining it keeps each test's forge reads
+// ordered. Imported at call time: the restart case resets the module registry.
+const handedOff = async (overrides) => {
+ const result = await handoff(overrides);
+ await (await import('./prWatcher.js')).sweepPendingMergeApp('app1');
+ return result;
+};
+const greenChecks = () => { f.pr.statusCheckRollup = [{ conclusion: 'SUCCESS' }]; };
beforeAll(async () => { workspace = await mkdtemp(join(tmpdir(), 'merge-handoff-')); });
afterAll(async () => { await rm(workspace, { recursive: true, force: true }); });
@@ -88,7 +96,7 @@ beforeEach(async () => {
number: 7, title: 'Example change', body: 'Closes #101', author: { login: 'example-user' },
commits: [{ messageHeadline: 'fix: example', messageBody: '' }], state: 'OPEN', isDraft: false,
isCrossRepository: false, headRefName: 'claim/issue-1', headRefOid: HEAD,
- mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }],
+ mergeStateStatus: 'CLEAN', statusCheckRollup: [{ status: 'IN_PROGRESS' }],
};
await writeFile(join(workspace, 'portos-review-status'), `REVIEW_STATUS=clean\nREVIEW_HEAD=${HEAD}\n`);
execGhMock.mockReset().mockImplementation(async (args) => {
@@ -104,8 +112,10 @@ beforeEach(async () => {
describe('pending-merge handoff', () => {
it('persists the verified binding and merges only that head once a concurrent lease releases, across a restart', async () => {
- const result = await handoff();
+ const result = await handedOff();
expect(result).toMatchObject({ queued: true, receipt: { appId: 'app1', prNumber: 7, headSha: HEAD, repository: 'github.com/example/repo' } });
+ // The receipt's immediate sweep found CI pending and spent no tick budget.
+ expect(mergePrMock).not.toHaveBeenCalled();
expect(pending()).toEqual([expect.objectContaining({
prBranch: 'claim/issue-1', sourceAgentId: 'agent-1', ticks: 0,
handoff: expect.objectContaining({ receiptId: result.receipt.id, headSha: HEAD, prCompletion: 'review-then-merge', reviewStatus: 'clean' }),
@@ -113,6 +123,7 @@ describe('pending-merge handoff', () => {
// Another run holds repository admission: the coordinator waits without
// spending its budget and never merges around the lease.
+ greenChecks();
const lease = await claimMergeAdmission({ agentId: 'agent-2', action: 'acquire' });
expect(lease.admitted).toBe(true);
expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ waiting: 1, merged: 0 });
@@ -147,15 +158,31 @@ describe('pending-merge handoff', () => {
expect(pending()).toEqual([]);
});
+ it('merges at once when CI already settled before the receipt, without waiting for the timer', async () => {
+ greenChecks();
+ expect(await handoff()).toMatchObject({ queued: true });
+ await vi.waitFor(() => expect(pending()).toEqual([]));
+ expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD });
+ });
+
+ it('reports a queued receipt only for the exact handed-off PR, branch and head', async () => {
+ await handedOff();
+ const target = { prUrl: 'https://GitHub.com/Example/Repo/pull/7', prBranch: 'claim/issue-1', headSha: HEAD.toUpperCase() };
+ expect(await hasQueuedMergeHandoff(target)).toBe(true);
+ expect(await hasQueuedMergeHandoff({ ...target, headSha: 'b'.repeat(40) })).toBe(false);
+ expect(await hasQueuedMergeHandoff({ ...target, prBranch: 'claim/issue-2' })).toBe(false);
+ expect(await hasQueuedMergeHandoff({ ...target, prUrl: 'https://github.com/example/other/pull/7' })).toBe(false);
+ });
+
it('accepts a merge-on-green run with no local reviewers', async () => {
f.tasks['task-agent-1'].metadata.prCompletion = 'merge-on-green';
await rm(join(workspace, 'portos-review-status'));
- expect(await handoff()).toMatchObject({ queued: true });
+ expect(await handedOff()).toMatchObject({ queued: true });
expect(pending()[0]).toMatchObject({ handoff: { reviewStatus: 'not-configured', prCompletion: 'merge-on-green' }, followUp: { reviewers: [] } });
});
it('invalidates a binding whose head moved and dispatches the recorded review policy instead of merging', async () => {
- await handoff();
+ await handedOff();
f.pr.headRefOid = 'd'.repeat(40);
expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0, escalated: 1, invalidated: 1 });
expect(mergePrMock).not.toHaveBeenCalled();
@@ -166,7 +193,8 @@ describe('pending-merge handoff', () => {
});
it('withholds the merge when the head moves inside the admission window', async () => {
- await handoff();
+ await handedOff();
+ greenChecks();
const views = [{ ...f.pr }, { ...f.pr, headRefOid: 'e'.repeat(40) }];
const forge = execGhMock.getMockImplementation();
execGhMock.mockImplementation(async (args) => (args[0] === 'pr' && args[1] === 'view'
@@ -177,7 +205,7 @@ describe('pending-merge handoff', () => {
});
it('keeps the head binding when an unbound duplicate is queued for the same PR', async () => {
- await handoff();
+ await handedOff();
const { queuePendingMerge } = await import('./prWatcher.js');
const { handoff: _binding, followUp: _roster, ...unbound } = pending()[0];
expect(await queuePendingMerge('app1', unbound)).toBe(true);
@@ -185,7 +213,7 @@ describe('pending-merge handoff', () => {
});
it('never merges an unreadable binding and hands it to the operator', async () => {
- await handoff();
+ await handedOff();
f.apps.set('app1', { ...f.apps.get('app1'), pendingMergePrs: [{ ...pending()[0], handoff: { headSha: 'not-a-sha' } }] });
expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0, invalidated: 1 });
expect(mergePrMock).not.toHaveBeenCalled();
diff --git a/server/services/prProbe.js b/server/services/prProbe.js
index 2eb29cb2d1..5d753b5f6e 100644
--- a/server/services/prProbe.js
+++ b/server/services/prProbe.js
@@ -61,11 +61,17 @@ export async function probePrForBranch(sourceWorkspace, branchName, resolvedForg
// `none` is a real answer, not a gap — callers that need "the agent never
// opened one" distinguished from "we couldn't ask" read `readable` for that.
if (found.status !== 'found') return { prState: null, prUrl: null, prNumber: null, cli, readable: true };
- // A remote handoff cannot cover local commits the agent never published.
- const localHead = cli === 'gh' && found.autoMergeEnabled === true
+ // A remote handoff — GitHub auto-merge or a server pending-merge receipt
+ // (#12247) — cannot cover local commits the agent never published.
+ const open = cli === 'gh' && String(found.detail || '').toUpperCase() === 'OPEN';
+ const localHead = open
? await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace)
- .then(result => result.exitCode === 0 ? result.stdout.trim() : null).catch(() => null)
+ .then(result => result.exitCode === 0 ? result.stdout.trim().toLowerCase() : null).catch(() => null)
: null;
+ const published = !!localHead && localHead === String(found.headRefOid || '').toLowerCase();
+ const mergeHandoffQueued = published && !!found.url
+ && await (await import('./cosMergeHandoff.js')).hasQueuedMergeHandoff({ prUrl: found.url, prBranch: branchName, headSha: localHead })
+ .catch(() => false);
return {
prState: found.detail ? String(found.detail).toUpperCase() : null,
prUrl: found.url || null,
@@ -75,7 +81,8 @@ export async function probePrForBranch(sourceWorkspace, branchName, resolvedForg
prNumber: found.number ?? null,
cli,
readable: !!found.detail,
- ...(cli === 'gh' && found.autoMergeEnabled === true && localHead && localHead === found.headRefOid ? { autoMergeEnabled: true } : {}),
+ ...(published && found.autoMergeEnabled === true ? { autoMergeEnabled: true } : {}),
+ ...(mergeHandoffQueued ? { mergeHandoffQueued: true } : {}),
};
}
diff --git a/server/services/prProbe.test.js b/server/services/prProbe.test.js
index 43ae66306e..cb830721b4 100644
--- a/server/services/prProbe.test.js
+++ b/server/services/prProbe.test.js
@@ -9,6 +9,8 @@ vi.mock('./github.js', () => ({
findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),
getPullRequestState: vi.fn().mockResolvedValue({ status: 'unavailable', state: null, detail: null }),
}));
+const hasQueuedMergeHandoff = vi.hoisted(() => vi.fn());
+vi.mock('./cosMergeHandoff.js', () => ({ hasQueuedMergeHandoff }));
vi.mock('./gitlab.js', () => ({
findMergeRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),
}));
@@ -26,6 +28,7 @@ beforeEach(() => {
findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });
findMergeRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });
getPullRequestState.mockResolvedValue({ status: 'unavailable', state: null, detail: null });
+ hasQueuedMergeHandoff.mockResolvedValue(false);
});
describe('probePrForBranch', () => {
@@ -55,6 +58,20 @@ describe('probePrForBranch', () => {
expect(await probePrForBranch('/repo', 'my-branch')).not.toHaveProperty('autoMergeEnabled', true);
});
+ it('reports a pending-merge receipt for the published head without claiming MERGED', async () => {
+ const pr = { status: 'found', url: 'https://github.com/example/repo/pull/7', number: 7, detail: 'OPEN', headRefOid: 'published-head' };
+ findPullRequestForBranch.mockResolvedValue(pr);
+ hasQueuedMergeHandoff.mockResolvedValue(true);
+ expect(await probePrForBranch('/repo', 'my-branch')).toMatchObject({ prState: 'OPEN', readable: true, mergeHandoffQueued: true });
+ expect(hasQueuedMergeHandoff).toHaveBeenCalledWith({ prUrl: pr.url, prBranch: 'my-branch', headSha: 'published-head' });
+
+ // Local commits the receipt never covered keep the run on recovery.
+ hasQueuedMergeHandoff.mockClear();
+ execGit.mockResolvedValue({ exitCode: 0, stdout: 'local-only-head\n' });
+ expect(await probePrForBranch('/repo', 'my-branch')).not.toHaveProperty('mergeHandoffQueued');
+ expect(hasQueuedMergeHandoff).not.toHaveBeenCalled();
+ });
+
it('uppercases whatever case the forge returned for prState', async () => {
findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1, detail: 'open' });
const result = await probePrForBranch('/repo', 'my-branch');
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index bf77a67d61..8bd15835f2 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -50,6 +50,7 @@ const GREEN_CHECK_VERDICTS = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);
// rather than a per-app map: simultaneous writes for different app ids would
// otherwise still load stale whole-file snapshots and clobber one another.
let pendingMergeWriteTail = Promise.resolve();
+const pendingMergeSweeps = new Map();
// Cache the gh-authenticated login PER HOST, for the process lifetime. Host-keyed
// for two reasons: (1) `gh api` does NOT infer the host from the working
@@ -361,7 +362,25 @@ async function notifyPendingMergeTimeout(app, pending, reason, description = nul
* agent handoff (cosMergeHandoff.js) merges only its recorded head; a moved
* head drops the binding and dispatches the recorded review/validation policy.
*/
-export async function processPendingMergePrs(app) {
+export function processPendingMergePrs(app, { spendTicks = true } = {}) {
+ return joinPendingMergeSweep(app?.id, () => runPendingMergePrs(app, { spendTicks }));
+}
+
+// The timer sweep, the task-generator sweep and a receipt sweep can overlap:
+// a caller joins the app's in-flight pass rather than double-escalating or
+// double-merging the same entry. Registration is synchronous, so a pass started
+// by one caller is visible to the next before either awaits.
+function joinPendingMergeSweep(appId, start) {
+ if (!appId) return start();
+ const inFlight = pendingMergeSweeps.get(appId);
+ if (inFlight) return inFlight;
+ const settled = start().finally(() => pendingMergeSweeps.delete(appId));
+ pendingMergeSweeps.set(appId, settled);
+ return settled;
+}
+
+async function runPendingMergePrs(app, { spendTicks }) {
+ const charge = spendTicks ? 1 : 0;
const pending = readPendingMergePrs(app).map(normalizePendingMerge).filter(Boolean);
if (pending.length === 0) return { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0 };
@@ -407,7 +426,7 @@ export async function processPendingMergePrs(app) {
// `result.errors` accounting is unchanged — the cycle is both an error and
// a tick.
result.errors += 1;
- const unreadable = { ...entry, ticks: entry.ticks + 1 };
+ const unreadable = { ...entry, ticks: entry.ticks + charge };
if (unreadable.ticks >= MAX_PENDING_MERGE_TICKS) {
await notifyPendingMergeTimeout(app, entry, 'it could not be read from the forge');
outcomes.set(key, null);
@@ -496,7 +515,7 @@ export async function processPendingMergePrs(app) {
console.error(`❌ Deterministic merge failed for PR #${entry.prNumber}: ${merge.error || 'unknown error'}`);
}
- const next = { ...entry, ticks: entry.ticks + 1 };
+ const next = { ...entry, ticks: entry.ticks + charge };
if (next.ticks >= MAX_PENDING_MERGE_TICKS) {
const reason = String(prView.state || '').toUpperCase() !== 'OPEN'
? `it is ${String(prView.state).toLowerCase()} rather than open`
@@ -559,6 +578,23 @@ export async function sweepPendingMergePrs() {
return totals;
}
+/**
+ * One immediate pass over an app right after a handoff receipt (#12247), so a
+ * head whose CI already settled merges now instead of at the next 30-minute
+ * timer. It spends no tick budget — the receipt is not a cadence cycle — and
+ * never throws: the timer sweep remains the owner of every queued entry.
+ */
+export function sweepPendingMergeApp(appId) {
+ return joinPendingMergeSweep(appId, async () => {
+ // A timer sweep may join this pass, so it answers in the same result shape.
+ const app = await getAppById(appId);
+ return app ? runPendingMergePrs(app, { spendTicks: false }) : { ok: false, reason: 'app-not-found' };
+ }).catch((err) => {
+ console.error(`❌ Receipt pending-merge sweep failed for app ${appId}: ${err.message}`);
+ return null;
+ });
+}
+
/**
* Merge a patch into the app's persisted watcher state. Re-reads the app first
* so the merge is against the freshest record.
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 4b9ad78193..9344ebf104 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -383,6 +383,17 @@ describe('merge-only PR watcher', () => {
expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
});
+ it('joins an overlapping sweep of the same app instead of escalating its entry twice', async () => {
+ const app = pendingApp();
+ mockApps.set(app.id, app);
+ execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'FAILURE' }] }));
+
+ const [timer, generator] = await Promise.all([processPendingMergePrs(app), processPendingMergePrs(app)]);
+
+ expect(timer).toBe(generator);
+ expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledTimes(1);
+ });
+
it('stops polling and notifies after the bounded pending-merge budget', async () => {
const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);
mockApps.set(app.id, app);
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 7b3d353a54..f1a6cf0154 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -589,6 +589,27 @@ function buildClaimOwnershipSection(agentId) {
].join('\n');
}
+// The record a review phase leaves for the handoff: one REVIEW_HEAD line naming
+// the commit its final clean round covered, beside REVIEW_STATUS (#12247).
+// A missing status file stays missing: a REVIEW_HEAD alone would read as unreadable evidence.
+const RECORD_REVIEW_HEAD = 'F="$(git rev-parse --git-path portos-review-status)"; if [ -f "$F" ]; then { grep -v "^REVIEW_HEAD=" "$F"; printf "REVIEW_HEAD=%s\\n" "$(git rev-parse HEAD)"; } > "$F.tmp" && mv "$F.tmp" "$F"; fi';
+
+/**
+ * A GitHub participant may hand its pending CI to the server coordinator, which
+ * merges only the recorded head under its own admission (cosMergeHandoff.js).
+ */
+function buildPendingMergeHandoffLines(agentId) {
+ const command = agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/merge-handoff',
+ payload: JSON.stringify({ agentId, prUrl: 'PR_URL', headSha: 'HEAD_SHA', worktreePath: 'WORKTREE_PATH' }) });
+ return [
+ '**PortOS pending-merge handoff (GitHub, same-repository PR, before waiting for CI):** The server coordinator waits for required CI and merges exactly your recorded head under its own admission, so this run need not hold its session open. When a configured local review round returns clean, record the head it reviewed beside REVIEW_STATUS (any later commit, fix, rebase or conflict resolution means that head was not reviewed, so rerun the affected review first):',
+ '```bash', RECORD_REVIEW_HEAD, '```',
+ 'Once the published head (`git rev-parse HEAD` equals the PR head) has passed local validation and every configured review, and the PR is ready (not draft), hand it off — unless review is `review-blocked` or the PR is being left open, whose stop rules still apply. Replace PR_URL, HEAD_SHA (the full 40-character head) and WORKTREE_PATH (this checkout):',
+ '```bash', command, '```',
+ 'Require a parsed JSON response with queued:true and a receipt whose headSha equals HEAD_SHA. Then the receipt is your merge outcome: do not wait for CI, acquire admission, merge, enable auto-merge, close the issue, release a claim, or remove the branch or worktree; the coordinator merges or dispatches recovery (a moved head, failed check or conflict). Report the PR URL, head and receipt id, say the PR is handed to the PortOS pending-merge coordinator with CI pending and is NOT yet merged, write the completion sentinel if this run uses one, and stop. This overrides later CI waits, MERGED-only completion and cleanup instructions, including delegated slashdo workflows. On queued:false with retryable:true, retry up to 3 times 5 seconds apart. Any other refusal, an HTTP/auth/transport error or unreadable JSON means no handoff: continue with the CI wait and admission-gated merge below. A refusal never permits merging without admission.',
+ ];
+}
+
/**
* Only the registered parent acquires, and only around the final verify-and-merge:
* sync, pregate, push and CI run concurrently across runs (#10803).
@@ -600,7 +621,8 @@ export function buildMergeAdmissionSection(agentId) {
return [
'## Repository merge admission',
'Admission serializes only the merge instant. The parent orchestrator (never a fan-out child) completes publication, validation, configured reviews and required CI on its own head WITHOUT admission — other runs and every PR in a swarm do this concurrently. Never hold admission while syncing, running pregate, pushing or waiting for CI/reviews. Do not chase the default branch: rebase only for an actual conflict, an enforced up-to-date branch policy, or evidenced integration risk (inspect semantic overlap as well as textual conflicts). This overrides mandatory base-sync instructions in delegated slashdo workflows.',
- 'Local admission forbids GitHub deferred auto-merge: GitHub cannot acquire this application lease at its later merge instant. Do not enable auto-merge for this workflow. Wait for the workflow CI gate, acquire/check admission, merge immediately on the verified head, confirm MERGED, then release. Any generic handoff prose applies only outside local admission and does not override this rule.',
+ 'Local admission forbids GitHub deferred auto-merge: GitHub cannot acquire this application lease at its later merge instant. Do not enable auto-merge for this workflow. Unless the PortOS pending-merge handoff below accepts your head, wait for the workflow CI gate, acquire/check admission, merge immediately on the verified head, confirm MERGED, then release. Any generic auto-merge handoff prose applies only outside local admission and does not override this rule.',
+ ...buildPendingMergeHandoffLines(agentId),
'Once required CI is green on the exact head you pushed (record that SHA as the CI-verified head) and configured reviews are satisfied, acquire admission. Require a parsed JSON response with admitted:true and a nonempty token; retain that token privately for check/release:',
'```bash', command('acquire'), '```',
'If an acquire/check refusal names lease-head-changed, release your token with outcome resync before acquiring again. If admitted:false with retryable:false, release any owned token with outcome leave-open, stop retrying, report the reason and message, and leave the PR/worktree intact. Otherwise, if admitted:false, report the reason and wait retryAfterMs (5 seconds), with a progress update at least every minute. Retry for at most 10 minutes, then record a leave-open outcome and finish with the PR (and any claim) intact. A refusal is never a reason to merge without admission. An HTTP/auth/transport error, unreadable JSON, or missing admission is a refusal, never permission to proceed. Do not modify another owner’s branch, checkout or lease.',
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index 66463c4a19..86c4229bda 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -1,4 +1,8 @@
import { describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';
import { PR_COMPLETIONS } from '../../lib/prDisposition.js';
import { resolveReviewPolicy } from '../../lib/reviewerConfig.js';
@@ -96,3 +100,37 @@ describe('claim parent merge admission instructions', () => {
expect(buildClaimFlowCompletionSection({ agentId: 'parent-example', leavePrOpen: true })).not.toContain('/merge-admission');
});
});
+
+describe('pending-merge handoff instructions (#12247)', () => {
+ it('offers the server handoff before the CI wait and stops on a receipt without merging', () => {
+ const prompt = buildClaimFlowCompletionSection({ agentId: 'parent-example' });
+ expect(prompt).toContain('/api/cos/merge-handoff');
+ expect(prompt).toContain('"agentId":"parent-example","prUrl":"PR_URL","headSha":"HEAD_SHA","worktreePath":"WORKTREE_PATH"');
+ expect(prompt.indexOf('/api/cos/merge-handoff')).toBeLessThan(prompt.indexOf('Once required CI is green'));
+ expect(prompt).toContain('NOT yet merged');
+ expect(prompt).toContain('A refusal never permits merging without admission');
+ expect(buildClaimFlowCompletionSection({ agentId: 'parent-example', leavePrOpen: true })).not.toContain('/merge-handoff');
+ });
+
+ // The recorded line must be the one shape cosMergeHandoff reads: REVIEW_STATUS
+ // kept, exactly one REVIEW_HEAD naming the reviewed commit.
+ it.skipIf(process.platform === 'win32')('records exactly one REVIEW_HEAD for the reviewed commit beside REVIEW_STATUS', () => {
+ const prompt = buildClaimFlowCompletionSection({ agentId: 'parent-example' });
+ const command = prompt.split('\n').find((line) => line.includes('REVIEW_HEAD=%s'));
+ const repo = mkdtempSync(join(tmpdir(), 'review-head-'));
+ try {
+ const git = (...args) => execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim();
+ git('init', '-q');
+ git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'example');
+ const statusFile = join(repo, git('rev-parse', '--git-path', 'portos-review-status'));
+ // No reviewers ran: the record must not invent a status file the server would read as unreadable.
+ execFileSync('sh', ['-c', command], { cwd: repo });
+ expect(existsSync(statusFile)).toBe(false);
+ writeFileSync(statusFile, `REVIEW_STATUS=clean\nREVIEW_HEAD=${'f'.repeat(40)}\n`);
+ execFileSync('sh', ['-c', command], { cwd: repo });
+ expect(readFileSync(statusFile, 'utf8')).toBe(`REVIEW_STATUS=clean\nREVIEW_HEAD=${git('rev-parse', 'HEAD')}\n`);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+ });
+});