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, compressToolResult, createRuntime, formatStatusText, replayState, runCommand, } = __test; function bigText(lines = 200): string { return Array.from({ length: lines }, (_, i) => `line ${i + 1}`).join("\n"); } 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, }; expect(formatStatusText(runtime, { contextWindow: 200_000 })).toBe( "cmprss: -25%", ); }); 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 = (result?.details as any).cmprss.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 = (result?.details as any).cmprss.hash; expect(runtime.retrieve(hash)).toBe(original); expect(runtime.entries[0]).toMatchObject({ op: "block", originalText: original, }); }); 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 = (result?.details as any).cmprss.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 = (result?.details as any).cmprss.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("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("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("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((result?.details as any).cmprss.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"); }); });