import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { appendFile, cp, mkdir, mkdtemp, readFile, rm, writeFile, } from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const MAX_FIXTURE_BYTES = 50_000; const CMPRSS_THRESHOLD_BYTES = 20_000; const CASES = ["baseline", "current", "modified"] as const; type CaseName = (typeof CASES)[number]; type Usage = { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens: number; }; type Benchmark = { files: Record; prompt: string; expected: Record; expectedCompressors: Record; }; type EventSummary = { usage: Usage; compression: { blocks: number; originalBytes: number; compressedBytes: number; retrievals: number; retrievedContextBytes: number; netSavedBytes: number; }; toolCalls: Record; finalText: string; provider?: string; model?: string; }; type HardScore = { score: number; correct: number; total: number; fields: Record; parsed?: Record; }; function repeated(label: string, count: number, width: number): string[] { return Array.from({ length: count }, (_, index) => `${label} ${String(index + 1).padStart(3, "0")} `.padEnd(width, "x"), ); } export function createBenchmark(): Benchmark { const expected = { jsonCode: "JX-7391-ORBIT", searchNeedle: "SEARCH-CEDAR-482", diffNewValue: "DIFF-QUARTZ-913", stackRootCause: "STACK-EMBER-267", logFailure: "LOG-ANCHOR-644", logTail: "TAIL-SILVER-508", textMiddle: "TEXT-MARIGOLD-351", }; const records = Array.from({ length: 120 }, (_, index) => ({ id: index + 1, status: "ready", payload: `record-${index + 1}-${"j".repeat(145)}`, ...(index === 59 ? { releaseCode: expected.jsonCode } : {}), })); const json = JSON.stringify({ benchmark: "cmprss-json", records }, null, 2); const search = Array.from({ length: 190 }, (_, index) => { const body = index === 94 ? `needle=${expected.searchNeedle}` : `ordinary match ${index + 1} ${"s".repeat(112)}`; return `src/catalog.ts:${index + 1}:${body}`; }).join("\n"); const diffLines = [ "diff --git a/config.ts b/config.ts", "--- a/config.ts", "+++ b/config.ts", ]; for (let index = 0; index < 145; index++) { diffLines.push(`@@ -${index + 1},1 +${index + 1},1 @@`); diffLines.push( `-export const value${index + 1} = "old-${"d".repeat(55)}";`, ); const value = index === 19 ? expected.diffNewValue : `new-${index + 1}-${"d".repeat(55)}`; diffLines.push(`+export const value${index + 1} = "${value}";`); } const diff = diffLines.join("\n"); const stackLines = ["Error: benchmark top-level exception"]; for (let index = 0; index < 285; index++) { stackLines.push( ` at dependencyFunction${index + 1} (/vendor/package-${index % 17}/generated-file-${index + 1}.js:${index + 10}:42) ${"q".repeat(25)}`, ); } stackLines.push(`Caused by: Error: ${expected.stackRootCause}`); const stacktrace = stackLines.join("\n"); const logLines = repeated("build activity", 310, 96); logLines[154] = `ERROR build failed: ${expected.logFailure}`; logLines[309] = `completion token: ${expected.logTail}`; const log = logLines.join("\n"); const narrativeLines = repeated("calm narrative segment", 315, 96); narrativeLines[157] = `middle token: ${expected.textMiddle}`; const narrative = narrativeLines.join("\n"); const files = { "fixtures/data.json": json, "fixtures/search.txt": search, "fixtures/change.diff": diff, "fixtures/stacktrace.txt": stacktrace, "fixtures/build.log": log, "fixtures/narrative.txt": narrative, }; for (const [path, content] of Object.entries(files)) { const size = Buffer.byteLength(content); if (size <= CMPRSS_THRESHOLD_BYTES || size >= MAX_FIXTURE_BYTES) throw new Error(`invalid benchmark fixture size: ${path}=${size}B`); } return { files, expected, expectedCompressors: { "fixtures/data.json": "json", "fixtures/search.txt": "search", "fixtures/change.diff": "diff", "fixtures/stacktrace.txt": "stacktrace", "fixtures/build.log": "log", "fixtures/narrative.txt": "text", }, prompt: `Read these six files exactly once each, using the read tool with only its path parameter and no offset or limit: fixtures/data.json, fixtures/search.txt, fixtures/change.diff, fixtures/stacktrace.txt, fixtures/build.log, fixtures/narrative.txt. After every read completes, recover the exact requested values. Use cmprss_retrieve when available and necessary. Return only one JSON object with exactly these string keys: jsonCode, searchNeedle, diffNewValue, stackRootCause, logFailure, logTail, textMiddle. Do not guess, omit keys, add commentary, or wrap the JSON in Markdown.`, }; } function parseJsonObject(text: string): Record | undefined { const trimmed = text.trim(); const unfenced = trimmed .replace(/^```(?:json)?\s*/iu, "") .replace(/\s*```$/u, "") .trim(); for (const candidate of [ unfenced, unfenced.slice(unfenced.indexOf("{"), unfenced.lastIndexOf("}") + 1), ]) { if (!candidate) continue; try { const parsed = JSON.parse(candidate); if ( parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ) return parsed as Record; } catch {} } return undefined; } export function compareWithHistory( result: Record, history: Array>, ): Array<{ case: "baseline" | "current"; tokenDelta: number; tokenDeltaPercent: number; hardDelta: number; judgeDelta: number; }> { const targetCases = result.case === "modified" ? (["baseline", "current"] as const) : result.case === "current" ? (["baseline"] as const) : []; return targetCases.flatMap((caseName) => { const reference = history.findLast((entry) => entry.case === caseName); if (!reference) return []; const tokens = number(result.subject?.usage?.totalTokens); const referenceTokens = number(reference.subject?.usage?.totalTokens); return [ { case: caseName, tokenDelta: tokens - referenceTokens, tokenDeltaPercent: referenceTokens === 0 ? 0 : Math.round( ((tokens - referenceTokens) / referenceTokens) * 1_000, ) / 10, hardDelta: number(result.subject?.hardScore?.score) - number(reference.subject?.hardScore?.score), judgeDelta: number(result.judge?.result?.score) - number(reference.judge?.result?.score), }, ]; }); } export function scoreCandidate( text: string, expected: Record, ): HardScore { const parsed = parseJsonObject(text); const fields = Object.fromEntries( Object.entries(expected).map(([key, value]) => [ key, parsed?.[key] === value, ]), ); const total = Object.keys(expected).length; const correct = Object.values(fields).filter(Boolean).length; return { score: Math.round((correct / total) * 100), correct, total, fields, parsed, }; } function textContent(content: unknown): string { if (!Array.isArray(content)) return ""; return content .filter( (part): part is { type: "text"; text: string } => part !== null && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string", ) .map((part) => part.text) .join("\n"); } function number(value: unknown): number { return typeof value === "number" && Number.isFinite(value) ? value : 0; } export function summarizeEvents(events: unknown[]): EventSummary { const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, }; const compression = { blocks: 0, originalBytes: 0, compressedBytes: 0, retrievals: 0, retrievedContextBytes: 0, netSavedBytes: 0, }; const toolCalls: Record = {}; let finalText = ""; let provider: string | undefined; let model: string | undefined; for (const event of events) { if (event === null || typeof event !== "object") continue; const record = event as Record; if (record.type === "message_end" && record.message?.role === "assistant") { const current = record.message.usage ?? {}; usage.input += number(current.input); usage.output += number(current.output); usage.cacheRead += number(current.cacheRead); usage.cacheWrite += number(current.cacheWrite); usage.totalTokens += number(current.totalTokens); finalText = textContent(record.message.content); provider = record.message.provider ?? provider; model = record.message.model ?? model; } if (record.type !== "tool_execution_end") continue; const toolName = String(record.toolName ?? "unknown"); toolCalls[toolName] = (toolCalls[toolName] ?? 0) + 1; const details = record.result?.details; if (details?.cmprss) { compression.blocks++; compression.originalBytes += number(details.cmprss.originalBytes); compression.compressedBytes += number(details.cmprss.compressedBytes); } if (toolName === "cmprss_retrieve") { compression.retrievals++; compression.retrievedContextBytes += Buffer.byteLength( textContent(record.result?.content), ); } } compression.netSavedBytes = compression.originalBytes - compression.compressedBytes - compression.retrievedContextBytes; return { usage, compression, toolCalls, finalText, provider, model }; } type CliOptions = { cases: CaseName[]; model: string; judgeModel: string; thinking: string; repeats: number; dryRun: boolean; }; function parseArgs(args: string[]): CliOptions { const options: CliOptions = { cases: [], model: "openai-codex/gpt-5.6-luna", judgeModel: "openai-codex/gpt-5.6-luna", thinking: "off", repeats: 1, dryRun: false, }; for (let index = 0; index < args.length; index++) { const arg = args[index]; if (arg === "--case") { const value = args[++index] as CaseName | undefined; if (!value || !CASES.includes(value)) throw new Error(`--case must be one of: ${CASES.join(", ")}`); options.cases.push(value); } else if (arg === "--model") options.model = args[++index] ?? ""; else if (arg === "--judge-model") options.judgeModel = args[++index] ?? ""; else if (arg === "--thinking") options.thinking = args[++index] ?? ""; else if (arg === "--repeats") { options.repeats = Number(args[++index]); if (!Number.isInteger(options.repeats) || options.repeats < 1) throw new Error("--repeats must be a positive integer"); } else if (arg === "--dry-run") options.dryRun = true; else throw new Error(`unknown argument: ${arg}`); } if (options.cases.length === 0) options.cases = ["baseline", "current"]; return options; } function hash(text: string | Buffer): string { return createHash("sha256").update(text).digest("hex"); } async function writeBenchmark( root: string, benchmark: Benchmark, ): Promise { for (const [path, content] of Object.entries(benchmark.files)) { const target = join(root, path); await mkdir(dirname(target), { recursive: true }); await writeFile(target, content); } await mkdir(join(root, ".pi"), { recursive: true }); await writeFile( join(root, ".pi", "settings.json"), `${JSON.stringify( { cmprss: { enabled: true, thresholdBytes: CMPRSS_THRESHOLD_BYTES, maxStoredBlocks: 64, status: false, tools: ["read"], }, }, null, 2, )}\n`, ); } type PiRun = { events: unknown[]; durationMs: number; stderr: string; }; async function runPi( args: string[], cwd: string, eventsPath: string, stderrPath: string, ): Promise { const started = performance.now(); const child = spawn(process.env.PI_BENCH_PI ?? "pi", args, { cwd, env: { ...process.env, PI_SKIP_VERSION_CHECK: "1", RTK_DISABLED: "1", }, stdio: ["ignore", "pipe", "pipe"], }); const events: unknown[] = []; let stdout = ""; let stderr = ""; child.stdout.setEncoding("utf8"); child.stderr.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { stdout += chunk; }); child.stderr.on("data", (chunk: string) => { stderr += chunk; }); const code = await new Promise((resolveCode, reject) => { child.once("error", reject); child.once("close", resolveCode); }); await writeFile(eventsPath, stdout); await writeFile(stderrPath, stderr); for (const line of stdout.split("\n")) { if (!line.trim()) continue; try { events.push(JSON.parse(line)); } catch { throw new Error(`pi emitted non-JSON output: ${line.slice(0, 200)}`); } } if (code !== 0) throw new Error(`pi exited ${code}: ${stderr.trim()}`); return { events, durationMs: performance.now() - started, stderr }; } function commonPiArgs(model: string, thinking: string): string[] { return [ "--mode", "json", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--approve", "--offline", "--model", model, "--thinking", thinking, ]; } async function gitHead(cwd: string): Promise { const child = spawn("git", ["rev-parse", "HEAD"], { cwd, stdio: ["ignore", "pipe", "ignore"], }); let stdout = ""; child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { stdout += chunk; }); const code = await new Promise((resolveCode) => child.once("close", resolveCode), ); return code === 0 ? stdout.trim() : undefined; } async function runJudge( candidate: string, benchmark: Benchmark, options: CliOptions, cwd: string, resultDir: string, ): Promise<{ parsed?: Record; summary: EventSummary }> { const prompt = `Grade the candidate against the expected answer field by field. Allow semantically equivalent wording, but not missing or invented values. Return only JSON with keys score (integer 0..100), fieldScores (object mapping every expected key to 0 or 1), and reason (one short string).\n\nExpected:\n${JSON.stringify(benchmark.expected)}\n\nCandidate:\n${JSON.stringify(candidate)}`; const run = await runPi( [ ...commonPiArgs(options.judgeModel, "off"), "--no-tools", "--system-prompt", "You are a blinded benchmark judge. Follow the grading prompt exactly.", prompt, ], cwd, join(resultDir, "judge-events.jsonl"), join(resultDir, "judge-stderr.txt"), ); return { parsed: parseJsonObject(summarizeEvents(run.events).finalText), summary: summarizeEvents(run.events), }; } function stateRoot(): string { return join( process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "pi", "cmprss-ab", ); } function timestamp(): string { return new Date().toISOString().replaceAll(":", "-"); } async function runCase( caseName: CaseName, repeat: number, options: CliOptions, benchmark: Benchmark, repoRoot: string, extensionPath: string, historyPath: string, ): Promise> { const runId = `${timestamp()}_${caseName}_${repeat}`; const resultDir = join(dirname(historyPath), "runs", runId); await mkdir(resultDir, { recursive: true }); const fixtureRoot = await mkdtemp(join(tmpdir(), "cmprss-ab-")); try { await writeBenchmark(fixtureRoot, benchmark); await cp(join(fixtureRoot, "fixtures"), join(resultDir, "fixtures"), { recursive: true, }); const args = [ ...commonPiArgs(options.model, options.thinking), "--tools", "read,cmprss_retrieve", "--system-prompt", "You are running a controlled retrieval benchmark. Follow the user prompt exactly and use no unrequested tools.", ]; let extensionSha256: string | undefined; if (caseName !== "baseline") { const source = await readFile(extensionPath); extensionSha256 = hash(source); await writeFile(join(resultDir, "cmprss.ts"), source); args.push("--extension", extensionPath); } args.push(benchmark.prompt); const subject = await runPi( args, fixtureRoot, join(resultDir, "subject-events.jsonl"), join(resultDir, "subject-stderr.txt"), ); const summary = summarizeEvents(subject.events); const hardScore = scoreCandidate(summary.finalText, benchmark.expected); const judge = await runJudge( summary.finalText, benchmark, options, fixtureRoot, resultDir, ); const fixtureHashes = Object.fromEntries( Object.entries(benchmark.files).map(([path, content]) => [ path, hash(content), ]), ); const result = { schemaVersion: 1, runId, case: caseName, repeat, createdAt: new Date().toISOString(), modelRequested: options.model, judgeModelRequested: options.judgeModel, thinking: options.thinking, gitHead: await gitHead(repoRoot), extensionSha256, prompt: benchmark.prompt, promptSha256: hash(benchmark.prompt), expected: benchmark.expected, fixtureHashes, subject: { ...summary, durationMs: Math.round(subject.durationMs), hardScore, }, judge: { result: judge.parsed, usage: judge.summary.usage, provider: judge.summary.provider, model: judge.summary.model, }, artifacts: resultDir, }; await writeFile( join(resultDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`, ); await appendFile(historyPath, `${JSON.stringify(result)}\n`); return result; } finally { await rm(fixtureRoot, { recursive: true, force: true }); } } function signed(value: number): string { return value > 0 ? `+${value}` : String(value); } function printResult( result: Record, history: Array>, ): void { const subject = result.subject; const soft = number(result.judge?.result?.score); console.log( [ result.case.padEnd(8), `tokens=${String(subject.usage.totalTokens).padStart(7)}`, `hard=${String(subject.hardScore.score).padStart(3)}`, `judge=${String(soft).padStart(3)}`, `net=${String(subject.compression.netSavedBytes).padStart(8)}B`, `retrieve=${subject.compression.retrievals}`, `time=${(subject.durationMs / 1000).toFixed(1)}s`, ].join(" "), ); for (const comparison of compareWithHistory(result, history)) { console.log( ` vs ${comparison.case}: tokens=${signed(comparison.tokenDelta)} (${signed(comparison.tokenDeltaPercent)}%) hard=${signed(comparison.hardDelta)} judge=${signed(comparison.judgeDelta)}`, ); } } async function readHistory(path: string): Promise>> { let text: string; try { text = await readFile(path, "utf8"); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; } return text .split("\n") .filter(Boolean) .map((line) => JSON.parse(line) as Record); } async function main(): Promise { const options = parseArgs(process.argv.slice(2)); const benchmark = createBenchmark(); if (options.dryRun) { console.log( JSON.stringify( { cases: options.cases, model: options.model, judgeModel: options.judgeModel, fixtureBytes: Object.fromEntries( Object.entries(benchmark.files).map(([path, content]) => [ path, Buffer.byteLength(content), ]), ), expectedCompressors: benchmark.expectedCompressors, prompt: benchmark.prompt, }, null, 2, ), ); return; } const extensionDir = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const repoRoot = resolve(extensionDir, "../.."); const extensionPath = join(extensionDir, "index.ts"); const root = stateRoot(); const historyPath = join(root, "history.jsonl"); await mkdir(root, { recursive: true }); const history = await readHistory(historyPath); console.log( `cmprss A/B · model=${options.model} · judge=${options.judgeModel}`, ); for (const caseName of options.cases) { for (let repeat = 1; repeat <= options.repeats; repeat++) { const result = await runCase( caseName, repeat, options, benchmark, repoRoot, extensionPath, historyPath, ); printResult(result, history); history.push(result); } } console.log(`history: ${historyPath}`); } const invokedPath = process.argv[1] ? resolve(process.argv[1]) : ""; if (invokedPath === fileURLToPath(import.meta.url)) { main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); }