repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/cmprss/__tests__/cmprss.test.ts

Raw
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, test } from "vitest";
import cmprssExtension, { __test } from "../index.ts";

const {
	DEFAULT_CONFIG,
	MAX_RETRIEVE_BYTES,
	compressToolResult,
	createRuntime,
	formatStatusText,
	replayState,
	retrieveToolResult,
	runCommand,
} = __test;

function bigText(lines = 200): string {
	return Array.from({ length: lines }, (_, i) => `line ${i + 1}`).join("\n");
}

function cmprssDetails(result: ReturnType<typeof compressToolResult>) {
	if (!result) throw new Error("expected compressed result");
	return (result.details as any).cmprss;
}

describe("cmprss extension", () => {
	test("registers command, retrieve tool, and Pi hooks", () => {
		const events: string[] = [];
		const tools: string[] = [];
		const commands: string[] = [];
		cmprssExtension({
			on(name: string) {
				events.push(name);
			},
			registerTool(tool: { name: string }) {
				tools.push(tool.name);
			},
			registerCommand(name: string) {
				commands.push(name);
			},
			appendEntry() {},
		} as any);

		expect(events).toEqual([
			"session_start",
			"session_shutdown",
			"tool_result",
			"model_select",
		]);
		expect(tools).toEqual(["cmprss_retrieve"]);
		expect(commands).toEqual(["cmprss"]);
	});

	test("formats status as saved context percentage when context window is known", () => {
		const runtime = createRuntime(DEFAULT_CONFIG);
		runtime.stats = {
			blocks: 1,
			originalBytes: 400_000,
			compressedBytes: 200_000,
			retrievedBytes: 0,
		};

		expect(formatStatusText(runtime, { contextWindow: 200_000 })).toBe(
			" -25%",
		);
		expect(formatStatusText(runtime)).toBe(" 50000t");
	});

	test("leaves small output unchanged", () => {
		const runtime = createRuntime(DEFAULT_CONFIG);
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: { command: "echo hi" },
			content: [{ type: "text", text: "hi" }],
			details: { exitCode: 0 },
			isError: false,
		});

		expect(result).toBeUndefined();
		expect(runtime.stats.blocks).toBe(0);
	});

	test("uses fullOutputPath as persisted original when Pi pre-truncated bash", () => {
		const dir = mkdtempSync(join(tmpdir(), "cmprss-"));
		try {
			const full = bigText(6000);
			const shown = full.split("\n").slice(-2000).join("\n");
			const fullOutputPath = join(dir, "out.log");
			writeFileSync(fullOutputPath, full);
			const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 200 });

			const result = compressToolResult(runtime, {
				toolName: "bash",
				input: {},
				content: [{ type: "text", text: shown }],
				details: { fullOutputPath, truncation: { truncated: true } },
				isError: false,
			});

			const hash = cmprssDetails(result).hash;
			expect(runtime.retrieve(hash)).toBe(full);
			expect(readFileSync(fullOutputPath, "utf8")).toBe(full);
		} finally {
			rmSync(dir, { recursive: true, force: true });
		}
	});

	test("compresses oversized output and retrieves exact original", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 200 });
		const original = bigText();
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: { command: "make test" },
			content: [{ type: "text", text: original }],
			details: { exitCode: 1 },
			isError: false,
		});

		expect(result?.content?.[0]?.text).toContain("[cmprss: bash");
		expect(result?.content?.[0]?.text).toContain("cmprss_retrieve");
		expect(result?.details).toMatchObject({ exitCode: 1 });
		const hash = cmprssDetails(result).hash;
		expect(runtime.retrieve(hash)).toBe(original);
		expect(runtime.entries[0]).toMatchObject({
			op: "block",
			originalText: original,
		});
	});

	test("retrieves bounded UTF-8 byte ranges with an actionable continuation", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
		const original = `${"x".repeat(MAX_RETRIEVE_BYTES - 1)}😀tail`;
		const compressed = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: original }],
			isError: false,
		});
		const hash = cmprssDetails(compressed).hash;

		const first = retrieveToolResult(runtime, hash);
		const firstDetails = first.details as any;
		expect(firstDetails).toMatchObject({
			hash,
			offset: 0,
			nextOffset: MAX_RETRIEVE_BYTES - 1,
			returnedBytes: MAX_RETRIEVE_BYTES - 1,
			hasMore: true,
		});
		expect(first.content[0].text).not.toBe(original);
		expect(first.content[0].text).toContain(`offset=${MAX_RETRIEVE_BYTES - 1}`);

		const second = retrieveToolResult(runtime, hash, firstDetails.nextOffset);
		expect(second.content[0].text).toBe("😀tail");
		expect(second.details).toMatchObject({
			offset: MAX_RETRIEVE_BYTES - 1,
			hasMore: false,
		});
	});

	test("rejects oversized and non-boundary retrieval ranges", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 1 });
		const compressed = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: `a😀${"b".repeat(20_000)}` }],
			isError: false,
		});
		const hash = cmprssDetails(compressed).hash;

		expect(() =>
			retrieveToolResult(runtime, hash, 0, MAX_RETRIEVE_BYTES + 1),
		).toThrow(`limit must be at most ${MAX_RETRIEVE_BYTES}`);
		expect(() => retrieveToolResult(runtime, hash, 2, 10)).toThrow(
			"offset must be a UTF-8 boundary",
		);
		expect(() => retrieveToolResult(runtime, hash, 1, 1)).toThrow(
			"limit must include a complete UTF-8 character",
		);
	});

	test("retrieval reduces reported savings and replays that accounting", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
		const compressed = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: bigText(3_000) }],
			isError: false,
		});
		const hash = cmprssDetails(compressed).hash;
		const savedBefore = runCommand(runtime, "status");

		const retrieved = retrieveToolResult(runtime, hash, 0, 1_000);
		const savedAfter = runCommand(runtime, "status");

		expect(savedAfter).not.toBe(savedBefore);
		expect(runtime.stats.retrievedBytes).toBe(
			Buffer.byteLength(retrieved.content[0].text),
		);
		expect(runtime.entries.at(-1)).toMatchObject({
			op: "retrieve",
			hash,
			contextBytes: runtime.stats.retrievedBytes,
		});

		const replayed = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
		replayState(
			replayed,
			runtime.entries.map((data) => ({
				type: "custom",
				customType: "cmprss-state",
				data,
			})),
		);
		expect(runCommand(replayed, "status")).toBe(savedAfter);
	});

	test("replay restores persisted originals after restart", () => {
		const first = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 200 });
		const original = bigText();
		const result = compressToolResult(first, {
			toolName: "bash",
			input: { command: "logs" },
			content: [{ type: "text", text: original }],
			isError: false,
		});
		const hash = cmprssDetails(result).hash;

		const second = createRuntime(DEFAULT_CONFIG);
		replayState(
			second,
			first.entries.map((data) => ({
				type: "custom",
				customType: "cmprss-state",
				data,
			})),
		);

		expect(second.retrieve(hash)).toBe(original);
	});

	test("clear tombstones prior persisted originals", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 200 });
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: bigText() }],
			isError: false,
		});
		const hash = cmprssDetails(result).hash;

		runCommand(runtime, "clear");

		expect(() => runtime.retrieve(hash)).toThrow("cmprss: unknown hash");
		expect(runtime.stats.blocks).toBe(0);
	});

	test("does not compress custom tools unless configured", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
		expect(
			compressToolResult(runtime, {
				toolName: "web_fetch",
				input: {},
				content: [{ type: "text", text: bigText() }],
				isError: false,
			}),
		).toBeUndefined();

		const configured = createRuntime({
			...DEFAULT_CONFIG,
			thresholdBytes: 10,
			tools: [...DEFAULT_CONFIG.tools, "web_fetch"],
		});
		expect(
			compressToolResult(configured, {
				toolName: "web_fetch",
				input: {},
				content: [{ type: "text", text: bigText() }],
				isError: false,
			}),
		).toBeDefined();
	});

	test("never recompresses retrieval results", () => {
		const runtime = createRuntime({
			...DEFAULT_CONFIG,
			thresholdBytes: 10,
			tools: ["custom"],
		});
		expect(
			compressToolResult(runtime, {
				toolName: "cmprss_retrieve",
				input: { hash: "abc" },
				content: [{ type: "text", text: bigText() }],
				isError: false,
			}),
		).toBeUndefined();
	});

	test("does not compress explicit read windows or mutation tools", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
		for (const event of [
			{
				toolName: "read",
				input: { path: "x", offset: 10 },
				content: [{ type: "text", text: bigText() }],
				isError: false,
			},
			{
				toolName: "read",
				input: { path: "x", limit: 10 },
				content: [{ type: "text", text: bigText() }],
				isError: false,
			},
			{
				toolName: "edit",
				input: {},
				content: [{ type: "text", text: bigText() }],
				isError: false,
			},
			{
				toolName: "write",
				input: {},
				content: [{ type: "text", text: bigText() }],
				isError: false,
			},
		]) {
			expect(compressToolResult(runtime, event as any)).toBeUndefined();
		}
	});

	test("json array compression keeps anchors and error items", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const rows = Array.from({ length: 40 }, (_, i) => ({
			id: i + 1,
			status: "ok",
		}));
		rows[20] = { id: 21, status: "fatal error" };
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: JSON.stringify(rows) }],
			isError: false,
		});
		const text = result?.content?.[0]?.text ?? "";

		expect(text).toContain('"id": 1');
		expect(text).toContain('"id": 40');
		expect(text).toContain("fatal error");
		expect(text).toContain("json array: 40 items");
	});

	test("json array compression remains bounded for duplicate scalars", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [
				{ type: "text", text: JSON.stringify(Array(1_000).fill("same")) },
			],
			isError: false,
		});

		expect(Buffer.byteLength(result?.content?.[0]?.text ?? "")).toBeLessThan(
			1_000,
		);
	});

	test("json object compression preserves structurally rare array items", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const rows = Array.from({ length: 40 }, (_, i) => ({
			id: i + 1,
			status: "ready",
			...(i === 20 ? { releaseCode: "RARE-21" } : {}),
		}));
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text: JSON.stringify({ rows }) }],
			isError: false,
		});

		expect(result?.content?.[0]?.text).toContain('"releaseCode": "RARE-21"');
	});

	test("search compression preserves paths and line numbers", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const text = Array.from(
			{ length: 80 },
			(_, i) => `src/a.ts:${i + 1}:match ${i + 1}`,
		).join("\n");
		const result = compressToolResult(runtime, {
			toolName: "grep",
			input: {},
			content: [{ type: "text", text }],
			isError: false,
		});

		expect(result?.content?.[0]?.text).toContain("src/a.ts:1:match 1");
		expect(result?.content?.[0]?.text).toContain("src/a.ts:80:match 80");
		expect(result?.content?.[0]?.text).toContain("search: 80 matches");
	});

	test("search compression preserves a short middle outlier", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const text = Array.from({ length: 80 }, (_, i) =>
			i === 40
				? "src/a.ts:41:needle=RARE-41"
				: `src/a.ts:${i + 1}:ordinary match ${"x".repeat(80)}`,
		).join("\n");
		const result = compressToolResult(runtime, {
			toolName: "grep",
			input: {},
			content: [{ type: "text", text }],
			isError: false,
		});

		expect(result?.content?.[0]?.text).toContain("src/a.ts:41:needle=RARE-41");
	});

	test("stacktrace compression wins before search-like frame paths", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const text = [
			"Error: top",
			...Array.from(
				{ length: 300 },
				(_, i) => `    at fn${i} (/dep/file${i}.js:${i}:1)`,
			),
			"Caused by: Error: root",
		].join("\n");
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text }],
			isError: false,
		});

		expect(cmprssDetails(result).compressor).toBe("stacktrace");
		expect(result?.content?.[0]?.text).toContain("Caused by: Error: root");
	});

	test("log compression preserves failures and tail", () => {
		const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 80 });
		const text = [
			...Array.from({ length: 50 }, (_, i) => `noise ${i}`),
			"ERROR build failed",
			"Traceback (most recent call last):",
			"Exception: boom",
			...Array.from({ length: 50 }, (_, i) => `tail ${i}`),
		].join("\n");
		const result = compressToolResult(runtime, {
			toolName: "bash",
			input: {},
			content: [{ type: "text", text }],
			isError: false,
		});

		expect(result?.content?.[0]?.text).toContain("ERROR build failed");
		expect(result?.content?.[0]?.text).toContain("Traceback");
		expect(result?.content?.[0]?.text).toContain("tail 49");
	});
});