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

sweep.ts

253 lines · 9.6 KB · TypeScript
/**
 * The health sweep: recover stale wakes, wake Patch for queued fingerprints
 * (only when wakes are on, under the breaker, cap, and lease), reconcile open
 * error runs into fingerprints, drain recorded outcomes into Activity, and
 * refresh the platform signals the health page shows.
 */
import {
	AGENT_EXECUTE_NOTE,
	PLATFORM_WEATHER_NOTE,
	RETRIAGE_COOLDOWN_MS,
	anomalyTripped,
	hourBucket,
	isAgentExecuteOrigin,
	isPlatformWeather,
	skipReason,
	softTriageForOutcome,
} from './fingerprint.ts'
import { loadHealthConfig, resolveOrg, type HealthConfig } from './config.ts'
import { recordErrorRun } from './intake.ts'
import { applyTriageToMatchingOpenRuns, wakeOne, type WakeAction } from './outcome.ts'
import { runGet, runList, selfPackageId, softTriageRuns, withTimeout } from './platform.ts'
import { refreshPlatformSnapshot } from './signals.ts'
import { TOPICS, emitHealthEvent, eventKey } from '../events/emit.ts'
import {
	addTimeline,
	getCounter,
	initSchema,
	listByStatuses,
	listStaleWoken,
	requeueStaleClaims,
	recordHeartbeat,
	releaseLease,
	updateFingerprint,
	type FingerprintRecord,
} from './store.ts'

export type SweepInput = {
	/** Report what would happen without waking, triaging, or changing fingerprints. */
	dryRun?: boolean
	/** Most fingerprints to wake in this run (1 to 3, default 1). */
	limit?: number
	/** false skips the reconcile for this run. It never runs while the reconcile switch is off. */
	reconcile?: boolean
	/** Heartbeat label: `job`, `event`, or `manual`. */
	source?: string
}

const RECONCILE_TIMEOUT_MS = 20_000

function canRetriage(record: FingerprintRecord): boolean {
	if (record.status === 'queued' || record.status === 'claimed') return true
	if (record.status === 'woken') return false
	if (!record.completed_at) return true
	return Date.now() - Date.parse(record.completed_at) >= RETRIAGE_COOLDOWN_MS
}

/** Scan open error runs into fingerprints and soft-triage the rows the skip rules cover. */
export async function reconcileOpenErrors(config: HealthConfig, dryRun: boolean) {
	const org = await resolveOrg(config)
	const self = selfPackageId()
	const page = await runList({ status: 'error', error_triage: 'open', limit: 100 })
	const executeIds: string[] = []
	const out = { scanned: page.runs.length, queued: 0, created: 0, skippedExecute: 0, skippedSelf: 0, skippedSmoke: 0, noise: 0, softTriaged: 0 }
	for (const run of page.runs) {
		const skip = skipReason(run, self)
		if (skip === 'agent-execute') {
			out.skippedExecute++
			if (run.id) executeIds.push(run.id)
			continue
		}
		if (skip === 'self-package') {
			// Factory's own failures stay open in Activity: they are real failures of
			// the sweep job or the github-issues webhook, and a person should see them.
			out.skippedSelf++
			continue
		}
		if (skip) {
			out.skippedSmoke++
			continue
		}
		if (dryRun) {
			if (isPlatformWeather(run)) out.noise++
			else out.queued++
			continue
		}
		const recorded = await recordErrorRun(org, run, { softTriage: true })
		if (recorded.created) out.created++
		if (recorded.standingNoise) out.noise++
		else if (recorded.queued) out.queued++
	}
	if (!dryRun) {
		out.softTriaged += await softTriageRuns(executeIds, 'ignored', AGENT_EXECUTE_NOTE)
	}
	return out
}

/** Re-apply recorded outcomes to matching Activity rows that arrived after the outcome. */
async function drainRecordedOutcomes(dryRun: boolean) {
	const records = await listByStatuses(['fixed', 'noise'], 40)
	let updated = 0
	if (dryRun) return { fingerprints: records.length, updated }
	for (const record of records) {
		const soft = softTriageForOutcome(record.outcome || record.status)
		if (soft) updated += (await applyTriageToMatchingOpenRuns(record, soft, `Factory health sweep: ${record.outcome || record.status}`)).updated
	}
	return { fingerprints: records.length, updated }
}

async function closeBeforeWake(record: FingerprintRecord, dryRun: boolean): Promise<WakeAction | null> {
	let sample = null
	try {
		sample = record.sample_run_id ? await withTimeout(runGet(record.sample_run_id), 5_000, null) : null
	} catch {
		sample = null
	}
	if (!sample) return null
	if (isAgentExecuteOrigin(sample)) {
		if (!dryRun) {
			await updateFingerprint(record.fingerprint, { status: 'skipped_execute', summary: 'No wake: the sample run came from an agent execute call.' })
			await addTimeline(record.fingerprint, 'skipped', 'sweep', 'Agent execute origin; Activity rows ignored')
			await applyTriageToMatchingOpenRuns(record, 'ignored', AGENT_EXECUTE_NOTE)
		}
		return { ok: true, fingerprint: record.fingerprint, skipped: 'agent-execute' }
	}
	if (isPlatformWeather(sample)) {
		if (!dryRun) {
			await updateFingerprint(record.fingerprint, {
				status: 'noise',
				outcome: 'noise',
				classification: 'noise',
				completed_at: new Date().toISOString(),
				summary: PLATFORM_WEATHER_NOTE,
			})
			await addTimeline(record.fingerprint, 'outcome', 'sweep', 'noise: platform isolate weather')
		}
		return { ok: true, fingerprint: record.fingerprint, skipped: 'platform-weather' }
	}
	return null
}

export async function healthSweep(input: SweepInput = {}) {
	const started = Date.now()
	const source = ['job', 'event', 'manual'].includes(String(input.source)) ? String(input.source) : 'manual'
	const dryRun = input.dryRun === true
	const limit = Math.min(Math.max(Math.trunc(input.limit ?? 1) || 1, 1), 3)
	await initSchema()
	const config = await loadHealthConfig()
	try {
		const result = await runSweep(config, { dryRun, limit, reconcile: input.reconcile })
		if (!dryRun) await recordHeartbeat(`sweep:${source}`, true, Date.now() - started, summarize(result))
		return result
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error)
		if (!dryRun) await recordHeartbeat(`sweep:${source}`, false, Date.now() - started, message).catch(() => {})
		throw error
	}
}

function summarize(result: Awaited<ReturnType<typeof runSweep>>): string {
	const parts = [`woke ${result.woke}`]
	if (result.wakes.skipped) parts.push(`wakes ${result.wakes.skipped}`)
	if (result.reconcile && 'error' in result.reconcile) parts.push('reconcile failed')
	else if (result.reconcile) parts.push(`scanned ${result.reconcile.scanned}`, `new ${result.reconcile.created}`)
	if (result.recovered.length) parts.push(`recovered ${result.recovered.length}`)
	return parts.join(', ')
}

async function runSweep(config: HealthConfig, opts: { dryRun: boolean; limit: number; reconcile?: boolean }) {
	const { dryRun } = opts
	const recovered: string[] = []
	if (!dryRun) {
		for (const stale of await listStaleWoken()) {
			await updateFingerprint(stale.fingerprint, {
				status: 'failed',
				outcome: 'failed',
				completed_at: new Date().toISOString(),
				summary: 'No outcome was recorded within the stale-wake window.',
			})
			await releaseLease(stale.fingerprint)
			await addTimeline(stale.fingerprint, 'outcome', 'sweep', 'failed: no outcome recorded after the wake')
			recovered.push(stale.fingerprint)
			await emitHealthEvent(TOPICS.wakeStale, eventKey('health', 'stale', stale.fingerprint, stale.woken_at ?? ''), {
				fingerprint: stale.fingerprint,
				...(stale.woken_at ? { wokenAt: stale.woken_at } : {}),
			})
		}
		await requeueStaleClaims()
	}

	const bucket = hourBucket()
	const fingerprintsThisHour = await getCounter(`fingerprints:${bucket}`)
	const eventsThisHour = await getCounter(`events:${bucket}`)
	const anomaly = anomalyTripped({ fingerprints: fingerprintsThisHour, events: eventsThisHour })

	// Wakes go first: reconcile can spend the whole run soft-triaging Activity rows.
	const actions: WakeAction[] = []
	let woke = 0
	let wakesSkipped: string | null = null
	if (!config.wakesEnabled) wakesSkipped = 'off'
	else if (anomaly) wakesSkipped = 'anomaly-breaker'
	else {
		const queued = (await listByStatuses(['queued'], 20)).filter(canRetriage)
		for (const record of queued) {
			if (woke >= opts.limit) break
			try {
				const closed = await closeBeforeWake(record, dryRun)
				if (closed) {
					actions.push(closed)
					continue
				}
				const action = await wakeOne(record, config, { dryRun, actor: 'sweep' })
				actions.push(action)
				if ('skipped' in action && (action.skipped === 'hourly-cap' || action.skipped === 'lease-held' || action.skipped === 'wake-failed')) break
				if ('woke' in action || 'wouldWake' in action) woke++
			} catch (error) {
				actions.push({ ok: false, fingerprint: record.fingerprint, skipped: 'error', detail: error instanceof Error ? error.message : String(error) })
			}
		}
	}

	// The switch always wins: a reconcile writes Activity triage across the org.
	const shouldReconcile = config.reconcileEnabled && opts.reconcile !== false
	type Reconciled = Awaited<ReturnType<typeof reconcileOpenErrors>> | { error: string }
	type Drained = { fingerprints: number; updated: number } | { error: string }
	let reconcile: Reconciled | null = null
	let drain: Drained | null = null
	if (shouldReconcile) {
		try {
			reconcile = await withTimeout<Reconciled>(reconcileOpenErrors(config, dryRun), RECONCILE_TIMEOUT_MS, { error: 'timed out' })
		} catch (error) {
			reconcile = { error: error instanceof Error ? error.message : String(error) }
		}
		try {
			drain = await withTimeout<Drained>(drainRecordedOutcomes(dryRun), RECONCILE_TIMEOUT_MS, { error: 'timed out' })
		} catch (error) {
			drain = { error: error instanceof Error ? error.message : String(error) }
		}
	}

	const platform = dryRun ? null : await refreshPlatformSnapshot()
	return {
		ok: true as const,
		dryRun,
		switches: { intake: config.intakeEnabled, reconcile: config.reconcileEnabled, wakes: config.wakesEnabled },
		woke,
		wakes: { skipped: wakesSkipped, actions },
		anomaly: { tripped: anomaly, fingerprintsThisHour, eventsThisHour },
		reconcile,
		drain,
		recovered,
		platformSignals: platform ? { ok: platform.ok } : null,
	}
}