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

harness.ts

171 lines · 5.4 KB · TypeScript
/**
 * Eval harness for signals routing. Runs the routing request builder over all
 * fixtures and scores them against expected labels using a simple heuristic
 * classifier (since we cannot call the real model in offline tests).
 *
 * The heuristic mirrors the routing logic's fallback: when the model is
 * unavailable, signals are classified by source, severity, and label patterns.
 * This validates that the fixture set is internally consistent and that the
 * heuristic baseline is usable as a fallback when the model is down.
 *
 * Usage:
 *   node --experimental-strip-types src/signals/eval/harness.ts
 */
import { fixtures, type EvalFixture } from './fixtures.ts'
import { buildRoutingRequestBody } from '../routing/request.ts'
import { DEFAULT_CONFIDENCE_THRESHOLD } from '../routing/types.ts'

type EvalResult = {
	id: string
	expectedLabel: string
	predictedLabel: string
	correct: boolean
	confidence: number
}

const NOISE_PATTERNS = [
	/\bduplicate\b/i,
	/\bwontfix\b/i,
	/\bwon't fix\b/i,
	/\bspam\b/i,
	/\bbot scan/i,
	/\bnoise\b/i,
	/\bno action\b/i,
	/\bnot actionable\b/i,
	/\boff.topic\b/i,
	/\brate.?limit.*normal/i,
	/\bisolate.*weather\b/i,
]

const WAKE_PATTERNS = [
	/\bproduction deploy fail/i,
	/\benterprise customer\b/i,
	/\bcredential.*not mapped\b/i,
	/\bdata.?corruption\b/i,
	/\boutage\b/i,
	/\bDOWN\b/,
]

function heuristicRoute(fixture: EvalFixture): { label: string; confidence: number } {
	const text = `${fixture.title} ${fixture.body} ${fixture.labels.join(' ')}`

	for (const pattern of NOISE_PATTERNS) {
		if (pattern.test(text)) return { label: 'ignore', confidence: 0.85 }
	}

	if (fixture.severity === 'info') return { label: 'ignore', confidence: 0.75 }

	if (fixture.labels.includes('question')) return { label: 'ignore', confidence: 0.8 }

	if (/\bflak/i.test(text) && fixture.severity === 'low') return { label: 'ignore', confidence: 0.75 }

	if (/\bpraise\b|\bloves?\b|\bgreat feedback\b|\bpositive/i.test(text) && fixture.severity !== 'critical') {
		return { label: 'ignore', confidence: 0.7 }
	}

	if (/payment.*insufficient|decline.*code/i.test(text) && fixture.severity === 'low') {
		return { label: 'ignore', confidence: 0.7 }
	}

	for (const pattern of WAKE_PATTERNS) {
		if (pattern.test(text)) return { label: 'wake_grok', confidence: 0.8 }
	}

	if (fixture.severity === 'critical' && fixture.labels.some((l) => ['P0', 'billing', 'data-loss', 'outage'].includes(l))) {
		return { label: 'wake_grok', confidence: 0.85 }
	}

	if (fixture.severity === 'critical' && /\b(down|broken|fail|corrupt|block)/i.test(text)) {
		return { label: 'wake_grok', confidence: 0.7 }
	}

	return { label: 'create_work_item', confidence: 0.75 }
}

function runEval(): { results: EvalResult[]; summary: EvalSummary } {
	const results: EvalResult[] = []

	for (const fixture of fixtures) {
		const config = {
			projectId: fixture.projectId,
			questions: [{ key: 'actionability', label: 'Actionable', description: 'test' }],
			criteria: {
				create_work_item: { label: 'Create a work item', destination: 'board-card' as const, promptTemplateId: null },
				wake_grok: { label: 'Wake Grok Bot', destination: 'grok-wake' as const, promptTemplateId: null },
				ignore: { label: 'No action needed', destination: 'none' as const, promptTemplateId: null },
			},
			confidenceThreshold: DEFAULT_CONFIDENCE_THRESHOLD,
			enabled: true,
		}
		buildRoutingRequestBody(fixture, config)

		const prediction = heuristicRoute(fixture)

		results.push({
			id: fixture.id,
			expectedLabel: fixture.expectedLabel,
			predictedLabel: prediction.label,
			correct: prediction.label === fixture.expectedLabel,
			confidence: prediction.confidence,
		})
	}

	const total = results.length
	const correct = results.filter((r) => r.correct).length
	const accuracy = total > 0 ? correct / total : 0

	const byExpected: Record<string, { total: number; correct: number }> = {}
	for (const r of results) {
		const bucket = byExpected[r.expectedLabel] ?? { total: 0, correct: 0 }
		bucket.total += 1
		if (r.correct) bucket.correct += 1
		byExpected[r.expectedLabel] = bucket
	}

	const perLabel: Record<string, { accuracy: number; total: number; correct: number }> = {}
	for (const [label, counts] of Object.entries(byExpected)) {
		perLabel[label] = { ...counts, accuracy: counts.total > 0 ? counts.correct / counts.total : 0 }
	}

	const incorrect = results.filter((r) => !r.correct)

	return {
		results,
		summary: {
			total,
			correct,
			accuracy,
			perLabel,
			incorrect: incorrect.map((r) => ({ id: r.id, expected: r.expectedLabel, predicted: r.predictedLabel })),
		},
	}
}

type EvalSummary = {
	total: number
	correct: number
	accuracy: number
	perLabel: Record<string, { accuracy: number; total: number; correct: number }>
	incorrect: Array<{ id: string; expected: string; predicted: string }>
}

const { summary } = runEval()

console.log('=== Signals routing eval ===')
console.log(`Total fixtures: ${summary.total}`)
console.log(`Correct: ${summary.correct}`)
console.log(`Accuracy: ${(summary.accuracy * 100).toFixed(1)}%`)
console.log()
console.log('Per-label accuracy:')
for (const [label, stats] of Object.entries(summary.perLabel)) {
	console.log(`  ${label}: ${(stats.accuracy * 100).toFixed(1)}% (${stats.correct}/${stats.total})`)
}
if (summary.incorrect.length > 0) {
	console.log()
	console.log('Incorrect predictions:')
	for (const { id, expected, predicted } of summary.incorrect) {
		console.log(`  ${id}: expected=${expected}, predicted=${predicted}`)
	}
}

export { runEval, heuristicRoute, type EvalResult, type EvalSummary }