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

store.ts

473 lines · 16.8 KB · TypeScript
/**
 * Factory health storage: one SQL row per fingerprint, hourly counters, the
 * global wake lease, a per-fingerprint timeline, and job heartbeats. SQL (not
 * the JSON ledger) because many run.error.recorded handlers write at once and
 * each statement must stand alone.
 */
import { packageStorage } from 'kody:runtime'
import {
	LEASE_STALE_MS,
	MAX_LINKED_RUNS,
	fingerprintFor,
	nextStatusAfterEvent,
	normalizeErrorFamily,
	normalizeOrg,
	ownerFor,
	type RunSnippet,
} from './fingerprint.ts'

export type FingerprintRecord = {
	fingerprint: string
	org: string
	surface: string
	owner: string
	package_id: string | null
	kody_id: string | null
	error_family: string
	sample_message: string
	sample_run_id: string | null
	run_ids: string[]
	count: number
	first_seen: string
	last_seen: string
	status: string
	outcome: string | null
	classification: string | null
	summary: string | null
	pr_url: string | null
	wake_count: number
	woken_at: string | null
	completed_at: string | null
}

export type TimelineEvent = { id: number; fingerprint: string; at: string; kind: string; actor: string; detail: string }
export type Heartbeat = { id: number; source: string; at: string; ok: boolean; duration_ms: number; detail: string }

type Row = Record<string, unknown>

type Binding = string | number | boolean | null

export async function sql(query: string, bindings: Binding[] = []): Promise<Row[]> {
	const result = (await packageStorage().sql(query, bindings)) as { rows?: unknown[] } | unknown[] | null
	if (!result) return []
	if (Array.isArray(result)) return result as Row[]
	return Array.isArray(result.rows) ? (result.rows as Row[]) : []
}

let schemaReady: Promise<void> | null = null

/** Idempotent; cached per isolate so warm requests skip the DDL. */
export function initSchema(): Promise<void> {
	schemaReady ??= createSchema().catch((error) => {
		schemaReady = null
		throw error
	})
	return schemaReady
}

/** Test hook: a fresh database needs the schema again. */
export function resetSchemaCache(): void {
	schemaReady = null
}

async function createSchema() {
	await sql(`CREATE TABLE IF NOT EXISTS health_fingerprints (
		fingerprint TEXT PRIMARY KEY,
		org TEXT NOT NULL,
		surface TEXT NOT NULL,
		owner TEXT NOT NULL,
		package_id TEXT,
		kody_id TEXT,
		error_family TEXT NOT NULL,
		sample_message TEXT,
		sample_run_id TEXT,
		run_ids_json TEXT NOT NULL,
		count INTEGER NOT NULL,
		first_seen TEXT NOT NULL,
		last_seen TEXT NOT NULL,
		status TEXT NOT NULL,
		outcome TEXT,
		classification TEXT,
		summary TEXT,
		pr_url TEXT,
		wake_count INTEGER NOT NULL DEFAULT 0,
		woken_at TEXT,
		completed_at TEXT,
		claimed_at TEXT
	)`)
	await sql('CREATE INDEX IF NOT EXISTS health_fingerprints_status ON health_fingerprints (status, last_seen)')
	await sql(`CREATE TABLE IF NOT EXISTS health_counters (
		key TEXT PRIMARY KEY,
		value INTEGER NOT NULL,
		updated_at TEXT NOT NULL
	)`)
	await sql(`CREATE TABLE IF NOT EXISTS health_lease (
		id TEXT PRIMARY KEY,
		holder TEXT,
		fingerprint TEXT,
		acquired_at TEXT
	)`)
	await sql(`CREATE TABLE IF NOT EXISTS health_events (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		fingerprint TEXT NOT NULL,
		at TEXT NOT NULL,
		kind TEXT NOT NULL,
		actor TEXT NOT NULL,
		detail TEXT
	)`)
	await sql('CREATE INDEX IF NOT EXISTS health_events_fingerprint ON health_events (fingerprint, id)')
	await sql(`CREATE TABLE IF NOT EXISTS health_heartbeats (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		source TEXT NOT NULL,
		at TEXT NOT NULL,
		ok INTEGER NOT NULL,
		duration_ms INTEGER NOT NULL,
		detail TEXT
	)`)
}

function str(value: unknown): string | null {
	return value == null || value === '' ? null : String(value)
}

function parseRecord(row: Row): FingerprintRecord {
	let runIds: string[] = []
	try {
		const parsed = JSON.parse(String(row.run_ids_json || '[]'))
		if (Array.isArray(parsed)) runIds = parsed.map(String)
	} catch {
		runIds = []
	}
	return {
		fingerprint: String(row.fingerprint),
		org: String(row.org),
		surface: String(row.surface),
		owner: String(row.owner),
		package_id: str(row.package_id),
		kody_id: str(row.kody_id),
		error_family: String(row.error_family),
		sample_message: String(row.sample_message || ''),
		sample_run_id: str(row.sample_run_id),
		run_ids: runIds,
		count: Number(row.count || 0),
		first_seen: String(row.first_seen),
		last_seen: String(row.last_seen),
		status: String(row.status),
		outcome: str(row.outcome),
		classification: str(row.classification),
		summary: str(row.summary),
		pr_url: str(row.pr_url),
		wake_count: Number(row.wake_count || 0),
		woken_at: str(row.woken_at),
		completed_at: str(row.completed_at),
	}
}

export async function getFingerprint(fingerprint: string): Promise<FingerprintRecord | null> {
	const rows = await sql('SELECT * FROM health_fingerprints WHERE fingerprint = ?', [fingerprint])
	return rows[0] ? parseRecord(rows[0]) : null
}

export const STATUS_GROUPS: Record<string, string[]> = {
	open: ['queued', 'claimed', 'woken', 'failed'],
	queued: ['queued'],
	'in-flight': ['claimed', 'woken'],
	done: ['fixed', 'recommendation', 'noise', 'skipped_execute'],
}

export async function listFingerprints(opts: { group?: string; query?: string; limit?: number } = {}): Promise<FingerprintRecord[]> {
	const where: string[] = []
	const bindings: Binding[] = []
	const statuses = opts.group ? STATUS_GROUPS[opts.group] : undefined
	if (statuses) {
		where.push(`status IN (${statuses.map(() => '?').join(',')})`)
		bindings.push(...statuses)
	}
	const query = String(opts.query ?? '').trim().slice(0, 120)
	if (query) {
		where.push("(fingerprint LIKE ? ESCAPE '\\' OR sample_message LIKE ? ESCAPE '\\')")
		const like = `%${query.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
		bindings.push(like, like)
	}
	bindings.push(Math.min(Math.max(opts.limit ?? 100, 1), 200))
	const rows = await sql(
		`SELECT * FROM health_fingerprints ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY last_seen DESC LIMIT ?`,
		bindings,
	)
	return rows.map(parseRecord)
}

export async function listByStatuses(statuses: string[], limit = 40): Promise<FingerprintRecord[]> {
	if (!statuses.length) return []
	const rows = await sql(
		`SELECT * FROM health_fingerprints WHERE status IN (${statuses.map(() => '?').join(',')}) ORDER BY first_seen ASC LIMIT ?`,
		[...statuses, limit],
	)
	return rows.map(parseRecord)
}

export async function listSiblings(record: Pick<FingerprintRecord, 'fingerprint' | 'owner'>, limit = 20): Promise<FingerprintRecord[]> {
	const rows = await sql(
		'SELECT * FROM health_fingerprints WHERE fingerprint != ? AND owner = ? ORDER BY last_seen DESC LIMIT ?',
		[record.fingerprint, record.owner, limit],
	)
	return rows.map(parseRecord)
}

export async function listStaleWoken(now = Date.now()): Promise<FingerprintRecord[]> {
	const cutoff = new Date(now - LEASE_STALE_MS).toISOString()
	const rows = await sql(
		"SELECT * FROM health_fingerprints WHERE status = 'woken' AND (woken_at IS NULL OR woken_at < ?) ORDER BY woken_at ASC LIMIT 20",
		[cutoff],
	)
	return rows.map(parseRecord)
}

export async function countByStatus(): Promise<Record<string, number>> {
	const rows = await sql('SELECT status, COUNT(*) AS n FROM health_fingerprints GROUP BY status')
	const out: Record<string, number> = {}
	for (const row of rows) out[String(row.status)] = Number(row.n || 0)
	return out
}

/** One row per fingerprint: a repeat only bumps the count, last seen, and linked runs. */
export async function upsertFromRun(org: string, run: RunSnippet, now = new Date()) {
	const fingerprint = fingerprintFor(org, run)
	const at = now.toISOString()
	const existing = await getFingerprint(fingerprint)
	const runId = run.id || null
	const runIds = existing ? [...existing.run_ids] : []
	const seenBefore = Boolean(runId && runIds.includes(runId))
	if (runId && !seenBefore) {
		runIds.unshift(runId)
		if (runIds.length > MAX_LINKED_RUNS) runIds.length = MAX_LINKED_RUNS
	}
	const message = String(run.error_message || '').slice(0, 500)

	if (!existing) {
		await sql(
			`INSERT INTO health_fingerprints (
				fingerprint, org, surface, owner, package_id, kody_id, error_family,
				sample_message, sample_run_id, run_ids_json, count, first_seen, last_seen, status
			) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, 'queued')
			ON CONFLICT(fingerprint) DO UPDATE SET
				count = health_fingerprints.count + 1,
				last_seen = excluded.last_seen`,
			[
				fingerprint,
				normalizeOrg(org),
				run.surface || 'unknown',
				ownerFor(run),
				run.package_id || null,
				run.kody_id || null,
				normalizeErrorFamily(run.error_message),
				message,
				runId,
				JSON.stringify(runIds),
				at,
				at,
			],
		)
		const after = await getFingerprint(fingerprint)
		const count = after?.count ?? 1
		return { fingerprint, created: count === 1, count, status: after?.status ?? 'queued', requeued: false }
	}

	// A run already linked (event then reconcile) is the same occurrence, not a new one.
	if (seenBefore) {
		return { fingerprint, created: false, count: existing.count, status: existing.status, requeued: false }
	}
	const status = nextStatusAfterEvent({
		status: existing.status,
		completedAt: existing.completed_at,
		runStartedAt: run.started_at,
		now: now.getTime(),
	})
	const requeued = status === 'queued' && existing.status !== 'queued'
	await sql(
		`UPDATE health_fingerprints SET
			count = count + 1, last_seen = ?, sample_message = ?, sample_run_id = ?, run_ids_json = ?, status = ?
			${requeued ? ', outcome = NULL, completed_at = NULL' : ''}
		WHERE fingerprint = ?`,
		[at, message || existing.sample_message, runId || existing.sample_run_id, JSON.stringify(runIds), status, fingerprint],
	)
	return { fingerprint, created: false, count: existing.count + 1, status, requeued }
}

const UPDATABLE = ['status', 'outcome', 'classification', 'summary', 'pr_url', 'wake_count', 'woken_at', 'completed_at'] as const

export async function updateFingerprint(
	fingerprint: string,
	fields: Partial<Pick<FingerprintRecord, (typeof UPDATABLE)[number]>>,
): Promise<void> {
	const sets: string[] = []
	const bindings: Binding[] = []
	for (const key of UPDATABLE) {
		if (fields[key] !== undefined) {
			sets.push(`${key} = ?`)
			bindings.push(fields[key])
		}
	}
	if (!sets.length) return
	bindings.push(fingerprint)
	await sql(`UPDATE health_fingerprints SET ${sets.join(', ')} WHERE fingerprint = ?`, bindings)
}

export async function addTimeline(fingerprint: string, kind: string, actor: string, detail = ''): Promise<void> {
	await sql('INSERT INTO health_events (fingerprint, at, kind, actor, detail) VALUES (?, ?, ?, ?, ?)', [
		fingerprint,
		new Date().toISOString(),
		kind,
		actor,
		detail.slice(0, 1000),
	])
}

export async function listTimeline(fingerprint: string, limit = 50): Promise<TimelineEvent[]> {
	const rows = await sql('SELECT * FROM health_events WHERE fingerprint = ? ORDER BY id DESC LIMIT ?', [fingerprint, limit])
	return rows.map((row) => ({
		id: Number(row.id),
		fingerprint: String(row.fingerprint),
		at: String(row.at),
		kind: String(row.kind),
		actor: String(row.actor),
		detail: String(row.detail || ''),
	}))
}

export async function incrementCounter(key: string, by = 1): Promise<number> {
	await sql(
		`INSERT INTO health_counters (key, value, updated_at) VALUES (?, ?, ?)
		ON CONFLICT(key) DO UPDATE SET value = health_counters.value + excluded.value, updated_at = excluded.updated_at`,
		[key, by, new Date().toISOString()],
	)
	return getCounter(key)
}

export async function getCounter(key: string): Promise<number> {
	const rows = await sql('SELECT value FROM health_counters WHERE key = ?', [key])
	return Number(rows[0]?.value || 0)
}

/** Counters whose key starts with `prefix`, keyed by the remainder (the hour bucket). */
export async function getCounters(prefix: string, sinceBucket: string): Promise<Record<string, number>> {
	const rows = await sql('SELECT key, value FROM health_counters WHERE key >= ? AND key < ?', [
		`${prefix}${sinceBucket}`,
		`${prefix}\uffff`,
	])
	const out: Record<string, number> = {}
	for (const row of rows) out[String(row.key).slice(prefix.length)] = Number(row.value || 0)
	return out
}

export async function getLastCounterUpdate(prefix: string): Promise<string | null> {
	const rows = await sql('SELECT MAX(updated_at) AS at FROM health_counters WHERE key >= ? AND key < ?', [prefix, `${prefix}\uffff`])
	return str(rows[0]?.at)
}

export type Lease = { holder: string | null; fingerprint: string | null; acquired_at: string | null }

/**
 * One wake in flight at a time. A single conditional upsert: the row is taken
 * only when it is missing, stale, or already held for this fingerprint, and
 * RETURNING says whether this caller got it. No read-then-write window.
 */
export async function tryAcquireLease(fingerprint: string, holder: string, now = Date.now()) {
	const cutoff = new Date(now - LEASE_STALE_MS).toISOString()
	const rows = await sql(
		`INSERT INTO health_lease (id, holder, fingerprint, acquired_at) VALUES ('global', ?, ?, ?)
		ON CONFLICT(id) DO UPDATE SET holder = excluded.holder, fingerprint = excluded.fingerprint, acquired_at = excluded.acquired_at
		WHERE health_lease.acquired_at IS NULL OR health_lease.acquired_at < ? OR health_lease.fingerprint = excluded.fingerprint
		RETURNING id`,
		[holder, fingerprint, new Date(now).toISOString(), cutoff],
	)
	if (rows.length) return { ok: true as const }
	const existing = await getLease()
	return { ok: false as const, heldBy: existing?.fingerprint || existing?.holder || 'unknown' }
}

/**
 * Atomically move one fingerprint to `claimed`. Only one caller can win: the
 * UPDATE matches the row only while it is in one of `from`, and RETURNING
 * reports whether a row changed.
 */
export async function claimFingerprint(fingerprint: string, from: string[]): Promise<boolean> {
	if (!from.length) return false
	const rows = await sql(
		`UPDATE health_fingerprints SET status = 'claimed', claimed_at = ? WHERE fingerprint = ? AND status IN (${from.map(() => '?').join(',')}) RETURNING fingerprint`,
		[new Date().toISOString(), fingerprint, ...from],
	)
	return rows.length > 0
}

/** Give a claim back (wake refused or failed). Only touches a row that is still claimed. */
export async function unclaimFingerprint(fingerprint: string, to: string): Promise<void> {
	await sql("UPDATE health_fingerprints SET status = ?, claimed_at = NULL WHERE fingerprint = ? AND status = 'claimed'", [to, fingerprint])
}

const CLAIM_STALE_MS = 10 * 60 * 1000

/** A run that died between claim and wake leaves a claimed row; put those back in the queue. */
export async function requeueStaleClaims(now = Date.now()): Promise<number> {
	const rows = await sql(
		"UPDATE health_fingerprints SET status = 'queued', claimed_at = NULL WHERE status = 'claimed' AND (claimed_at IS NULL OR claimed_at < ?) RETURNING fingerprint",
		[new Date(now - CLAIM_STALE_MS).toISOString()],
	)
	return rows.length
}

/** Take one slot of an hourly cap in one statement. False when the cap is already used up. */
export async function reserveCounterSlot(key: string, cap: number): Promise<boolean> {
	const rows = await sql(
		`INSERT INTO health_counters (key, value, updated_at) VALUES (?, 1, ?)
		ON CONFLICT(key) DO UPDATE SET value = health_counters.value + 1, updated_at = excluded.updated_at
		WHERE health_counters.value < ?
		RETURNING value`,
		[key, new Date().toISOString(), cap],
	)
	return rows.length > 0
}

/** Return a reserved slot when the wake it was reserved for did not go out. */
export async function refundCounterSlot(key: string): Promise<void> {
	await sql('UPDATE health_counters SET value = value - 1 WHERE key = ? AND value > 0', [key])
}

export async function releaseLease(fingerprint?: string): Promise<void> {
	if (fingerprint) {
		await sql('DELETE FROM health_lease WHERE id = ? AND fingerprint = ?', ['global', fingerprint])
		return
	}
	await sql('DELETE FROM health_lease WHERE id = ?', ['global'])
}

export async function getLease(): Promise<Lease | null> {
	const rows = await sql('SELECT * FROM health_lease WHERE id = ?', ['global'])
	const row = rows[0]
	return row ? { holder: str(row.holder), fingerprint: str(row.fingerprint), acquired_at: str(row.acquired_at) } : null
}

const HEARTBEATS_KEPT = 200

export async function recordHeartbeat(source: string, ok: boolean, durationMs: number, detail = ''): Promise<void> {
	await sql('INSERT INTO health_heartbeats (source, at, ok, duration_ms, detail) VALUES (?, ?, ?, ?, ?)', [
		source,
		new Date().toISOString(),
		ok ? 1 : 0,
		Math.max(0, Math.round(durationMs)),
		detail.slice(0, 500),
	])
	await sql('DELETE FROM health_heartbeats WHERE id <= (SELECT MAX(id) FROM health_heartbeats) - ?', [HEARTBEATS_KEPT])
}

export async function listHeartbeats(source: string, limit = 24): Promise<Heartbeat[]> {
	const rows = await sql('SELECT * FROM health_heartbeats WHERE source = ? ORDER BY id DESC LIMIT ?', [source, limit])
	return rows.map((row) => ({
		id: Number(row.id),
		source: String(row.source),
		at: String(row.at),
		ok: Number(row.ok) === 1,
		duration_ms: Number(row.duration_ms || 0),
		detail: String(row.detail || ''),
	}))
}