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-recheck.ts

166 lines · 5.3 KB · TypeScript
import { evaluateHeadCi, findAddressingPull } from './ci-gate.ts'
import {
	getBranchHeadSha,
	listOpenPullsForBase,
	listWorkflowRunsForSha,
} from './github.ts'
import runNow from './run.ts'
import { normalizeRepoSlug } from './shared.ts'
import {
	attachCiEpisodeAgent,
	claimCiEpisode,
	closeCiEpisode,
	getAutomation,
	getCiEpisode,
	touchCiEpisode,
} from './storage.ts'

export type CiRecheckInput = {
	repo: string
	branch: string
	/** SHA from the webhook that scheduled this re-check (may no longer be head). */
	triggerSha?: string
	trigger?: {
		event?: string
		conclusion?: string
		checkSuiteId?: string | null
		htmlUrl?: string | null
		workflowName?: string | null
		checkName?: string | null
	}
	/** Resolve everything but never claim, launch, or close. */
	dryRun?: boolean
}

/**
 * Deferred re-check for prod-ci-failure. The webhook schedules this through
 * `workflows.create({ runAt: now + recheckDelaySeconds })`; it never runs
 * inside the webhook request.
 *
 * Re-reads the branch head from GitHub and:
 * - green → closes the open episode (main recovered; the next red launches again)
 * - pending / unknown → does nothing (the head's own completion event re-checks)
 * - red + open episode → skips; something already owns this red stretch
 * - red + open PR naming the red SHA / failing run → records it and skips
 * - red otherwise → atomically claims the episode, then launches one agent
 *
 * @example
 * import ciRecheck from 'kody:@kentcdodds/codebase-cleanup/ci-recheck'
 * await ciRecheck({ repo: 'acme/widgets', branch: 'main', dryRun: true })
 */
export default async function ciRecheck(input: CiRecheckInput) {
	if (!input || typeof input.repo !== 'string' || typeof input.branch !== 'string') {
		throw new Error('repo and branch are required')
	}
	const repo = normalizeRepoSlug(input.repo)
	const branch = input.branch
	const dryRun = input.dryRun === true
	const config = await getAutomation('prod-ci-failure')
	const base = { ok: true as const, repo, branch, dryRun, triggerSha: input.triggerSha ?? null }

	if (!config.enabled && !dryRun) {
		return { ...base, action: 'skip', reason: 'automation-disabled' }
	}

	const headSha = await getBranchHeadSha({ repo, branch })
	const runs = await listWorkflowRunsForSha({ repo, sha: headSha })
	const verdict = evaluateHeadCi({ runs, branch, ciWorkflows: config.ciWorkflows })
	const episode = await getCiEpisode(repo, branch)
	const withHead = { ...base, headSha, verdict: verdict.state, failing: verdict.failing }

	if (verdict.state === 'green') {
		if (episode?.status === 'open') {
			if (!dryRun) {
				await closeCiEpisode({ repo, branch, sha: headSha, note: null })
			}
			return { ...withHead, action: 'reset', reason: 'head-green', closedEpisode: episode }
		}
		return { ...withHead, action: 'skip', reason: 'head-green' }
	}

	if (verdict.state !== 'red') {
		return { ...withHead, action: 'skip', reason: `head-${verdict.state}`, pending: verdict.pending }
	}

	if (episode?.status === 'open') {
		if (!dryRun) await touchCiEpisode({ repo, branch, sha: headSha })
		return { ...withHead, action: 'skip', reason: 'agent-already-working', episode }
	}

	let pull: ReturnType<typeof findAddressingPull> = null
	try {
		const pulls = await listOpenPullsForBase({ repo, base: branch })
		pull = findAddressingPull({ pulls, headSha, failing: verdict.failing })
	} catch {
		// Best effort only: a PR lookup failure must not block the fix.
		pull = null
	}
	if (pull) {
		if (!dryRun) {
			await claimCiEpisode({
				repo,
				branch,
				sha: headSha,
				source: 'external-pr',
				note: `Open PR already addresses this failure: ${pull.html_url}`,
			})
		}
		return { ...withHead, action: 'skip', reason: 'pr-already-open', pull: pull.html_url }
	}

	if (dryRun) {
		return { ...withHead, action: 'would-launch' }
	}

	const claimed = await claimCiEpisode({ repo, branch, sha: headSha, source: 'automation' })
	if (!claimed) {
		return {
			...withHead,
			action: 'skip',
			reason: 'agent-already-working',
			episode: await getCiEpisode(repo, branch),
		}
	}

	const first = verdict.failing[0]
	const launch = await runNow({
		automation: 'prod-ci-failure',
		repo,
		ignoreEnabled: true,
		ci: {
			headSha,
			conclusion: first?.conclusion ?? input.trigger?.conclusion,
			htmlUrl: first?.url ?? input.trigger?.htmlUrl ?? null,
			workflowName: verdict.failing.map((f) => f.name).join(', ') || null,
			checkName: input.trigger?.checkName ?? null,
			event: input.trigger?.event,
		},
	})
	const result = (launch as { results?: Array<Record<string, unknown>> }).results?.[0] ?? {}

	if (result.spawned === true || result.skipped === 'already-launched-for-sha') {
		await attachCiEpisodeAgent({
			repo,
			branch,
			agentId: (result.agentId as string | null) ?? null,
			agentUrl: (result.agentUrl as string | null) ?? null,
		})
		return {
			...withHead,
			action: result.spawned === true ? 'launched' : 'skip',
			reason: result.spawned === true ? 'head-red' : 'already-launched-for-sha',
			agentId: result.agentId ?? null,
			agentUrl: result.agentUrl ?? null,
		}
	}

	// Launch failed or was skipped for another reason: release the claim so the
	// next failure event can try again.
	await closeCiEpisode({
		repo,
		branch,
		sha: null,
		note: `released: ${String(result.error ?? result.skipped ?? 'launch did not spawn').slice(0, 180)}`,
	})
	return { ...withHead, action: 'error', reason: 'launch-failed', launch: result }
}