/** * Post-merge watch: after an implementer's PR merges, the factory watches the * merge commit's checks on the default branch. On red it messages the same * implementer session to fix main; if main is not green again within * `postMergeFixTimeoutMinutes`, it queues a P0 red-main repair work item that * the normal sweep hands to a fresh agent (same slot, scope, and shadow rules). * The factory never merges and never reverts. */ import { githubReadonlyRequest, type GithubFetch } from '../lib/github-readonly.ts' import { summarizeChecks } from '../exports/refresh-pr.ts' import { rankOf } from './priority-queue.ts' import { newWorkItemId, nowIso, type Ledger, type WorkItem } from './work-item.ts' export type PostMergePhase = | 'watching' | 'implementer-notified' | 'green' | 'fixed' | 'fallback-queued' | 'gave-up' export type PostMergeWatch = { repoRef: string prUrl: string mergeCommit: string startedAt: string phase: PostMergePhase implementerRunId: string | null notifiedAt?: string fallbackItemId?: string checkedAt?: string note?: string } export const ACTIVE_WATCH: ReadonlySet = new Set(['watching', 'implementer-notified']) export type PostMergeSettings = { /** Minutes the implementer has to get main green before a fallback agent is queued. */ postMergeFixTimeoutMinutes: number /** Minutes to wait for the merge commit's checks to report at all before giving up. */ postMergePendingTimeoutMinutes: number } export type PostMergeDeps = { github: GithubFetch | null /** Send a message to the implementer session; false when the runner cannot or the send failed. */ notify: (runId: string, message: string) => Promise shadowMode: boolean now?: () => number } export type PostMergeOutcome = { workItemId: string; from: PostMergePhase; to: PostMergePhase; reason: string } const MIN = 60_000 export function beginWatch(item: WorkItem, mergeCommit: string | undefined, at = nowIso()): WorkItem { if (!item.pr || !item.repoRef || !mergeCommit || !/^[0-9a-f]{40}$/.test(mergeCommit)) return item if (item.postMerge) return item return { ...item, postMerge: { repoRef: item.repoRef, prUrl: item.pr.url, mergeCommit, startedAt: at, phase: 'watching', implementerRunId: item.runId ?? null }, } } function repoPath(repoRef: string): string { const [owner, name] = repoRef.split('/') return `/repos/${encodeURIComponent(owner!)}/${encodeURIComponent(name!)}` } async function commitChecks(gh: GithubFetch, repoRef: string, sha: string) { return summarizeChecks(await githubReadonlyRequest(gh, `${repoPath(repoRef)}/commits/${sha}/check-runs?per_page=100`)) } async function failingNames(gh: GithubFetch, repoRef: string, sha: string): Promise { const r = await githubReadonlyRequest<{ check_runs?: Array<{ name?: string; conclusion?: string | null }> }>(gh, `${repoPath(repoRef)}/commits/${sha}/check-runs?per_page=100`) return (r.check_runs ?? []).filter((c) => c.conclusion && !['success', 'neutral', 'skipped'].includes(c.conclusion)).map((c) => String(c.name ?? 'check')).slice(0, 10) } /** Head of the default branch and its checks (green again = fixed). */ async function mainHead(gh: GithubFetch, repoRef: string): Promise<{ sha: string; checks: ReturnType } | null> { const repo = await githubReadonlyRequest<{ default_branch?: string }>(gh, repoPath(repoRef)) const branch = repo.default_branch || 'main' const c = await githubReadonlyRequest<{ sha?: string }>(gh, `${repoPath(repoRef)}/commits/${encodeURIComponent(branch)}`) if (!c.sha || !/^[0-9a-f]{40}$/.test(c.sha)) return null return { sha: c.sha, checks: await commitChecks(gh, repoRef, c.sha) } } export function implementerMessage(w: PostMergeWatch, failing: string[], timeoutMin: number): string { return [ `Main CI failed after your PR merged (${w.prUrl}, merge commit ${w.mergeCommit.slice(0, 12)} on ${w.repoRef}).`, failing.length ? `Failing checks: ${failing.join(', ')}.` : '', 'Please check whether your merge broke main. If it did, open one focused fix PR against the default branch (do not force-push, do not revert unrelated work).', `If main is not green again within ${timeoutMin} minutes, the factory hands the repair to another agent.`, ].filter(Boolean).join('\n') } export function fallbackItem(parent: WorkItem, w: PostMergeWatch, failing: string[], at = nowIso()): WorkItem { const title = `Red main after ${w.prUrl.replace('https://github.com/', '')} (${w.mergeCommit.slice(0, 7)})` return { id: newWorkItemId(), projectId: parent.projectId, title, body: [ `Main CI on ${w.repoRef} went red at merge commit ${w.mergeCommit} from ${w.prUrl}, and the implementer did not get it green in time.`, failing.length ? `Failing checks at the merge commit: ${failing.join(', ')}.` : '', 'Find what broke main and open one focused fix PR. If main is already green, stop and report that.', ].filter(Boolean).join('\n\n'), state: 'planned', priority: 0, needsKent: false, rank: rankOf(0, false), source: 'ci-failure', externalId: w.mergeCommit, fingerprint: `red-main:${w.repoRef.toLowerCase()}:${w.mergeCommit}`, signalIds: [], labels: ['P0', 'red-main'], repoRef: w.repoRef, planCardId: null, runId: null, createdAt: at, updatedAt: at, events: [{ at, from: null, to: 'planned', reason: `red-main fallback for ${parent.id}`, actor: 'sweep', meta: { parent: parent.id, mergeCommit: w.mergeCommit } }], shadow: false, links: [{ kind: 'pr', url: w.prUrl, label: 'merged PR', reason: 'red-main', at }], } } function setPhase(item: WorkItem, to: PostMergePhase, reason: string, patch: Partial, at: string): WorkItem { const w = item.postMerge! return { ...item, postMerge: { ...w, ...patch, phase: to, checkedAt: at, note: reason }, updatedAt: at, events: [...item.events, { at, from: item.state, to: item.state, reason: `post-merge: ${reason}`, actor: 'sweep', meta: { postMerge: to, mergeCommit: w.mergeCommit } }], } } /** * Advance one item's post-merge watch by at most one phase. Mutates the ledger * (caller decides whether to save). In shadow mode it observes only: no * messages and no fallback items. */ export async function advanceWatch(ledger: Ledger, itemId: string, s: PostMergeSettings, deps: PostMergeDeps): Promise { const item = ledger.items[itemId] const w = item?.postMerge if (!item || !w || !ACTIVE_WATCH.has(w.phase) || !deps.github) return null const now = deps.now?.() ?? Date.now() const at = new Date(now).toISOString() const out = (to: PostMergePhase, reason: string, patch: Partial = {}): PostMergeOutcome => { ledger.items[itemId] = setPhase(item, to, reason, patch, at) return { workItemId: itemId, from: w.phase, to, reason } } if (w.phase === 'watching') { const checks = await commitChecks(deps.github, w.repoRef, w.mergeCommit) if (checks === 'success') return out('green', 'main checks passed on the merge commit') if (checks === 'pending' || checks === 'none') { if (now - Date.parse(w.startedAt) > s.postMergePendingTimeoutMinutes * MIN) return out('gave-up', `merge commit checks still ${checks} after ${s.postMergePendingTimeoutMinutes} min`) return null } const failing = await failingNames(deps.github, w.repoRef, w.mergeCommit) if (deps.shadowMode) return out('gave-up', `shadow: main red after merge (${failing.join(', ') || 'checks failed'}); would notify the implementer`) const sent = w.implementerRunId ? await deps.notify(w.implementerRunId, implementerMessage(w, failing, s.postMergeFixTimeoutMinutes)) : false if (sent) return out('implementer-notified', `main red after merge; asked implementer ${w.implementerRunId} to fix`, { notifiedAt: at }) const fb = fallbackItem(item, w, failing, at) if (!Object.values(ledger.items).some((i) => i.fingerprint === fb.fingerprint)) ledger.items[fb.id] = fb return out('fallback-queued', `main red after merge; implementer unreachable, queued ${fb.id}`, { fallbackItemId: fb.id }) } // implementer-notified: fixed when main's head is green again. const head = await mainHead(deps.github, w.repoRef) if (head && head.checks === 'success') return out('fixed', `main green again at ${head.sha.slice(0, 7)}`) const notifiedAt = Date.parse(w.notifiedAt ?? w.startedAt) if (now - notifiedAt <= s.postMergeFixTimeoutMinutes * MIN) return null if (deps.shadowMode) return null const failing = await failingNames(deps.github, w.repoRef, w.mergeCommit).catch(() => []) const fb = fallbackItem(item, w, failing, at) if (!Object.values(ledger.items).some((i) => i.fingerprint === fb.fingerprint)) ledger.items[fb.id] = fb return out('fallback-queued', `implementer did not get main green within ${s.postMergeFixTimeoutMinutes} min; queued ${fb.id}`, { fallbackItemId: fb.id }) } /** Read a GitHub PR's merge state. */ export async function readPrMerge(gh: GithubFetch, prUrl: string): Promise<{ merged: boolean; mergeCommit: string | null }> { const m = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)$/.exec(prUrl) if (!m) return { merged: false, mergeCommit: null } const pr = await githubReadonlyRequest<{ merged?: boolean; merge_commit_sha?: string | null }>(gh, `/repos/${encodeURIComponent(m[1]!)}/${encodeURIComponent(m[2]!)}/pulls/${m[3]}`) const sha = pr.merge_commit_sha && /^[0-9a-f]{40}$/.test(pr.merge_commit_sha) ? pr.merge_commit_sha : null return { merged: pr.merged === true && sha != null, mergeCommit: sha } }