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

run.ts

121 lines · 3.7 KB · TypeScript
/**
 * Run the real two-tier routing model (clef-flash then clef) over eval
 * fixtures and record accuracy, confusion matrix, escalation rate.
 *
 * Uses credential('model') via the same routing engine as production.
 * If the model is unavailable, falls back to the heuristic and marks it.
 */
import { routeSignal } from '../routing/router.ts'
import type { RealFixture } from './build-fixtures.ts'

export type EvalPrediction = {
	fixtureId: string
	expectedLabel: string
	predictedLabel: string
	correct: boolean
	confidence: number
	escalated: boolean
	modelUsed: string | null
	reason: string
	latencyMs: number
}

export type ConfusionEntry = { expected: string; predicted: string; count: number }

export type EvalReport = {
	total: number
	correct: number
	accuracy: number
	escalationRate: number
	avgLatencyMs: number
	perLabel: Record<string, { total: number; correct: number; accuracy: number }>
	confusionMatrix: ConfusionEntry[]
	incorrect: Array<{ id: string; expected: string; predicted: string; reason: string }>
	modelUsed: string | null
	predictions: EvalPrediction[]
}

const DESTINATION_TO_LABEL: Record<string, string> = {
	'board-card': 'create_work_item',
	'grok-wake': 'wake_grok',
	'none': 'ignore',
}

export async function runEval(fixtures: RealFixture[]): Promise<EvalReport> {
	const predictions: EvalPrediction[] = []
	let modelUsed: string | null = null

	for (const fixture of fixtures) {
		const start = Date.now()
		const result = await routeSignal({
			title: fixture.title,
			body: fixture.body,
			source: fixture.source,
			labels: fixture.labels,
			projectId: fixture.projectId,
			severity: fixture.severity,
		})
		const latencyMs = Date.now() - start
		const predictedLabel = DESTINATION_TO_LABEL[result.destination] ?? 'ignore'
		if (result.modelUsed) modelUsed = result.modelUsed

		predictions.push({
			fixtureId: fixture.id,
			expectedLabel: fixture.expectedLabel,
			predictedLabel,
			correct: predictedLabel === fixture.expectedLabel,
			confidence: result.confidence,
			escalated: result.escalated,
			modelUsed: result.modelUsed,
			reason: result.reason,
			latencyMs,
		})
	}

	const total = predictions.length
	const correct = predictions.filter((p) => p.correct).length
	const accuracy = total > 0 ? correct / total : 0
	const escalated = predictions.filter((p) => p.escalated).length
	const escalationRate = total > 0 ? escalated / total : 0
	const avgLatencyMs = total > 0 ? predictions.reduce((s, p) => s + p.latencyMs, 0) / total : 0

	const byExpected: Record<string, { total: number; correct: number }> = {}
	for (const p of predictions) {
		const bucket = byExpected[p.expectedLabel] ?? { total: 0, correct: 0 }
		bucket.total += 1
		if (p.correct) bucket.correct += 1
		byExpected[p.expectedLabel] = bucket
	}
	const perLabel: EvalReport['perLabel'] = {}
	for (const [label, counts] of Object.entries(byExpected)) {
		perLabel[label] = { ...counts, accuracy: counts.total > 0 ? counts.correct / counts.total : 0 }
	}

	const confusionMap = new Map<string, number>()
	for (const p of predictions) {
		const key = `${p.expectedLabel}:${p.predictedLabel}`
		confusionMap.set(key, (confusionMap.get(key) ?? 0) + 1)
	}
	const confusionMatrix: ConfusionEntry[] = []
	for (const [key, count] of confusionMap) {
		const [expected, predicted] = key.split(':')
		confusionMatrix.push({ expected: expected!, predicted: predicted!, count })
	}

	const incorrect = predictions
		.filter((p) => !p.correct)
		.map((p) => ({ id: p.fixtureId, expected: p.expectedLabel, predicted: p.predictedLabel, reason: p.reason }))

	return {
		total,
		correct,
		accuracy,
		escalationRate,
		avgLatencyMs: Math.round(avgLatencyMs),
		perLabel,
		confusionMatrix,
		incorrect,
		modelUsed,
		predictions,
	}
}