repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/iq/core.ts

Raw
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createInterface } from "node:readline";
import type { Api, Model, Usage } from "@earendil-works/pi-ai";

export const RECORD_VERSION = 2;
export const RUBRIC_VERSION = 1;
export const PROMPT_VERSION = 3;
/**
 * Pseudo-observations pulling a thin dimension toward the judge's own average.
 * Anchoring on a fixed rating would reward long sessions, because a lenient
 * judge moves every extra observation away from the anchor in one direction.
 */
export const EVIDENCE_PRIOR_WEIGHT = 2;
export const TELEMETRY_VERSION = 1;
export const CHUNK_TARGET_CHARS = 50_000;
export const MIN_USER_MESSAGES = 3;
export const MIN_TOOL_RESULTS = 1;
export const SESSION_SETTLE_MS = 5 * 60 * 1_000;

/** Rough aptitude buckets, derived from session shape rather than judged. */
export const ARCHETYPES = ["agentic", "worker", "texter"] as const;
export const MIN_ARCHETYPE_SESSIONS = 3;
export const TEXTER_CALLS_PER_TURN = 0.4;
export const TEXTER_TEXT_CHARS_PER_TURN = 600;
export const WORKER_EDIT_SHARE = 0.12;
export const AGENTIC_CALLS_PER_TURN = 1.15;
export const AGENTIC_EXTERNAL_SHARE = 0.2;
export const AGENTIC_DISTINCT_TOOLS = 6;
export const ARCHETYPE_WEIGHTS = { quality: 0.5, speed: 0.25, thrift: 0.25 };

const EDIT_TOOLS = new Set([
	"apply_patch",
	"edit",
	"multi_edit",
	"notebook_edit",
	"patch",
	"str_replace_editor",
	"write",
]);

const LOCAL_TOOLS = new Set([
	...EDIT_TOOLS,
	"bash",
	"find",
	"grep",
	"ls",
	"powershell",
	"read",
]);

export const DIMENSIONS = [
	{
		name: "comprehension_judgment",
		label: "judgment",
		weight: 0.25,
		description:
			"Understands the actual goal and constraints, finds root causes, chooses proportional scope, and makes sound engineering decisions.",
	},
	{
		name: "reasoning_adaptation",
		label: "adaptation",
		weight: 0.25,
		description:
			"Forms and tests useful hypotheses, integrates evidence, notices mistakes, and adapts rather than defending a failed path.",
	},
	{
		name: "context_management",
		label: "context",
		weight: 0.2,
		description:
			"Retains decisions and constraints across a long trajectory, uses compaction and harness context well, and avoids repeated drift.",
	},
	{
		name: "execution_reliability",
		label: "reliability",
		weight: 0.2,
		description:
			"Uses tools effectively, preserves safety boundaries and unrelated work, validates claims, and closes the requested loop.",
	},
	{
		name: "collaboration_steerability",
		label: "steerability",
		weight: 0.1,
		description:
			"Responds precisely to steering and corrections, communicates decision-relevant information, and leaves authority with the engineer.",
	},
] as const;

export type DimensionName = (typeof DIMENSIONS)[number]["name"];

export interface IqSettings {
	judgeModel?: string | null;
	/** Rotation pool, so more counter judges cost calibration breadth, not money. */
	counterJudgeModels?: string[] | null;
	/** Share of newly scored sessions that a counter judge also scores. */
	counterSampleRate?: number;
	/** Shared, synced state directory; unset means the per-host default. */
	stateDir?: string | null;
}

export type Archetype = (typeof ARCHETYPES)[number];
export type TaskType = Archetype | "mixed";

/** Share sampled when counter judges are configured but no rate is set. */
export const DEFAULT_COUNTER_SAMPLE_RATE = 0.2;

/**
 * Effective counter sampling share: an explicit rate always wins, configured
 * counter judges declare intent to sample, and without either nothing runs.
 */
export function effectiveCounterSampleRate(iq: IqSettings): number {
	if (iq.counterSampleRate !== undefined) return iq.counterSampleRate;
	return (iq.counterJudgeModels?.length ?? 0) > 0
		? DEFAULT_COUNTER_SAMPLE_RATE
		: 0;
}

/** Deterministic per-session facts that need no judge and carry their own version. */
export interface SessionTelemetry {
	version: typeof TELEMETRY_VERSION;
	sha256: string;
	model?: string;
	assistantTurns: number;
	toolCalls: number;
	distinctTools: number;
	editCalls: number;
	localCalls: number;
	assistantTextChars: number;
	userTextChars: number;
	inputTokens: number;
	outputTokens: number;
	cacheReadTokens: number;
	cacheWriteTokens: number;
	/** Provider-reported cost, zero on subscription plans, so never rank on it. */
	recordedCost: number;
	costSamples: number;
	latencyMs: number;
	latencySamples: number;
	outputTokensPerSecond: number | null;
	wallMs: number | null;
	taskType: TaskType;
}

export interface ModelRates {
	input: number;
	output: number;
	cacheRead: number;
	cacheWrite: number;
}

export type PriceLookup = (model: string) => ModelRates | undefined;

/** One scored session, shared by the local dashboard and cross-host exports. */
export interface SessionView {
	key: string;
	model: string;
	judge: string;
	rubricVersion: number;
	promptVersion: number;
	statistics: StatisticsCard;
	overall: number | null;
	dimensions: Record<DimensionName, number | null>;
	observations: number;
	scoredAt: string;
	name: string;
	taskType?: TaskType;
	telemetry?: SessionTelemetry;
	host?: string;
}

export interface ArchetypeCell {
	archetype: Archetype;
	sessions: number;
	quality: number;
	outputTokensPerSecond: number | null;
	costPerSession: number | null;
	fit: number | null;
}

export interface ModelArchetypes {
	model: string;
	label: Archetype | "generalist" | "unrated";
	cells: ArchetypeCell[];
}

export interface NormalizedEvent {
	id: string;
	at?: string;
	kind: string;
	[key: string]: unknown;
}

export interface SourceSignature {
	path: string;
	size: number;
	mtimeMs: number;
}

export interface TelemetryAccumulator {
	assistantTurns: number;
	toolCalls: number;
	tools: Set<string>;
	editCalls: number;
	localCalls: number;
	assistantTextChars: number;
	userTextChars: number;
	inputTokens: number;
	outputTokens: number;
	cacheReadTokens: number;
	cacheWriteTokens: number;
	recordedCost: number;
	costSamples: number;
	latencyMs: number;
	latencySamples: number;
}

export interface PreparedSession {
	source: SourceSignature & {
		sha256: string;
		sessionId: string;
		name: string;
		cwd: string;
		startedAt?: string;
		endedAt?: string;
		model?: string;
		userMessages: number;
		assistantMessages: number;
		toolResults: number;
		models: string[];
	};
	events: NormalizedEvent[];
	chunks: NormalizedEvent[][];
	sourceChars: number;
	eligibility: SessionEligibility;
	telemetry: SessionTelemetry;
}

export interface SessionPlan {
	source: PreparedSession["source"];
	sourceChars: number;
	chunkCount: number;
	eligibility: SessionEligibility;
	telemetry: SessionTelemetry;
}

export type SessionEligibility =
	| { ranked: true }
	| {
			ranked: false;
			reason: "trivial" | "mixed-model" | "model-missing" | "settling";
	  };

export interface EvidenceObservation {
	dimension: DimensionName;
	rating: number;
	importance: number;
	confidence: number;
	eventIds: string[];
	observation: string;
	sourceChunk: number;
}

export interface DimensionScore {
	score: number | null;
	meanRating: number | null;
	evidence: number;
	evidenceWeight: number;
}

/** Sufficient statistics: enough to rescore later without re-judging anything. */
export interface DimensionStatistics {
	weightedRating: number;
	weight: number;
	evidence: number;
}

export type StatisticsCard = Record<DimensionName, DimensionStatistics>;
export type Baseline = Record<DimensionName, number | null>;

export interface ScoreCard {
	overall: number | null;
	observedDimensionWeight: number;
	dimensions: Record<DimensionName, DimensionScore>;
}

export interface JudgeUsage {
	input: number;
	output: number;
	cacheRead: number;
	cacheWrite: number;
	totalTokens: number;
	cost: number;
	calls: number;
	retries: number;
	/** How often malformed judge output had to be cleaned up before scoring. */
	repairs: number;
}

export interface SessionScoreRecord {
	version: typeof RECORD_VERSION;
	rubricVersion: typeof RUBRIC_VERSION;
	promptVersion: typeof PROMPT_VERSION;
	source: PreparedSession["source"];
	judge: string;
	score: ScoreCard;
	observations: EvidenceObservation[];
	usage: JudgeUsage;
	chunkCount: number;
	elapsedMs: number;
	scoredAt: string;
	/** Provenance for shared, synced state directories. */
	host?: string;
}

export interface ModelAggregate {
	model: string;
	score: number;
	sessions: number;
	minimum: number;
	maximum: number;
	lastScoredAt: string;
	dimensions: Record<DimensionName, number | null>;
	evidence: number;
}

/** Measured behavior per model, from session telemetry rather than judging. */
export interface TelemetryAggregate {
	model: string;
	sessions: number;
	meanTurns: number;
	meanToolCalls: number;
	/** Edit calls as a share of all tool calls, percent. */
	editShare: number;
	meanOutputTokens: number;
	/** Cache-read share of the prompt stream, percent. */
	cacheReadShare: number;
	/** Mean latency per measured sample, 0 when nothing was sampled. */
	meanLatencyMs: number;
	meanTokensPerSecond: number | null;
	taskTypes: Partial<Record<TaskType, number>>;
}

export function aggregateTelemetry(
	entries: readonly { source: { model?: string; sha256: string } }[],
	telemetry: ReadonlyMap<string, SessionTelemetry>,
): TelemetryAggregate[] {
	const byModel = new Map<string, SessionTelemetry[]>();
	for (const entry of entries) {
		if (!entry.source.model) continue;
		const found = telemetry.get(entry.source.sha256);
		if (!found) continue;
		const list = byModel.get(entry.source.model) ?? [];
		list.push(found);
		byModel.set(entry.source.model, list);
	}
	const aggregates: TelemetryAggregate[] = [];
	for (const [model, list] of byModel) {
		const count = list.length;
		const sum = (pick: (entry: SessionTelemetry) => number) =>
			list.reduce((total, entry) => total + pick(entry), 0);
		const toolCalls = sum((entry) => entry.toolCalls);
		const input = sum((entry) => entry.inputTokens);
		const cacheRead = sum((entry) => entry.cacheReadTokens);
		const latencySamples = sum((entry) => entry.latencySamples);
		const speeds = list
			.map((entry) => entry.outputTokensPerSecond)
			.filter((value): value is number => value !== null);
		const taskTypes: Partial<Record<TaskType, number>> = {};
		for (const entry of list)
			taskTypes[entry.taskType] = (taskTypes[entry.taskType] ?? 0) + 1;
		aggregates.push({
			model,
			sessions: count,
			meanTurns: round(sum((entry) => entry.assistantTurns) / count, 1),
			meanToolCalls: round(toolCalls / count, 1),
			editShare:
				toolCalls > 0
					? round((100 * sum((entry) => entry.editCalls)) / toolCalls, 1)
					: 0,
			meanOutputTokens: round(sum((entry) => entry.outputTokens) / count, 0),
			cacheReadShare:
				input + cacheRead > 0
					? round((100 * cacheRead) / (input + cacheRead), 1)
					: 0,
			meanLatencyMs:
				latencySamples > 0
					? round(sum((entry) => entry.latencyMs) / latencySamples, 0)
					: 0,
			meanTokensPerSecond: speeds.length
				? round(
						speeds.reduce((total, value) => total + value, 0) / speeds.length,
						1,
					)
				: null,
			taskTypes,
		});
	}
	return aggregates.sort(
		(left, right) =>
			right.sessions - left.sessions || left.model.localeCompare(right.model),
	);
}

export interface ScanEstimate {
	calls: number;
	inputTokens: number;
	outputTokens: number;
	cost: number;
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}

function settingBlock(value: unknown): Record<string, unknown> {
	return isRecord(value) ? value : {};
}

function optionalSetting(
	merged: Record<string, unknown>,
	key: string,
	requirement: string,
): string | null | undefined {
	if (!(key in merged)) return undefined;
	const value = merged[key];
	if (value === null) return null;
	if (typeof value !== "string" || !value.trim())
		throw new Error(`iq.${key} must be ${requirement}`);
	return value.trim();
}

/** Accepts one reference or a list, so a single judge needs no array syntax. */
function referenceList(
	merged: Record<string, unknown>,
	key: string,
): string[] | null | undefined {
	if (!(key in merged)) return undefined;
	const value = merged[key];
	if (value === null) return null;
	const entries = Array.isArray(value) ? value : [value];
	const references: string[] = [];
	for (const entry of entries) {
		if (typeof entry !== "string" || !entry.trim())
			throw new Error(
				`iq.${key} must be provider/model, a list of provider/model, or null`,
			);
		const reference = entry.trim();
		if (!references.includes(reference)) references.push(reference);
	}
	return references.length > 0 ? references : null;
}

export function readIqSettings(
	globalSettings: unknown,
	projectSettings: unknown,
): IqSettings {
	const global = settingBlock(globalSettings);
	const project = settingBlock(projectSettings);
	const merged = {
		...settingBlock(global.iq),
		...settingBlock(project.iq),
	};
	const settings: IqSettings = {};
	const judgeModel = optionalSetting(
		merged,
		"judgeModel",
		"provider/model or null",
	);
	if (judgeModel !== undefined) settings.judgeModel = judgeModel;
	const counterJudgeModels = referenceList(merged, "counterJudgeModel");
	if (counterJudgeModels !== undefined)
		settings.counterJudgeModels = counterJudgeModels;
	const stateDir = optionalSetting(
		merged,
		"stateDir",
		"a directory path or null",
	);
	if (stateDir !== undefined) settings.stateDir = stateDir;
	if ("counterSampleRate" in merged) {
		const rate = merged.counterSampleRate;
		if (
			typeof rate !== "number" ||
			!Number.isFinite(rate) ||
			rate < 0 ||
			rate > 1
		)
			throw new Error("iq.counterSampleRate must be a number between 0 and 1");
		settings.counterSampleRate = rate;
	}
	return settings;
}

/**
 * Picks the counter-judge sample from session content, so the same sessions are
 * chosen on every host and every run instead of drifting with randomness.
 */
export function counterSampled(sha256: string, rate: number): boolean {
	if (!(rate > 0)) return false;
	if (rate >= 1) return true;
	const bucket = Number.parseInt(sha256.slice(0, 8), 16);
	return Number.isFinite(bucket) && bucket / 0xff_ff_ff_ff < rate;
}

/**
 * Assigns one judge out of a pool to a session, from content rather than order,
 * so the assignment survives reruns and is identical on every host.
 * Uses a different hash slice than the sample, keeping the two independent.
 */
export function judgeForSession<T>(
	sha256: string,
	pool: readonly T[],
): T | undefined {
	if (pool.length === 0) return undefined;
	const bucket = Number.parseInt(sha256.slice(8, 16), 16);
	return pool[Number.isFinite(bucket) ? bucket % pool.length : 0];
}

export function defaultModelReference(
	globalSettings: unknown,
	projectSettings: unknown,
): string | undefined {
	const global = settingBlock(globalSettings);
	const project = settingBlock(projectSettings);
	const provider = project.defaultProvider ?? global.defaultProvider;
	const model = project.defaultModel ?? global.defaultModel;
	return typeof provider === "string" &&
		typeof model === "string" &&
		provider.trim() &&
		model.trim()
		? `${provider.trim()}/${model.trim()}`
		: undefined;
}

export function parseModelReference(
	reference: string,
): { provider: string; modelId: string } | undefined {
	const separator = reference.indexOf("/");
	if (separator <= 0 || separator === reference.length - 1) return undefined;
	return {
		provider: reference.slice(0, separator),
		modelId: reference.slice(separator + 1),
	};
}

function textContent(content: unknown): string {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	return content
		.filter(
			(part): part is { type: "text"; text: string } =>
				isRecord(part) && part.type === "text" && typeof part.text === "string",
		)
		.map((part) => part.text)
		.join("\n");
}

function boundText(value: unknown, maximum: number): string {
	const text = String(value ?? "").replaceAll("\0", "");
	if (text.length <= maximum) return text;
	const side = Math.floor((maximum - 80) / 2);
	return `${text.slice(0, side)}\n…[${text.length - side * 2} chars omitted]…\n${text.slice(-side)}`;
}

function compactValue(value: unknown, depth = 0): unknown {
	if (depth > 4) return "[depth omitted]";
	if (typeof value === "string") return boundText(value, 1_200);
	if (Array.isArray(value))
		return value.slice(0, 20).map((item) => compactValue(item, depth + 1));
	if (isRecord(value)) {
		const result: Record<string, unknown> = {};
		for (const [key, child] of Object.entries(value).slice(0, 30))
			result[key] = compactValue(child, depth + 1);
		return result;
	}
	return value;
}

function normalizeMessageEntry(
	entry: Record<string, unknown>,
): NormalizedEvent | undefined {
	if (!isRecord(entry.message) || typeof entry.id !== "string")
		return undefined;
	const message = entry.message;
	const common = {
		id: entry.id,
		at: typeof entry.timestamp === "string" ? entry.timestamp : undefined,
	};
	if (message.role === "user") {
		return {
			...common,
			kind: "user",
			text: boundText(textContent(message.content), 8_000),
		};
	}
	if (message.role === "assistant") {
		const blocks = Array.isArray(message.content) ? message.content : [];
		const text = blocks
			.filter(
				(block): block is { type: "text"; text: string } =>
					isRecord(block) &&
					block.type === "text" &&
					typeof block.text === "string",
			)
			.map((block) => block.text)
			.join("\n");
		const toolCalls = blocks
			.filter(
				(block): block is Record<string, unknown> =>
					isRecord(block) &&
					block.type === "toolCall" &&
					typeof block.name === "string",
			)
			.map((block) => ({
				name: block.name,
				arguments: compactValue(block.arguments),
			}));
		return {
			...common,
			kind: "assistant",
			model:
				typeof message.provider === "string" &&
				typeof message.model === "string"
					? `${message.provider}/${message.model}`
					: undefined,
			stopReason: message.stopReason,
			errorMessage: boundText(message.errorMessage, 1_000),
			text: boundText(text, 4_000),
			toolCalls,
		};
	}
	if (message.role === "toolResult") {
		return {
			...common,
			kind: "toolResult",
			tool: message.toolName,
			isError: message.isError === true,
			text: boundText(
				textContent(message.content),
				message.isError === true ? 4_000 : 2_000,
			),
		};
	}
	return undefined;
}

function normalizeEntry(
	entry: Record<string, unknown>,
): NormalizedEvent | undefined {
	if (entry.type === "message") return normalizeMessageEntry(entry);
	if (typeof entry.id !== "string") return undefined;
	const common = {
		id: entry.id,
		at: typeof entry.timestamp === "string" ? entry.timestamp : undefined,
	};
	if (entry.type === "compaction") {
		return {
			...common,
			kind: "compaction",
			tokensBefore: entry.tokensBefore,
			summary: boundText(entry.summary, 6_000),
			implementation:
				isRecord(entry.details) && isRecord(entry.details.decay)
					? "decay"
					: "default",
		};
	}
	if (entry.type === "model_change")
		return {
			...common,
			kind: "modelChange",
			model: `${entry.provider}/${entry.modelId}`,
		};
	if (entry.type === "thinking_level_change")
		return {
			...common,
			kind: "thinkingLevelChange",
			thinkingLevel: entry.thinkingLevel,
		};
	if (entry.type === "branch_summary")
		return {
			...common,
			kind: "branchSummary",
			summary: boundText(entry.summary, 4_000),
		};
	if (entry.type === "custom_message")
		return {
			...common,
			kind: "customMessage",
			customType: entry.customType,
			text: boundText(textContent(entry.content), 2_000),
		};
	return undefined;
}

const MAX_PLAUSIBLE_LATENCY_MS = 30 * 60 * 1_000;

function numberAt(value: unknown, key: string): number {
	if (!isRecord(value)) return 0;
	const found = value[key];
	return typeof found === "number" && Number.isFinite(found) && found > 0
		? found
		: 0;
}

export function emptyTelemetryAccumulator(): TelemetryAccumulator {
	return {
		assistantTurns: 0,
		toolCalls: 0,
		tools: new Set<string>(),
		editCalls: 0,
		localCalls: 0,
		assistantTextChars: 0,
		userTextChars: 0,
		inputTokens: 0,
		outputTokens: 0,
		cacheReadTokens: 0,
		cacheWriteTokens: 0,
		recordedCost: 0,
		costSamples: 0,
		latencyMs: 0,
		latencySamples: 0,
	};
}

/** Accumulates cost, speed, and tool-shape facts that normalization drops. */
export function accumulateTelemetry(
	entry: Record<string, unknown>,
	total: TelemetryAccumulator,
): void {
	if (entry.type !== "message" || !isRecord(entry.message)) return;
	const message = entry.message;
	if (message.role === "user") {
		total.userTextChars += textContent(message.content).length;
		return;
	}
	if (message.role !== "assistant") return;
	total.assistantTurns++;
	const blocks = Array.isArray(message.content) ? message.content : [];
	for (const block of blocks) {
		if (!isRecord(block)) continue;
		if (block.type === "text" && typeof block.text === "string")
			total.assistantTextChars += block.text.length;
		if (block.type === "toolCall" && typeof block.name === "string") {
			const name = block.name.toLowerCase();
			total.toolCalls++;
			total.tools.add(name);
			if (EDIT_TOOLS.has(name)) total.editCalls++;
			if (LOCAL_TOOLS.has(name)) total.localCalls++;
		}
	}
	const usage = message.usage;
	total.inputTokens += numberAt(usage, "input");
	total.outputTokens += numberAt(usage, "output");
	total.cacheReadTokens += numberAt(usage, "cacheRead");
	total.cacheWriteTokens += numberAt(usage, "cacheWrite");
	const cost = isRecord(usage) ? numberAt(usage.cost, "total") : 0;
	if (cost > 0) {
		total.recordedCost += cost;
		total.costSamples++;
	}
	const requestedAt = message.timestamp;
	const persistedAt =
		typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
	if (typeof requestedAt !== "number" || Number.isNaN(persistedAt)) return;
	const latency = persistedAt - requestedAt;
	if (latency <= 0 || latency > MAX_PLAUSIBLE_LATENCY_MS) return;
	total.latencyMs += latency;
	total.latencySamples++;
}

/** Rough bucket for what the session was, not for how good the model is. */
export function classifyTaskType(
	telemetry: Omit<SessionTelemetry, "taskType">,
): TaskType {
	const turns = Math.max(1, telemetry.assistantTurns);
	const callsPerTurn = telemetry.toolCalls / turns;
	const textPerTurn = telemetry.assistantTextChars / turns;
	const editShare = telemetry.toolCalls
		? telemetry.editCalls / telemetry.toolCalls
		: 0;
	const externalShare = telemetry.toolCalls
		? 1 - telemetry.localCalls / telemetry.toolCalls
		: 0;
	if (
		telemetry.toolCalls === 0 ||
		(callsPerTurn < TEXTER_CALLS_PER_TURN &&
			textPerTurn > TEXTER_TEXT_CHARS_PER_TURN)
	)
		return "texter";
	if (editShare >= WORKER_EDIT_SHARE) return "worker";
	if (
		callsPerTurn >= AGENTIC_CALLS_PER_TURN ||
		externalShare >= AGENTIC_EXTERNAL_SHARE ||
		telemetry.distinctTools >= AGENTIC_DISTINCT_TOOLS
	)
		return "agentic";
	return "mixed";
}

export function finishTelemetry(
	total: TelemetryAccumulator,
	source: {
		sha256: string;
		model?: string;
		startedAt?: string;
		endedAt?: string;
	},
): SessionTelemetry {
	const started = source.startedAt ? Date.parse(source.startedAt) : NaN;
	const ended = source.endedAt ? Date.parse(source.endedAt) : NaN;
	const wallMs =
		Number.isNaN(started) || Number.isNaN(ended) || ended < started
			? null
			: ended - started;
	const partial = {
		version: TELEMETRY_VERSION,
		sha256: source.sha256,
		model: source.model,
		assistantTurns: total.assistantTurns,
		toolCalls: total.toolCalls,
		distinctTools: total.tools.size,
		editCalls: total.editCalls,
		localCalls: total.localCalls,
		assistantTextChars: total.assistantTextChars,
		userTextChars: total.userTextChars,
		inputTokens: total.inputTokens,
		outputTokens: total.outputTokens,
		cacheReadTokens: total.cacheReadTokens,
		cacheWriteTokens: total.cacheWriteTokens,
		recordedCost: Number(total.recordedCost.toFixed(6)),
		costSamples: total.costSamples,
		latencyMs: Math.round(total.latencyMs),
		latencySamples: total.latencySamples,
		outputTokensPerSecond:
			total.latencyMs > 0 && total.outputTokens > 0
				? Number((total.outputTokens / (total.latencyMs / 1_000)).toFixed(2))
				: null,
		wallMs,
	} satisfies Omit<SessionTelemetry, "taskType">;
	return { ...partial, taskType: classifyTaskType(partial) };
}

export async function fileSha256(
	path: string,
	signal?: AbortSignal,
): Promise<string> {
	const hash = createHash("sha256");
	for await (const chunk of createReadStream(path)) {
		signal?.throwIfAborted();
		hash.update(chunk);
	}
	return hash.digest("hex");
}

export function chunkEvents(
	events: readonly NormalizedEvent[],
	targetChars = CHUNK_TARGET_CHARS,
): NormalizedEvent[][] {
	const chunks: NormalizedEvent[][] = [];
	let current: NormalizedEvent[] = [];
	let chars = 0;
	for (const event of events) {
		const eventChars = JSON.stringify(event).length;
		if (current.length > 0 && chars + eventChars > targetChars) {
			chunks.push(current);
			current = [];
			chars = 0;
		}
		current.push(event);
		chars += eventChars;
	}
	if (current.length > 0) chunks.push(current);
	return chunks;
}

export function eligibilityFor(input: {
	userMessages: number;
	toolResults: number;
	models: readonly string[];
	mtimeMs: number;
	now?: number;
}): SessionEligibility {
	if ((input.now ?? Date.now()) - input.mtimeMs < SESSION_SETTLE_MS)
		return { ranked: false, reason: "settling" };
	if (input.models.length === 0)
		return { ranked: false, reason: "model-missing" };
	if (input.models.length > 1) return { ranked: false, reason: "mixed-model" };
	if (
		input.userMessages < MIN_USER_MESSAGES ||
		input.toolResults < MIN_TOOL_RESULTS
	)
		return { ranked: false, reason: "trivial" };
	return { ranked: true };
}

export async function prepareSession(
	path: string,
	now = Date.now(),
	signal?: AbortSignal,
): Promise<PreparedSession> {
	const before = await stat(path);
	const events: NormalizedEvent[] = [];
	const models = new Set<string>();
	let sessionId = "";
	let name = "";
	let cwd = "";
	let startedAt: string | undefined;
	let endedAt: string | undefined;
	let userMessages = 0;
	let assistantMessages = 0;
	let toolResults = 0;
	const telemetry = emptyTelemetryAccumulator();
	const hash = createHash("sha256");
	const stream = createReadStream(path);
	stream.on("data", (data) => hash.update(data));
	const lines = createInterface({ input: stream, crlfDelay: Infinity });
	for await (const line of lines) {
		signal?.throwIfAborted();
		if (!line.trim()) continue;
		const parsed: unknown = JSON.parse(line);
		if (!isRecord(parsed)) continue;
		if (parsed.type === "session") {
			if (typeof parsed.id === "string") sessionId = parsed.id;
			if (typeof parsed.cwd === "string") cwd = parsed.cwd;
			if (typeof parsed.timestamp === "string") startedAt = parsed.timestamp;
			continue;
		}
		if (typeof parsed.timestamp === "string") endedAt = parsed.timestamp;
		if (parsed.type === "session_info" && typeof parsed.name === "string")
			name = parsed.name;
		accumulateTelemetry(parsed, telemetry);
		const event = normalizeEntry(parsed);
		if (!event) continue;
		events.push(event);
		if (event.kind === "user") userMessages++;
		if (event.kind === "toolResult") toolResults++;
		if (event.kind === "assistant") {
			assistantMessages++;
			if (typeof event.model === "string") models.add(event.model);
		}
	}
	const after = await stat(path);
	if (before.size !== after.size || before.mtimeMs !== after.mtimeMs)
		throw new Error("session changed while being read");
	const chunks = chunkEvents(events);
	const modelList = [...models].sort();
	const sha256 = hash.digest("hex");
	return {
		source: {
			path,
			size: after.size,
			mtimeMs: after.mtimeMs,
			sha256,
			sessionId,
			name,
			cwd,
			startedAt,
			endedAt,
			model: modelList.length === 1 ? modelList[0] : undefined,
			userMessages,
			assistantMessages,
			toolResults,
			models: modelList,
		},
		events,
		chunks,
		sourceChars: events.reduce(
			(total, event) => total + JSON.stringify(event).length,
			0,
		),
		eligibility: eligibilityFor({
			userMessages,
			toolResults,
			models: modelList,
			mtimeMs: after.mtimeMs,
			now,
		}),
		telemetry: finishTelemetry(telemetry, {
			sha256,
			model: modelList.length === 1 ? modelList[0] : undefined,
			startedAt,
			endedAt,
		}),
	};
}

export function sessionPlan(prepared: PreparedSession): SessionPlan {
	return {
		source: prepared.source,
		sourceChars: prepared.sourceChars,
		chunkCount: prepared.chunks.length,
		eligibility: prepared.eligibility,
		telemetry: prepared.telemetry,
	};
}

export function reduceScore(
	observations: readonly EvidenceObservation[],
): ScoreCard {
	const dimensions = {} as Record<DimensionName, DimensionScore>;
	let weightedScore = 0;
	let observedDimensionWeight = 0;
	for (const definition of DIMENSIONS) {
		const found = observations.filter(
			(observation) => observation.dimension === definition.name,
		);
		if (found.length === 0) {
			dimensions[definition.name] = {
				score: null,
				meanRating: null,
				evidence: 0,
				evidenceWeight: 0,
			};
			continue;
		}
		let weightedRating = 9;
		let totalWeight = 3;
		for (const observation of found) {
			const weight = observation.importance * observation.confidence;
			weightedRating += observation.rating * weight;
			totalWeight += weight;
		}
		const meanRating = weightedRating / totalWeight;
		const score = Number((100 + 15 * (meanRating - 3)).toFixed(1));
		dimensions[definition.name] = {
			score,
			meanRating: Number(meanRating.toFixed(3)),
			evidence: found.length,
			evidenceWeight: Number((totalWeight - 3).toFixed(2)),
		};
		weightedScore += score * definition.weight;
		observedDimensionWeight += definition.weight;
	}
	return {
		overall:
			observedDimensionWeight > 0
				? Number((weightedScore / observedDimensionWeight).toFixed(1))
				: null,
		observedDimensionWeight: Number(observedDimensionWeight.toFixed(2)),
		dimensions,
	};
}

/** Coerces thrown values to Error for uniform handling. */
export function asError(value: unknown): Error {
	return value instanceof Error ? value : new Error(String(value));
}

/** One-line, length-capped message for UI surfaces and records. */
export function boundedError(value: unknown): string {
	return asError(value).message.replaceAll(/\s+/g, " ").slice(0, 300);
}

export function emptyJudgeUsage(): JudgeUsage {
	return {
		input: 0,
		output: 0,
		cacheRead: 0,
		cacheWrite: 0,
		totalTokens: 0,
		cost: 0,
		calls: 0,
		retries: 0,
		repairs: 0,
	};
}

export function addUsage(
	total: JudgeUsage,
	usage: Usage,
	attempts: number,
): void {
	total.input += usage.input;
	total.output += usage.output;
	total.cacheRead += usage.cacheRead;
	total.cacheWrite += usage.cacheWrite;
	total.totalTokens += usage.totalTokens;
	total.cost += usage.cost.total;
	total.calls++;
	total.retries += attempts - 1;
}

function ratesFor(model: Model<Api>, inputTokens: number) {
	let rates = model.cost;
	for (const tier of [...(model.cost.tiers ?? [])].sort(
		(left, right) => left.inputTokensAbove - right.inputTokensAbove,
	)) {
		if (inputTokens > tier.inputTokensAbove) rates = tier;
	}
	return rates;
}

export function estimateScan(
	plans: readonly SessionPlan[],
	model: Model<Api>,
): ScanEstimate {
	let calls = 0;
	let inputTokens = 0;
	let outputTokens = 0;
	let cost = 0;
	for (const plan of plans) {
		const sourcePerChunk =
			plan.chunkCount > 0 ? plan.sourceChars / 4 / plan.chunkCount : 0;
		for (let chunk = 0; chunk < plan.chunkCount; chunk++) {
			const requestInput = Math.ceil(
				sourcePerChunk + 1_800 + Math.min(chunk * 350, 12_000),
			);
			const requestOutput = 400;
			const rates = ratesFor(model, requestInput);
			calls++;
			inputTokens += requestInput;
			outputTokens += requestOutput;
			cost +=
				(requestInput * rates.input + requestOutput * rates.output) / 1_000_000;
		}
	}
	return { calls, inputTokens, outputTokens, cost };
}

export function viewFromRecord(
	record: SessionScoreRecord,
	telemetry?: SessionTelemetry,
	host?: string,
): SessionView {
	const dimensions = {} as Record<DimensionName, number | null>;
	for (const definition of DIMENSIONS)
		dimensions[definition.name] =
			record.score.dimensions[definition.name].score;
	return {
		key: record.source.sha256,
		model: record.source.model ?? "",
		judge: record.judge,
		rubricVersion: record.rubricVersion,
		promptVersion: record.promptVersion,
		statistics: statisticsFrom(record.observations),
		overall: record.score.overall,
		dimensions,
		observations: record.observations.length,
		scoredAt: record.scoredAt,
		name: record.source.name || record.source.sessionId,
		taskType: telemetry?.taskType,
		telemetry,
		host,
	};
}

function mean(values: readonly number[]): number {
	return values.reduce((sum, value) => sum + value, 0) / values.length;
}

export function statisticsFrom(
	observations: readonly EvidenceObservation[],
): StatisticsCard {
	const card = {} as StatisticsCard;
	for (const definition of DIMENSIONS)
		card[definition.name] = { weightedRating: 0, weight: 0, evidence: 0 };
	for (const observation of observations) {
		const entry = card[observation.dimension];
		const weight = observation.importance * observation.confidence;
		entry.weightedRating += observation.rating * weight;
		entry.weight += weight;
		entry.evidence++;
	}
	return card;
}

/** The judge's own average rating per dimension, which anchors every score. */
export function baselineFrom(cards: readonly StatisticsCard[]): Baseline {
	const baseline = {} as Baseline;
	for (const definition of DIMENSIONS) {
		let weightedRating = 0;
		let weight = 0;
		for (const card of cards) {
			weightedRating += card[definition.name].weightedRating;
			weight += card[definition.name].weight;
		}
		baseline[definition.name] = weight > 0 ? weightedRating / weight : null;
	}
	return baseline;
}

/**
 * Scores one session relative to the judge's own average, so judge leniency
 * cancels out and 100 means typical rather than competent.
 */
export function scoreFromStatistics(
	card: StatisticsCard,
	baseline: Baseline,
	priorWeight = EVIDENCE_PRIOR_WEIGHT,
): ScoreCard {
	const dimensions = {} as Record<DimensionName, DimensionScore>;
	let weightedScore = 0;
	let observedDimensionWeight = 0;
	for (const definition of DIMENSIONS) {
		const entry = card[definition.name];
		if (entry.evidence === 0) {
			dimensions[definition.name] = {
				score: null,
				meanRating: null,
				evidence: 0,
				evidenceWeight: 0,
			};
			continue;
		}
		const center = baseline[definition.name] ?? 3;
		const meanRating =
			(center * priorWeight + entry.weightedRating) /
			(priorWeight + entry.weight);
		const score = Number((100 + 15 * (meanRating - center)).toFixed(1));
		dimensions[definition.name] = {
			score,
			meanRating: Number(meanRating.toFixed(3)),
			evidence: entry.evidence,
			evidenceWeight: Number(entry.weight.toFixed(2)),
		};
		weightedScore += score * definition.weight;
		observedDimensionWeight += definition.weight;
	}
	return {
		overall:
			observedDimensionWeight > 0
				? Number((weightedScore / observedDimensionWeight).toFixed(1))
				: null,
		observedDimensionWeight: Number(observedDimensionWeight.toFixed(2)),
		dimensions,
	};
}

/** Rescores a whole scope against its own baseline; no judging is repeated. */
export function rescoreViews(
	views: readonly SessionView[],
	priorWeight = EVIDENCE_PRIOR_WEIGHT,
): SessionView[] {
	const baseline = baselineFrom(views.map((view) => view.statistics));
	return views.map((view) => {
		const score = scoreFromStatistics(view.statistics, baseline, priorWeight);
		const dimensions = {} as Record<DimensionName, number | null>;
		for (const definition of DIMENSIONS)
			dimensions[definition.name] = score.dimensions[definition.name].score;
		return { ...view, overall: score.overall, dimensions };
	});
}

function round(value: number, digits = 1): number {
	return Number(value.toFixed(digits));
}

export function aggregateScored(
	views: readonly SessionView[],
): ModelAggregate[] {
	const byModel = new Map<string, SessionView[]>();
	for (const view of views) {
		if (!view.model || view.overall === null) continue;
		const found = byModel.get(view.model) ?? [];
		found.push(view);
		byModel.set(view.model, found);
	}
	const result: ModelAggregate[] = [];
	for (const [model, modelViews] of byModel) {
		const scores = modelViews
			.map((view) => view.overall)
			.filter((score): score is number => score !== null);
		const dimensions = {} as Record<DimensionName, number | null>;
		for (const definition of DIMENSIONS) {
			const found = modelViews
				.map((view) => view.dimensions[definition.name])
				.filter((score): score is number => score !== null);
			dimensions[definition.name] = found.length ? round(mean(found)) : null;
		}
		result.push({
			model,
			score: round(mean(scores)),
			sessions: modelViews.length,
			minimum: Math.min(...scores),
			maximum: Math.max(...scores),
			lastScoredAt:
				modelViews
					.map((view) => view.scoredAt)
					.sort()
					.at(-1) ?? "",
			dimensions,
			evidence: modelViews.reduce(
				(total, view) => total + view.observations,
				0,
			),
		});
	}
	return result.sort(
		(left, right) =>
			right.score - left.score || left.model.localeCompare(right.model),
	);
}

export function aggregateModels(
	records: readonly SessionScoreRecord[],
	telemetry?: ReadonlyMap<string, SessionTelemetry>,
): ModelAggregate[] {
	return aggregateScored(
		records.map((record) =>
			viewFromRecord(record, telemetry?.get(record.source.sha256)),
		),
	);
}

export interface JudgeAgreement {
	counter: string;
	pairs: number;
	meanAbsolute: number;
	bias: number;
	/** Per-model bias exposes judge favouritism, the reason to run a counter. */
	perModel: { model: string; pairs: number; bias: number }[];
}

/**
 * Compares two judges on the sessions both scored.
 * Bias is counter minus primary, so a positive value means the counter is kinder.
 */
export function compareJudges(
	records: readonly SessionScoreRecord[],
	primary: string,
	counter: string,
): JudgeAgreement | undefined {
	const byKey = new Map<
		string,
		{ primary?: number; counter?: number; model: string }
	>();
	for (const record of records) {
		if (record.score.overall === null) continue;
		if (record.rubricVersion !== RUBRIC_VERSION) continue;
		if (record.promptVersion !== PROMPT_VERSION) continue;
		const side =
			record.judge === primary
				? "primary"
				: record.judge === counter
					? "counter"
					: undefined;
		if (!side) continue;
		const found = byKey.get(record.source.sha256) ?? {
			model: record.source.model ?? "",
		};
		found[side] = record.score.overall;
		byKey.set(record.source.sha256, found);
	}
	const differences: number[] = [];
	const byModel = new Map<string, number[]>();
	for (const pair of byKey.values()) {
		if (pair.primary === undefined || pair.counter === undefined) continue;
		const difference = pair.counter - pair.primary;
		differences.push(difference);
		if (!pair.model) continue;
		const found = byModel.get(pair.model) ?? [];
		found.push(difference);
		byModel.set(pair.model, found);
	}
	if (differences.length === 0) return undefined;
	return {
		counter,
		pairs: differences.length,
		meanAbsolute: round(mean(differences.map(Math.abs))),
		bias: round(mean(differences)),
		perModel: [...byModel]
			.map(([model, values]) => ({
				model,
				pairs: values.length,
				bias: round(mean(values)),
			}))
			.sort((left, right) => Math.abs(right.bias) - Math.abs(left.bias)),
	};
}

/** One agreement per counter that actually shares sessions with the judge. */
export function compareAllJudges(
	records: readonly SessionScoreRecord[],
	primary: string,
	counters: readonly string[],
): JudgeAgreement[] {
	return counters
		.map((counter) => compareJudges(records, primary, counter))
		.filter((entry): entry is JudgeAgreement => entry !== undefined)
		.sort(
			(left, right) =>
				right.pairs - left.pairs || left.counter.localeCompare(right.counter),
		);
}

export function priceSession(
	telemetry: SessionTelemetry,
	rates: ModelRates,
): number {
	return (
		(telemetry.inputTokens * rates.input +
			telemetry.outputTokens * rates.output +
			telemetry.cacheReadTokens * rates.cacheRead +
			telemetry.cacheWriteTokens * rates.cacheWrite) /
		1_000_000
	);
}

/** Percentile rank in [0,1]; a lone sample sits in the middle, never at the top. */
function percentile(values: readonly number[], value: number): number {
	if (values.length < 2) return 0.5;
	const below = values.filter((other) => other < value).length;
	const equal = values.filter((other) => other === value).length;
	return (below + (equal - 1) / 2) / (values.length - 1);
}

/**
 * Combines judged quality with measured speed and current prices.
 * Fit is relative to the models present, so it moves when the field moves.
 */
export function aggregateArchetypes(
	views: readonly SessionView[],
	prices: PriceLookup = () => undefined,
): ModelArchetypes[] {
	const cells = new Map<string, Map<Archetype, SessionView[]>>();
	for (const view of views) {
		const archetype = view.taskType;
		if (!view.model || view.overall === null || !archetype) continue;
		if (archetype === "mixed") continue;
		const byArchetype = cells.get(view.model) ?? new Map();
		const found = byArchetype.get(archetype) ?? [];
		found.push(view);
		byArchetype.set(archetype, found);
		cells.set(view.model, byArchetype);
	}
	const raw = new Map<string, ArchetypeCell[]>();
	for (const [model, byArchetype] of cells) {
		const list: ArchetypeCell[] = [];
		for (const archetype of ARCHETYPES) {
			const found = byArchetype.get(archetype);
			if (!found?.length) continue;
			const speeds = found
				.map((view) => view.telemetry?.outputTokensPerSecond)
				.filter((speed): speed is number => typeof speed === "number");
			const rates = prices(model);
			const costs = rates
				? found
						.map((view) => view.telemetry)
						.filter((item): item is SessionTelemetry => item !== undefined)
						.map((item) => priceSession(item, rates))
				: [];
			list.push({
				archetype,
				sessions: found.length,
				quality: round(
					mean(
						found
							.map((view) => view.overall)
							.filter((score): score is number => score !== null),
					),
				),
				outputTokensPerSecond: speeds.length ? round(mean(speeds)) : null,
				costPerSession: costs.length ? round(mean(costs), 4) : null,
				fit: null,
			});
		}
		if (list.length) raw.set(model, list);
	}
	const ranked = [...raw.values()]
		.flat()
		.filter((cell) => cell.sessions >= MIN_ARCHETYPE_SESSIONS);
	const field = new Map<
		Archetype,
		{ quality: number[]; speed: number[]; cost: number[] }
	>();
	for (const archetype of ARCHETYPES) {
		const found = ranked.filter((cell) => cell.archetype === archetype);
		field.set(archetype, {
			quality: found.map((cell) => cell.quality),
			speed: found
				.map((cell) => cell.outputTokensPerSecond)
				.filter((speed): speed is number => speed !== null),
			cost: found
				.map((cell) => cell.costPerSession)
				.filter((cost): cost is number => cost !== null),
		});
	}
	const result: ModelArchetypes[] = [];
	for (const [model, list] of raw) {
		for (const cell of list) {
			if (cell.sessions < MIN_ARCHETYPE_SESSIONS) continue;
			const reference = field.get(cell.archetype);
			if (!reference) continue;
			let weighted = ARCHETYPE_WEIGHTS.quality;
			let score =
				percentile(reference.quality, cell.quality) * ARCHETYPE_WEIGHTS.quality;
			if (cell.outputTokensPerSecond !== null && reference.speed.length) {
				score +=
					percentile(reference.speed, cell.outputTokensPerSecond) *
					ARCHETYPE_WEIGHTS.speed;
				weighted += ARCHETYPE_WEIGHTS.speed;
			}
			if (cell.costPerSession !== null && reference.cost.length) {
				score +=
					(1 - percentile(reference.cost, cell.costPerSession)) *
					ARCHETYPE_WEIGHTS.thrift;
				weighted += ARCHETYPE_WEIGHTS.thrift;
			}
			cell.fit = round((score / weighted) * 100);
		}
		const rated = list.filter(
			(cell): cell is ArchetypeCell & { fit: number } => cell.fit !== null,
		);
		const best = [...rated].sort(
			(left, right) => right.fit - left.fit || right.quality - left.quality,
		);
		const leader = best[0];
		const runnerUp = best[1];
		result.push({
			model,
			label: !leader
				? "unrated"
				: runnerUp && leader.fit - runnerUp.fit < 5
					? "generalist"
					: leader.archetype,
			cells: list,
		});
	}
	return result.sort((left, right) => left.model.localeCompare(right.model));
}