repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/modes.ts

Raw
File outline
const MAX_DIFF_LINES = 200;
const MAX_DIFF_BYTES = 32 * 1024;
const DIFF_TRUNCATION = "…[diff truncated]";
const DIFF_CONTEXT = 3;
const MAX_DIFF_MATRIX_CELLS = 100_000;
const DIFF_PREVIEW_LINES = 4;

type DiffLine = { kind: " " | "+" | "-"; text: string };

export type SplitCounts = { train: number; val: number; test: number };

export function upperBoundCalls(counts: SplitCounts): {
	target: number;
	optimizer: 12;
} {
	return {
		target: counts.val + 3 * (counts.train + counts.val) + counts.test,
		optimizer: 12,
	};
}

export function buildConfirmation(options: {
	sourcePath: string;
	suitePath: string;
	splitCounts: SplitCounts;
	warning?: string;
}): string {
	const calls = upperBoundCalls(options.splitCounts);
	return [
		`Source: ${sanitizeTerminalText(options.sourcePath)}`,
		`Suite: ${sanitizeTerminalText(options.suitePath)}`,
		`Splits: train ${options.splitCounts.train}, validation ${options.splitCounts.val}, test ${options.splitCounts.test}`,
		`Upper bound: ${calls.target} target calls, ${calls.optimizer} optimizer calls.`,
		...(options.warning ? [`Warning: ${options.warning}`] : []),
		"The trusted checker executes project code with your process environment.",
		"Overkill will not write the source skill or suite. Continue?",
	].join("\n");
}

export function formatScore(score: number): string {
	return score.toFixed(3).replace(/\.?0+$/u, "");
}

export function formatProgress(options: {
	stage: string;
	terminal?: string | null;
	completed?: number;
	total?: number;
	currentScore?: number;
	bestScore?: number;
}): string {
	const stage =
		options.terminal === "staged"
			? "candidate staged"
			: options.stage === "complete" && options.terminal === "no_improvement"
				? "no improvement"
				: options.stage;
	const fields = ["Overkill", stage];
	if (options.completed !== undefined)
		fields.push(
			options.total === undefined
				? String(options.completed)
				: `${options.completed}/${options.total}`,
		);
	if (options.bestScore !== undefined)
		fields.push(`best ${formatScore(options.bestScore)}`);
	else if (options.currentScore !== undefined)
		fields.push(`score ${formatScore(options.currentScore)}`);
	return fields.join(" ");
}

export function formatResultPaths(options: {
	sourcePath: string;
	reportPath?: string | null;
	stagedPath?: string | null;
}): string {
	const lines = [`Source: ${sanitizeTerminalText(options.sourcePath)}`];
	if (options.reportPath)
		lines.push(`Report: ${sanitizeTerminalText(options.reportPath)}`);
	if (options.stagedPath)
		lines.push(`Staged: ${sanitizeTerminalText(options.stagedPath)}`);
	return lines.join("\n");
}

export function sanitizeTerminalText(value: string): string {
	return value.replace(
		/[\u0000-\u001f\u007f-\u009f]/gu,
		(character) =>
			`\\u${character.codePointAt(0)?.toString(16).padStart(4, "0")}`,
	);
}

function splitLines(text: string): string[] {
	return text === "" ? [] : text.split("\n").map(sanitizeTerminalText);
}

/** A small deterministic LCS diff keeps unchanged interior lines as context. */
function diffLines(source: string, staged: string): DiffLine[] {
	const before = splitLines(source);
	const after = splitLines(staged);
	if (before.length * after.length > MAX_DIFF_MATRIX_CELLS)
		return [
			{ kind: "-", text: `…[${before.length} source lines diff omitted]` },
			{ kind: "+", text: `…[${after.length} staged lines diff omitted]` },
		];
	const rows = before.length + 1;
	const columns = after.length + 1;
	const lengths = Array.from({ length: rows }, () => new Uint32Array(columns));
	for (
		let beforeIndex = before.length - 1;
		beforeIndex >= 0;
		beforeIndex -= 1
	) {
		const current = lengths[beforeIndex];
		const next = lengths[beforeIndex + 1];
		if (!current || !next) continue;
		for (let afterIndex = after.length - 1; afterIndex >= 0; afterIndex -= 1)
			current[afterIndex] =
				before[beforeIndex] === after[afterIndex]
					? (next[afterIndex + 1] ?? 0) + 1
					: Math.max(next[afterIndex] ?? 0, current[afterIndex + 1] ?? 0);
	}
	const lines: DiffLine[] = [];
	let beforeIndex = 0;
	let afterIndex = 0;
	while (beforeIndex < before.length || afterIndex < after.length) {
		if (
			beforeIndex < before.length &&
			afterIndex < after.length &&
			before[beforeIndex] === after[afterIndex]
		) {
			lines.push({ kind: " ", text: before[beforeIndex] ?? "" });
			beforeIndex += 1;
			afterIndex += 1;
		} else if (
			afterIndex < after.length &&
			(beforeIndex === before.length ||
				(lengths[beforeIndex]?.[afterIndex + 1] ?? 0) >
					(lengths[beforeIndex + 1]?.[afterIndex] ?? 0))
		) {
			lines.push({ kind: "+", text: after[afterIndex] ?? "" });
			afterIndex += 1;
		} else {
			lines.push({ kind: "-", text: before[beforeIndex] ?? "" });
			beforeIndex += 1;
		}
	}
	return lines;
}

function hunkHeader(lines: readonly DiffLine[]): string {
	let beforeStart = 1;
	let afterStart = 1;
	const first = lines.findIndex((line) => line.kind !== " ");
	const leading = Math.max(0, first - DIFF_CONTEXT);
	for (const line of lines.slice(0, leading)) {
		if (line.kind !== "+") beforeStart += 1;
		if (line.kind !== "-") afterStart += 1;
	}
	const last =
		lines.length -
		1 -
		[...lines].reverse().findIndex((line) => line.kind !== " ");
	const end = Math.min(lines.length, last + DIFF_CONTEXT + 1);
	const hunk = lines.slice(leading, end);
	const beforeCount = hunk.filter((line) => line.kind !== "+").length;
	const afterCount = hunk.filter((line) => line.kind !== "-").length;
	const normalizedBeforeStart = beforeCount === 0 ? 0 : beforeStart;
	const normalizedAfterStart = afterCount === 0 ? 0 : afterStart;
	return `@@ -${normalizedBeforeStart},${beforeCount} +${normalizedAfterStart},${afterCount} @@\n${hunk.map((line) => `${line.kind}${line.text}`).join("\n")}`;
}

export function buildReviewDiffPreview(diff: string): string {
	const changes = diff
		.split("\n")
		.filter(
			(line) =>
				(line.startsWith("+") && !line.startsWith("+++")) ||
				(line.startsWith("-") && !line.startsWith("---")),
		);
	const preview = changes.slice(0, DIFF_PREVIEW_LINES);
	if (changes.length > preview.length)
		preview.push(`… ${changes.length - preview.length} more changed lines`);
	return preview.join("\n");
}

export function buildReviewDiff(
	sourcePath: string,
	stagedPath: string,
	source: string,
	staged: string,
): string {
	const changes = diffLines(source, staged);
	const safeSourcePath = sanitizeTerminalText(sourcePath);
	const safeStagedPath = sanitizeTerminalText(stagedPath);
	if (changes.every((line) => line.kind === " "))
		return `--- ${safeSourcePath}\n+++ ${safeStagedPath}\n`;
	const full = [
		`--- ${safeSourcePath}`,
		`+++ ${safeStagedPath}`,
		hunkHeader(changes),
	];
	const output: string[] = [];
	let truncated = false;
	for (const line of full.join("\n").split("\n")) {
		const candidate = `${[...output, line].join("\n")}\n`;
		if (
			output.length >= MAX_DIFF_LINES - 2 ||
			Buffer.byteLength(`${candidate}${DIFF_TRUNCATION}\n`, "utf8") >
				MAX_DIFF_BYTES
		) {
			truncated = true;
			break;
		}
		output.push(line);
	}
	if (truncated) {
		const header = output[2];
		const match = header?.match(/^@@ -(\d+),\d+ \+(\d+),\d+ @@$/);
		if (match) {
			const hunk = output.slice(3);
			const beforeCount = hunk.filter((line) => !line.startsWith("+")).length;
			const afterCount = hunk.filter((line) => !line.startsWith("-")).length;
			output[2] = `@@ -${beforeCount === 0 ? 0 : match[1]},${beforeCount} +${afterCount === 0 ? 0 : match[2]},${afterCount} @@`;
		}
	}
	return `${output.join("\n")}\n${truncated ? `# ${DIFF_TRUNCATION}\n` : ""}`;
}