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

run.ts

454 lines · 11.3 KB · TypeScript
import { createAgent } from 'kody:@kentcdodds/cursor/agents'
import {
	buildDevinSessionRequest,
	devinOrgConfigured,
	launchDevinSession,
} from './devin.ts'
import { hasCommitsInLast24h } from './github.ts'
import { resolvePrompt } from './prompts.ts'
import { isScopedAutomation } from './scope-core.ts'
import { runScoped } from './scoped-run.ts'
import {
	agentUrlOf,
	githubUrl,
	isAutomationId,
	launcherOf,
	unknownAutomationMessage,
	normalizeRepoSlug,
	type AutomationId,
	type DevinMode,
} from './shared.ts'
import {
	findCiDedupe,
	getAutomation,
	recordLaunch,
	upsertCiDedupe,
} from './storage.ts'

export type RunNowInput = {
	automation: AutomationId
	/** Limit to one repo; default = all configured repos for the automation. */
	repo?: string
	dryRun?: boolean
	/** Bypass automation.enabled check (jobs still respect platform enabled). */
	force?: boolean
	/** Bypass only the automation.enabled check (does not skip the CI per-SHA dedupe). */
	ignoreEnabled?: boolean
	/** Optional CI context for prod-ci-failure. */
	ci?: {
		headSha?: string
		conclusion?: string
		htmlUrl?: string | null
		checkName?: string | null
		workflowName?: string | null
		event?: string
	}
	/** Skip the 24h commit gate even when configured (non-scoped automations). */
	skipCommitGate?: boolean
	/** docs-freshness / keep-tests-tight: skip the weekly full sweep even on its weekday. */
	scopedOnly?: boolean
	/** docs-freshness / keep-tests-tight: run the full-repo sweep now. */
	fullSweep?: boolean
}

function requireAutomationId(value: unknown): AutomationId {
	if (!isAutomationId(value)) {
		throw new Error(unknownAutomationMessage())
	}
	return value
}

function buildExtra(automation: AutomationId, ci: RunNowInput['ci']) {
	if (automation !== 'prod-ci-failure' || !ci) return ''
	const lines = [
		'## Failure context',
		ci.event ? `- Event: ${ci.event}` : null,
		ci.conclusion ? `- Conclusion: ${ci.conclusion}` : null,
		ci.headSha ? `- Head SHA: \`${ci.headSha}\`` : null,
		ci.checkName ? `- Check: ${ci.checkName}` : null,
		ci.workflowName ? `- Workflow: ${ci.workflowName}` : null,
		ci.htmlUrl ? `- URL: ${ci.htmlUrl}` : null,
	].filter(Boolean)
	return lines.join('\n')
}

async function spawnOrPreview(input: {
	automation: AutomationId
	repo: string
	branch: string
	model: { id: string; params?: Array<{ id: string; value: string }> }
	prompt: string
	dryRun: boolean
	headSha: string | null
	skipped: string | null
	devinMode: DevinMode
	maxAcuLimit: number | null
	outcome?: string | null
	files?: string[] | null
}) {
	if (launcherOf(input.automation) === 'devin') return await launchOrPreviewDevin(input)
	const spawnedAt = new Date().toISOString()
	const meta = {
		outcome: input.outcome ?? null,
		files: input.files && input.files.length > 0 ? JSON.stringify(input.files) : null,
	}
	if (input.skipped) {
		if (!input.dryRun) {
			await recordLaunch({
				...meta,
				automation: input.automation,
				repo: input.repo,
				branch: input.branch,
				head_sha: input.headSha,
				agent_id: null,
				agent_url: null,
				spawned_at: spawnedAt,
				dry_run: 0,
				skipped: input.skipped,
			})
		}
		return {
			ok: true as const,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			dryRun: input.dryRun,
			skipped: input.skipped,
			prompt: input.prompt,
			promptChars: input.prompt.length,
			model: input.model,
			wouldSpawn: false,
		}
	}

	if (input.dryRun) {
		await recordLaunch({
				...meta,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			head_sha: input.headSha,
			agent_id: null,
			agent_url: null,
			spawned_at: spawnedAt,
			dry_run: 1,
			skipped: null,
		})
		return {
			ok: true as const,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			dryRun: true,
			skipped: null,
			prompt: input.prompt,
			promptChars: input.prompt.length,
			model: input.model,
			wouldSpawn: true,
			repository: githubUrl(input.repo),
			ref: input.branch,
		}
	}

	try {
		const created = await createAgent({
			prompt: { text: input.prompt },
			model: input.model,
			name: `${input.automation} ${input.repo}`.slice(0, 60),
			repository: githubUrl(input.repo),
			ref: input.branch,
		})
		const agent =
			(created as { agent?: { id?: string; url?: string } })?.agent ??
			(created as { id?: string; url?: string })
		const agentId = agent?.id || null
		const agentUrl = agentUrlOf(agent)
		await recordLaunch({
				...meta,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			head_sha: input.headSha,
			agent_id: agentId,
			agent_url: agentUrl,
			spawned_at: spawnedAt,
			dry_run: 0,
			skipped: null,
		})
		if (input.headSha) {
			await upsertCiDedupe({
				repo: input.repo,
				headSha: input.headSha,
				agentId,
				agentUrl,
				spawnedAt,
			})
		}
		return {
			ok: true as const,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			dryRun: false,
			skipped: null,
			spawned: true,
			agentId,
			agentUrl,
			promptChars: input.prompt.length,
			model: input.model,
		}
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error)
		await recordLaunch({
				...meta,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			head_sha: input.headSha,
			agent_id: null,
			agent_url: null,
			spawned_at: spawnedAt,
			dry_run: 0,
			skipped: `spawn-failed:${message.slice(0, 180)}`,
			outcome: 'spawn-failed',
		})
		return {
			ok: false as const,
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			dryRun: false,
			error: message,
			promptChars: input.prompt.length,
			model: input.model,
		}
	}
}

/**
 * Devin launcher (general-audit): same skip / dryRun / record semantics as the
 * Cursor path. dryRun returns the exact create-session request without sending it.
 */
async function launchOrPreviewDevin(input: Parameters<typeof spawnOrPreview>[0]) {
	const spawnedAt = new Date().toISOString()
	const launcher = 'devin' as const
	const request = buildDevinSessionRequest({
		automation: input.automation,
		repo: input.repo,
		prompt: input.prompt,
		devinMode: input.devinMode,
		maxAcuLimit: input.maxAcuLimit,
	})
	const record = (fields: { agent_id?: string | null; agent_url?: string | null; dry_run: number; skipped: string | null }) =>
		recordLaunch({
			automation: input.automation,
			repo: input.repo,
			branch: input.branch,
			head_sha: input.headSha,
			agent_id: fields.agent_id ?? null,
			agent_url: fields.agent_url ?? null,
			spawned_at: spawnedAt,
			dry_run: fields.dry_run,
			skipped: fields.skipped,
		})

	if (input.skipped) {
		if (!input.dryRun) await record({ dry_run: 0, skipped: input.skipped })
		return {
			ok: true as const,
			automation: input.automation,
			launcher,
			repo: input.repo,
			branch: input.branch,
			dryRun: input.dryRun,
			skipped: input.skipped,
			promptChars: input.prompt.length,
			devinMode: input.devinMode,
			wouldSpawn: false,
		}
	}

	if (input.dryRun) {
		await record({ dry_run: 1, skipped: null })
		return {
			ok: true as const,
			automation: input.automation,
			launcher,
			repo: input.repo,
			branch: input.branch,
			dryRun: true,
			skipped: null,
			prompt: input.prompt,
			promptChars: input.prompt.length,
			devinMode: input.devinMode,
			devinRequest: request,
			devinOrgConfigured: await devinOrgConfigured(),
			wouldSpawn: true,
		}
	}

	try {
		const session = await launchDevinSession(request)
		await record({ agent_id: session.sessionId, agent_url: session.url, dry_run: 0, skipped: null })
		return {
			ok: true as const,
			automation: input.automation,
			launcher,
			repo: input.repo,
			branch: input.branch,
			dryRun: false,
			skipped: null,
			spawned: true,
			agentId: session.sessionId,
			agentUrl: session.url,
			devinMode: session.devinMode ?? input.devinMode,
			promptChars: input.prompt.length,
		}
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error)
		await record({ dry_run: 0, skipped: `spawn-failed:${message.slice(0, 180)}` })
		return {
			ok: false as const,
			automation: input.automation,
			launcher,
			repo: input.repo,
			branch: input.branch,
			dryRun: false,
			error: message,
			promptChars: input.prompt.length,
			devinMode: input.devinMode,
		}
	}
}

/**
 * Run one automation now against its configured repos (or a single repo).
 * Pass `dryRun: true` to resolve prompts without spawning Cursor agents or
 * Devin sessions (general-audit returns the exact Devin request instead).
 *
 * @example
 * import runNow from 'kody:@kentcdodds/codebase-cleanup/run'
 * await runNow({ automation: 'docs-freshness', dryRun: true })
 */
export default async function runNow(input: RunNowInput) {
	const automation = requireAutomationId(input?.automation)
	const dryRun = input.dryRun === true
	const force = input.force === true
	const ignoreEnabled = input.ignoreEnabled === true
	const config = await getAutomation(automation)

	if (!config.enabled && !dryRun && !force && !ignoreEnabled) {
		return {
			ok: true,
			automation,
			skipped: 'automation-disabled',
			hint: 'Set enabled:true via config.set, or pass force:true / dryRun:true',
		}
	}

	const repos = input.repo
		? [normalizeRepoSlug(input.repo)]
		: config.repos.map((r) => normalizeRepoSlug(r))

	if (repos.length === 0) {
		return { ok: true, automation, skipped: 'no-repos' }
	}

	const results = []
	for (const repo of repos) {
		if (isScopedAutomation(automation)) {
			try {
				results.push(
					await runScoped({
						automation,
						repo,
						config,
						dryRun,
						scopedOnly: input.scopedOnly,
						fullSweep: input.fullSweep,
						spawn: (launch) =>
							spawnOrPreview({
								automation,
								repo,
								branch: config.branch,
								model: config.model,
								prompt: launch.prompt,
								dryRun,
								headSha: null,
								skipped: launch.skipped,
								devinMode: config.devinMode,
								maxAcuLimit: config.maxAcuLimit,
								outcome: launch.outcome,
								files: launch.files,
							}),
					}),
				)
			} catch (error) {
				results.push({ ok: false, automation, repo, error: error instanceof Error ? error.message : String(error) })
			}
			continue
		}
		const headSha = input.ci?.headSha ?? null

		if (automation === 'prod-ci-failure' && headSha && !dryRun && !force) {
			const existing = await findCiDedupe(repo, headSha)
			if (existing) {
				results.push({
					ok: true,
					automation,
					repo,
					branch: config.branch,
					skipped: 'already-launched-for-sha',
					agentId: existing.agent_id,
					agentUrl: existing.agent_url,
					headSha,
				})
				continue
			}
		}

		let skipped: string | null = null
		if (config.skipIfNoCommits24h && !input.skipCommitGate) {
			try {
				const hasCommits = await hasCommitsInLast24h({
					repo,
					branch: config.branch,
				})
				if (!hasCommits) skipped = 'no-commits-24h'
			} catch (error) {
				const message = error instanceof Error ? error.message : String(error)
				skipped = `commit-check-failed:${message.slice(0, 120)}`
			}
		}

		const prompt = resolvePrompt({
			automation,
			repo,
			branch: config.branch,
			extra: buildExtra(automation, input.ci),
			notify: config.notify,
		})

		results.push(
			await spawnOrPreview({
				automation,
				repo,
				branch: config.branch,
				model: config.model,
				prompt,
				dryRun,
				headSha,
				skipped,
				devinMode: config.devinMode,
				maxAcuLimit: config.maxAcuLimit,
			}),
		)
	}

	return {
		ok: true,
		automation,
		dryRun,
		results,
	}
}