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: audit claim-run merges for bypassed admission or pending CI (#12549)

[._.]/ Adam Eivy48e665003826
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 4ae64a6854..6a541a783d 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -82,6 +82,27 @@ 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.
+### Post-merge gate audit (#12549)
+
+Admission and "merge on green" are prompt rules; an agent with `gh` access can
+still merge around them. When a claim run finishes, `mergeGateAudit.js` (hung
+off the post-cleanup audit in `agentWorktreeCleanup.js`) lists the PRs merged
+from 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
+run (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.
+
+A violation is written to the run (`mergeGateViolations`), the run-events ledger
+(`run.merge-gate-violation`) and a notification. If the flagged head's checks
+fail, ONE recovery task for the default branch is queued; its description names
+the merged SHA, so concurrent runs and repeat audits deduplicate on the task
+queue. Heads whose checks were still running are watched on the app
+(`mergeGateWatches`) and resolved by a bounded fast poll and the 30-minute
+pending-merge sweep. Detection only: nothing merges, reverts or changes branch
+protection.
+
### Pending-merge handoff (#12247)
A participant that has pushed a head and satisfied its configured reviews may
diff --git a/server/lib/README.md b/server/lib/README.md
index f5279d955d..9af85d6b34 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -738,6 +738,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. |
+| `mergeGateAudit.js` | Pure verdicts for the post-merge gate audit (#12549): `assessMergeGate({repository, headSha, mergedAt, checks, history, heldLease, receipts})` flags a merged claim PR that held no merge-admission lease at `mergedAt` (`leaseCoversMerge`) or whose head had a check not completed-green before it (`classifyHeadChecks`), and exempts a head the pending-merge coordinator was handed (`receipts`). `null` checks = forge unreadable, never a verdict. The forge reads and recovery filing live in `../services/mergeGateAudit.js`. |
| `mergeGateContract.js` | `buildManagedGithubMergeScript()` emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |
| `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. |
| `prDisposition.js` | `resolveAppPrCompletion(app, metadata)` supplies the reviewed automatic merge default for new tasks while preserving explicit managed-app choices and legacy review toggles. `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; `prStaysOpen(task)` is the combined policy-or-human verdict. 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`. |
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index eeab5a6887..e122576957 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -99,7 +99,10 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze([
// `endTime` that no exit ever produced, and nothing would say where it came
// from. Adding this kind is not an envelope shape change — older builds fold
// unknown kinds as no-ops — so AGENT_RUN_EVENT_SCHEMA_VERSION stays at 1.
- 'run.reconciled'
+ 'run.reconciled',
+ // A completed claim run merged a PR without the merge-admission lease or
+ // before its head's checks were green (#12549). Unknown kinds fold as no-ops.
+ 'run.merge-gate-violation'
]);
/** All writeable kinds in the shared machine-local ledger. */
diff --git a/server/lib/index.js b/server/lib/index.js
index 2ef5b7a4c5..3a54d3a044 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -707,6 +707,7 @@ export * from './openapiSpec.js';
export * from './openapiDowngrade.js';
export * from './orchestrationProfile.js';
export * from './apiToolResource.js';
+export * from './mergeGateAudit.js';
export * from './mergeGateContract.js';
export * from './preflightPlan.js';
export * from './prDisposition.js';
diff --git a/server/lib/mergeGateAudit.js b/server/lib/mergeGateAudit.js
new file mode 100644
index 0000000000..79946173f0
--- /dev/null
+++ b/server/lib/mergeGateAudit.js
@@ -0,0 +1,130 @@
+/**
+ * Pure verdicts for the post-merge gate audit (#12549).
+ *
+ * The merge-admission lease and the "required CI is green" rule are prompt
+ * instructions; an agent with full forge access can still merge around them.
+ * Given what the forge reports about a merged head and what PortOS recorded
+ * about the run's admission leases, these functions decide whether the merge
+ * respected both gates. No I/O: `services/mergeGateAudit.js` gathers the inputs.
+ */
+
+export const MERGE_GATE_VIOLATIONS = Object.freeze({
+ NO_ADMISSION_LEASE: 'no-admission-lease',
+ CHECKS_NOT_GREEN_AT_MERGE: 'checks-not-green-at-merge',
+});
+
+// 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;
+
+const GREEN_CONCLUSIONS = new Set(['success', 'neutral', 'skipped']);
+const RED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure']);
+
+const time = (value) => {
+ const ms = Date.parse(value);
+ return Number.isFinite(ms) ? ms : null;
+};
+
+/**
+ * Classify a merged head's check runs against the moment it merged.
+ *
+ * Absent and empty are different: `checks === null` means the forge could not be
+ * 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 {string} mergedAt
+ * @returns {{ readable: boolean, notGreenAtMerge: string[], failing: string[], settled: boolean }}
+ */
+export function classifyHeadChecks(checks, mergedAt) {
+ if (!Array.isArray(checks)) return { readable: false, notGreenAtMerge: [], failing: [], settled: false };
+ const mergedMs = time(mergedAt);
+ const notGreenAtMerge = [];
+ const failing = [];
+ let settled = true;
+ for (const check of checks) {
+ const name = String(check?.name || 'unnamed check');
+ const completed = check?.status === 'completed';
+ const conclusion = String(check?.conclusion || '').toLowerCase();
+ if (!completed) settled = false;
+ if (completed && RED_CONCLUSIONS.has(conclusion)) failing.push(name);
+ const completedMs = time(check?.completed_at);
+ const greenBeforeMerge = completed && GREEN_CONCLUSIONS.has(conclusion)
+ && mergedMs !== null && completedMs !== null && completedMs <= mergedMs;
+ if (!greenBeforeMerge) notGreenAtMerge.push(name);
+ }
+ return { readable: true, notGreenAtMerge, failing, settled };
+}
+
+/** One agent-lease interval, whatever shape recorded it. */
+function leaseInterval(entry) {
+ const releasedMs = time(entry?.releasedAt);
+ if (releasedMs === null) return null;
+ const acquiredMs = time(entry?.acquiredAt) ?? releasedMs - LEGACY_LEASE_WINDOW_MS;
+ return { repository: entry?.repository, outcome: entry?.outcome, acquiredMs, releasedMs };
+}
+
+/**
+ * Did the run hold the repository's merge-admission lease at `mergedAt`?
+ *
+ * @param {object} evidence
+ * @param {string} evidence.repository
+ * @param {string} evidence.mergedAt
+ * @param {Array<object>} [evidence.history] released leases (`mergeAdmissionHistory` and the legacy `lastMergeAdmission`)
+ * @param {{repository?: string, acquiredAt?: string}|null} [evidence.heldLease] a lease the run still holds
+ */
+function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = null }) {
+ const mergedMs = time(mergedAt);
+ if (mergedMs === null) return false;
+ if (heldLease?.repository === repository) {
+ const acquiredMs = time(heldLease.acquiredAt);
+ if (acquiredMs !== null && acquiredMs <= mergedMs + 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;
+ });
+}
+
+/**
+ * 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.
+ *
+ * @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<object>} [input.history]
+ * @param {object|null} [input.heldLease]
+ * @param {Array<object>|null} input.checks check runs of the merged head; null when unreadable
+ * @returns {{ exempt: boolean, violations: Array<{code: string, message: string}>, checks: ReturnType<typeof classifyHeadChecks> }}
+ */
+export 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)) {
+ return { exempt: true, violations: [], checks: classification };
+ }
+ const violations = [];
+ if (!leaseCoversMerge({ repository, mergedAt, history, heldLease })) {
+ violations.push({
+ code: MERGE_GATE_VIOLATIONS.NO_ADMISSION_LEASE,
+ message: 'merged without holding the repository merge-admission lease',
+ });
+ }
+ if (classification.notGreenAtMerge.length > 0) {
+ violations.push({
+ code: MERGE_GATE_VIOLATIONS.CHECKS_NOT_GREEN_AT_MERGE,
+ message: `merged before ${classification.notGreenAtMerge.length} check(s) on the head finished green`,
+ });
+ }
+ return { exempt: false, violations, checks: classification };
+}
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 07e44dbc33..0b5989b07a 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -102,8 +102,12 @@ export async function cleanupAgentWorktree(agentId, success, options = {}) {
// output buffer for the duration of the probes.
const originalTask = options?.originalTask || null;
run.then(
- (warnings) => auditRepoState(agentId, success, originalTask, warnings)
- .catch(err => emitLog('warn', `🔎 Repo-state audit failed for ${agentId}: ${err.message}`, { agentId })),
+ (warnings) => Promise.all([
+ auditRepoState(agentId, success, originalTask, warnings)
+ .catch(err => emitLog('warn', `🔎 Repo-state audit failed for ${agentId}: ${err.message}`, { agentId })),
+ auditMergeGate(agentId, originalTask)
+ .catch(err => emitLog('warn', `🚦 Merge-gate audit failed for ${agentId}: ${err.message}`, { agentId })),
+ ]),
// A cleanup that threw has no end state to audit; `settled` still rejects.
() => {}
// Nothing awaits this chain, so a throw from the reporting itself would surface
@@ -138,6 +142,19 @@ async function auditRepoState(agentId, success, originalTask, warnings) {
});
}
+/**
+ * Post-merge gate audit (#12549): did a claim run's merged PR hold the merge
+ * admission lease and land on green checks? Detection only; it flags and files
+ * one default-branch recovery task. Lazily imported like the repo-state audit.
+ */
+async function auditMergeGate(agentId, originalTask) {
+ const { auditClaimMergeGate } = await import('./mergeGateAudit.js');
+ const { getAgentRecord } = await import('./cos.js');
+ const agentState = await getAgentRecord(agentId).catch(() => null);
+ if (!agentState) return;
+ await auditClaimMergeGate({ agentId, task: originalTask, agentState });
+}
+
// A disposition is selected once, after forge evidence is available. Merge is
// still governed by success/skipMerge even for stand-down: the existing local
// cleanup contract is independent of who opened the PR.
diff --git a/server/services/cos.js b/server/services/cos.js
index d8cf1a44a2..944ac778fd 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -578,6 +578,13 @@ async function bootDaemon(state) {
if (sweep && (sweep.merged || sweep.escalated || sweep.timedOut)) {
emitLog('info', `🤖 Pending merges: ${sweep.merged} merged, ${sweep.escalated} escalated, ${sweep.timedOut} timed out`);
}
+ // Flagged merges (#12549) whose checks were still running when the run ended.
+ const { sweepMergeGateWatches } = await import('./mergeGateAudit.js');
+ const gate = await sweepMergeGateWatches().catch((err) => {
+ console.warn(`⚠️ sweepMergeGateWatches failed: ${err?.message || err}`);
+ return null;
+ });
+ if (gate?.recovered) emitLog('info', `🚦 Merge-gate watches: ${gate.recovered} recovery task(s) queued, ${gate.remaining} still watching`);
},
metadata: { description: 'CoS pending merge-only PR drain' }
});
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index 4ece555b5f..eb24d6f7be 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -23,6 +23,8 @@ export const ADMISSION_QUEUE_TIMEOUT_MS = 15_000;
// deadline may still land, with the same exposure as two CLEAN merges.
export const AGENT_LEASE_MAX_HOLD_MS = 5 * 60 * 1000;
export const MERGE_ADMISSION_OUTCOMES = ['merged', 'leave-open', 'resync'];
+const MERGE_ADMISSION_HISTORY_LIMIT = 25;
+const MERGE_HANDOFF_RECEIPT_LIMIT = 25;
const serverOwner = randomUUID();
const sweepTokens = new Set();
const refuse = (reason) => ({ admitted: false, reason, retryAfterMs });
@@ -312,6 +314,25 @@ export async function resolveMergeHandoffOwner(agentId) {
return { refused: 'handoff-owner-unverified' };
}
+/**
+ * Record that the pending-merge coordinator was handed exactly this PR head, on
+ * the run that handed it off. The post-merge gate audit (#12549) reads it to
+ * tell the coordinator's merge from an agent merging around admission.
+ *
+ * @returns {Promise<{ recorded: true }|{ recorded?: false, reason: string }>}
+ */
+export async function recordMergeHandoffReceipt({ agentId, receipt }) {
+ return transaction(async (state, save) => {
+ const agent = state.agents[agentId];
+ if (!agent || agent.id !== agentId) return { recorded: false, reason: 'handoff-owner-unverified' };
+ const prior = Array.isArray(agent.metadata?.mergeHandoffReceipts) ? agent.metadata.mergeHandoffReceipts : [];
+ state.agents[agentId] = { ...agent, metadata: { ...agent.metadata,
+ mergeHandoffReceipts: [...prior, receipt].slice(-MERGE_HANDOFF_RECEIPT_LIMIT) } };
+ await save(state);
+ return { recorded: true };
+ }, 'handoff-receipt');
+}
+
/** 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) => {
@@ -358,8 +379,14 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {
if (action === 'check') return expired(lease) ? refuse('lease-expired') : { admitted: true, token, repository };
if (action !== 'release' || !MERGE_ADMISSION_OUTCOMES.includes(outcome)) return refuse('outcome-required');
delete state.mergeAdmissions[repository];
+ // The post-merge gate audit (#12549) asks whether a lease was held at the
+ // instant a PR merged, so the interval outlives the lease. Bounded: a swarm
+ // parent cycles one lease per child PR.
+ const released = { repository, outcome, acquiredAt: lease.acquiredAt, releasedAt: new Date().toISOString() };
+ const history = Array.isArray(agent.metadata?.mergeAdmissionHistory) ? agent.metadata.mergeAdmissionHistory : [];
state.agents[agentId] = { ...agent, metadata: { ...agent.metadata,
- lastMergeAdmission: { repository, outcome, releasedAt: new Date().toISOString() },
+ lastMergeAdmission: released,
+ mergeAdmissionHistory: [...history, released].slice(-MERGE_ADMISSION_HISTORY_LIMIT),
} };
await save(state);
return { admitted: false, released: true, outcome };
diff --git a/server/services/cosMergeAdmission.test.js b/server/services/cosMergeAdmission.test.js
index 7064febcca..4a814077ed 100644
--- a/server/services/cosMergeAdmission.test.js
+++ b/server/services/cosMergeAdmission.test.js
@@ -142,6 +142,10 @@ describe('repository final merge workflow', () => {
expect((await release('a', a.token)).released).not.toBe(true);
expect(await release('a', next.token)).toMatchObject({ released: true });
expect(fixture.state.agents.a.metadata.lastMergeAdmission.outcome).toBe('merged');
+ // The merge-gate audit (#12549) needs the held interval, not just the last release time.
+ expect(fixture.state.agents.a.metadata.mergeAdmissionHistory.at(-1)).toMatchObject({
+ repository: 'github.com/example/repo', outcome: 'merged', acquiredAt: expect.any(String), releasedAt: expect.any(String),
+ });
const last = await acquire('a');
expect(await release('a', last.token, 'abandoned')).toMatchObject({ admitted: false, reason: 'outcome-required' });
expect(fixture.state.mergeAdmissions['github.com/example/repo'].token).toBe(last.token);
diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.js
index 30d8053611..8b7b1f0140 100644
--- a/server/services/cosMergeHandoff.js
+++ b/server/services/cosMergeHandoff.js
@@ -150,6 +150,12 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat
id: randomUUID(), appId: app.id, prUrl, prNumber: pr.number, headSha: head, repository,
queuedAt: new Date().toISOString(),
};
+ // The post-merge gate audit (#12549) must not flag the coordinator's own merge
+ // of this head, and the queue entry is gone once it merges. Record the receipt
+ // on the run first: a stale receipt for a head never queued is harmless.
+ const { recordMergeHandoffReceipt } = await import('./cosMergeAdmission.js');
+ const recorded = await recordMergeHandoffReceipt({ agentId, receipt: { receiptId: receipt.id, prUrl, headSha: head, acceptedAt: receipt.queuedAt } });
+ if (!recorded.recorded) return refuse('queue-write-failed');
const { queuePendingMerge, followUpHandoffReceipt } = await import('./prWatcher.js');
const queued = await queuePendingMerge(app.id, {
prUrl, prNumber: pr.number, prBranch: view.headRefName, sourceAgentId: agentId,
diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.js
index b81a110ef0..d6fca66b07 100644
--- a/server/services/cosMergeHandoff.test.js
+++ b/server/services/cosMergeHandoff.test.js
@@ -118,6 +118,10 @@ 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 handedOff();
expect(result).toMatchObject({ queued: true, receipt: { appId: 'app1', prNumber: 7, headSha: HEAD, repository: 'github.com/example/repo' } });
+ // The merge-gate audit (#12549) exempts exactly this head from the run's own record.
+ expect(f.state.agents['agent-1'].metadata.mergeHandoffReceipts).toEqual([
+ expect.objectContaining({ receiptId: result.receipt.id, prUrl: PR_URL, headSha: HEAD }),
+ ]);
// The receipt's immediate sweep found CI pending and spent no tick budget.
expect(mergePrMock).not.toHaveBeenCalled();
expect(pending()).toEqual([expect.objectContaining({
diff --git a/server/services/mergeGateAudit.js b/server/services/mergeGateAudit.js
new file mode 100644
index 0000000000..becae861c6
--- /dev/null
+++ b/server/services/mergeGateAudit.js
@@ -0,0 +1,329 @@
+/**
+ * Post-merge gate audit for claim runs (#12549).
+ *
+ * The merge-admission lease and the "required CI is green" rule are prompt
+ * instructions, and a claim agent has full forge access, so nothing stops it
+ * merging around them. This runs after the run completes and asks the forge:
+ * did each PR the run merged hold the repository's admission lease, and were all
+ * checks on the merged head green before `mergedAt`? A miss is recorded on the
+ * run, in the run-events ledger and as a notification. When the flagged head's
+ * checks then fail, ONE recovery task is queued for the default branch so
+ * concurrent runs inherit a single fix rather than each writing their own.
+ *
+ * Detection only: it never merges, reverts or edits a repository.
+ */
+
+import { execGh } from './github.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
+import { emitLog } from './cosEvents.js';
+import { appendRunEvent } from './agentRunEventLog.js';
+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
+import { getAppById, getActiveApps, updateApp } from './apps.js';
+import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
+import { assessMergeGate, classifyHeadChecks, MERGE_GATE_VIOLATIONS } from '../lib/mergeGateAudit.js';
+
+// A flagged head whose checks never settle is dropped after this long; the
+// sweep owns it until then.
+export const MERGE_GATE_WATCH_TTL_MS = 6 * 60 * 60 * 1000;
+// Fast follow-up after a flag, so a head failing in minutes is reported in
+// minutes; the 30-minute CoS sweep is the durable fallback after a restart.
+export const MERGE_GATE_POLL_INTERVAL_MS = 2 * 60 * 1000;
+const MERGE_GATE_POLL_CAP = 15;
+const LIST_LIMIT = 50;
+const SHORT_SHA = 12;
+
+const MERGED_PR_FIELDS = 'number,url,headRefOid,mergedAt,baseRefName';
+
+const readList = (value) => (Array.isArray(value) ? value : []);
+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 }) {
+ 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}',
+ ], 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;
+}
+
+async function readMergedPrs({ repoSpec, forgeExec, branch, since }) {
+ const raw = await execGh([
+ 'pr', 'list', '--repo', repoSpec, '--head', branch, '--state', 'merged',
+ '--json', MERGED_PR_FIELDS, '--limit', '5',
+ ], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);
+ const prs = raw === null ? null : safeJSONParse(raw, null);
+ if (!Array.isArray(prs)) return null;
+ // A reused branch name can carry an earlier run's PR.
+ return prs.filter((pr) => isPlainObject(pr) && /^[0-9a-f]{40}$/i.test(String(pr.headRefOid || ''))
+ && Number.isFinite(Date.parse(pr.mergedAt)) && (since === null || Date.parse(pr.mergedAt) >= since));
+}
+
+/** A lease the run still holds (it exited without releasing), from the trusted admission state. */
+async function readHeldLease(agent, repository) {
+ const { readMergeAdmissionStateForSafetyCheck } = await import('./cosState.js');
+ const snapshot = await readMergeAdmissionStateForSafetyCheck().catch(() => null);
+ const lease = snapshot?.trusted ? snapshot.mergeAdmissions?.[repository] : null;
+ return isPlainObject(lease) && lease.kind === 'agent' && lease.agentId === agent.id
+ && lease.startedAt === agent.startedAt && lease.taskId === agent.taskId ? lease : null;
+}
+
+function recoveryContext(watch, failing, appName) {
+ return [
+ `A pull request merged in ${appName} (${watch.repository}) before its head's checks finished green`
+ + `${watch.codes.includes(MERGE_GATE_VIOLATIONS.NO_ADMISSION_LEASE) ? ' and without the merge-admission lease' : ''}, `
+ + 'and those checks have now failed.',
+ '',
+ `Merged PR: ${watch.prUrl}`,
+ `Merged head: ${watch.headSha}`,
+ `Base branch: ${watch.baseBranch}`,
+ `Failing checks: ${failing.slice(0, 10).join(', ')}`,
+ `Merging run: ${watch.agentId}`,
+ '',
+ `Make ${watch.baseBranch} green again, in one pull request: either fix what the failing checks report or revert the merge.`,
+ 'Other claim runs hit the same failure and may already be writing their own fixes. '
+ + `Before changing anything, check open pull requests and recent commits on ${watch.baseBranch} for a fix that already landed or is in flight, `
+ + 'and reuse it instead of writing a competing one.',
+ ].join('\n');
+}
+
+async function fileRecoveryTask(watch, failing, app) {
+ const { addTask } = await import('./cosTaskStore.js');
+ const created = await addTask({
+ description: `${RECOVERY_TASK_PREFIX} Default branch ${watch.baseBranch} is red after PR #${watch.prNumber} merged past the merge gate (${watch.headSha.slice(0, SHORT_SHA)}) in ${app.name || watch.repository}`,
+ priority: 'HIGH',
+ app: app.id,
+ isRecovery: true,
+ metadata: { mergeGateRecovery: { repository: watch.repository, headSha: watch.headSha, prUrl: watch.prUrl, baseBranch: watch.baseBranch } },
+ context: recoveryContext(watch, failing, app.name || watch.repository),
+ useWorktree: true,
+ openPR: true,
+ }, 'user');
+ if (created?.duplicate) {
+ emitLog('info', `🚦 Merge-gate recovery for ${watch.headSha.slice(0, SHORT_SHA)} already queued as ${created.id}`, { agentId: watch.agentId });
+ return null;
+ }
+ emitLog('warn', `🚦 Queued merge-gate recovery for ${watch.baseBranch} (PR #${watch.prNumber}, ${failing.length} failing check(s))`, { agentId: watch.agentId, prUrl: watch.prUrl });
+ return created?.id || null;
+}
+
+// apps.json is one store: serialize this module's read-modify-write of its field.
+let watchWriteTail = Promise.resolve();
+function mutateWatches(appId, mutate) {
+ const next = watchWriteTail.catch(() => undefined).then(async () => {
+ const app = await getAppById(appId);
+ if (!app) return null;
+ return updateApp(appId, { mergeGateWatches: mutate(readWatches(app)) });
+ });
+ watchWriteTail = next;
+ return next;
+}
+
+async function notifyViolation(watch, violations, failing) {
+ const codes = violations.map((violation) => violation.message).join('; ');
+ return addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ priority: PRIORITY_LEVELS.HIGH,
+ title: `PR #${watch.prNumber} bypassed the merge gate`,
+ description: `Run ${watch.agentId} ${codes}.${failing.length ? ` ${failing.length} check(s) on the merged head already failed.` : ''}`,
+ link: watch.prUrl,
+ metadata: { agentId: watch.agentId, prNumber: watch.prNumber, headSha: watch.headSha },
+ }).catch((err) => console.error(`❌ Failed to notify about merge-gate violation on PR #${watch.prNumber}: ${err.message}`));
+}
+
+async function recordViolation(agent, watch, violations, checkNames) {
+ emitLog('warn', `🚦 Merge gate bypassed by ${agent.id}: PR #${watch.prNumber} ${violations.map((violation) => violation.message).join('; ')}`,
+ { agentId: agent.id, taskId: agent.taskId, prUrl: watch.prUrl });
+ await appendRunEvent({
+ kind: 'run.merge-gate-violation',
+ runId: agent.metadata?.runId,
+ agentId: agent.id,
+ taskId: agent.taskId,
+ eventId: `merge-gate:${agent.id}:${watch.prNumber}:${watch.headSha}`,
+ data: { prNumber: watch.prNumber, headSha: watch.headSha, mergedAt: watch.mergedAt, codes: watch.codes, checks: checkNames.slice(0, 10) },
+ });
+}
+
+/**
+ * Audit the PRs a completed claim run merged.
+ *
+ * @param {object} params
+ * @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 }>}
+ */
+export async function auditClaimMergeGate({ agentId, task, agentState }) {
+ const metadata = agentState?.metadata || {};
+ const branches = [...new Set([...readList(metadata.claimBranches), metadata.claimBranch].filter((b) => typeof b === 'string' && b))];
+ const none = (skipReason) => ({ audited: 0, violations: 0, skipReason });
+ if (branches.length === 0) return none('not-a-claim-run');
+ if (!metadata.sourceWorkspace) return none('no-source-workspace');
+
+ const origin = await getOriginInfo(metadata.sourceWorkspace).catch(() => null);
+ const repoSpec = githubRepoSpec(origin);
+ if (!repoSpec) return none('not-a-github-repo');
+ const appId = task?.metadata?.app || null;
+ const app = appId ? await getAppById(appId).catch(() => null) : null;
+ const forgeExec = await resolveForgeExecOptions(metadata.sourceWorkspace, { forgeAccount: app?.forgeAccount });
+ const { repositoryKey } = await import('./cosMergeAdmission.js');
+ const repository = repositoryKey(origin);
+ const startedMs = Date.parse(agentState?.startedAt);
+ const since = Number.isFinite(startedMs) ? startedMs : null;
+
+ const audited = new Set(readList(metadata.mergeGateAudits));
+ const newAudits = [];
+ const found = [];
+ let unreadable = false;
+ for (const branch of branches) {
+ const prs = await readMergedPrs({ repoSpec, forgeExec, branch, since });
+ if (prs === null) { unreadable = 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 });
+ 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));
+ 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 });
+
+ const violationRecords = [];
+ for (const { pr, headSha, verdict } of found) {
+ const codes = verdict.violations.map((violation) => violation.code);
+ const watch = {
+ key: watchKey(repository, headSha), repository, agentId, taskId: agentState?.taskId ?? null,
+ prUrl: pr.url, prNumber: pr.number, headSha, baseBranch: pr.baseRefName || 'the default branch',
+ mergedAt: pr.mergedAt, flaggedAt: new Date().toISOString(), codes,
+ };
+ const checkNames = verdict.checks.notGreenAtMerge;
+ await recordViolation({ ...agentState, id: agentId }, watch, verdict.violations, checkNames);
+ await notifyViolation(watch, verdict.violations, verdict.checks.failing);
+ violationRecords.push({ prUrl: pr.url, prNumber: pr.number, headSha, mergedAt: pr.mergedAt, detectedAt: watch.flaggedAt,
+ codes, notGreenAtMerge: checkNames.slice(0, 10) });
+ if (app && verdict.checks.readable) await watchFlaggedHead(watch, verdict.checks, app);
+ }
+
+ if (newAudits.length > 0 || violationRecords.length > 0) {
+ const { updateAgent } = await import('./cosAgentLifecycle.js');
+ await updateAgent(agentId, { metadata: {
+ mergeGateAudits: [...audited, ...newAudits].slice(-LIST_LIMIT),
+ ...(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 };
+}
+
+// Already-failed checks queue the recovery now; checks still running arm a watch
+// that the sweep resolves. Settled-and-green needs no recovery: the default
+// 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;
+ 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);
+}
+
+const pollers = new Map();
+
+// Bounded fast poll after a flag; every callback owns its rejections.
+function scheduleWatchPolls(appId) {
+ if (pollers.has(appId)) return;
+ let polls = 0;
+ const tick = () => {
+ polls += 1;
+ sweepMergeGateWatches({ appId }).then((result) => {
+ if (result.remaining === 0 || polls >= MERGE_GATE_POLL_CAP) pollers.delete(appId);
+ else pollers.set(appId, setTimeout(tick, MERGE_GATE_POLL_INTERVAL_MS).unref());
+ }).catch((err) => {
+ console.error(`❌ Merge-gate watch poll for app ${appId} failed: ${err.message}`);
+ pollers.delete(appId);
+ });
+ };
+ pollers.set(appId, setTimeout(tick, MERGE_GATE_POLL_INTERVAL_MS).unref());
+}
+
+/** Test seam: stop any armed fast polls. */
+export function __cancelMergeGatePolls() {
+ for (const timer of pollers.values()) clearTimeout(timer);
+ pollers.clear();
+}
+
+let sweepInFlight = null;
+
+async function sweepApp(app) {
+ const watches = readWatches(app);
+ if (watches.length === 0) return { checked: 0, recovered: 0, remaining: 0 };
+ const origin = await getOriginInfo(app.repoPath).catch(() => null);
+ const repoSpec = githubRepoSpec(origin);
+ if (!repoSpec) return { checked: 0, recovered: 0, remaining: watches.length };
+ const forgeExec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });
+ const settledKeys = new Set();
+ 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 });
+ 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) => {
+ emitLog('warn', `🚦 Merge-gate recovery for PR #${watch.prNumber} not queued: ${err.message}`, { agentId: watch.agentId });
+ return false;
+ });
+ if (queued) { settledKeys.add(watch.key); recovered += 1; }
+ } else if (checks.readable && checks.settled) {
+ settledKeys.add(watch.key);
+ }
+ }
+ if (settledKeys.size > 0) await mutateWatches(app.id, (current) => current.filter((entry) => !settledKeys.has(entry.key)));
+ return { checked: watches.length, recovered, remaining: watches.length - settledKeys.size };
+}
+
+/**
+ * Resolve every flagged head still being watched: failing checks queue the one
+ * recovery task, settled green checks close the watch.
+ *
+ * @param {{ appId?: string }} [options] limit to one app
+ * @returns {Promise<{ checked: number, recovered: number, remaining: number }>}
+ */
+export function sweepMergeGateWatches({ appId = null } = {}) {
+ // A concurrent sweep joins the one in flight; recovery dedupe rides on the task queue.
+ if (sweepInFlight) return sweepInFlight;
+ sweepInFlight = (async () => {
+ const totals = { checked: 0, recovered: 0, remaining: 0 };
+ const apps = appId ? [await getAppById(appId).catch(() => null)].filter(Boolean) : await getActiveApps().catch(() => []);
+ for (const app of apps.filter((candidate) => readWatches(candidate).length > 0)) {
+ const result = await sweepApp(app).catch((err) => {
+ console.error(`❌ Merge-gate watch sweep failed for ${app.name}: ${err.message}`);
+ return { checked: 0, recovered: 0, remaining: readWatches(app).length };
+ });
+ totals.checked += result.checked;
+ totals.recovered += result.recovered;
+ totals.remaining += result.remaining;
+ }
+ return totals;
+ })().finally(() => { sweepInFlight = null; });
+ return sweepInFlight;
+}
diff --git a/server/services/mergeGateAudit.test.js b/server/services/mergeGateAudit.test.js
new file mode 100644
index 0000000000..5862e71c8f
--- /dev/null
+++ b/server/services/mergeGateAudit.test.js
@@ -0,0 +1,167 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Post-merge gate audit (#12549) at the finalizer boundary: the forge, the
+// 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,
+}));
+
+const execGhMock = vi.fn();
+vi.mock('./github.js', () => ({ execGh: (...args) => execGhMock(...args) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async (cwd) => ({ cwd, env: {} }) }));
+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async () => ({ host: 'github.com', fullName: 'example/repo' }) }));
+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('./cosState.js', () => ({
+ readMergeAdmissionStateForSafetyCheck: async () => ({
+ trusted: true, agents: {}, mergeAdmissions: f.held ? { 'github.com/example/repo': f.held } : {},
+ }),
+}));
+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; },
+}));
+// addTask's real dedupe is first-line + app against open tasks; mirror it.
+const addTaskMock = vi.fn(async (data) => {
+ 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 };
+ f.tasks.push(created);
+ return created;
+});
+vi.mock('./cosTaskStore.js', () => ({ addTask: (...args) => addTaskMock(...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 appendRunEventMock = vi.fn(async () => ({ appended: true }));
+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent: (...args) => appendRunEventMock(...args) }));
+
+import { auditClaimMergeGate, sweepMergeGateWatches, __cancelMergeGatePolls } from './mergeGateAudit.js';
+
+const HEAD = 'a'.repeat(40);
+const PR_URL = 'https://github.com/example/repo/pull/7';
+const MERGED_AT = '2026-10-20T02:16:47Z';
+const task = { id: 'task-agent-1', metadata: { app: 'app1' } };
+
+const run = (agentId = 'agent-1') => auditClaimMergeGate({ agentId, task, agentState: { ...f.agent, id: agentId } });
+const check = (overrides) => ({ name: 'build', status: 'completed', conclusion: 'success', completed_at: '2026-10-20T02:10:00Z', ...overrides });
+const lease = (overrides) => ({ repository: 'github.com/example/repo', outcome: 'merged',
+ acquiredAt: '2026-10-20T02:16:30Z', releasedAt: '2026-10-20T02:16:55Z', ...overrides });
+
+beforeEach(() => {
+ f.agent = {
+ id: 'agent-1', taskId: 'task-agent-1', startedAt: '2026-10-20T02:00:00Z',
+ metadata: { sourceWorkspace: '/repos/source', claimBranches: ['claim/issue-1'], runId: 'run-1' },
+ };
+ f.apps = new Map([['app1', { id: 'app1', name: 'Example App', repoPath: '/repos/source', forgeAccount: null }]]);
+ f.tasks = [];
+ f.held = null;
+ f.prs = [{ number: 7, url: PR_URL, headRefOid: HEAD, mergedAt: MERGED_AT, baseRefName: 'main' }];
+ f.checks = [check()];
+ 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');
+ throw new Error('unexpected forge read');
+ });
+});
+
+afterEach(() => __cancelMergeGatePolls());
+
+describe('post-merge gate audit', () => {
+ it('flags a merge made without a lease before its checks were green and queues ONE recovery when they fail', async () => {
+ // The #12549 incident: merged 25s after the build started, check failed minutes later.
+ f.checks = [check({ name: 'build (22.x)', conclusion: 'failure', completed_at: '2026-10-20T02:20:00Z' })];
+
+ expect(await run()).toMatchObject({ audited: 1, violations: 1 });
+ expect(f.agent.metadata.mergeGateViolations).toEqual([expect.objectContaining({
+ prUrl: PR_URL, prNumber: 7, headSha: HEAD, mergedAt: MERGED_AT,
+ codes: ['no-admission-lease', 'checks-not-green-at-merge'], notGreenAtMerge: ['build (22.x)'],
+ })]);
+ expect(appendRunEventMock).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'run.merge-gate-violation', agentId: 'agent-1', runId: 'run-1',
+ }));
+ expect(notifyMock).toHaveBeenCalledWith(expect.objectContaining({ priority: 'high', link: PR_URL }));
+ expect(f.tasks).toHaveLength(1);
+ expect(f.tasks[0]).toMatchObject({ app: 'app1', isRecovery: true, priority: 'HIGH' });
+ expect(f.tasks[0].description).toContain(HEAD.slice(0, 12));
+
+ // A concurrent run auditing the same merged head queues nothing more, and a
+ // repeat finalize of the first run is a no-op.
+ f.agent = { ...f.agent, id: 'agent-2' };
+ await run('agent-2');
+ await run('agent-2');
+ expect(f.tasks).toHaveLength(1);
+ });
+
+ it('watches a flagged head whose checks are still running and queues the recovery when they finish red', async () => {
+ f.checks = [check({ name: 'build', status: 'in_progress', conclusion: null, completed_at: null })];
+ expect(await run()).toMatchObject({ violations: 1 });
+ expect(f.tasks).toEqual([]);
+ expect(f.apps.get('app1').mergeGateWatches).toEqual([expect.objectContaining({ headSha: HEAD, prNumber: 7 })]);
+
+ f.checks = [check({ name: 'build', conclusion: 'failure', completed_at: '2026-10-20T02:20:00Z' })];
+ expect(await sweepMergeGateWatches()).toMatchObject({ recovered: 1, remaining: 0 });
+ expect(await sweepMergeGateWatches()).toMatchObject({ checked: 0 });
+ expect(f.tasks).toHaveLength(1);
+ expect(f.apps.get('app1').mergeGateWatches).toEqual([]);
+ });
+
+ it('records a lease-only violation but queues no recovery when the head settles green', async () => {
+ f.checks = [check({ name: 'build', status: 'in_progress', conclusion: null, completed_at: null })];
+ f.agent.metadata.mergeAdmissionHistory = [lease()];
+ await run();
+ expect(f.agent.metadata.mergeGateViolations[0].codes).toEqual(['checks-not-green-at-merge']);
+
+ f.checks = [check({ name: 'build', completed_at: '2026-10-20T02:25:00Z' })];
+ expect(await sweepMergeGateWatches()).toMatchObject({ recovered: 0, remaining: 0 });
+ expect(f.tasks).toEqual([]);
+ });
+
+ it('never flags an admission-gated merge on green checks, a held-but-unreleased lease or a coordinator merge', async () => {
+ // Held lease, green checks.
+ f.agent.metadata.mergeAdmissionHistory = [lease()];
+ expect(await run()).toMatchObject({ audited: 1, violations: 0 });
+
+ // The run exited holding the lease it merged under.
+ f.agent.metadata = { ...f.agent.metadata, mergeAdmissionHistory: [], mergeGateAudits: [] };
+ f.held = { kind: 'agent', agentId: 'agent-1', startedAt: f.agent.startedAt, taskId: f.agent.taskId,
+ repository: 'github.com/example/repo', acquiredAt: '2026-10-20T02:16:30Z' };
+ expect(await run()).toMatchObject({ violations: 0 });
+
+ // The coordinator merged the handed-off head under its own lease: no agent
+ // 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' }] };
+ f.checks = [check({ status: 'in_progress', conclusion: null, completed_at: null })];
+ expect(await run()).toMatchObject({ violations: 0 });
+
+ expect(f.agent.metadata.mergeGateViolations).toBeUndefined();
+ expect(f.tasks).toEqual([]);
+ 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 });
+ expect(f.tasks).toEqual([]);
+
+ f.agent.metadata.claimBranches = [];
+ expect(await run()).toMatchObject({ skipReason: 'not-a-claim-run' });
+ });
+});