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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: harden merge-gate audit evidence (#12549)
[._.]/ Adam Eivy0c930a24ea84
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 6a541a783d..79b5f7bad6 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -88,11 +88,15 @@ Admission and "merge on green" are prompt rules; an agent with `gh` access canstill merge around them. When a claim run finishes, `mergeGateAudit.js` (hungoff the post-cleanup audit in `agentWorktreeCleanup.js`) lists the PRs mergedfrom the run's bound claim branches and flags each one that either held no-admission lease at `mergedAt` or had a check on the merged head that was not-completed-green before it. The lease evidence is `mergeAdmissionHistory` on the+admission lease at `mergedAt` (within the 5-minute hold) or had a check run or+commit status on the merged head that was not completed-green before it (runs+created after the merge are ignored). The lease evidence is `mergeAdmissionHistory` on therun (each release records its `acquiredAt`/`releasedAt`) plus a lease it still-holds. A head named by a `mergeHandoffReceipts` entry — recorded when the run-handed it to the pending-merge coordinator — is never flagged.+holds. A head the pending-merge coordinator merged itself is never flagged: the+coordinator marks the run's `mergeHandoffReceipts` entry (`coordinatorMergedAt`)+when its own merge call succeeds, so a run that handed a head off and then merged+around the queue is still caught. An audit whose forge reads fail is kept as an+`audit` entry in `mergeGateWatches` and retried by the sweep.A violation is written to the run (`mergeGateViolations`), the run-events ledger(`run.merge-gate-violation`) and a notification. If the flagged head's checksdiff --git a/server/lib/mergeGateAudit.js b/server/lib/mergeGateAudit.jsindex 79946173f0..7ec92ff37b 100644--- a/server/lib/mergeGateAudit.js+++ b/server/lib/mergeGateAudit.js@@ -16,9 +16,10 @@ export const MERGE_GATE_VIOLATIONS = Object.freeze({// Lease timestamps are local, `mergedAt` is the forge's clock; tolerate drift// without letting a merge made well outside the hold pass as covered.export const LEASE_CLOCK_SKEW_MS = 30 * 1000;-// A legacy `lastMergeAdmission` records only its release time. Agent leases hold-// at most 5 minutes (`AGENT_LEASE_MAX_HOLD_MS`), so that bounds when it began.-const LEGACY_LEASE_WINDOW_MS = 5 * 60 * 1000;+// Agent leases hold at most 5 minutes (`AGENT_LEASE_MAX_HOLD_MS`): past that a+// holder must re-acquire, so a merge later than this is not covered. It also+// bounds when a legacy `lastMergeAdmission` (release time only) began.+const LEASE_MAX_HOLD_MS = 5 * 60 * 1000;const GREEN_CONCLUSIONS = new Set(['success', 'neutral', 'skipped']);const RED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure']);@@ -35,7 +36,7 @@ const time = (value) => {* read, and no verdict is possible. An empty list is a repository with no CI on* that head, which has nothing to wait for.*- * @param {Array<{name?: string, status?: string, conclusion?: string|null, completed_at?: string|null}>|null} checks+ * @param {Array<{name?: string, status?: string, conclusion?: string|null, started_at?: string|null, completed_at?: string|null}>|null} checks* @param {string} mergedAt* @returns {{ readable: boolean, notGreenAtMerge: string[], failing: string[], settled: boolean }}*/@@ -51,6 +52,10 @@ export function classifyHeadChecks(checks, mergedAt) {const conclusion = String(check?.conclusion || '').toLowerCase();if (!completed) settled = false;if (completed && RED_CONCLUSIONS.has(conclusion)) failing.push(name);+ // A run created after the merge (a push workflow on the merge commit, a manual+ // rerun) was never something the merge could have waited for.+ const startedMs = time(check?.started_at);+ if (startedMs !== null && mergedMs !== null && startedMs > mergedMs + LEASE_CLOCK_SKEW_MS) continue;const completedMs = time(check?.completed_at);const greenBeforeMerge = completed && GREEN_CONCLUSIONS.has(conclusion)&& mergedMs !== null && completedMs !== null && completedMs <= mergedMs;@@ -63,7 +68,7 @@ export function classifyHeadChecks(checks, mergedAt) {function leaseInterval(entry) {const releasedMs = time(entry?.releasedAt);if (releasedMs === null) return null;- const acquiredMs = time(entry?.acquiredAt) ?? releasedMs - LEGACY_LEASE_WINDOW_MS;+ const acquiredMs = time(entry?.acquiredAt) ?? releasedMs - LEASE_MAX_HOLD_MS;return { repository: entry?.repository, outcome: entry?.outcome, acquiredMs, releasedMs };}@@ -81,12 +86,13 @@ function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = nullif (mergedMs === null) return false;if (heldLease?.repository === repository) {const acquiredMs = time(heldLease.acquiredAt);- if (acquiredMs !== null && acquiredMs <= mergedMs + LEASE_CLOCK_SKEW_MS) return true;+ if (acquiredMs !== null && acquiredMs <= mergedMs + LEASE_CLOCK_SKEW_MS && mergedMs <= acquiredMs + LEASE_MAX_HOLD_MS + LEASE_CLOCK_SKEW_MS) return true;}return history.some((entry) => {const lease = leaseInterval(entry);return lease && lease.repository === repository && lease.outcome === 'merged'- && lease.acquiredMs <= mergedMs + LEASE_CLOCK_SKEW_MS && lease.releasedMs >= mergedMs - LEASE_CLOCK_SKEW_MS;+ && lease.acquiredMs <= mergedMs + LEASE_CLOCK_SKEW_MS && lease.releasedMs >= mergedMs - LEASE_CLOCK_SKEW_MS+ && mergedMs <= lease.acquiredMs + LEASE_MAX_HOLD_MS + LEASE_CLOCK_SKEW_MS;});}@@ -94,14 +100,15 @@ function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = null* Judge one merged claim PR.** A head the pending-merge coordinator merged under its own admission is never- * flagged: the receipt recorded at handoff names exactly the head it may merge,- * and it merges only once every check is green.+ * flagged. Only a receipt the coordinator marked `coordinatorMergedAt` when its+ * own merge call succeeded counts: a bare handoff proves nothing about who+ * merged, and a run that merged around the queue leaves its receipt unmarked.** @param {object} input* @param {string} input.repository* @param {string} input.headSha* @param {string} input.mergedAt- * @param {Array<{headSha?: string}>} [input.receipts] handoff receipts recorded on the run+ * @param {Array<{headSha?: string, coordinatorMergedAt?: string}>} [input.receipts] handoff receipts recorded on the run* @param {Array<object>} [input.history]* @param {object|null} [input.heldLease]* @param {Array<object>|null} input.checks check runs of the merged head; null when unreadable@@ -110,7 +117,7 @@ function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = nullexport function assessMergeGate({ repository, headSha, mergedAt, receipts = [], history = [], heldLease = null, checks }) {const classification = classifyHeadChecks(checks, mergedAt);const head = String(headSha || '').toLowerCase();- if (receipts.some((receipt) => String(receipt?.headSha || '').toLowerCase() === head)) {+ if (receipts.some((receipt) => receipt?.coordinatorMergedAt && String(receipt.headSha || '').toLowerCase() === head)) {return { exempt: true, violations: [], checks: classification };}const violations = [];diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex eb24d6f7be..0ed83fee63 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -333,6 +333,29 @@ export async function recordMergeHandoffReceipt({ agentId, receipt }) {}, 'handoff-receipt');}+/**+ * Record that the pending-merge coordinator itself merged the head a receipt+ * names. Only the coordinator's own merge call writes this; a PR that merely+ * turns up MERGED (the run merged it around the queue) leaves the receipt+ * unmarked, so the post-merge gate audit still sees that merge.+ *+ * @returns {Promise<{ marked: true }|{ marked?: false, reason: string }>}+ */+export async function markMergeHandoffMerged({ agentId, receiptId, headSha }) {+ return transaction(async (state, save) => {+ const agent = state.agents[agentId];+ const receipts = Array.isArray(agent?.metadata?.mergeHandoffReceipts) ? agent.metadata.mergeHandoffReceipts : [];+ if (!receipts.some((receipt) => receipt?.receiptId === receiptId && receipt.headSha === headSha)) {+ return { marked: false, reason: 'receipt-unknown' };+ }+ const coordinatorMergedAt = new Date().toISOString();+ state.agents[agentId] = { ...agent, metadata: { ...agent.metadata, mergeHandoffReceipts: receipts.map((receipt) =>+ (receipt?.receiptId === receiptId ? { ...receipt, coordinatorMergedAt } : receipt)) } };+ await save(state);+ return { marked: true };+ }, 'handoff-merged');+}+/** 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.test.js b/server/services/cosMergeHandoff.test.jsindex d6fca66b07..8c7c8c5458 100644--- a/server/services/cosMergeHandoff.test.js+++ b/server/services/cosMergeHandoff.test.js@@ -145,6 +145,15 @@ describe('pending-merge handoff', () => {expect(await restarted.processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 1 });expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD });expect(pending()).toEqual([]);+ expect(f.state.agents['agent-1'].metadata.mergeHandoffReceipts[0].coordinatorMergedAt).toEqual(expect.any(String));+ });++ it('marks a receipt coordinator-merged only for its own merge, never for a PR that turned up merged', async () => {+ await handedOff();+ f.pr.state = 'MERGED';+ await processPendingMergePrs(f.apps.get('app1'));+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(f.state.agents['agent-1'].metadata.mergeHandoffReceipts[0].coordinatorMergedAt).toBeUndefined();});it.each([diff --git a/server/services/mergeGateAudit.js b/server/services/mergeGateAudit.jsindex becae861c6..b5a7d128ef 100644--- a/server/services/mergeGateAudit.js+++ b/server/services/mergeGateAudit.js@@ -43,16 +43,29 @@ const auditKey = (pr) => `${pr.number}@${String(pr.headRefOid).toLowerCase()}`;const watchKey = (repository, headSha) => `${repository}#${String(headSha).toLowerCase()}`;const readWatches = (app) => readList(app?.mergeGateWatches).filter((watch) => isPlainObject(watch) && watch.key);-/** The check runs of `headSha`, or null when the forge could not be read. */-async function readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha }) {+// Commit statuses (CI that reports through the status API rather than check+// runs) are mapped onto the check-run shape. A status has no start time worth+// trusting: its `created_at` moves when the context flips pending to success.+const CHECK_RUN_JQ = '.check_runs[] | {name, status, conclusion, started_at, completed_at}';+const STATUS_JQ = '.statuses[] | {name: .context, status: (if .state == "pending" then "in_progress" else "completed" end), conclusion: (if .state == "error" then "failure" else .state end), completed_at: .updated_at}';++async function readGhLines({ origin, repoSpec, forgeExec, path, jq }) {const raw = await execGh([- 'api', '--hostname', githubApiHost(origin.host), '--paginate',- `repos/${origin.fullName}/commits/${headSha}/check-runs?per_page=100`,- '--jq', '.check_runs[] | {name, status, conclusion, completed_at}',+ 'api', '--hostname', githubApiHost(origin.host), '--paginate', path, '--jq', jq,], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);if (raw === null) return null;- const runs = String(raw).split('\n').map((line) => line.trim()).filter(Boolean).map((line) => safeJSONParse(line, null));- return runs.every(isPlainObject) ? runs : null;+ const rows = String(raw).split('\n').map((line) => line.trim()).filter(Boolean).map((line) => safeJSONParse(line, null));+ return rows.every(isPlainObject) ? rows : null;+}++/** The check runs and commit statuses of `headSha`, or null when either could not be read. */+async function readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha }) {+ const base = `repos/${origin.fullName}/commits/${headSha}`;+ const [runs, statuses] = await Promise.all([+ readGhLines({ origin, repoSpec, forgeExec, path: `${base}/check-runs?per_page=100`, jq: CHECK_RUN_JQ }),+ readGhLines({ origin, repoSpec, forgeExec, path: `${base}/status?per_page=100`, jq: STATUS_JQ }),+ ]);+ return runs && statuses ? [...runs, ...statuses] : null;}async function readMergedPrs({ repoSpec, forgeExec, branch, since }) {@@ -159,7 +172,7 @@ async function recordViolation(agent, watch, violations, checkNames) {* @param {string} params.agentId* @param {object|null} params.task - the CoS task* @param {object|null} params.agentState - the persisted agent record- * @returns {Promise<{ audited: number, violations: number, skipReason?: string }>}+ * @returns {Promise<{ audited: number, violations: number, unresolved?: boolean, skipReason?: string }>}*/export async function auditClaimMergeGate({ agentId, task, agentState }) {const metadata = agentState?.metadata || {};@@ -182,26 +195,27 @@ export async function auditClaimMergeGate({ agentId, task, agentState }) {const audited = new Set(readList(metadata.mergeGateAudits));const newAudits = [];const found = [];- let unreadable = false;+ let unresolved = false;for (const branch of branches) {const prs = await readMergedPrs({ repoSpec, forgeExec, branch, since });- if (prs === null) { unreadable = true; continue; }+ if (prs === null) { unresolved = true; continue; }for (const pr of prs.filter((candidate) => !audited.has(auditKey(candidate)))) {const headSha = String(pr.headRefOid).toLowerCase();const checks = await readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha });+ // No verdict without readable evidence; the durable sweep retries the audit.+ if (checks === null) { unresolved = true; continue; }const heldLease = await readHeldLease({ ...agentState, id: agentId }, repository);const verdict = assessMergeGate({repository, headSha, mergedAt: pr.mergedAt, checks, heldLease,receipts: readList(metadata.mergeHandoffReceipts),history: [...readList(metadata.mergeAdmissionHistory), ...(metadata.lastMergeAdmission ? [metadata.lastMergeAdmission] : [])],});- // An unreadable check list is no verdict on the checks rule; retry on a later pass.- if (checks !== null) newAudits.push(auditKey(pr));+ newAudits.push(auditKey(pr));if (verdict.violations.length === 0) continue;found.push({ pr, headSha, verdict });}}- if (unreadable) emitLog('info', `🚦 Merge-gate audit for ${agentId} could not read every claim branch's PRs`, { agentId });+ if (unresolved) await persistPendingAudit({ agentId, taskId: agentState?.taskId ?? null, app });const violationRecords = [];for (const { pr, headSha, verdict } of found) {@@ -226,7 +240,20 @@ export async function auditClaimMergeGate({ agentId, task, agentState }) {...(violationRecords.length ? { mergeGateViolations: [...readList(metadata.mergeGateViolations), ...violationRecords].slice(-LIST_LIMIT) } : {}),} }).catch((err) => emitLog('warn', `🚦 Could not record merge-gate audit on ${agentId}: ${err.message}`, { agentId }));}- return { audited: newAudits.length, violations: found.length };+ return { audited: newAudits.length, violations: found.length, unresolved };+}++// The forge could not be read: keep the audit as work for the durable sweep+// rather than losing the run's only chance of being checked.+async function persistPendingAudit({ agentId, taskId, app }) {+ if (!app) {+ emitLog('warn', `🚦 Merge-gate audit for ${agentId} could not read the forge and has no app to retry under`, { agentId });+ return;+ }+ const key = `audit:${agentId}`;+ await mutateWatches(app.id, (existing) => (existing.some((entry) => entry.key === key) ? existing+ : [...existing, { key, kind: 'audit', agentId, taskId, flaggedAt: new Date().toISOString() }]))+ .catch((err) => emitLog('warn', `🚦 Could not queue a merge-gate audit retry for ${agentId}: ${err.message}`, { agentId }));}// Already-failed checks queue the recovery now; checks still running arm a watch@@ -234,11 +261,13 @@ export async function auditClaimMergeGate({ agentId, task, agentState }) {// branch is not red.async function watchFlaggedHead(watch, checks, app) {if (checks.failing.length > 0) {- await fileRecoveryTask(watch, checks.failing, app)- .catch((err) => emitLog('warn', `🚦 Merge-gate recovery for PR #${watch.prNumber} not queued: ${err.message}`, { agentId: watch.agentId }));- return;- }- if (checks.settled) return;+ // A failed queue write keeps the watch, so the sweep retries it.+ const queued = await fileRecoveryTask(watch, checks.failing, app).then(() => true, (err) => {+ emitLog('warn', `🚦 Merge-gate recovery for PR #${watch.prNumber} not queued: ${err.message}`, { agentId: watch.agentId });+ return false;+ });+ if (queued) return;+ } else if (checks.settled) return;await mutateWatches(app.id, (existing) => (existing.some((entry) => entry.key === watch.key) ? existing : [...existing, watch])).catch((err) => emitLog('warn', `🚦 Could not watch flagged head of PR #${watch.prNumber}: ${err.message}`, { agentId: watch.agentId }));scheduleWatchPolls(app.id);@@ -271,6 +300,20 @@ export function __cancelMergeGatePolls() {let sweepInFlight = null;+// True once the audit ran to a verdict. A run whose record is gone cannot be+// audited again; the entry waits out its TTL like any other unreadable evidence.+async function retryPendingAudit(watch, app) {+ const { getAgentRecord } = await import('./cosAgentLifecycle.js');+ const agentState = await getAgentRecord(watch.agentId).catch(() => null);+ if (!agentState) return false;+ const result = await auditClaimMergeGate({ agentId: watch.agentId, task: { id: watch.taskId, metadata: { app: app.id } }, agentState })+ .catch((err) => {+ emitLog('warn', `🚦 Merge-gate audit retry for ${watch.agentId} failed: ${err.message}`, { agentId: watch.agentId });+ return { unresolved: true };+ });+ return !result.unresolved;+}+async function sweepApp(app) {const watches = readWatches(app);if (watches.length === 0) return { checked: 0, recovered: 0, remaining: 0 };@@ -282,10 +325,14 @@ async function sweepApp(app) {let recovered = 0;for (const watch of watches) {if (Date.now() - Date.parse(watch.flaggedAt) >= MERGE_GATE_WATCH_TTL_MS) {- emitLog('info', `🚦 Dropping merge-gate watch for PR #${watch.prNumber}: checks did not settle in time`, { agentId: watch.agentId });+ emitLog('warn', `🚦 Dropping merge-gate ${watch.kind === 'audit' ? `audit of ${watch.agentId}: the forge stayed unreadable` : `watch for PR #${watch.prNumber}: checks did not settle`} in time`, { agentId: watch.agentId });settledKeys.add(watch.key);continue;}+ if (watch.kind === 'audit') {+ if (await retryPendingAudit(watch, app)) settledKeys.add(watch.key);+ continue;+ }const checks = classifyHeadChecks(await readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha: watch.headSha }), watch.mergedAt);if (checks.failing.length > 0) {const queued = await fileRecoveryTask(watch, checks.failing, app).then(() => true, (err) => {diff --git a/server/services/mergeGateAudit.test.js b/server/services/mergeGateAudit.test.jsindex 5862e71c8f..73d93d4e23 100644--- a/server/services/mergeGateAudit.test.js+++ b/server/services/mergeGateAudit.test.js@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// run's recorded lease history and the task queue are injected; the audit,// the watch sweep and the pure assessment run for real.const f = vi.hoisted(() => ({- agent: null, apps: new Map(), tasks: [], prs: [], checks: [], held: null,+ agent: null, apps: new Map(), tasks: [], prs: [], checks: [], statuses: [], held: null, addTaskFailures: 0,}));const execGhMock = vi.fn();@@ -24,9 +24,11 @@ vi.mock('./cosState.js', () => ({vi.mock('./cosMergeAdmission.js', () => ({ repositoryKey: (origin) => `${origin.host}/${origin.fullName}`.toLowerCase() }));vi.mock('./cosAgentLifecycle.js', () => ({updateAgent: async (_id, patch) => { f.agent = { ...f.agent, metadata: { ...f.agent.metadata, ...patch.metadata } }; return f.agent; },+ getAgentRecord: async () => f.agent,}));// addTask's real dedupe is first-line + app against open tasks; mirror it.const addTaskMock = vi.fn(async (data) => {+ if (f.addTaskFailures > 0) { f.addTaskFailures -= 1; throw new Error('queue unavailable'); }const open = f.tasks.find((task) => task.description.split('\n')[0] === data.description.split('\n')[0] && task.app === data.app);if (open) return { ...open, duplicate: true };const created = { id: `task-${f.tasks.length + 1}`, ...data };@@ -65,12 +67,18 @@ beforeEach(() => {f.held = null;f.prs = [{ number: 7, url: PR_URL, headRefOid: HEAD, mergedAt: MERGED_AT, baseRefName: 'main' }];f.checks = [check()];+ f.statuses = [];+ f.addTaskFailures = 0;addTaskMock.mockClear();notifyMock.mockClear();appendRunEventMock.mockClear();execGhMock.mockReset().mockImplementation(async (args) => {if (args[0] === 'pr' && args[1] === 'list') return JSON.stringify(f.prs);- if (args[0] === 'api') return f.checks.map((c) => JSON.stringify(c)).join('\n');+ if (args[0] === 'api') {+ const rows = args.some((arg) => String(arg).includes('/status')) ? f.statuses : f.checks;+ if (rows === null) throw new Error('forge down');+ return rows.map((c) => JSON.stringify(c)).join('\n');+ }throw new Error('unexpected forge read');});});@@ -142,7 +150,8 @@ describe('post-merge gate audit', () => {// lease on record and a check still reporting in progress must not flag it.f.held = null;f.agent.metadata = { ...f.agent.metadata, mergeGateAudits: [],- mergeHandoffReceipts: [{ receiptId: 'receipt-1', prUrl: PR_URL, headSha: HEAD, acceptedAt: '2026-10-20T02:10:00Z' }] };+ mergeHandoffReceipts: [{ receiptId: 'receipt-1', prUrl: PR_URL, headSha: HEAD, acceptedAt: '2026-10-20T02:10:00Z',+ coordinatorMergedAt: MERGED_AT }] };f.checks = [check({ status: 'in_progress', conclusion: null, completed_at: null })];expect(await run()).toMatchObject({ violations: 0 });@@ -151,16 +160,52 @@ describe('post-merge gate audit', () => {expect(notifyMock).not.toHaveBeenCalled();});- it('leaves a run alone when the forge cannot be read or the run is not a claim', async () => {- f.checks = null;- execGhMock.mockImplementation(async (args) => {- if (args[0] === 'pr') return JSON.stringify(f.prs);- throw new Error('forge down');- });- // Unreadable checks are no verdict on the checks rule; the missing lease still is.- expect(await run()).toMatchObject({ audited: 0, violations: 1 });+ it('still flags a run that merged around the queue after handing the head to the coordinator', async () => {+ // A bare handoff receipt (no coordinator merge recorded) proves nothing about who merged.+ f.agent.metadata.mergeHandoffReceipts = [{ receiptId: 'receipt-1', prUrl: PR_URL, headSha: HEAD, acceptedAt: '2026-10-20T02:10:00Z' }];+ expect(await run()).toMatchObject({ violations: 1 });+ expect(f.agent.metadata.mergeGateViolations[0].codes).toEqual(['no-admission-lease']);+ });++ it('flags a merge made on an expired lease and counts failing commit statuses and ignores post-merge runs', async () => {+ f.agent.metadata.mergeAdmissionHistory = [lease({ acquiredAt: '2026-10-20T02:05:00Z', releasedAt: '2026-10-20T02:17:00Z' })];+ f.checks = [+ check(),+ // A push workflow on the merge commit was never something the merge could wait for.+ check({ name: 'post-merge deploy', started_at: '2026-10-20T02:30:00Z', status: 'in_progress', conclusion: null, completed_at: null }),+ ];+ f.statuses = [{ name: 'ci/legacy', status: 'completed', conclusion: 'failure', completed_at: '2026-10-20T02:20:00Z' }];+ await run();+ expect(f.agent.metadata.mergeGateViolations).toEqual([expect.objectContaining({+ codes: ['no-admission-lease', 'checks-not-green-at-merge'], notGreenAtMerge: ['ci/legacy'],+ })]);+ expect(f.tasks).toHaveLength(1);+ });++ it('keeps an audit the forge could not answer and completes it from the durable sweep', async () => {+ f.statuses = null;+ expect(await run()).toMatchObject({ audited: 0, violations: 0, unresolved: true });+ expect(f.agent.metadata.mergeGateViolations).toBeUndefined();+ expect(f.apps.get('app1').mergeGateWatches).toEqual([expect.objectContaining({ kind: 'audit', agentId: 'agent-1' })]);++ f.statuses = [];+ expect(await sweepMergeGateWatches()).toMatchObject({ remaining: 0 });+ expect(f.agent.metadata.mergeGateViolations).toHaveLength(1);+ expect(f.apps.get('app1').mergeGateWatches).toEqual([]);+ });++ it('retries a recovery task the queue refused instead of dropping it', async () => {+ f.checks = [check({ conclusion: 'failure', completed_at: '2026-10-20T02:20:00Z' })];+ f.addTaskFailures = 1;+ await run();expect(f.tasks).toEqual([]);+ expect(f.apps.get('app1').mergeGateWatches).toEqual([expect.objectContaining({ headSha: HEAD })]);++ expect(await sweepMergeGateWatches()).toMatchObject({ recovered: 1, remaining: 0 });+ expect(f.tasks).toHaveLength(1);+ });+ it('skips a run that is not a claim', async () => {f.agent.metadata.claimBranches = [];expect(await run()).toMatchObject({ skipReason: 'not-a-claim-run' });});diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex 235b8b38f2..541ab535e0 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -619,6 +619,12 @@ async function runPendingMergePrs(app, { spendTicks }) {continue;}if (merge.success) {+ // The post-merge gate audit (#12549) exempts only a merge made here.+ if (binding) {+ const { markMergeHandoffMerged } = await import('./cosMergeAdmission.js');+ await markMergeHandoffMerged({ agentId: binding.agentId, receiptId: binding.receiptId, headSha: binding.headSha })+ .catch((err) => console.warn(`⚠️ Could not mark PR #${entry.prNumber} as coordinator-merged: ${err.message}`));+ }// Admission has released before potentially slow archival cleanup.outcomes.set(key, await finishMergedReceipt(app, entry, binding));result.merged += 1;