repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/prune/src/format.ts

Raw
File outline
/**
 * prune — format extract output to summary string
 */

import {
	DEFAULT_SECTION_LIMIT,
	DEFAULT_TRANSCRIPT_LIMIT,
	RECALL_NOTE,
	SECTION_CONTEXT,
	SECTION_CONTINUE,
	SECTION_FILES,
	SECTION_PREFS,
	SECTION_SESSION,
	SEPARATOR,
} from "./constants.ts";
import type { ExtractOutput, PruneOutput, TranscriptEntry } from "./types.ts";

export interface FormatOptions {
	sectionLimit?: number;
	transcriptLimit?: number;
	sourceEntriesProcessed?: number;
	tailKept?: number;
	splitPrefixMessages?: number;
	tokenEstimate?: number;
}

/**
 * Format extract output into a summary string for LLM context.
 */
export function format(
	data: ExtractOutput,
	options: FormatOptions = {},
): PruneOutput {
	const start = performance.now();
	const {
		sectionLimit = DEFAULT_SECTION_LIMIT,
		transcriptLimit = DEFAULT_TRANSCRIPT_LIMIT,
		sourceEntriesProcessed,
		tailKept,
		splitPrefixMessages,
		tokenEstimate,
	} = options;

	const sections: string[] = [];

	const sessionLines: string[] = [];
	for (const goal of data.goals.slice(0, sectionLimit)) {
		sessionLines.push(`- ${goal}`);
	}
	if (data.scopeChanges.length > 0) {
		sessionLines.push("- [Scope change]");
		for (const change of data.scopeChanges.slice(0, sectionLimit)) {
			sessionLines.push(`- ${change}`);
		}
	}
	if (sessionLines.length > 0) {
		sections.push(`${SECTION_SESSION}\n${sessionLines.join("\n")}`);
	}

	const fileLines = formatFileLines(data.files);
	if (fileLines.length > 0) {
		sections.push(`${SECTION_FILES}\n${fileLines.join("\n")}`);
	}

	if (data.context.length > 0) {
		sections.push(
			`${SECTION_CONTEXT}\n${data.context
				.slice(0, sectionLimit)
				.map((i) => `- ${i}`)
				.join("\n")}`,
		);
	}

	if (data.preferences.length > 0) {
		sections.push(
			`${SECTION_PREFS}\n${data.preferences
				.slice(0, sectionLimit)
				.map((i) => `- ${i}`)
				.join("\n")}`,
		);
	}

	const transcriptLines = capTranscript(
		data.transcript.map(formatTranscriptEntry).filter(Boolean),
		transcriptLimit,
	);

	const continueLines = formatContinueLines(data.transcript);
	if (continueLines.length > 0) {
		sections.push(`${SECTION_CONTINUE}\n${continueLines.join("\n")}`);
	}

	const parts: string[] = [];
	if (sections.length > 0) parts.push(sections.join("\n\n"));
	if (transcriptLines.length > 0) parts.push(transcriptLines.join("\n"));

	const footer = formatFooter({
		sourceEntriesProcessed,
		tailKept,
		splitPrefixMessages,
		tokenEstimate,
	});
	if (footer) parts.push(footer);
	parts.push(RECALL_NOTE);

	const summary = parts.join(SEPARATOR);
	const elapsedMs = performance.now() - start;

	return {
		summary,
		stats: {
			messagesIn: data.transcript.length,
			messagesOut: summary.split("\n").length,
			reduction: 0,
			elapsedMs,
		},
	};
}

function formatFileLines(files: ExtractOutput["files"]): string[] {
	const lines: string[] = [];
	const modified = capSet(files.modified, 10);
	const created = capSet(files.created, 10);
	const read = capSet(files.read, 10);
	if (modified) lines.push(`- Modified: ${modified}`);
	if (created) lines.push(`- Created: ${created}`);
	if (read) lines.push(`- Read: ${read}`);
	return lines;
}

function capSet(set: Set<string>, limit: number): string {
	const arr = [...set];
	if (arr.length === 0) return "";
	if (arr.length <= limit) return arr.join(", ");
	return `${arr.slice(0, limit).join(", ")} (+${arr.length - limit} more)`;
}

function capTranscript(lines: string[], limit: number): string[] {
	if (lines.length <= limit) return lines;
	const omitted = lines.length - limit;
	return [`...(${omitted} earlier lines omitted)`, "", ...lines.slice(-limit)];
}

function formatFooter(options: {
	sourceEntriesProcessed?: number;
	tailKept?: number;
	splitPrefixMessages?: number;
	tokenEstimate?: number;
}): string {
	if (options.sourceEntriesProcessed == null || options.tailKept == null)
		return "";
	const before =
		options.tokenEstimate == null
			? ""
			: `; before ${formatTokenEstimate(options.tokenEstimate)} tok`;
	const split =
		options.splitPrefixMessages == null
			? ""
			: `; split-prefix ${options.splitPrefixMessages}`;
	return `prune: ${options.sourceEntriesProcessed} entries summarized${before}; raw kept ${options.tailKept} entries${split}`;
}

function formatContinueLines(transcript: TranscriptEntry[]): string[] {
	if (transcript.length === 0) return [];
	const lastUser = findLast(transcript, (entry) => entry.role === "user");
	const lastFailure = findLast(transcript, (entry) => entry.role === "error");
	const lastAction = findLast(transcript, (entry) => entry.role !== "user");
	const lines: string[] = [];
	if (lastUser) lines.push(`- Current request: ${formatBriefEntry(lastUser)}`);
	if (lastAction) lines.push(`- Last action: ${formatBriefEntry(lastAction)}`);
	if (lastFailure)
		lines.push(`- Last failure: ${formatBriefEntry(lastFailure)}`);
	lines.push(
		"- Next: continue current request; use prune_recall before redoing old work.",
	);
	return lines;
}

function findLast<T>(
	items: T[],
	predicate: (item: T) => boolean,
): T | undefined {
	for (let i = items.length - 1; i >= 0; i--) {
		if (predicate(items[i])) return items[i];
	}
	return undefined;
}

function formatBriefEntry(entry: TranscriptEntry): string {
	if (entry.tool) {
		const cmd = entry.cmd ? ` ${entry.cmd}` : "";
		return `${entry.tool}${cmd}${entry.ref ? ` (${entry.ref})` : ""}`;
	}
	return `${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
}

function formatTokenEstimate(tokens: number): string {
	if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`;
	return String(tokens);
}

/**
 * Format a single transcript entry.
 */
function formatTranscriptEntry(entry: TranscriptEntry): string {
	switch (entry.role) {
		case "user":
			return `[user]\n${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
		case "assistant":
			if (entry.tool) {
				const args = entry.cmd ? ` "${entry.cmd}"` : "";
				return `* ${entry.tool}${args}${entry.ref ? ` (${entry.ref})` : ""}`;
			}
			return `[assistant]\n${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
		case "error":
			return `[tool_error] ${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
		default:
			return "";
	}
}