repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/aftermath-scoring.ts

Raw
File outline
import { createHash } from "node:crypto";
import { defineTool } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import {
	canonicalJson,
	type DeterministicCheck,
	defaultStructuredOutputSdk,
	type FrozenTask,
	type StructuredOutputSdkSeam,
} from "./aftermath-mining.ts";
import type { CheckerResult } from "./checker.ts";

export type DeterministicCheckResult = {
	type: DeterministicCheck["type"];
	passed: boolean;
};

export type DeterministicScore = {
	score: number;
	passed: boolean;
	checks: DeterministicCheckResult[];
};

export function normalizeResponse(response: string): string {
	return response.replace(/\r\n?/g, "\n");
}

function normalizedHeading(value: string): string {
	return value.trim().replace(/\s+/gu, " ").toLowerCase();
}

function hasAtxHeading(response: string, expected: string): boolean {
	for (const line of normalizeResponse(response).split("\n")) {
		const match = /^(?:#{1,6})[\t ]+(.*)$/u.exec(line);
		if (!match) continue;
		const content = (match[1] ?? "").replace(/[\t ]*#+[\t ]*$/u, "");
		if (normalizedHeading(content) === normalizedHeading(expected)) return true;
	}
	return false;
}

function evaluateCheck(response: string, check: DeterministicCheck): boolean {
	const normalized = normalizeResponse(response);
	if (check.type === "contains") {
		if (check.caseSensitive) return normalized.includes(check.value);
		return normalized.toLowerCase().includes(check.value.toLowerCase());
	}
	if (check.type === "section_present")
		return hasAtxHeading(normalized, check.heading);
	const count = Array.from(normalized).length;
	return check.type === "min_chars"
		? count >= check.count
		: count <= check.count;
}

/** Scores declaration-order local checks without invoking a model. */
export function evaluateDeterministicChecks(
	response: string,
	checks: readonly DeterministicCheck[],
): DeterministicScore {
	if (checks.length === 0)
		throw new Error("deterministic task requires checks");
	const results = checks.map((check) => ({
		type: check.type,
		passed: evaluateCheck(response, check),
	}));
	const passedCount = results.filter((result) => result.passed).length;
	return {
		score: passedCount / results.length,
		passed: passedCount === results.length,
		checks: results,
	};
}

export function responseHash(response: string): string {
	return createHash("sha256")
		.update(normalizeResponse(response), "utf8")
		.digest("hex");
}

const rubricOutput = defineTool({
	name: "structured_output",
	label: "Structured output",
	description: "Return one rubric judgment as the final action.",
	parameters: Type.Object(
		{
			score: Type.Number({ minimum: 0, maximum: 1 }),
			passed: Type.Boolean(),
			rationale: Type.String({
				maxLength: 4096,
				description: "At most 4096 UTF-8 bytes.",
			}),
		},
		{ additionalProperties: false },
	),
	async execute(_id, params) {
		return {
			content: [{ type: "text" as const, text: "Rubric judgment received." }],
			details: params,
			terminate: true,
		};
	},
});

export type RubricJudgeSession = {
	prompt: (
		text: string,
		options?: { expandPromptTemplates?: boolean },
	) => Promise<void>;
	subscribe: (
		listener: (event: {
			type: string;
			toolName?: string;
			isError?: boolean;
			result?: { details?: unknown };
		}) => void,
	) => () => void;
	abort: () => Promise<void>;
	dispose: () => void | Promise<void>;
};

export async function createRubricJudgeSession(
	options: {
		cwd: string;
		agentDir: string;
		model: { thinking: string };
		targetModel: unknown;
	},
	sdk: StructuredOutputSdkSeam = defaultStructuredOutputSdk,
): Promise<RubricJudgeSession> {
	const settingsManager = sdk.SettingsManager.inMemory({
		compaction: { enabled: false },
		retry: { enabled: false },
	});
	const loader = new sdk.DefaultResourceLoader({
		cwd: options.cwd,
		agentDir: options.agentDir,
		settingsManager,
		noExtensions: true,
		noSkills: true,
		noPromptTemplates: true,
		noThemes: true,
		noContextFiles: true,
	});
	await loader.reload();
	const result = await sdk.createAgentSession({
		cwd: options.cwd,
		agentDir: options.agentDir,
		model: options.targetModel as never,
		thinkingLevel: options.model.thinking as never,
		tools: ["structured_output"],
		customTools: [rubricOutput],
		sessionManager: sdk.SessionManager.inMemory(options.cwd),
		settingsManager,
		resourceLoader: loader,
	});
	return result.session as unknown as RubricJudgeSession;
}

export class RubricJudgeCancelledError extends Error {
	constructor() {
		super("rubric judge cancelled");
	}
}

export type RubricJudgeResult = {
	score: number;
	passed: boolean;
	rationale: string;
	cacheKey: string;
};

class RubricJudgeOutputError extends Error {}

function boundedResponse(response: string): string {
	const maximum = 64 * 1024;
	const marker = "…[truncated]";
	if (Buffer.byteLength(response, "utf8") <= maximum)
		return normalizeResponse(response);
	let result = "";
	for (const character of normalizeResponse(response)) {
		if (
			Buffer.byteLength(result, "utf8") +
				Buffer.byteLength(character, "utf8") +
				Buffer.byteLength(marker, "utf8") >
			maximum
		)
			break;
		result += character;
	}
	return `${result}${marker}`;
}

export function rubricCacheKey(taskId: string, response: string): string {
	return `${taskId}:${responseHash(boundedResponse(response))}`;
}

function judgeResult(value: unknown): Omit<RubricJudgeResult, "cacheKey"> {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new RubricJudgeOutputError("rubric judge output must be an object");
	const record = value as Record<string, unknown>;
	if (
		Object.keys(record).length !== 3 ||
		Object.keys(record).some(
			(key) => key !== "score" && key !== "passed" && key !== "rationale",
		)
	)
		throw new RubricJudgeOutputError("rubric judge output has unknown fields");
	if (
		typeof record.score !== "number" ||
		!Number.isFinite(record.score) ||
		record.score < 0 ||
		record.score > 1 ||
		typeof record.passed !== "boolean" ||
		typeof record.rationale !== "string" ||
		Buffer.byteLength(record.rationale, "utf8") > 4096
	)
		throw new RubricJudgeOutputError("rubric judge output is invalid");
	return {
		score: record.score,
		passed: record.passed,
		rationale: record.rationale,
	};
}

export function generatedTaskPrompt(
	task: Pick<FrozenTask, "intent" | "context">,
): string {
	return `${task.intent}\n\nContext:\n${task.context}`;
}

export function createGeneratedTaskScorer(
	tasks: readonly FrozenTask[],
	options: {
		judge?: (
			task: FrozenTask,
			response: string,
			signal?: AbortSignal,
		) => Promise<Pick<RubricJudgeResult, "score" | "passed" | "rationale">>;
	} = {},
): (options: {
	id: string;
	response: string;
	signal?: AbortSignal;
}) => Promise<CheckerResult> {
	const byId = new Map(tasks.map((task) => [task.id, task]));
	return async ({ id, response, signal }) => {
		const task = byId.get(id);
		if (!task) throw new Error("generated task is not frozen");
		if (task.checks) {
			const result = evaluateDeterministicChecks(response, task.checks);
			return {
				score: result.score,
				passed: result.passed,
				feedback: `${result.checks.filter((check) => check.passed).length}/${result.checks.length} deterministic checks passed`,
				checks: result.checks,
			};
		}
		if (!task.rubric || !options.judge)
			throw new Error("rubric task requires a frozen judge");
		const result = await options.judge(task, response, signal);
		return {
			score: result.score,
			passed: result.passed,
			feedback: result.rationale,
		};
	};
}

type RubricTask = Pick<
	FrozenTask,
	| "id"
	| "intent"
	| "context"
	| "sourceSessionIds"
	| "observedOutcome"
	| "rubric"
>;

/** Retries one malformed structured output in a fresh judge session. */
export async function runRubricJudge(
	task: RubricTask,
	response: string,
	seam: { createSession: () => Promise<RubricJudgeSession> },
	signal?: AbortSignal,
	onCall?: () => Promise<void>,
): Promise<RubricJudgeResult> {
	for (let attempt = 0; ; attempt += 1) {
		try {
			return await runRubricJudgeAttempt(task, response, seam, signal, onCall);
		} catch (error) {
			if (!(error instanceof RubricJudgeOutputError) || attempt === 1)
				throw error;
		}
	}
}

async function runRubricJudgeAttempt(
	task: RubricTask,
	response: string,
	seam: { createSession: () => Promise<RubricJudgeSession> },
	signal?: AbortSignal,
	onCall?: () => Promise<void>,
): Promise<RubricJudgeResult> {
	if (!task.rubric) throw new Error("rubric task requires a rubric");
	const session = await seam.createSession();
	const bounded = boundedResponse(response);
	const cacheKey = rubricCacheKey(task.id, response);
	let output: unknown;
	let outputs = 0;
	let abortPromise: Promise<void> | undefined;
	const abort = () => (abortPromise ??= session.abort());
	const unsubscribe = session.subscribe((event) => {
		if (
			event.type === "tool_execution_end" &&
			event.toolName === "structured_output" &&
			!event.isError
		) {
			outputs += 1;
			output = event.result?.details;
		}
	});
	const onAbort = () => void abort();
	signal?.addEventListener("abort", onAbort, { once: true });
	try {
		if (signal?.aborted) {
			await abort();
			throw new RubricJudgeCancelledError();
		}
		await onCall?.();
		if (signal?.aborted) {
			await abort();
			throw new RubricJudgeCancelledError();
		}
		await session.prompt(
			`Judge the frozen task response and terminate by calling structured_output exactly once with {"score":number from 0 through 1,"passed":boolean,"rationale":string of at most 4096 UTF-8 bytes}.\ninput:${canonicalJson({ judgePromptVersion: 1, task, response: bounded })}`,
			{ expandPromptTemplates: false },
		);
		// A valid terminating output is durable work: return it so callers can
		// persist the cache before their cancellation checkpoint.
		if (outputs === 1) return { ...judgeResult(output), cacheKey };
		if (signal?.aborted) {
			await abort();
			throw new RubricJudgeCancelledError();
		}
		throw new RubricJudgeOutputError(
			"rubric judge must emit exactly one structured output",
		);
	} finally {
		signal?.removeEventListener("abort", onAbort);
		unsubscribe();
		await Promise.resolve(session.dispose());
	}
}