repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/aftermath-harvest.ts

Raw
File outline
import { resolve } from "node:path";

const DIGEST_CAP = 16 * 1024;
const TEXT_CAP = 4 * 1024;
const ARRAY_CAP = 32;
const TRUNCATION = "…[truncated]";

export type Digest = {
	sessionId: string;
	cwd: string;
	leafId: string;
	userPrompts: string[];
	assistantResponses: string[];
	toolNames: string[];
	touchedPaths: string[];
	skillActivations: string[];
	followUps: string[];
};

type Entry = {
	id?: unknown;
	type?: unknown;
	message?: {
		role?: unknown;
		content?: unknown;
	};
};

function utf8(value: string): number {
	return Buffer.byteLength(value, "utf8");
}

/** Truncates on code-point boundaries and always accounts for its marker. */
export function truncateDigestText(value: string, maximum = TEXT_CAP): string {
	if (utf8(value) <= maximum) return value;
	const allowed = maximum - utf8(TRUNCATION);
	let output = "";
	for (const character of value) {
		if (utf8(output) + utf8(character) > allowed) break;
		output += character;
	}
	return `${output}${TRUNCATION}`;
}

function textContent(content: unknown): string {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	return content
		.filter(
			(block): block is { type: "text"; text: string } =>
				typeof block === "object" &&
				block !== null &&
				(block as { type?: unknown }).type === "text" &&
				typeof (block as { text?: unknown }).text === "string",
		)
		.map((block) => block.text)
		.join("");
}

function retain<T>(values: T[]): T[] {
	if (values.length <= ARRAY_CAP) return values;
	return [...values.slice(0, 8), ...values.slice(-24)];
}

function canonicalize(value: unknown): unknown {
	if (Array.isArray(value)) return value.map(canonicalize);
	if (typeof value !== "object" || value === null) return value;
	return Object.fromEntries(
		Object.entries(value as Record<string, unknown>)
			.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
			.map(([key, child]) => [key, canonicalize(child)]),
	);
}

export function stableDigestJson(digest: Digest): string {
	return JSON.stringify(canonicalize(digest));
}

function reduceDigest(digest: Digest): Digest {
	const textKeys: Array<
		keyof Pick<Digest, "userPrompts" | "assistantResponses" | "followUps">
	> = ["userPrompts", "assistantResponses", "followUps"];
	const allArrayKeys: Array<
		Exclude<keyof Digest, "sessionId" | "cwd" | "leafId">
	> = [
		"userPrompts",
		"assistantResponses",
		"followUps",
		"toolNames",
		"touchedPaths",
		"skillActivations",
	];
	while (utf8(stableDigestJson(digest)) > DIGEST_CAP) {
		let removed = false;
		// Preserve final user/assistant text; shed only older branch text first.
		for (const key of textKeys) {
			const keepFinal = key !== "followUps" ? 1 : 0;
			if (digest[key].length > keepFinal) {
				digest[key].shift();
				removed = true;
				break;
			}
		}
		if (removed) continue;
		let shortened = false;
		for (const key of ["cwd", "leafId"] as const) {
			if (utf8(digest[key]) > utf8(TRUNCATION)) {
				digest[key] = truncateDigestText(
					digest[key],
					Math.max(utf8(TRUNCATION), Math.floor(utf8(digest[key]) / 2)),
				);
				shortened = true;
				break;
			}
		}
		if (shortened) continue;
		for (const key of allArrayKeys) {
			const index = digest[key].findIndex(
				(value) => utf8(value) > utf8(TRUNCATION),
			);
			if (index >= 0) {
				const value = digest[key].at(index);
				if (value === undefined) continue;
				digest[key][index] = truncateDigestText(
					value,
					Math.max(utf8(TRUNCATION), Math.floor(utf8(value) / 2)),
				);
				shortened = true;
				break;
			}
		}
		if (!shortened) throw new Error("digest metadata cannot fit the cap");
	}
	return digest;
}

function skillFromUser(text: string): string | undefined {
	return /^<skill name="([^"]+)" location="[^"]+">\n[\s\S]*?\n<\/skill>(?:\n\n[\s\S]+)?$/.exec(
		text,
	)?.[1];
}

function toolCalls(content: unknown): Array<{ name: string; path?: string }> {
	if (!Array.isArray(content)) return [];
	const calls: Array<{ name: string; path?: string }> = [];
	for (const block of content) {
		if (
			typeof block !== "object" ||
			block === null ||
			(block as { type?: unknown }).type !== "toolCall" ||
			typeof (block as { name?: unknown }).name !== "string"
		)
			continue;
		const raw = (block as { arguments?: unknown }).arguments;
		const path =
			typeof raw === "object" &&
			raw !== null &&
			typeof (raw as { path?: unknown }).path === "string"
				? (raw as { path: string }).path
				: undefined;
		calls.push({ name: (block as { name: string }).name, path });
	}
	return calls;
}

export function buildDigest(options: {
	sessionId: string;
	cwd: string;
	branch: readonly unknown[];
	knownSkillPaths?: ReadonlyMap<string, string>;
}): Digest {
	const digest: Digest = {
		sessionId: truncateDigestText(options.sessionId),
		cwd: truncateDigestText(options.cwd),
		leafId: "",
		userPrompts: [],
		assistantResponses: [],
		toolNames: [],
		touchedPaths: [],
		skillActivations: [],
		followUps: [],
	};
	let followsAssistant = false;
	for (const value of options.branch) {
		if (typeof value !== "object" || value === null) continue;
		const entry = value as Entry;
		if (typeof entry.id === "string")
			digest.leafId = truncateDigestText(entry.id);
		if (entry.type !== "message" || !entry.message) continue;
		const role = entry.message.role;
		const text = textContent(entry.message.content);
		if (role === "user") {
			if (text) digest.userPrompts.push(truncateDigestText(text));
			if (followsAssistant && text)
				digest.followUps.push(truncateDigestText(text));
			const skill = skillFromUser(text);
			if (
				skill &&
				(!options.knownSkillPaths ||
					[...options.knownSkillPaths.values()].includes(skill))
			)
				digest.skillActivations.push(truncateDigestText(skill));
			followsAssistant = false;
			continue;
		}
		if (role !== "assistant") {
			followsAssistant = false;
			continue;
		}
		if (text) digest.assistantResponses.push(truncateDigestText(text));
		for (const call of toolCalls(entry.message.content)) {
			digest.toolNames.push(truncateDigestText(call.name));
			if (
				call.path &&
				["read", "edit", "write", "grep", "find", "ls"].includes(call.name)
			)
				digest.touchedPaths.push(
					truncateDigestText(resolve(options.cwd, call.path)),
				);
			if (call.name === "read" && call.path) {
				const canonical = resolve(options.cwd, call.path);
				const skill = options.knownSkillPaths?.get(canonical);
				if (skill) digest.skillActivations.push(truncateDigestText(skill));
			}
		}
		followsAssistant = true;
	}
	for (const key of [
		"userPrompts",
		"assistantResponses",
		"toolNames",
		"touchedPaths",
		"skillActivations",
		"followUps",
	] as const)
		digest[key] = retain(digest[key]);
	return reduceDigest(digest);
}

export function rankSkillEvidence(
	digests: readonly Pick<Digest, "sessionId" | "skillActivations">[],
	loadedSkills?: ReadonlySet<string>,
): { counts: Record<string, number>; suggestion?: string } {
	const sessions = new Map<string, Set<string>>();
	for (const digest of digests) {
		for (const skill of new Set(digest.skillActivations)) {
			if (loadedSkills && !loadedSkills.has(skill)) continue;
			const set = sessions.get(skill) ?? new Set<string>();
			set.add(digest.sessionId);
			sessions.set(skill, set);
		}
	}
	const counts = Object.fromEntries(
		[...sessions.entries()]
			.map(([skill, ids]) => [skill, ids.size] as const)
			.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),
	);
	const ranked = Object.entries(counts).sort(
		([leftName, left], [rightName, right]) =>
			right - left ||
			(leftName < rightName ? -1 : leftName > rightName ? 1 : 0),
	);
	const [first, second] = ranked;
	if (!first || first[1] < 3 || (second && first[1] < second[1] * 2))
		return { counts };
	return { counts, suggestion: first[0] };
}