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

scoped-run.ts

147 lines · 5.9 KB · TypeScript
import { hasCommitsInLast24h } from './github.ts'
import { resolvePrompt } from './prompts.ts'
import { scopedTemplates } from './prompts/templates.ts'
import {
	branchNameFor,
	buildScope,
	chunkFilesBlock,
	denverWeekday,
	isCodePath,
	reasonsBlock,
	type ScopedAutomation,
} from './scope-core.ts'
import { baseFromLookback, compareFiles, findLastFix, getHeadSha, laterOf, repoPathsAt } from './scope.ts'
import { denverDayKey, type AutomationConfig } from './shared.ts'
import { countAgentsOnDay, getLastScannedSha, setLastScannedSha } from './storage.ts'
import { chunkDecisions, triageItems } from './triage.ts'

/** What runScoped needs from run.ts (injected to avoid an import cycle). */
export type SpawnFn = (input: {
	prompt: string
	skipped: string | null
	outcome: string
	files: string[] | null
	branchName: string | null
}) => Promise<Record<string, unknown>>

const weekMs = 7 * 24 * 60 * 60 * 1000

/**
 * One scoped docs-freshness / keep-tests-tight run for one repo:
 * range (last cleanup merge or stored floor ... HEAD) -> scope -> Jev triage
 * -> Clef chunks -> at most maxAgentsPerDay agents. On the configured
 * weekday it runs the full-repo prompt instead. dryRun spawns nothing and
 * never moves the floor.
 */
export async function runScoped(input: {
	automation: ScopedAutomation
	repo: string
	config: AutomationConfig
	dryRun: boolean
	/** Skip the weekly full sweep even on its weekday. */
	scopedOnly?: boolean
	/** Force the full sweep regardless of weekday. */
	fullSweep?: boolean
	now?: Date
	spawn: SpawnFn
}) {
	const { automation, repo, config, dryRun, spawn } = input
	const now = input.now ?? new Date()
	const dayKey = denverDayKey(now)
	const head = await getHeadSha(repo, config.branch)
	const used = dryRun ? 0 : await countAgentsOnDay(automation, dayKey, (iso) => denverDayKey(new Date(iso)))
	const remaining = Math.max(0, config.maxAgentsPerDay - used)
	const advance = async () => {
		if (!dryRun) await setLastScannedSha(repo, automation, head)
	}

	const sweepDay = config.fullSweepWeekday !== null && denverWeekday(now) === config.fullSweepWeekday
	if (input.fullSweep || (sweepDay && !input.scopedOnly)) {
		const branchName = branchNameFor(automation, dayKey)
		const active = await hasCommitsInLast24h({ repo, branch: config.branch, sinceMs: weekMs, now })
		const skipped = !active ? 'no-commits-7d' : remaining < 1 ? 'over-daily-cap' : null
		const prompt = resolvePrompt({ automation, repo, branch: config.branch, notify: config.notify, branchName })
		const launch = await spawn({ prompt, skipped, outcome: skipped ?? 'spawned-full-sweep', files: null, branchName })
		if (!skipped && launch.ok !== false) await advance()
		return { ok: true, automation, repo, mode: 'full-sweep', head, dryRun, launches: [launch] }
	}

	const lastFix = await findLastFix({ repo, base: config.branch, automation })
	const floor = await getLastScannedSha(repo, automation)
	let base = await laterOf(repo, lastFix?.sha ?? null, floor)
	const baseSource = base ? (base === floor ? 'last-scanned-sha' : 'last-fix-merge') : 'lookback-24h'
	if (!base) base = await baseFromLookback(repo, config.branch, now)
	const range = { base, head, baseSource, lastFix, floor }

	const noop = async (extra: Record<string, unknown>) => {
		const launch = await spawn({ prompt: '', skipped: 'no-relevant-changes', outcome: 'no-relevant-changes', files: null, branchName: null })
		await advance()
		return { ok: true, automation, repo, mode: 'scoped', dryRun, range, skipped: 'no-relevant-changes', ...extra, launches: [launch] }
	}
	if (!base || base === head) return await noop({ changedFiles: 0, considered: 0, kept: [] })

	const compared = await compareFiles({ repo, base, head })
	let repoPaths: Set<string> | undefined
	if (automation === 'keep-tests-tight' && compared.files.some((f) => isCodePath(f.path))) {
		try {
			repoPaths = await repoPathsAt(repo, head)
		} catch {
			repoPaths = undefined
		}
	}
	const items = buildScope({ automation, files: compared.files, repoPaths })
	const triage = await triageItems({ automation, repo, items, threshold: config.triageThreshold })
	const summary = {
		changedFiles: compared.files.length,
		commits: compared.totalCommits,
		compareWindows: compared.windows,
		considered: items.length,
		triage: { source: triage.source, jevCalls: triage.jevCalls, ms: triage.ms, errors: triage.errors },
		decisions: triage.decisions,
	}
	if (triage.kept.length === 0) return await noop({ ...summary, kept: [] })

	const grouped = await chunkDecisions({ repo, kept: triage.kept, chunkMin: config.chunkMin, chunkMax: config.chunkMax })
	const rangeText = `${base.slice(0, 12)}...${head.slice(0, 12)}`
	const launches: Array<Record<string, unknown>> = []
	let allSpawned = true
	for (const [index, chunk] of grouped.chunks.entries()) {
		const branchName = branchNameFor(automation, dayKey, grouped.chunks.length > 1 ? index : undefined)
		const prompt = resolvePrompt({
			automation,
			repo,
			branch: config.branch,
			notify: config.notify,
			branchName,
			templateOverride: scopedTemplates[automation],
			files: chunkFilesBlock(chunk),
			range: rangeText,
			reasons: reasonsBlock(
				automation,
				chunk.files.map((f) => f.reason),
			),
		})
		const files = chunk.files.map((f) => f.path)
		const skipped = index >= remaining ? 'over-daily-cap' : null
		if (skipped) allSpawned = false
		const launch = await spawn({ prompt, skipped, outcome: skipped ?? 'spawned', files, branchName })
		if (launch.ok === false) allSpawned = false
		const { prompt: fullPrompt, ...rest } = launch as { prompt?: string }
		launches.push({ chunk: chunk.id, area: chunk.area, files, ...rest, ...(dryRun && index === 0 ? { prompt: fullPrompt } : {}) })
	}
	if (allSpawned) await advance()
	return {
		ok: true,
		automation,
		repo,
		mode: 'scoped',
		dryRun,
		range,
		...summary,
		kept: triage.kept,
		grouping: { method: grouped.grouping, errors: grouped.errors },
		chunks: grouped.chunks.map((c) => ({ id: c.id, area: c.area, files: c.files.length })),
		agentsRemainingToday: remaining,
		launches,
	}
}