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

handle-ci-failure.ts

166 lines · 4.8 KB · TypeScript
import { workflows } from 'kody:runtime'
import { isFailureConclusion, parseCiCompletedPayload } from './ci-parse.ts'
import { recheckIdempotencyKey } from './ci-gate.ts'
import { normalizeRepoSlug } from './shared.ts'
import { getAutomation, getCiEpisode } from './storage.ts'

function header(
	headers: Record<string, string> | undefined,
	name: string,
): string {
	if (!headers) return ''
	const want = name.toLowerCase()
	for (const [key, value] of Object.entries(headers)) {
		if (key.toLowerCase() === want) return String(value || '')
	}
	return ''
}

type WebhookInput = {
	webhook?: { name?: string; receivedAt?: string }
	request?: {
		headers?: Record<string, string>
		json?: unknown
		body?: string
	}
	/** Resolve the decision and the would-be re-check without scheduling it. */
	dryRun?: boolean
}

/**
 * Ingest a GitHub CI webhook (check_suite / workflow_run / check_run).
 *
 * Never launches an agent inline. A failure on the configured branch of a
 * configured repo schedules ONE deferred re-check (`./ci-recheck`) via
 * `workflows.create` with `runAt = now + recheckDelaySeconds` (default 60s),
 * keyed per (repo, branch, head SHA, check suite) so the check_suite,
 * workflow_run and check_run deliveries for one CI run collapse to one
 * re-check. The re-check decides whether to launch (head still red, nobody
 * already on it). A non-failure completion only schedules a re-check while a
 * red episode is open, so the episode can reset once the head goes green.
 *
 * @example
 * import handleCiFailure from 'kody:@kentcdodds/codebase-cleanup/handle-ci-failure'
 * await handleCiFailure({
 *   request: {
 *     headers: { 'x-github-event': 'check_suite' },
 *     json: {
 *       action: 'completed',
 *       check_suite: { id: 1, conclusion: 'failure', head_branch: 'main', head_sha: 'abc' },
 *       repository: { full_name: 'acme/widgets' },
 *     },
 *   },
 *   dryRun: true,
 * })
 */
export default async function handleCiFailure(input: WebhookInput = {}) {
	const headers = input.request?.headers ?? {}
	const event = header(headers, 'x-github-event')
	const delivery = header(headers, 'x-github-delivery')
	const dryRun = input.dryRun === true

	if (event === 'ping') {
		return { ok: true, ignored: true, reason: 'ping', delivery }
	}

	const parsed = parseCiCompletedPayload({ event, json: input.request?.json })
	if (!parsed) {
		return { ok: true, ignored: true, reason: 'not-a-completed-ci-event', event, delivery }
	}

	const config = await getAutomation('prod-ci-failure')
	let repo: string
	try {
		repo = normalizeRepoSlug(parsed.repo)
	} catch {
		return { ok: true, ignored: true, reason: 'repo-not-configured', repo: parsed.repo, delivery }
	}
	if (!config.repos.map((r) => normalizeRepoSlug(r)).includes(repo)) {
		return { ok: true, ignored: true, reason: 'repo-not-configured', repo, delivery }
	}

	if (parsed.branch !== config.branch) {
		return {
			ok: true,
			ignored: true,
			reason: 'branch-mismatch',
			branch: parsed.branch,
			expected: config.branch,
			delivery,
		}
	}

	if (!config.enabled && !dryRun) {
		return { ok: true, ignored: true, reason: 'automation-disabled', delivery }
	}

	const failure = isFailureConclusion(parsed.conclusion)
	if (!failure) {
		const episode = await getCiEpisode(repo, parsed.branch)
		if (episode?.status !== 'open') {
			return {
				ok: true,
				ignored: true,
				reason: 'not-a-failure-event',
				conclusion: parsed.conclusion,
				delivery,
			}
		}
	}

	const delayMs = Math.max(0, config.recheckDelaySeconds) * 1000
	const runAt = new Date(Date.now() + delayMs).toISOString()
	const idempotencyKey = recheckIdempotencyKey({
		repo,
		branch: parsed.branch,
		headSha: parsed.headSha,
		checkSuiteId: parsed.checkSuiteId,
		event: parsed.event,
		conclusion: parsed.conclusion,
	})
	const params = {
		repo,
		branch: parsed.branch,
		triggerSha: parsed.headSha,
		trigger: {
			event: parsed.event,
			conclusion: parsed.conclusion,
			checkSuiteId: parsed.checkSuiteId,
			htmlUrl: parsed.htmlUrl,
			workflowName: parsed.workflowName,
			checkName: parsed.checkName,
		},
	}
	const summary = {
		ok: true,
		delivery,
		event: parsed.event,
		repo,
		branch: parsed.branch,
		headSha: parsed.headSha,
		conclusion: parsed.conclusion,
		purpose: failure ? 'failure-recheck' : 'green-reset-check',
		runAt,
		idempotencyKey,
	}

	if (dryRun) {
		return { ...summary, dryRun: true, scheduled: false, params }
	}
	if (!workflows) {
		throw new Error('kody:runtime workflows is unavailable; cannot defer the CI re-check')
	}
	const created = await workflows.create({
		workflowName: 'codebase-cleanup ci-recheck',
		exportName: './ci-recheck',
		runAt,
		idempotencyKey,
		params,
	})
	return {
		...summary,
		scheduled: true,
		workflowId: (created as { id?: string })?.id ?? null,
		workflowStatus: (created as { status?: string })?.status ?? null,
	}
}