Skip to content
← Public packages

@kentcdodds/codebase-cleanup

Cursor cloud agents for legacy cleanup, docs freshness, tight tests, and prod CI fixes, plus a weekly Devin general audit.

FollowFork

Files

ci-gate.ts

129 lines · 4.0 KB · TypeScript
/**
 * Pure decision helpers for prod-ci-failure's deferred re-check
 * (no kody:runtime imports, so they unit-test directly).
 */
import type { OpenPullSummary, WorkflowRunSummary } from './github.ts'
import { isFailureConclusion } from './ci-parse.ts'

export type HeadCiVerdict = {
	/**
	 * red: the latest attempt of at least one relevant workflow failed/timed out.
	 * pending: nothing red yet, but a relevant workflow is still running.
	 * green: every relevant workflow's latest attempt completed without failure.
	 * unknown: no relevant workflow runs found for the head (yet), or only
	 * cancelled ones. Neither launches nor resets.
	 */
	state: 'red' | 'pending' | 'green' | 'unknown'
	failing: Array<{ name: string; conclusion: string; url: string; runId: number }>
	pending: Array<{ name: string; status: string; url: string }>
	considered: number
}

function matchesWorkflowFilter(run: WorkflowRunSummary, filters: string[]) {
	if (filters.length === 0) return true
	const name = run.name.toLowerCase()
	const path = run.path.toLowerCase()
	return filters.some((raw) => {
		const f = raw.toLowerCase()
		return name.includes(f) || path === f || path.endsWith(`/${f}`)
	})
}

/**
 * Decide whether the branch head is red from its workflow runs.
 * Only push-triggered runs on `branch` count (deploys chained via
 * workflow_run, CLA issue_comment runs, etc. are ignored); `ciWorkflows`
 * narrows further. Each workflow is judged by its newest attempt.
 */
export function evaluateHeadCi(input: {
	runs: WorkflowRunSummary[]
	branch: string
	ciWorkflows?: string[]
}): HeadCiVerdict {
	const filters = (input.ciWorkflows ?? []).map((f) => f.trim()).filter(Boolean)
	const relevant = input.runs.filter(
		(r) =>
			r.event === 'push' &&
			r.head_branch === input.branch &&
			matchesWorkflowFilter(r, filters),
	)
	const latest = new Map<number, WorkflowRunSummary>()
	for (const run of relevant) {
		const prev = latest.get(run.workflow_id)
		if (
			!prev ||
			run.run_attempt > prev.run_attempt ||
			(run.run_attempt === prev.run_attempt && run.created_at > prev.created_at)
		) {
			latest.set(run.workflow_id, run)
		}
	}
	const failing: HeadCiVerdict['failing'] = []
	const pending: HeadCiVerdict['pending'] = []
	let completedOk = 0
	for (const run of latest.values()) {
		if (run.status !== 'completed') {
			pending.push({ name: run.name, status: run.status, url: run.html_url })
		} else if (run.conclusion && isFailureConclusion(run.conclusion)) {
			failing.push({
				name: run.name,
				conclusion: run.conclusion,
				url: run.html_url,
				runId: run.id,
			})
		} else if (run.conclusion !== 'cancelled') {
			completedOk += 1
		}
	}
	const state: HeadCiVerdict['state'] =
		failing.length > 0
			? 'red'
			: pending.length > 0
				? 'pending'
				: completedOk > 0
					? 'green'
					: 'unknown'
	return { state, failing, pending, considered: latest.size }
}

/**
 * Best-effort: an open PR that already says it addresses this failure, by
 * naming the red head SHA (7+ chars) or one of the failing run ids/URLs.
 */
export function findAddressingPull(input: {
	pulls: OpenPullSummary[]
	headSha: string
	failing: HeadCiVerdict['failing']
}) {
	const shortSha = input.headSha.slice(0, 7)
	const needles = [
		shortSha,
		...input.failing.flatMap((f) => [String(f.runId), f.url]).filter(Boolean),
	].filter((n) => n.length >= 7)
	if (needles.length === 0) return null
	return (
		input.pulls.find((p) => {
			const text = `${p.title}\n${p.body}`
			return needles.some((n) => text.includes(n))
		}) ?? null
	)
}

/**
 * One deferred re-check per (repo, branch, head SHA, check suite). check_suite,
 * workflow_run and check_run deliveries for the same CI run share the suite id,
 * so they collapse onto one workflow.
 */
export function recheckIdempotencyKey(input: {
	repo: string
	branch: string
	headSha: string
	checkSuiteId: string | null
	event: string
	conclusion: string
}) {
	const suite = input.checkSuiteId
		? `suite-${input.checkSuiteId}`
		: `${input.event}-${input.conclusion}`
	return `codebase-cleanup:ci-recheck:${input.repo}:${input.branch}:${input.headSha}:${suite}`
}