Skip to content

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

fix: judge merge-gate checks as they stood at the merge, not after reruns

[._.]/ Adam Eivy443d928c2984
diff --git a/server/lib/README.md b/server/lib/README.md
index 9af85d6b34..36be2704c5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -738,7 +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`. |
+| `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` over `foldHeadChecks`, which dates every run attempt and status post against `mergedAt` so a later rerun or re-posted context cannot rewrite what the merge saw), and exempts a head the pending-merge coordinator marked merged (`receipts`; `awaitsCoordinatorMark` names the unmarked window). `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/mergeGateAudit.js b/server/lib/mergeGateAudit.js
index c983788e40..65c2bafe20 100644
--- a/server/lib/mergeGateAudit.js
+++ b/server/lib/mergeGateAudit.js
@@ -29,14 +29,74 @@ const time = (value) => {
return Number.isFinite(ms) ? ms : null;
};
+const isGreen = (check, mergedMs) => check.status === 'completed' && GREEN_CONCLUSIONS.has(String(check.conclusion || '').toLowerCase())
+ && mergedMs !== null && time(check.completed_at) !== null && time(check.completed_at) <= mergedMs;
+
/**
- * Classify a merged head's check runs against the moment it merged.
+ * Reduce the forge's check-run and commit-status history for a head to one
+ * record per check, as the merge saw it.
+ *
+ * A rerun adds an attempt rather than replacing one, and a status context is
+ * re-posted in place, so the newest record can postdate the merge. Each check's
+ * attempts are dated by when they existed: a run's first attempt by its suite's
+ * creation (a run queued before the merge may not start until well after it), a
+ * rerun by its start, a status by its post time. A check none of whose attempts
+ * existed at `mergedAt` was never something the merge could wait for. Of the rest,
+ * an attempt that was green before the merge stands for the check; otherwise the
+ * newest attempt does, so a head still red (or fixed only after the merge) is
+ * reported as it now stands.
+ *
+ * Forge timestamps on both sides, so no clock-skew allowance applies.
+ *
+ * @param {object} evidence
+ * @param {Array<{id?: number, name?: string, status?: string, conclusion?: string|null, suite?: number, started_at?: string|null, completed_at?: string|null}>} evidence.runs every attempt (`filter=all`)
+ * @param {Array<{id?: number, created_at?: string|null}>} evidence.suites
+ * @param {Array<{context?: string, state?: string, created_at?: string|null}>} evidence.statuses every status posted, in any order
+ * @param {string} mergedAt
+ * @returns {Array<{name: string, status: string, conclusion: string|null, completed_at: string|null}>}
+ */
+export function foldHeadChecks({ runs, suites, statuses }, mergedAt) {
+ const mergedMs = time(mergedAt);
+ const suiteCreated = new Map(suites.map((suite) => [suite.id, time(suite.created_at)]));
+ const groups = new Map();
+ const add = (key, attempt) => groups.set(key, [...(groups.get(key) || []), attempt]);
+
+ for (const run of [...runs].sort((a, b) => (a.id ?? 0) - (b.id ?? 0))) {
+ const key = `run:${run.suite}:${run.name}`;
+ const first = !groups.has(key);
+ const created = suiteCreated.get(run.suite) ?? null;
+ const at = first ? created : (time(run.started_at) ?? created);
+ add(key, { at, check: { name: run.name, status: run.status, conclusion: run.conclusion ?? null, completed_at: run.completed_at ?? null } });
+ }
+ const orderedStatuses = statuses.map((status, index) => ({ status, index, at: time(status.created_at) }))
+ .sort((a, b) => (a.at ?? 0) - (b.at ?? 0) || b.index - a.index);
+ for (const { status, at } of orderedStatuses) {
+ add(`status:${status.context}`, { at, check: {
+ name: status.context,
+ status: status.state === 'pending' ? 'in_progress' : 'completed',
+ conclusion: status.state === 'error' ? 'failure' : status.state,
+ completed_at: status.created_at ?? null,
+ } });
+ }
+
+ const folded = [];
+ for (const attempts of groups.values()) {
+ const existing = attempts.filter((attempt) => attempt.at === null || mergedMs === null || attempt.at <= mergedMs);
+ if (existing.length === 0) continue;
+ const atMerge = existing[existing.length - 1].check;
+ folded.push(isGreen(atMerge, mergedMs) ? atMerge : attempts[attempts.length - 1].check);
+ }
+ return folded;
+}
+
+/**
+ * Classify a merged head's folded checks (`foldHeadChecks`) 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, created_at?: string|null, completed_at?: string|null}>|null} checks
+ * @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 }}
*/
@@ -47,21 +107,11 @@ export function classifyHeadChecks(checks, mergedAt) {
const failing = [];
let settled = true;
for (const check of checks) {
- // A run whose suite was created after the merge (a manual rerun, a scheduled
- // workflow) was never something the merge could have waited for, so it can
- // neither flag the merge nor drive a recovery. Judged by creation, not start:
- // a check queued before the merge may not begin until well after it.
- const createdMs = time(check?.created_at);
- if (createdMs !== null && mergedMs !== null && createdMs > mergedMs + LEASE_CLOCK_SKEW_MS) continue;
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);
+ if (completed && RED_CONCLUSIONS.has(String(check?.conclusion || '').toLowerCase())) failing.push(name);
+ if (!isGreen(check || {}, mergedMs)) notGreenAtMerge.push(name);
}
return { readable: true, notGreenAtMerge, failing, settled };
}
@@ -98,6 +148,20 @@ function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = null
});
}
+const sameHandoff = (receipt, prUrl, headSha) => String(receipt?.prUrl || '').toLowerCase() === String(prUrl || '').toLowerCase()
+ && String(receipt?.headSha || '').toLowerCase() === String(headSha || '').toLowerCase();
+
+/**
+ * Was this PR handed to the pending-merge coordinator without the coordinator
+ * having recorded a merge of it? The coordinator marks its receipt just after
+ * its merge call succeeds, so within that window an unmarked receipt cannot yet
+ * tell the coordinator's merge from the run's own.
+ */
+export function awaitsCoordinatorMark({ receipts = [], prUrl, headSha }) {
+ const matching = receipts.filter((receipt) => sameHandoff(receipt, prUrl, headSha));
+ return matching.length > 0 && !matching.some((receipt) => receipt.coordinatorMergedAt);
+}
+
/**
* Judge one merged claim PR.
*
@@ -119,10 +183,7 @@ function leaseCoversMerge({ repository, mergedAt, history = [], heldLease = null
*/
export function assessMergeGate({ repository, prUrl, headSha, mergedAt, receipts = [], history = [], heldLease = null, checks }) {
const classification = classifyHeadChecks(checks, mergedAt);
- const head = String(headSha || '').toLowerCase();
- const pr = String(prUrl || '').toLowerCase();
- if (receipts.some((receipt) => receipt?.coordinatorMergedAt && String(receipt.prUrl || '').toLowerCase() === pr
- && String(receipt.headSha || '').toLowerCase() === head)) {
+ if (receipts.some((receipt) => receipt?.coordinatorMergedAt && sameHandoff(receipt, prUrl, headSha))) {
return { exempt: true, violations: [], checks: classification };
}
const violations = [];
diff --git a/server/services/mergeGateAudit.js b/server/services/mergeGateAudit.js
index 32c70af4a3..9d103a3834 100644
--- a/server/services/mergeGateAudit.js
+++ b/server/services/mergeGateAudit.js
@@ -24,7 +24,7 @@ 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';
+import { assessMergeGate, awaitsCoordinatorMark, classifyHeadChecks, foldHeadChecks, 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.
@@ -36,6 +36,10 @@ const MERGE_GATE_POLL_CAP = 15;
const LIST_LIMIT = 50;
const SHORT_SHA = 12;
+// The coordinator marks its receipt just after its merge call returns; a merge
+// this recent whose receipt is still unmarked is judged on the next sweep.
+const COORDINATOR_MARK_GRACE_MS = 2 * 60 * 1000;
+
const MERGED_PR_FIELDS = 'number,url,headRefOid,mergedAt,baseRefName';
const readList = (value) => (Array.isArray(value) ? value : []);
@@ -43,11 +47,12 @@ 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);
-// Commit statuses (CI that reports through the status API rather than check
-// runs) are mapped onto the check-run shape.
-const CHECK_RUN_JQ = '.check_runs[] | {name, status, conclusion, suite: .check_suite.id, completed_at}';
+// Every attempt and every posted status, not the latest per name: the audit asks
+// what existed at the merge, and a rerun or re-posted context since then replaces
+// the answer. Commit statuses cover CI that reports outside the check-run API.
+const CHECK_RUN_JQ = '.check_runs[] | {id, name, status, conclusion, suite: .check_suite.id, started_at, completed_at}';
const CHECK_SUITE_JQ = '.check_suites[] | {id, created_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}';
+const STATUS_JQ = '.[] | {context, state, created_at}';
async function readGhLines({ origin, repoSpec, forgeExec, path, jq }) {
const raw = await execGh([
@@ -58,21 +63,16 @@ async function readGhLines({ origin, repoSpec, forgeExec, path, jq }) {
return rows.every(isPlainObject) ? rows : null;
}
-/**
- * The check runs and commit statuses of `headSha`, or null when any read failed.
- * Each run carries its suite's `created_at`; a status has no creation time worth
- * trusting (its context flips pending to success in place) and carries none.
- */
-async function readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha }) {
+/** The checks of `headSha` as they stood at `mergedAt` (`foldHeadChecks`), or null when any read failed. */
+async function readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha, mergedAt }) {
const base = `repos/${origin.fullName}/commits/${headSha}`;
const [runs, suites, 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}/check-runs?filter=all&per_page=100`, jq: CHECK_RUN_JQ }),
readGhLines({ origin, repoSpec, forgeExec, path: `${base}/check-suites?per_page=100`, jq: CHECK_SUITE_JQ }),
- readGhLines({ origin, repoSpec, forgeExec, path: `${base}/status?per_page=100`, jq: STATUS_JQ }),
+ readGhLines({ origin, repoSpec, forgeExec, path: `${base}/statuses?per_page=100`, jq: STATUS_JQ }),
]);
if (!runs || !suites || !statuses) return null;
- const created = new Map(suites.map((suite) => [suite.id, suite.created_at]));
- return [...runs.map(({ suite, ...run }) => ({ ...run, created_at: created.get(suite) ?? null })), ...statuses];
+ return foldHeadChecks({ runs, suites, statuses }, mergedAt);
}
async function readMergedPrs({ repoSpec, forgeExec, branch, since }) {
@@ -87,6 +87,11 @@ async function readMergedPrs({ repoSpec, forgeExec, branch, since }) {
&& Number.isFinite(Date.parse(pr.mergedAt)) && (since === null || Date.parse(pr.mergedAt) >= since));
}
+async function getAgentRecord(agentId) {
+ const lifecycle = await import('./cosAgentLifecycle.js');
+ return lifecycle.getAgentRecord(agentId);
+}
+
/** 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');
@@ -208,14 +213,21 @@ export async function auditClaimMergeGate({ agentId, task, agentState }) {
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 });
+ const checks = await readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha, mergedAt: pr.mergedAt });
// No verdict without readable evidence; the durable sweep retries the audit.
if (checks === null) { unresolved = true; continue; }
+ // The coordinator may have merged and marked its receipt while the forge was
+ // being read, so judge against the run's record as it stands now.
+ const current = (await getAgentRecord(agentId).catch(() => null))?.metadata || metadata;
+ const receipts = readList(current.mergeHandoffReceipts);
+ if (awaitsCoordinatorMark({ receipts, prUrl: pr.url, headSha }) && Date.now() - Date.parse(pr.mergedAt) < COORDINATOR_MARK_GRACE_MS) {
+ unresolved = true;
+ continue;
+ }
const heldLease = await readHeldLease({ ...agentState, id: agentId }, repository);
const verdict = assessMergeGate({
- repository, prUrl: pr.url, headSha, mergedAt: pr.mergedAt, checks, heldLease,
- receipts: readList(metadata.mergeHandoffReceipts),
- history: [...readList(metadata.mergeAdmissionHistory), ...(metadata.lastMergeAdmission ? [metadata.lastMergeAdmission] : [])],
+ repository, prUrl: pr.url, headSha, mergedAt: pr.mergedAt, checks, heldLease, receipts,
+ history: [...readList(current.mergeAdmissionHistory), ...(current.lastMergeAdmission ? [current.lastMergeAdmission] : [])],
});
newAudits.push(auditKey(pr));
if (verdict.violations.length === 0) continue;
@@ -310,7 +322,6 @@ 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 })
@@ -340,7 +351,7 @@ async function sweepApp(app) {
if (await retryPendingAudit(watch, app)) settledKeys.add(watch.key);
continue;
}
- const checks = classifyHeadChecks(await readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha: watch.headSha }), watch.mergedAt);
+ const checks = classifyHeadChecks(await readHeadCheckRuns({ origin, repoSpec, forgeExec, headSha: watch.headSha, mergedAt: watch.mergedAt }), 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 });
diff --git a/server/services/mergeGateAudit.test.js b/server/services/mergeGateAudit.test.js
index 7a654be9ba..4235a8b75d 100644
--- a/server/services/mergeGateAudit.test.js
+++ b/server/services/mergeGateAudit.test.js
@@ -53,7 +53,9 @@ 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', suite: 1, completed_at: '2026-10-20T02:10:00Z', ...overrides });
+let runId = 0;
+const check = (overrides) => ({ id: ++runId, name: 'build', status: 'completed', conclusion: 'success', suite: 1,
+ started_at: '2026-10-20T02:09:30Z', 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 });
@@ -182,7 +184,11 @@ describe('post-merge gate audit', () => {
// A push workflow on the merge commit was never something the merge could wait for.
check({ name: 'post-merge deploy', suite: 2, conclusion: 'failure', completed_at: '2026-10-20T02:31:00Z' }),
];
- f.statuses = [{ name: 'ci/legacy', status: 'completed', conclusion: 'failure', completed_at: '2026-10-20T02:20:00Z' }];
+ // Newest first, as the statuses API lists them.
+ f.statuses = [
+ { context: 'ci/legacy', state: 'failure', created_at: '2026-10-20T02:20:00Z' },
+ { context: 'ci/legacy', state: 'pending', created_at: '2026-10-20T02:10:00Z' },
+ ];
await run();
expect(f.agent.metadata.mergeGateViolations).toEqual([expect.objectContaining({
codes: ['no-admission-lease', 'checks-not-green-at-merge'], notGreenAtMerge: ['ci/legacy'],
@@ -192,6 +198,67 @@ describe('post-merge gate audit', () => {
expect(f.tasks[0].context).not.toContain('post-merge deploy');
});
+ it('judges a check as the merge saw it, not by what a rerun or re-posted status says since', async () => {
+ f.agent.metadata.mergeAdmissionHistory = [lease()];
+ f.checks = [
+ check({ name: 'unit' }),
+ // Rerun of a green attempt, started and failing after the merge.
+ check({ name: 'unit', status: 'in_progress', conclusion: null, started_at: '2026-10-20T02:40:00Z', completed_at: null }),
+ check({ name: 'lint' }),
+ check({ name: 'lint', conclusion: 'failure', started_at: '2026-10-20T02:41:00Z', completed_at: '2026-10-20T02:42:00Z' }),
+ ];
+ f.statuses = [
+ { context: 'ci/legacy', state: 'failure', created_at: '2026-10-20T02:50:00Z' },
+ { context: 'ci/legacy', state: 'success', created_at: '2026-10-20T02:12:00Z' },
+ { context: 'ci/legacy', state: 'pending', created_at: '2026-10-20T02:10:00Z' },
+ ];
+ expect(await run()).toMatchObject({ audited: 1, violations: 0 });
+ expect(f.tasks).toEqual([]);
+ });
+
+ it('flags a merge on a check that was red at the merge even when a later rerun went green', async () => {
+ f.agent.metadata.mergeAdmissionHistory = [lease()];
+ f.checks = [
+ check({ conclusion: 'failure' }),
+ check({ started_at: '2026-10-20T02:30:00Z', completed_at: '2026-10-20T02:35:00Z' }),
+ ];
+ expect(await run()).toMatchObject({ violations: 1 });
+ expect(f.agent.metadata.mergeGateViolations[0]).toMatchObject({ codes: ['checks-not-green-at-merge'], notGreenAtMerge: ['build'] });
+ expect(f.tasks).toEqual([]);
+ });
+
+ it('does not count a check suite created moments after the merge against it', async () => {
+ f.agent.metadata.mergeAdmissionHistory = [lease()];
+ f.suites = [{ id: 1, created_at: '2026-10-20T02:09:00Z' }, { id: 2, created_at: '2026-10-20T02:17:00Z' }];
+ f.checks = [check(), check({ name: 'post-merge deploy', suite: 2, status: 'in_progress', conclusion: null, completed_at: null })];
+ expect(await run()).toMatchObject({ violations: 0 });
+ });
+
+ it('reads the run record again after the forge reads so a coordinator mark that landed meanwhile exempts the merge', async () => {
+ const unmarked = { receiptId: 'receipt-1', prUrl: PR_URL, headSha: HEAD, acceptedAt: '2026-10-20T02:10:00Z' };
+ f.agent.metadata.mergeHandoffReceipts = [unmarked];
+ const marked = { ...unmarked, coordinatorMergedAt: MERGED_AT };
+ execGhMock.mockImplementationOnce(async () => JSON.stringify(f.prs)).mockImplementation(async (args) => {
+ if (args[0] === 'pr') return JSON.stringify(f.prs);
+ // The coordinator's mark lands while the check reads are in flight.
+ f.agent = { ...f.agent, metadata: { ...f.agent.metadata, mergeHandoffReceipts: [marked] } };
+ const path = args.find((arg) => String(arg).startsWith('repos/'));
+ const rows = path.includes('/check-suites') ? f.suites : path.includes('/statuses') ? f.statuses : f.checks;
+ return rows.map((c) => JSON.stringify(c)).join('\n');
+ });
+ expect(await run()).toMatchObject({ audited: 1, violations: 0 });
+ expect(f.tasks).toEqual([]);
+ });
+
+ it('holds the verdict on a just-merged head whose handoff receipt the coordinator has not marked yet', async () => {
+ f.agent.metadata.mergeHandoffReceipts = [{ receiptId: 'receipt-1', prUrl: PR_URL, headSha: HEAD, acceptedAt: '2026-10-20T02:10:00Z' }];
+ f.prs = [{ ...f.prs[0], mergedAt: new Date(Date.now() - 10 * 1000).toISOString() }];
+ f.checks = [check({ completed_at: '2026-10-20T02:10:00Z' })];
+ 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' })]);
+ });
+
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 });