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

rank-core.ts

152 lines · 7.2 KB · TypeScript
import { round, sanitizeForPrompt, truncate } from './shared.ts'
import type { ConfidenceEffect, Lane, Metrics, Opportunity, RankedOpportunity } from './types.ts'

export type Evaluate = (input: { state: unknown; questions: Record<string, unknown>; model?: string }) => Promise<{
	ok: boolean
	answers?: Record<string, any>
	error?: string
}>

/** Opportunities sent to one Jev call (two questions each). */
export const maxJevOpportunities = 12
export const scoreCriteria = [
	'Not worth changing: savings are tiny, speculative, or not worth the churn',
	'Minor: small savings, low priority',
	'Worth doing: clear savings with low risk to shipping confidence',
	'Clearly worth doing: large savings, or removes flakiness that erodes trust in CI',
	'Top priority: big savings and keeps or improves confidence in shipping',
]
export const worthThreshold = 0.3

/** Deterministic value in [0, 1]. Confidence first; speed, cost, and redundant work weigh the same. */
export function deterministicScore(opportunity: Opportunity) {
	const speed = Math.min(1, Math.max(0, opportunity.minutesSavedPerPr) / 5)
	const cost = Math.min(1, Math.max(0, opportunity.runnerMinutesSavedPerWeek) / 2000)
	const redundant = ['dedupe-setup', 'cancel-in-progress', 'path-filter-docs', 'cache-setup'].includes(opportunity.kind)
		? Math.min(1, Math.max(0, opportunity.runnerMinutesSavedPerWeek) / 1000)
		: 0
	let value = (speed + cost + redundant) / 2
	if (opportunity.kind === 'fix-flaky') value += 0.4
	if (opportunity.confidenceEffect === 'reduces') value *= 0.6
	return round(Math.min(1, value), 3)
}

export function buildJevRequest(metrics: Metrics, opportunities: ReadonlyArray<Opportunity>) {
	const questions: Record<string, unknown> = {}
	opportunities.forEach((opportunity, index) => {
		questions[`o${index}_value`] = {
			type: 'score',
			instructions: `How worth changing is opportunity o${index} ("${sanitizeForPrompt(truncate(opportunity.title, 120))}") given the goals?`,
			criteria: scoreCriteria,
		}
		questions[`o${index}_coverage`] = {
			type: 'choice',
			instructions: `Does opportunity o${index} reduce what CI verifies before a change merges?`,
			criteria: {
				none: 'No: every check, test, and platform still runs before merge; only how fast or how cheaply',
				reduces: 'Yes: it drops, skips, samples, or moves a check, test, or platform later than today',
			},
		}
	})
	const state = {
		goals: {
			primary: 'Be confident in shipping: CI must keep catching real problems before merge.',
			secondary: 'Faster PR feedback, lower runner cost, and less redundant work, weighted equally.',
		},
		repo: metrics.repo,
		week: { prTimeToGreenP50Min: metrics.prTimeToGreenMin.p50, runnerMinutesPerWeek: metrics.runnerMinutesPerWeek.total, billedMinutesPerWeek: metrics.billedMinutesPerWeek.total },
		opportunities: opportunities.map((opportunity, index) => ({
			id: `o${index}`,
			kind: opportunity.kind,
			title: sanitizeForPrompt(truncate(opportunity.title, 160)),
			evidence: sanitizeForPrompt(truncate(opportunity.evidence, 400)),
			change: sanitizeForPrompt(truncate(opportunity.change, 400)),
			minutesSavedPerPr: opportunity.minutesSavedPerPr,
			runnerMinutesSavedPerWeek: opportunity.runnerMinutesSavedPerWeek,
		})),
	}
	return { state, questions }
}

export function parseJevAnswers(answers: Record<string, any> | undefined, count: number) {
	const out: Array<{ score: number | null; coverage: ConfidenceEffect | null; coverageProbability: number | null }> = []
	for (let index = 0; index < count; index++) {
		const value = answers?.[`o${index}_value`]
		const coverage = answers?.[`o${index}_coverage`]
		const rawScore = typeof value?.score === 'number' ? value.score : null
		// Jev scores are the expected 0-based rubric position (legend keys "0".."n-1"); normalize to [0, 1].
		const levels = value?.legend && typeof value.legend === 'object' ? Object.keys(value.legend).length : scoreCriteria.length
		const score = rawScore === null ? null : Math.min(1, Math.max(0, rawScore / Math.max(1, levels - 1)))
		const choice = coverage?.choice === 'none' || coverage?.choice === 'reduces' ? (coverage.choice as ConfidenceEffect) : null
		const reducesProbability = typeof coverage?.probabilities?.reduces === 'number' ? coverage.probabilities.reduces : null
		out.push({ score, coverage: choice, coverageProbability: reducesProbability })
	}
	return out
}

export function laneFor(opportunity: Opportunity & { confidenceEffect: ConfidenceEffect }): Lane {
	return opportunity.confidenceEffect === 'reduces' ? 'recommend' : 'work'
}

/**
 * Combine deterministic values with Jev's scores. Coverage is conservative:
 * an opportunity reduces coverage when the rules say so or when Jev leans
 * that way, and a reducing opportunity is never autopiloted.
 */
export function combineRanking(input: {
	opportunities: ReadonlyArray<Opportunity>
	jev: ReturnType<typeof parseJevAnswers> | null
}): RankedOpportunity[] {
	const ranked = input.opportunities.map((opportunity, index) => {
		const jev = input.jev?.[index] ?? null
		const det = deterministicScore(opportunity)
		const jevSaysReduces = jev?.coverage === 'reduces' || (jev?.coverageProbability ?? 0) > 0.5
		const confidenceEffect: ConfidenceEffect = opportunity.confidenceEffect === 'reduces' || jevSaysReduces ? 'reduces' : 'none'
		const score = jev?.score == null ? det : round(0.5 * det + 0.5 * jev.score, 3)
		const worthChanging =
			score >= worthThreshold &&
			(opportunity.minutesSavedPerPr >= 0.5 || opportunity.runnerMinutesSavedPerWeek >= 60 || opportunity.kind === 'fix-flaky')
		const merged = { ...opportunity, confidenceEffect }
		return {
			...merged,
			lane: laneFor(merged),
			deterministicScore: det,
			jevScore: jev?.score == null ? null : round(jev.score, 3),
			jevCoverage: jev?.coverage ?? null,
			score,
			worthChanging,
		}
	})
	return ranked.sort((a, b) => b.score - a.score || b.runnerMinutesSavedPerWeek - a.runnerMinutesSavedPerWeek)
}

/** Rank with the decision model (Clef, Jev-shaped questions) when available; fall back to the deterministic score when the call fails. */
export async function rankOpportunities(input: {
	metrics: Metrics
	opportunities: ReadonlyArray<Opportunity>
	evaluate: Evaluate | null
}) {
	const preOrdered = [...input.opportunities].sort((a, b) => deterministicScore(b) - deterministicScore(a))
	const forJev = preOrdered.slice(0, maxJevOpportunities)
	const rest = preOrdered.slice(maxJevOpportunities)
	let jev: ReturnType<typeof parseJevAnswers> | null = null
	let jevStatus: { used: boolean; error: string | null } = { used: false, error: null }
	if (input.evaluate && forJev.length) {
		try {
			const result = await input.evaluate(buildJevRequest(input.metrics, forJev))
			if (result?.ok) {
				jev = parseJevAnswers(result.answers, forJev.length)
				jevStatus = { used: true, error: null }
			} else {
				jevStatus = { used: false, error: truncate(result?.error ?? 'jev call failed', 200) }
			}
		} catch (error) {
			jevStatus = { used: false, error: truncate(error instanceof Error ? error.message : String(error), 200) }
		}
	}
	const ranked = [
		...combineRanking({ opportunities: forJev, jev }),
		...combineRanking({ opportunities: rest, jev: null }),
	].sort((a, b) => b.score - a.score || b.runnerMinutesSavedPerWeek - a.runnerMinutesSavedPerWeek)
	return { ranked, jev: jevStatus }
}