Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

intake.ts

119 lines · 4.8 KB · TypeScript
/**
 * Error intake for the factory health feed: turn one failed run into (at most)
 * one fingerprint row. Cheap by design: storage writes and a best-effort
 * Activity soft-triage only. It never wakes anyone; the sweep does that.
 */
import { workflows } from 'kody:runtime'
import {
	AGENT_EXECUTE_NOTE,
	PLATFORM_WEATHER_NOTE,
	STANDING_NOISE_NOTE,
	hourBucket,
	isPlatformWeather,
	orgFromActivityUrl,
	skipReason,
	type RunSnippet,
} from './fingerprint.ts'
import { loadHealthConfig, rememberOrg, resolveOrg, type HealthConfig } from './config.ts'
import { selfPackageId, softTriageRun } from './platform.ts'
import { addTimeline, incrementCounter, initSchema, updateFingerprint, upsertFromRun } from './store.ts'
import { TOPICS, emitHealthEvent, eventKey } from '../events/emit.ts'

export type RunErrorRecordedEvent = {
	event?: string
	run?: RunSnippet
	activity_url?: string
	synthetic?: boolean
}

/** Record one error run. Shared by the event handler and the reconcile sweep. */
export async function recordErrorRun(org: string, run: RunSnippet, opts: { softTriage: boolean }) {
	const upserted = await upsertFromRun(org, run)
	if (upserted.created) await addTimeline(upserted.fingerprint, 'first-seen', 'intake', `Run ${run.id ?? 'unknown'}`)
	if (upserted.requeued) await addTimeline(upserted.fingerprint, 'requeued', 'intake', `New run ${run.id ?? 'unknown'} after the cooldown`)

	const weather = isPlatformWeather(run)
	const standingNoise = weather || upserted.status === 'noise'
	if (weather && upserted.status !== 'noise') {
		await updateFingerprint(upserted.fingerprint, {
			status: 'noise',
			outcome: 'noise',
			classification: 'noise',
			completed_at: new Date().toISOString(),
			summary: PLATFORM_WEATHER_NOTE,
		})
		await addTimeline(upserted.fingerprint, 'outcome', 'intake', 'noise: platform isolate weather')
	}
	if (standingNoise && opts.softTriage) {
		await softTriageRun(run.id, 'resolved', weather ? PLATFORM_WEATHER_NOTE : STANDING_NOISE_NOTE)
	}
	return { ...upserted, standingNoise, queued: !standingNoise && upserted.status === 'queued' }
}

/**
 * Event sweeps wake Patch soon after a new failure, without waiting for the
 * 30-minute health-sweep job. Idempotency keys bound them: one wake sweep per
 * fingerprint per hour, and one reconcile sweep per hour no matter how many
 * events arrive.
 */
async function scheduleEventSweep(kind: 'wake' | 'reconcile', fingerprint: string) {
	try {
		if (!workflows) return { scheduled: false as const, reason: 'no-workflows' as const }
		await workflows.create({
			exportName: './health/sweep',
			idempotencyKey:
				kind === 'wake' ? `kody-factory:health-sweep:${fingerprint}:${hourBucket()}` : `kody-factory:health-reconcile:${hourBucket()}`,
			params: { limit: 1, reconcile: kind === 'reconcile', source: 'event' },
		})
		return { scheduled: true as const }
	} catch {
		return { scheduled: false as const, reason: 'workflow-create-failed' as const }
	}
}

export async function handleRunError(event: RunErrorRecordedEvent = {}, config?: HealthConfig) {
	const cfg = config ?? (await loadHealthConfig())
	if (!cfg.intakeEnabled) return { ok: true as const, skipped: 'intake-off' as const }
	const run = event.run
	if (!run?.id && !run?.error_message && !run?.surface) return { ok: true as const, skipped: 'empty-event' as const }

	const skip = skipReason(run, selfPackageId())
	if (skip === 'agent-execute') {
		await softTriageRun(run.id, 'ignored', AGENT_EXECUTE_NOTE)
		return { ok: true as const, skipped: skip, runId: run.id ?? null }
	}
	if (skip) return { ok: true as const, skipped: skip, runId: run.id ?? null }

	const eventOrg = orgFromActivityUrl(event.activity_url)
	if (eventOrg && !cfg.org) await rememberOrg(eventOrg)
	const org = cfg.org ?? eventOrg ?? (await resolveOrg(cfg))

	await initSchema()
	const recorded = await recordErrorRun(org, run, { softTriage: true })
	const bucket = hourBucket()
	const eventsThisHour = await incrementCounter(`events:${bucket}`)
	if (recorded.created) await incrementCounter(`fingerprints:${bucket}`)
	if (recorded.queued && recorded.created) {
		await emitHealthEvent(TOPICS.fingerprintQueued, eventKey('health', 'fp', recorded.fingerprint, 'queued'), {
			fingerprint: recorded.fingerprint,
			org,
			count: recorded.count,
			...(typeof run.id === 'string' ? { runId: run.id } : {}),
		})
	}

	const sweep = recorded.queued && cfg.wakesEnabled ? await scheduleEventSweep('wake', recorded.fingerprint) : { scheduled: false as const }
	const reconcile = cfg.reconcileEnabled ? await scheduleEventSweep('reconcile', recorded.fingerprint) : { scheduled: false as const }
	return {
		ok: true as const,
		fingerprint: recorded.fingerprint,
		created: recorded.created,
		count: recorded.count,
		status: recorded.status,
		queued: recorded.queued,
		eventsThisHour,
		synthetic: event.synthetic === true,
		eventSweep: sweep,
		eventReconcile: reconcile,
	}
}