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: hand verified agent PR heads to the pending-merge coordinator (#12247)

[._.]/ Adam Eivybf5df9a5a390
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 6866c84b39..2952be1d0c 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -82,6 +82,30 @@ and reports progress every minute; after 10 minutes the reviewed PR (and any
claim) is left open — a refusal is never permission to merge without admission. Sweep deferrals preserve their retry budget; the sweep already
holds the lease only around its own read → assess → pinned merge.
+### Pending-merge handoff (#12247)
+
+A participant that has pushed a head and satisfied its configured reviews may
+hand the CI wait to the server instead of holding its session open:
+`POST /api/cos/merge-handoff` (host-control gated) takes the registered agent
+ID, the PR URL, the full head SHA and — for a claim run, which cuts its own
+checkout — the worktree path. The server binds everything else itself: the
+repository from the run's registration, the PR branch it must own (a bound
+claim branch, `reviewLoopMergeTarget` or `prDeliveryTarget`), a same-repository
+open non-draft PR whose live head equals the SHA, a checkout of this repository
+on that branch at that SHA, a merging completion policy (not leave-open, a JIRA
+handoff or read-only), and the worktree's `portos-review-status` (`clean`;
+absence is accepted only for merge-on-green). Fork targets are refused. The
+binding is persisted on the app's `pendingMergePrs` entry and the response
+carries a receipt.
+
+The pr-watcher pending-merge sweep then merges only the recorded head, under
+its own admission lease, once the PR is `CLEAN` with every reported check
+green; GitHub auto-merge is never enabled. A head that moved invalidates the
+binding and dispatches a follow-up with the recorded review roster; a failed
+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.
+
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 c546f1e80f..040bbd2972 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -540,7 +540,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taskStatusTransition.js` | The CoS task STATUS TRANSITION vocabulary (#6620) — `resolveTaskStatusTransition(previousStatus, nextStatus)` classifies one update's status pair ONCE and returns `{ action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }`, so `writeTaskUpdate`'s blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted `tasks:changed` action all read one answer instead of re-deriving seven. A falsy `nextStatus` means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. `isTerminalTaskStatus(status)` is the shared `completed`/`blocked` predicate `cosTaskStore` and `cosTaskMerge` both read. Pure — metadata predicates (is this block a pause?) stay at the application site. |
| `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. |
-| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator; a pinned run is also "still choosing" until it binds) a claim run registers on its agent record; `bindClaimBranch` / `releaseClaimBranch` patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile, and `claimBranchAdmission(...)` gates coordinator adoption and detach with the same branch/repository owners; `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). |
+| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator; a pinned run is also "still choosing" until it binds) a claim run registers on its agent record; `bindClaimBranch` / `releaseClaimBranch` patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), `ownsClaimBranch(agent, branch)` is explicit registered/bound ownership only (never a picker's "may pick"), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile, and `claimBranchAdmission(...)` gates coordinator adoption and detach with the same branch/repository owners; `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). |
| `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing; plus the retired-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`, `taskExecutionKey`) for tasks and records written before a task rename. |
| `scheduleExecutionFieldsValidation.js` | `scheduleExecutionFieldsSchema` validates optional prompt and provider/model selections before schedule writes, preserving null/empty clears. |
| `scheduleRunOrder.js` | Storage rules for a task's advisory `suggestedAfter` list — which OTHER scheduled tasks to run first. `normalizeSuggestedAfter` drops blanks, duplicates and self-references and caps at `SUGGESTED_AFTER_MAX`; the shipped order it defaults to is `auditCatalog.AUDIT_SUGGESTED_AFTER`, layered at read time in `getScheduleStatus`. Advisory only — the ENFORCED dependency field is `runAfter`. Pure — no I/O. |
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.js
index 1f67c98eed..cd625b2a21 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -205,8 +205,9 @@ function registeredClaimBranch(agent) {
}
// Every branch the run registered — its pinned target plus each branch it bound
-// — minus the ones it explicitly released.
-function ownsClaimBranch(agent, branchName) {
+// — minus the ones it explicitly released. A picker's "may pick" fallback is
+// not ownership: callers that grant authority over a branch use this alone.
+export function ownsClaimBranch(agent, branchName) {
if (ownershipList(agent, 'claimReleasedBranches').includes(branchName)) return false;
return registeredClaimBranch(agent) === branchName || ownershipList(agent, 'claimBranches').includes(branchName);
}
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 6d2a5a0a2d..ec23933f9b 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -358,6 +358,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// CoS: queue, release or steer an agent that runs shell commands in a
// worktree, or a job that runs a shell command directly.
'POST /api/cos/merge-admission',
+ 'POST /api/cos/merge-handoff',
'POST /api/cos/claim-ownership',
'POST /api/cos/start',
'POST /api/cos/resume',
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 547c7c7911..295be779bb 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -33,6 +33,21 @@ router.post('/merge-admission', asyncHandler(async (req, res) => {
res.json(await claimMergeAdmission(input));
}));
+// A registered run hands its published, reviewed head to the server's
+// pending-merge coordinator instead of waiting for CI itself (#12247). The
+// repository, branch, checkout and policy come from the run's registration.
+const mergeHandoffSchema = z.object({
+ agentId: z.string().min(1).max(200),
+ prUrl: z.string().url().max(2048),
+ headSha: z.string().regex(/^[0-9a-fA-F]{40}$/),
+ worktreePath: z.string().min(1).max(4096).optional(),
+});
+router.post('/merge-handoff', asyncHandler(async (req, res) => {
+ const input = validateRequest(mergeHandoffSchema, req.body ?? {});
+ const { handoffPendingMerge } = await import('../services/cosMergeHandoff.js');
+ res.json(await handoffPendingMerge(input));
+}));
+
// A claim run binds (or hands off) the concrete branch it checks out; a
// branch-reconcile worker rechecks live ownership right before mutating (#10089).
const claimBranchSchema = z.string().min(1).max(200);
diff --git a/server/routes/cosAgentRoutes.mergeAdmission.test.js b/server/routes/cosAgentRoutes.mergeAdmission.test.js
index 3117b63103..e6e9e8f86e 100644
--- a/server/routes/cosAgentRoutes.mergeAdmission.test.js
+++ b/server/routes/cosAgentRoutes.mergeAdmission.test.js
@@ -4,6 +4,8 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
const claimMergeAdmission = vi.hoisted(() => vi.fn(async ({ outcome }) => ({ admitted: false, released: true, outcome })));
+const handoffPendingMerge = vi.hoisted(() => vi.fn(async () => ({ queued: false, reason: 'handoff-owner-unverified', retryable: false })));
+vi.mock('../services/cosMergeHandoff.js', () => ({ handoffPendingMerge }));
vi.mock('../services/cos.js', () => ({}));
vi.mock('../services/agentOrchestrator.js', () => ({}));
vi.mock('../services/cosMergeAdmission.js', async (importOriginal) => ({
@@ -35,3 +37,23 @@ describe('POST /api/cos/merge-admission outcomes', () => {
expect(claimMergeAdmission).not.toHaveBeenCalled();
});
});
+
+describe('POST /api/cos/merge-handoff', () => {
+ const body = { agentId: 'parent-example', prUrl: 'https://github.com/example/repo/pull/7', headSha: 'a'.repeat(40) };
+ it('passes a well-formed handoff to the service and returns its verdict', async () => {
+ const res = await request(app).post('/api/cos/merge-handoff').send(body);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ queued: false, reason: 'handoff-owner-unverified', retryable: false });
+ expect(handoffPendingMerge).toHaveBeenCalledWith(body);
+ });
+
+ it.each([
+ ['an abbreviated head', { headSha: 'abc123' }],
+ ['a non-URL PR', { prUrl: 'pull/7' }],
+ ['no agent', { agentId: '' }],
+ ])('rejects %s before the service runs', async (_name, override) => {
+ handoffPendingMerge.mockClear();
+ expect((await request(app).post('/api/cos/merge-handoff').send({ ...body, ...override })).status).toBe(400);
+ expect(handoffPendingMerge).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index 0dda82ffb6..cf9bf82025 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -23,7 +23,7 @@ export const MERGE_ADMISSION_OUTCOMES = ['merged', 'leave-open', 'resync'];
const serverOwner = randomUUID();
const sweepTokens = new Set();
const refuse = (reason) => ({ admitted: false, reason, retryAfterMs });
-const repositoryKey = (origin) => origin?.host && origin?.fullName
+export const repositoryKey = (origin) => origin?.host && origin?.fullName
? `${origin.host.replace(/^ssh\.github\.com$/i, 'github.com')}/${origin.fullName}`.toLowerCase()
: null;
const ownerPath = (agent) => agent?.metadata?.sourceWorkspace || agent?.sourceWorkspace
@@ -218,6 +218,41 @@ async function verifiedParticipant(agent, repository) {
return await verifiedReviewCoordinator(agent, repository) || verifiedWorktreeDelivery(agent, repository);
}
+/**
+ * The registered run a pending-merge handoff may bind (#12247): the same live
+ * participant proof acquire uses, plus which branch that run owns and the
+ * registered checkout holding it (null for a claim run, which cuts its own).
+ * Nothing here is taken from the request. Fork review targets are refused —
+ * the coordinator merges same-repository heads only.
+ */
+export async function resolveMergeHandoffOwner(agentId) {
+ const { readMergeAdmissionStateForSafetyCheck } = await import('./cosState.js');
+ const snapshot = await readMergeAdmissionStateForSafetyCheck().catch(() => null);
+ if (!snapshot?.trusted || !isPlainObject(snapshot.agents)) return { refused: 'ownership-unreadable' };
+ const agent = snapshot.agents[agentId];
+ if (!agent || agent.id !== agentId || agent.status !== 'running' || !agent.startedAt || !agent.taskId) {
+ return { refused: 'handoff-owner-unverified' };
+ }
+ const repository = ownerPath(agent) ? repositoryKey(await getOriginInfo(ownerPath(agent)).catch(() => null)) : null;
+ if (!repository) return { refused: 'repository-unreadable' };
+ const task = await liveTask(agent);
+ if (!task) return { refused: 'handoff-owner-unverified' };
+ const meta = agent.metadata || {};
+ if (meta.reviewLoopMergeTarget?.fork || task.metadata?.forkHead) return { refused: 'fork-target-unsupported' };
+ const owner = { agent, task, repository };
+ if (isTruthyMeta(meta.claimPicksOwnBranch) || meta.claimBranch) {
+ const { ownsClaimBranch } = await import('../lib/claimContinuation.js');
+ return { ...owner, owns: (branch) => ownsClaimBranch(agent, branch), workspacePath: null };
+ }
+ if (await verifiedReviewCoordinator(agent, repository) === true) {
+ return { ...owner, owns: (branch) => branch === meta.reviewLoopMergeTarget.branch, workspacePath: meta.workspacePath };
+ }
+ if (await verifiedWorktreeDelivery(agent, repository)) {
+ return { ...owner, owns: (branch) => branch === meta.prDeliveryTarget.branch, workspacePath: meta.prDeliveryTarget.workspacePath };
+ }
+ return { refused: 'handoff-owner-unverified' };
+}
+
/** The ID is the registered parent, never a worker-child ID or a cwd PID. */
export async function claimMergeAdmission({ agentId, action, token, outcome }) {
return transaction(async (state, save, measure) => {
diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.js
new file mode 100644
index 0000000000..5fc8a37aaa
--- /dev/null
+++ b/server/services/cosMergeHandoff.js
@@ -0,0 +1,161 @@
+/**
+ * Hand a validated, published PR head to the pending-merge coordinator (#12247).
+ *
+ * A registered run that has pushed its head and satisfied its configured
+ * reviews may stop waiting for CI. The server — never the request — binds the
+ * repository, PR, exact head, completion policy and review evidence, persists
+ * that binding on the app's pending-merge queue, and prWatcher merges only that
+ * head under its own repository admission once required checks are green.
+ * GitHub auto-merge is never enabled: it cannot take the local admission lease
+ * at the deferred merge instant, and it can merge before unenforced checks run.
+ */
+import { randomUUID } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { execGh } from './github.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { parsePullRequestUrl } from '../lib/gitForge.js';
+import { githubRepoSpec } from '../lib/workTracker.js';
+import { execGit } from '../lib/execGit.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
+import { isTruthyMeta } from '../lib/metadataFlags.js';
+import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';
+
+const SHA_PATTERN = /^[0-9a-f]{40}$/;
+// Transient: the caller may retry the same handoff. Everything else means the
+// run keeps the PR on its own immediate CI/admission path.
+const RETRYABLE = new Set(['ownership-unreadable', 'pr-unreadable', 'queue-write-failed']);
+const refuse = (reason) => ({ queued: false, reason, retryable: RETRYABLE.has(reason) });
+const samePath = (a, b) => typeof a === 'string' && typeof b === 'string' && resolve(a) === resolve(b);
+
+// The task's own app, else the single active app checked out at the run's
+// source workspace; either must still point at the run's repository.
+async function resolveHandoffApp(task, agent, repository, repositoryKey) {
+ const { getAppById, getActiveApps } = await import('./apps.js');
+ const source = agent.metadata?.sourceWorkspace;
+ const byId = task.metadata?.app ? await getAppById(task.metadata.app).catch(() => null) : null;
+ const candidates = byId ? [byId]
+ : (await getActiveApps().catch(() => [])).filter((app) => source && samePath(app.repoPath, source));
+ if (candidates.length !== 1 || !candidates[0]?.repoPath) return null;
+ const origin = await getOriginInfo(candidates[0].repoPath).catch(() => null);
+ return repositoryKey(origin) === repository ? candidates[0] : null;
+}
+
+// The checkout the run reviewed must be this repository, on the PR branch, at
+// exactly the head being handed off.
+async function checkoutAtHead(workspace, branch, head, repository, repositoryKey) {
+ if (repositoryKey(await getOriginInfo(workspace).catch(() => null)) !== repository) return false;
+ const [ref, sha] = await Promise.all([
+ execGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], workspace).catch(() => null),
+ execGit(['rev-parse', '--verify', 'HEAD^{commit}'], workspace).catch(() => null),
+ ]);
+ return ref?.stdout?.trim() === branch && sha?.stdout?.trim().toLowerCase() === head;
+}
+
+// The worktree-private status the review phase writes. null = no file (no
+// local reviewers ran); 'unreadable' covers an unreadable or empty file.
+async function readReviewStatus(workspace) {
+ const gitPath = await execGit(['rev-parse', '--git-path', 'portos-review-status'], workspace).catch(() => null);
+ const relative = gitPath?.stdout?.trim();
+ if (!relative) return 'unreadable';
+ const content = await readFile(resolve(workspace, relative), 'utf-8').catch((err) => (err.code === 'ENOENT' ? null : undefined));
+ if (content === null) return null;
+ const statuses = [...String(content ?? '').matchAll(/^REVIEW_STATUS=(\S+)\s*$/gm)].map((m) => m[1]);
+ if (statuses.length === 0) return 'unreadable';
+ return statuses.find((status) => status !== 'clean') ?? 'clean';
+}
+
+async function followUpRoster(task, policy) {
+ if (policy !== PR_COMPLETIONS.REVIEW_THEN_MERGE) return { reviewers: [], usernames: [], optionalReviewers: [], reviewerMaxRounds: {} };
+ const [{ resolveReviewLoopOptions }, { normalizeReviewers }] = await Promise.all([
+ import('./codeReview.js'), import('../lib/validation.js'),
+ ]);
+ const options = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers });
+ return {
+ reviewers: options.reviewers, usernames: options.usernames,
+ optionalReviewers: options.optionalReviewers, reviewerMaxRounds: options.reviewerMaxRounds,
+ };
+}
+
+/**
+ * @param {{ agentId: string, prUrl: string, headSha: string, worktreePath?: string }} input
+ * @returns {Promise<{ queued: true, receipt: object }|{ queued: false, reason: string, retryable: boolean }>}
+ */
+export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePath = null }) {
+ const head = String(headSha || '').toLowerCase();
+ const pr = parsePullRequestUrl(prUrl);
+ if (!pr || !SHA_PATTERN.test(head)) return refuse('handoff-target-invalid');
+
+ const { resolveMergeHandoffOwner, repositoryKey } = await import('./cosMergeAdmission.js');
+ const owner = await resolveMergeHandoffOwner(agentId);
+ if (owner.refused) return refuse(owner.refused);
+ const { agent, task, repository } = owner;
+ const prOrigin = { host: pr.host, fullName: `${pr.owner}/${pr.repo}` };
+ if (repositoryKey(prOrigin) !== repository) return refuse('pr-repository-mismatch');
+ const repoSpec = githubRepoSpec(prOrigin);
+ if (!repoSpec) return refuse('forge-unsupported');
+
+ const policy = resolvePrCompletion(task.metadata);
+ if (policy === PR_COMPLETIONS.LEAVE_OPEN || agent.metadata?.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN
+ || leavesPrForHuman(task) || isTruthyMeta(task.metadata?.reviewLoopLeaveOpen) || isTruthyMeta(task.metadata?.readOnly)) {
+ return refuse('completion-policy-leaves-open');
+ }
+
+ const app = await resolveHandoffApp(task, agent, repository, repositoryKey);
+ if (!app) return refuse('pending-merge-app-unresolved');
+
+ const forgeExec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });
+ const raw = await execGh([
+ 'pr', 'view', String(pr.number), '--repo', repoSpec,
+ '--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid',
+ ], undefined, { cwd: forgeExec.cwd, env: forgeExec.env, backoffKey: repoSpec }).catch(() => null);
+ const view = raw === null ? null : safeJSONParse(raw, null);
+ if (!isPlainObject(view) || view.number !== pr.number) return refuse('pr-unreadable');
+ if (String(view.state || '').toUpperCase() !== 'OPEN') return refuse('pr-not-open');
+ if (view.isDraft !== false) return refuse('pr-draft');
+ if (view.isCrossRepository !== false) return refuse('pr-cross-repository');
+ if (typeof view.headRefName !== 'string' || !owner.owns(view.headRefName)) return refuse('pr-branch-not-owned');
+ if (String(view.headRefOid || '').toLowerCase() !== head) return refuse('pr-head-moved');
+
+ // A registered checkout outranks a request-named one; a claim run cuts its
+ // own, so it names the path and the server verifies what is there.
+ const workspace = owner.workspacePath || worktreePath;
+ if (!workspace || !await checkoutAtHead(workspace, view.headRefName, head, repository, repositoryKey)) {
+ return refuse('checkout-head-unverified');
+ }
+ const reviewStatus = await readReviewStatus(workspace);
+ if (!(reviewStatus === 'clean' || (reviewStatus === null && policy === PR_COMPLETIONS.MERGE_ON_GREEN))) {
+ return refuse('review-evidence-incomplete');
+ }
+
+ const receipt = {
+ id: randomUUID(), appId: app.id, prUrl, prNumber: pr.number, headSha: head, repository,
+ queuedAt: new Date().toISOString(),
+ };
+ const { queuePendingMerge } = await import('./prWatcher.js');
+ const queued = await queuePendingMerge(app.id, {
+ prUrl, prNumber: pr.number, prBranch: view.headRefName, sourceAgentId: agentId,
+ sourceTask: {
+ id: task.id || null,
+ priority: task.priority || 'MEDIUM',
+ description: task.description || 'CoS automated task',
+ metadata: {
+ app: app.id, provider: task.metadata?.provider, providerId: task.metadata?.providerId,
+ model: task.metadata?.model, effort: task.metadata?.effort,
+ },
+ },
+ handoff: {
+ receiptId: receipt.id, agentId, startedAt: agent.startedAt, taskId: agent.taskId, repository,
+ headSha: head, prCompletion: policy, reviewStatus: reviewStatus ?? 'not-configured', acceptedAt: receipt.queuedAt,
+ },
+ followUp: await followUpRoster(task, policy),
+ }).catch((err) => {
+ console.error(`❌ Pending-merge handoff for PR #${pr.number} could not be persisted: ${err.message}`);
+ return false;
+ });
+ 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}`);
+ return { queued: true, receipt };
+}
diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.js
new file mode 100644
index 0000000000..533eb7f693
--- /dev/null
+++ b/server/services/cosMergeHandoff.test.js
@@ -0,0 +1,186 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+// Agent → server pending-merge handoff (#12247), end to end through the real
+// admission service and the real pr-watcher coordinator over synthetic stores.
+const f = vi.hoisted(() => ({
+ state: null, tasks: {}, apps: new Map(), checkouts: {}, pr: null, foreign: new Set(),
+}));
+vi.mock('./cosState.js', async () => {
+ const { createFileWriteQueue } = await import('../lib/fileWriteQueue.js');
+ return {
+ withStateLock: createFileWriteQueue(),
+ loadState: async () => f.state,
+ saveState: async (state) => { f.state = state; },
+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.state) }),
+ };
+});
+vi.mock('./cosTaskStore.js', () => ({ getTaskById: async (id) => f.tasks[id] ?? null }));
+vi.mock('../lib/gitRemote.js', () => ({
+ getOriginInfo: async (path) => ({ host: 'github.com', fullName: f.foreign.has(path) ? 'example/other' : 'example/repo' }),
+}));
+vi.mock('../lib/execGit.js', () => ({
+ execGit: async (args, cwd) => {
+ const checkout = f.checkouts[cwd];
+ if (!checkout) throw new Error('not a git checkout');
+ if (args[0] === 'symbolic-ref') return { stdout: `${checkout.branch}\n` };
+ if (args.includes('--git-path')) return { stdout: `${join(cwd, 'portos-review-status')}\n` };
+ if (args[0] === 'rev-parse') return { stdout: `${checkout.head}\n` };
+ throw new Error(`unexpected git ${args.join(' ')}`);
+ },
+}));
+const execGhMock = vi.fn();
+vi.mock('./github.js', () => ({
+ execGh: (...args) => execGhMock(...args),
+ ensureForgeReachable: async () => ({ ok: true, status: 'ok' }),
+}));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async (cwd) => ({ cwd, env: {} }) }));
+vi.mock('./apps.js', () => ({
+ getAppById: async (id) => f.apps.get(id) ?? null,
+ getActiveApps: async () => [...f.apps.values()],
+ updateApp: async (id, patch) => { const next = { ...f.apps.get(id), ...patch }; f.apps.set(id, next); return next; },
+}));
+vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent: async () => ({ ok: true, screening: { safe: true } }) }));
+vi.mock('./codeReview.js', () => ({
+ resolveReviewLoopOptions: async () => ({ reviewers: ['codex'], usernames: [], optionalReviewers: [], reviewerMaxRounds: {} }),
+}));
+const mergePrMock = vi.fn();
+vi.mock('./git.js', () => ({ mergePR: (...args) => mergePrMock(...args) }));
+const notifyMock = vi.fn(async () => ({ id: 'notification-1' }));
+vi.mock('./notifications.js', () => ({
+ addNotification: (...args) => notifyMock(...args),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+const followUpMock = vi.fn(async () => ({ id: 'follow-up-1' }));
+vi.mock('./agentWorktreeCleanup.js', () => ({ spawnReviewLoopFollowUp: (...args) => followUpMock(...args) }));
+
+import { handoffPendingMerge } from './cosMergeHandoff.js';
+import { processPendingMergePrs, readPendingMergePrs } from './prWatcher.js';
+import { claimMergeAdmission } from './cosMergeAdmission.js';
+
+const HEAD = 'a'.repeat(40);
+const PR_URL = 'https://github.com/example/repo/pull/7';
+let workspace;
+
+const claimAgent = (id, branch) => ({
+ id, taskId: `task-${id}`, startedAt: '2026-01-01T00:00:00.000Z', status: 'running',
+ metadata: { sourceWorkspace: '/repos/source', claimPicksOwnBranch: true, claimBranches: [branch] },
+});
+const handoff = (overrides = {}) => handoffPendingMerge({ agentId: 'agent-1', prUrl: PR_URL, headSha: HEAD, worktreePath: workspace, ...overrides });
+const pending = () => readPendingMergePrs(f.apps.get('app1'));
+
+beforeAll(async () => { workspace = await mkdtemp(join(tmpdir(), 'merge-handoff-')); });
+afterAll(async () => { await rm(workspace, { recursive: true, force: true }); });
+
+beforeEach(async () => {
+ f.state = { agents: { 'agent-1': claimAgent('agent-1', 'claim/issue-1'), 'agent-2': claimAgent('agent-2', 'claim/issue-2') }, mergeAdmissions: {} };
+ f.tasks = Object.fromEntries(['agent-1', 'agent-2'].map((id) => [`task-${id}`, {
+ id: `task-${id}`, status: 'in_progress', taskType: 'user', priority: 'MEDIUM', description: 'Example change',
+ metadata: { app: 'app1', prCompletion: 'review-then-merge' },
+ }]));
+ f.apps = new Map([['app1', { id: 'app1', repoPath: '/repos/source', forgeAccount: null }]]);
+ f.checkouts = { [workspace]: { branch: 'claim/issue-1', head: HEAD } };
+ f.foreign = new Set();
+ f.pr = {
+ 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' }],
+ };
+ await writeFile(join(workspace, 'portos-review-status'), 'REVIEW_STATUS=clean\n');
+ execGhMock.mockReset().mockImplementation(async (args) => {
+ if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify(f.pr);
+ if (args[0] === 'pr' && args[1] === 'diff') return 'diff --git a/example.js b/example.js\n+const ok = true;';
+ if (args[0] === 'api') return JSON.stringify({ number: 101, state: 'open', title: 'Example', body: 'Example need', assignees: [] });
+ throw new Error('unexpected forge read');
+ });
+ mergePrMock.mockReset().mockResolvedValue({ success: true });
+ notifyMock.mockClear();
+ followUpMock.mockClear();
+});
+
+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();
+ expect(result).toMatchObject({ queued: true, receipt: { appId: 'app1', prNumber: 7, headSha: HEAD, repository: 'github.com/example/repo' } });
+ 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' }),
+ })]);
+
+ // Another run holds repository admission: the coordinator waits without
+ // spending its budget and never merges around the lease.
+ 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 });
+ expect(mergePrMock).not.toHaveBeenCalled();
+ expect(pending()[0].ticks).toBe(0);
+ await claimMergeAdmission({ agentId: 'agent-2', action: 'release', token: lease.token, outcome: 'merged' });
+
+ // A fresh server process drives the persisted queue entry to a pinned merge.
+ vi.resetModules();
+ const restarted = await import('./prWatcher.js');
+ expect(await restarted.processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 1 });
+ expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD });
+ expect(pending()).toEqual([]);
+ });
+
+ it.each([
+ ['an unregistered caller', () => ({ agentId: 'ghost' }), 'handoff-owner-unverified'],
+ ['another run\'s branch', () => { f.pr.headRefName = 'claim/issue-2'; }, 'pr-branch-not-owned'],
+ ['a PR in another repository', () => ({ prUrl: 'https://github.com/example/other/pull/7' }), 'pr-repository-mismatch'],
+ ['a head that moved after review', () => { f.pr.headRefOid = 'b'.repeat(40); }, 'pr-head-moved'],
+ ['a checkout not at the handed-off head', () => { f.checkouts[workspace].head = 'c'.repeat(40); }, 'checkout-head-unverified'],
+ ['a checkout of another repository', () => { f.foreign.add(workspace); }, 'checkout-head-unverified'],
+ ['a draft PR', () => { f.pr.isDraft = true; }, 'pr-draft'],
+ ['a leave-open policy', () => { f.tasks['task-agent-1'].metadata.prCompletion = 'leave-open'; }, 'completion-policy-leaves-open'],
+ ['a JIRA human handoff', () => { f.tasks['task-agent-1'].metadata.jiraTicketId = 'EX-1'; }, 'completion-policy-leaves-open'],
+ ['blocked review evidence', () => writeFile(join(workspace, 'portos-review-status'), 'REVIEW_STATUS=review-blocked\n'), 'review-evidence-incomplete'],
+ ['missing required review evidence', () => rm(join(workspace, 'portos-review-status')), 'review-evidence-incomplete'],
+ ])('refuses %s and queues nothing', async (_name, arrange, reason) => {
+ const overrides = await arrange();
+ expect(await handoff(overrides || {})).toMatchObject({ queued: false, reason, retryable: false });
+ expect(pending()).toEqual([]);
+ });
+
+ 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(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();
+ f.pr.headRefOid = 'd'.repeat(40);
+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0, escalated: 1, invalidated: 1 });
+ expect(mergePrMock).not.toHaveBeenCalled();
+ expect(followUpMock).toHaveBeenCalledWith(expect.objectContaining({
+ prUrl: PR_URL, prBranch: 'claim/issue-1', prCompletion: 'review-then-merge', reviewers: ['codex'],
+ }));
+ expect(pending()).toEqual([]);
+ });
+
+ it('withholds the merge when the head moves inside the admission window', async () => {
+ await handoff();
+ const views = [{ ...f.pr }, { ...f.pr, headRefOid: 'e'.repeat(40) }];
+ const forge = execGhMock.getMockImplementation();
+ execGhMock.mockImplementation(async (args) => (args[0] === 'pr' && args[1] === 'view'
+ ? JSON.stringify(views.length > 1 ? views.shift() : views[0]) : forge(args)));
+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 0 });
+ expect(mergePrMock).not.toHaveBeenCalled();
+ expect(pending()).toEqual([expect.objectContaining({ ticks: 1, handoff: expect.objectContaining({ headSha: HEAD }) })]);
+ });
+
+ it('never merges an unreadable binding and hands it to the operator', async () => {
+ await handoff();
+ 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();
+ expect(notifyMock).toHaveBeenCalledWith(expect.objectContaining({ link: PR_URL, priority: 'high' }));
+ expect(pending()).toEqual([]);
+ });
+});
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 71c514025b..8859e16ffd 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -22,6 +22,7 @@ import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
import { createGithubActorTrust } from './forgeActorTrust.js';
import { createHash } from 'node:crypto';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import { PR_COMPLETIONS } from '../lib/prDisposition.js';
// Bound the gh query. The high-water mark (computePrCheck) advances to the max
@@ -275,8 +276,10 @@ export async function queuePendingMerge(appId, pending) {
if (index === -1) return [...existing, normalized];
const next = [...existing];
// Preserve the existing tick count so a duplicated completion callback
- // cannot reset an already-wedged PR's bounded-watch budget.
- next[index] = { ...normalized, ticks: existing[index].ticks };
+ // cannot reset an already-wedged PR's bounded-watch budget. A handoff of a
+ // different head is a new binding with its own budget.
+ const sameBinding = existing[index].handoff?.headSha === normalized.handoff?.headSha;
+ next[index] = { ...normalized, ticks: sameBinding ? existing[index].ticks : 0 };
return next;
});
return Boolean(result);
@@ -307,12 +310,39 @@ async function readPendingPullRequest(repoSpec, prNumber, { cwd, env } = {}) {
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
}
-async function notifyPendingMergeTimeout(app, pending, reason) {
+const HANDOFF_POLICIES = new Set([PR_COMPLETIONS.MERGE_ON_GREEN, PR_COMPLETIONS.REVIEW_THEN_MERGE]);
+const INVALID_HANDOFF = Symbol('invalid-handoff');
+
+// An agent handoff (#12247) pins the coordinator to one reviewed head. A legacy
+// PortOS-opened entry has no binding; a present-but-malformed one never merges.
+function readHandoffBinding(entry) {
+ if (!Object.hasOwn(entry, 'handoff')) return null;
+ const binding = entry.handoff;
+ return isPlainObject(binding) && /^[0-9a-f]{40}$/.test(binding.headSha)
+ && typeof binding.repository === 'string' && binding.repository
+ && typeof binding.agentId === 'string' && binding.agentId
+ && HANDOFF_POLICIES.has(binding.prCompletion) ? binding : INVALID_HANDOFF;
+}
+
+// A handoff's recovery inherits its recorded review policy and roster: a CI
+// fix or moved head is new, unreviewed code and must not ride the old verdict.
+function followUpPolicy(entry, binding) {
+ const roster = binding && isPlainObject(entry.followUp) ? entry.followUp : {};
+ return {
+ prCompletion: binding ? binding.prCompletion : PR_COMPLETIONS.MERGE_ON_GREEN,
+ reviewers: Array.isArray(roster.reviewers) ? roster.reviewers : [],
+ usernames: Array.isArray(roster.usernames) ? roster.usernames : [],
+ optionalReviewers: Array.isArray(roster.optionalReviewers) ? roster.optionalReviewers : [],
+ reviewerMaxRounds: isPlainObject(roster.reviewerMaxRounds) ? roster.reviewerMaxRounds : {},
+ };
+}
+
+async function notifyPendingMergeTimeout(app, pending, reason, description = null) {
return addNotification({
type: NOTIFICATION_TYPES.AGENT_WARNING,
priority: PRIORITY_LEVELS.HIGH,
title: `Merge-only PR #${pending.prNumber} needs attention`,
- description: `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`,
+ description: description || `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`,
link: pending.prUrl,
metadata: { appId: app.id, pendingMergePrNumber: pending.prNumber }
}).catch((err) => {
@@ -324,7 +354,9 @@ async function notifyPendingMergeTimeout(app, pending, reason) {
/**
* Drive merge-only PortOS PRs on the normal pr-watcher cadence. Green PRs are
* merged without consuming an agent lane; only a classified CI failure or
- * merge conflict recreates the pre-existing merge-only follow-up agent.
+ * merge conflict recreates the pre-existing merge-only follow-up agent. An
+ * 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) {
const pending = readPendingMergePrs(app).map(normalizePendingMerge).filter(Boolean);
@@ -346,10 +378,22 @@ export async function processPendingMergePrs(app) {
if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status };
const outcomes = new Map();
- const result = { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0, errors: 0 };
+ const result = { ok: true, checked: 0, merged: 0, escalated: 0, invalidated: 0, timedOut: 0, errors: 0 };
for (const entry of pending) {
const key = pendingMergeKey(entry);
+ let binding = readHandoffBinding(entry);
+ if (binding && binding !== INVALID_HANDOFF) {
+ const { repositoryKey } = await import('./cosMergeAdmission.js');
+ if (binding.repository !== repositoryKey(origin)) binding = INVALID_HANDOFF;
+ }
+ if (binding === INVALID_HANDOFF) {
+ await notifyPendingMergeTimeout(app, entry, null,
+ 'PortOS will not merge this handed-off PR: its recorded head/policy binding is unreadable or names another repository. Verify the PR and merge or re-dispatch it.');
+ outcomes.set(key, null);
+ result.invalidated += 1;
+ continue;
+ }
const prView = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);
if (!prView) {
// An unreadable PR is still a cycle this entry spent pending, so it has to
@@ -377,7 +421,10 @@ export async function processPendingMergePrs(app) {
continue;
}
- const failure = classifyPrFailure(prView);
+ // A head other than the one handed off was never validated by that run:
+ // drop the binding and dispatch fresh validation/review rather than merge.
+ const headMoved = binding && String(prView.headRefOid || '').toLowerCase() !== binding.headSha;
+ const failure = headMoved ? 'head-moved' : classifyPrFailure(prView);
if (failure) {
try {
const { spawnReviewLoopFollowUp } = await import('./agentWorktreeCleanup.js');
@@ -387,14 +434,14 @@ export async function processPendingMergePrs(app) {
prUrl: entry.prUrl,
prBranch: entry.prBranch,
sourceWorkspace: app.repoPath,
- prCompletion: PR_COMPLETIONS.MERGE_ON_GREEN,
- reviewers: [],
- usernames: [],
- optionalReviewers: [],
- reviewerMaxRounds: {}
+ ...followUpPolicy(entry, binding),
});
outcomes.set(key, null);
result.escalated += 1;
+ if (headMoved) {
+ result.invalidated += 1;
+ console.warn(`⚠️ Pending merge handoff for PR #${entry.prNumber} invalidated: head moved from the handed-off commit`);
+ }
} catch (err) {
console.error(`❌ Failed to escalate PR #${entry.prNumber}: ${err.message}`);
outcomes.set(key, entry);
@@ -409,6 +456,10 @@ export async function processPendingMergePrs(app) {
const admitted = await withPendingMergeAdmission(origin, async () => {
const currentPr = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);
if (!currentPr || !isPendingMergeReady(currentPr)) return { success: false, error: 'Current head is not merge-ready' };
+ const expectedHeadSha = binding ? binding.headSha : currentPr.headRefOid;
+ if (String(currentPr.headRefOid || '').toLowerCase() !== String(expectedHeadSha).toLowerCase()) {
+ return { success: false, error: 'Current head is not the handed-off head' };
+ }
const { assessPullRequestForAction } = await import('./prReviewerSecurity.js');
const readDiff = () => execGh(['pr', 'diff', String(entry.prNumber), '--repo', repoSpec],
undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);
@@ -423,7 +474,7 @@ export async function processPendingMergePrs(app) {
withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';
return assessment.ok
? await git.mergePR(app.repoPath, entry.prNumber, {
- forgeAccount: app?.forgeAccount || null, expectedHeadSha: currentPr.headRefOid,
+ forgeAccount: app?.forgeAccount || null, expectedHeadSha,
}).catch((err) => ({ success: false, error: err.message }))
: { success: false, error: withheldReason };
});