repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/prune/src/merge.ts

Raw
File outline
/**
 * prune — merge previous + fresh formatted summaries
 */

import {
	RECALL_NOTE,
	SECTION_COMMITS,
	SECTION_CONTEXT,
	SECTION_CONTINUE,
	SECTION_FILES,
	SECTION_PREFS,
	SECTION_SESSION,
	SEPARATOR,
} from "./constants.ts";

const HEADER_NAMES = [
	SECTION_SESSION,
	SECTION_FILES,
	SECTION_CONTEXT,
	SECTION_PREFS,
	SECTION_CONTINUE,
	SECTION_COMMITS,
];

/** Merge formatted summaries using stable section headers. */
export function merge(
	previousSummary: string | undefined,
	freshSummary: string,
): string {
	const fresh = stripFooter(freshSummary).trim();
	const prev = previousSummary ? stripFooter(previousSummary).trim() : "";
	if (!prev) return freshSummary;
	if (!fresh) return previousSummary || "";

	const headers = HEADER_NAMES.map((header) =>
		mergeSection(header, sectionOf(prev, header), sectionOf(fresh, header)),
	).filter(Boolean);

	const prevBrief = briefOf(prev);
	const freshBrief = briefOf(fresh);
	const mergedBrief = capBrief(
		[prevBrief, freshBrief].filter(Boolean).join("\n\n"),
	);

	const tailParts = [
		metadataOf(freshSummary) || metadataOf(previousSummary || ""),
		RECALL_NOTE,
	].filter(Boolean);
	const bodyParts = [headers.join("\n\n"), mergedBrief, ...tailParts].filter(
		Boolean,
	);
	return bodyParts.join(SEPARATOR);
}

function mergeSection(header: string, prev: string, fresh: string): string {
	if (header === SECTION_CONTEXT || header === SECTION_CONTINUE) return fresh;
	if (header === SECTION_FILES) {
		if (!prev) return fresh;
		if (!fresh) return prev;
		return mergeFiles(prev, fresh);
	}

	const prevLines = sanitizeStickyLines(header, contentLines(prev));
	const freshLines = sanitizeStickyLines(header, contentLines(fresh));
	const cap = header === SECTION_PREFS ? 15 : 8;
	const lines = dedup([...prevLines, ...freshLines]).slice(-cap);
	if (lines.length === 0) return "";
	return `${header}\n${lines.join("\n")}`;
}

function mergeFiles(prev: string, fresh: string): string {
	const cats = ["Modified", "Created", "Read"] as const;
	const merged: Record<string, Set<string>> = {};
	for (const cat of cats) merged[cat] = new Set();

	for (const text of [prev, fresh]) {
		for (const line of contentLines(text)) {
			for (const cat of cats) {
				const prefix = `- ${cat}: `;
				if (!line.startsWith(prefix)) continue;
				const rest = line
					.slice(prefix.length)
					.replace(/\s*\(\+\d+ more\)\s*$/, "");
				for (const item of rest.split(",")) {
					const trimmed = item.trim();
					if (trimmed) merged[cat].add(trimmed);
				}
			}
		}
	}

	for (const p of merged.Modified) merged.Created.delete(p);

	const lines: string[] = [];
	for (const cat of cats) {
		const rendered = capSet(merged[cat], 10);
		if (rendered) lines.push(`- ${cat}: ${rendered}`);
	}
	return lines.length === 0 ? "" : `${SECTION_FILES}\n${lines.join("\n")}`;
}

function sectionOf(text: string, header: string): string {
	const idx = text.indexOf(header);
	if (idx < 0) return "";
	const after = text.slice(idx);
	const candidates = HEADER_NAMES.filter((h) => h !== header)
		.map((h) => after.indexOf(h))
		.filter((n) => n > 0);
	const sep = after.indexOf(SEPARATOR);
	if (sep > 0) candidates.push(sep);
	const end = candidates.sort((a, b) => a - b)[0];
	return (end ? after.slice(0, end) : after).trim();
}

function briefOf(text: string): string {
	const parts = text.split(SEPARATOR);
	if (parts.length < 2) return "";
	const chunks = parts.slice(1).filter((part) => {
		const trimmed = part.trim();
		return (
			trimmed &&
			!trimmed.startsWith("prune:") &&
			!trimmed.startsWith("Use prune_recall")
		);
	});
	return chunks.join(SEPARATOR).trim();
}

function metadataOf(text: string): string {
	return (
		text
			.split(SEPARATOR)
			.map((p) => p.trim())
			.find((p) => p.startsWith("prune:")) || ""
	);
}

function stripFooter(text: string): string {
	return text
		.replace(RECALL_NOTE, "")
		.split(SEPARATOR)
		.filter((part) => !part.trim().startsWith("prune:"))
		.join(SEPARATOR)
		.trim();
}

function contentLines(section: string): string[] {
	return section
		.split("\n")
		.slice(1)
		.map((l) => l.trim())
		.filter(Boolean);
}

function sanitizeStickyLines(header: string, lines: string[]): string[] {
	if (header !== SECTION_SESSION && header !== SECTION_PREFS) return lines;
	return lines.filter((line) => !isLikelyToolOutputLine(line));
}

function isLikelyToolOutputLine(line: string): boolean {
	const body = line.replace(/^[-*]\s*/, "").trim();
	if (body === "[Scope change]") return false;
	return /^(?:Successfully (?:wrote|replaced|created|updated|deleted)|Could not find edits\[|\(pass\)|\(fail\)|diff --git\b|index [0-9a-f]{6,}\b|@@\b|---\s|\+\+\+\s|assert[A-Z]\w*\(|const\s|let\s|var\s|import\s|export\s|local\s+\w+\s*=\s*function\b|function\s|status=\d|for\s+file\s+in\s|bunx\s|bun\s+test\b|just\s|npm\s|pnpm\s|yarn\s|rg\s|git\s|sed\s|awk\s|[\w./-]+\.\w+:\d+)/i.test(
		body,
	);
}

function dedup(lines: string[]): string[] {
	const seen = new Set<string>();
	const out: string[] = [];
	for (const line of lines) {
		const key = line.toLowerCase();
		if (seen.has(key)) continue;
		seen.add(key);
		out.push(line);
	}
	return out;
}

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 capBrief(text: string, limit = 120): string {
	const lines = text.split("\n");
	if (lines.length <= limit) return text;
	const omitted = lines.length - limit;
	return `...(${omitted} earlier lines omitted)\n\n${lines.slice(-limit).join("\n")}`;
}