feat(cmprss): bound retrieval and add A/B benchmark
dabecc2355d52f181559102a54e648ccc1b143ab
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
- Parent 1: bd0d39d1d06c
bugabingas pi extensions
dabecc2355d52f181559102a54e648ccc1b143ab
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
+1324 / −26 text lines
+1 / −0 text lines
- Fix repeated Decay compactions so paraphrased memories reuse the same identity without being counted as new occurrences- Add Continuity to automatically resume the current task after context compaction while yielding to queued messages and active Goal or Tune runs- Fix Continuity so it resumes user intent only when actionable work remains and stops instead of rerunning completed checks, retrying known blockers, or inventing follow-up work- Make cmprss retrieval use bounded exact UTF-8 ranges, capped at 8192 bytes per call, with continuation offsets and replay-persistent savings accounting+18 / −9 text lines
- Register a `cmprss_retrieve` tool that returns the exact original block by hash.- Register a `cmprss_retrieve` tool that returns bounded exact UTF-8 ranges by hash and byte offset.Default maximum retrieved bytes: unlimited for exact hash retrieval, because retrieval is explicit.If the hash is unknown, throw or return an error result clearly saying `cmprss: unknown hash`.Use cmprss_retrieve(hash="<hash>") for exact original text.Use cmprss_retrieve(hash="<hash>") for bounded exact UTF-8 ranges. | { op: "block"; meta: CmprssBlockMeta; originalText: string; at: number };Only `cmprss_retrieve(hash)` returns the exact original.- Retrieval returns exact original for a known hash.- Retrieval returns exact bounded UTF-8 ranges for a known hash.- Retrieval never exceeds `8192` original bytes per call.- Retrieval accounting survives session replay and reduces reported savings.- Retrieval tool UI renders hash, offset, limit, range metadata, and expanded-only content.+25 / −3 text lines
- `cmprss_retrieve` — retrieve exact original text by hash.- `cmprss_retrieve` — retrieve bounded exact UTF-8 ranges by hash, byte offset, and byte limit.It stores the exact original in Pi session history, so restarting Pi can still retrieve the hidden bytes.Use cmprss_retrieve(hash="abc123") for exact original text.Use cmprss_retrieve(hash="abc123") for bounded exact UTF-8 ranges.## A/B evaluationRun the isolated one-shot baseline and current extension against deterministic fixtures for all six compressors:```textmise //extensions/cmprss:ab```After changing cmprss, run only the modified case and compare its persistent result with prior runs:```textmise //extensions/cmprss:ab -- --case modified```The default subject and blinded judge model is `openai-codex/gpt-5.6-luna`.Use `--model`, `--judge-model`, `--thinking`, or `--repeats` to override the fixed run parameters.The runner disables discovered extensions, skills, prompts, themes, context files, sessions, and RTK.It records provider usage, compression bytes, retrieval bytes, exact-answer score, blinded judge score, fixtures, events, and the tested extension source under `$XDG_STATE_HOME/pi/cmprss-ab`.Run `--dry-run` to inspect fixture sizes, expected compressors, and the prompt without calling a model.new file mode 100644+714 / −0 text lines
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<string, string>; prompt: string; expected: Record<string, string>; expectedCompressors: Record<string, string>;};type EventSummary = { usage: Usage; compression: { blocks: number; originalBytes: number; compressedBytes: number; retrievals: number; retrievedContextBytes: number; netSavedBytes: number; }; toolCalls: Record<string, number>; finalText: string; provider?: string; model?: string;};type HardScore = { score: number; correct: number; total: number; fields: Record<string, boolean>; parsed?: Record<string, unknown>;};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<string, unknown> | 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<string, unknown>; } catch {} } return undefined;}export function compareWithHistory( result: Record<string, any>, history: Array<Record<string, any>>,): 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<string, string>,): 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<string, number> = {}; 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<string, any>; 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<void> { 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<PiRun> { 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<number | null>((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<string | undefined> { 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<number | null>((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<string, unknown>; 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<Record<string, any>> { 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<string, any>, history: Array<Record<string, any>>,): 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<Array<Record<string, any>>> { 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<string, any>);}async function main(): Promise<void> { 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; });}new file mode 100644+206 / −0 text lines
import { Buffer } from "node:buffer";import { describe, expect, test } from "vitest";import { compareWithHistory, createBenchmark, scoreCandidate, summarizeEvents,} from "../__bench__/ab.ts";import { __test } from "../index.ts";const benchmark = createBenchmark();describe("cmprss A/B benchmark", () => { test("deterministically exercises every compressor below Pi's read cap", () => { for (const [path, expectedCompressor] of Object.entries( benchmark.expectedCompressors, )) { const content = benchmark.files[path]; expect(content, path).toBeDefined(); const size = Buffer.byteLength(content); expect(size, `${path} exceeds cmprss threshold`).toBeGreaterThan(20_000); expect(size, `${path} exceeds Pi read cap`).toBeLessThan(50_000); expect(__test.compressContent(content).compressor, path).toBe( expectedCompressor, ); } }); test("embeds every expected value exactly in its fixture", () => { expect(benchmark.files["fixtures/data.json"]).toContain( `"releaseCode": "${benchmark.expected.jsonCode}"`, ); expect(benchmark.files["fixtures/search.txt"]).toContain( `needle=${benchmark.expected.searchNeedle}`, ); expect(benchmark.files["fixtures/change.diff"]).toContain( `+export const value20 = "${benchmark.expected.diffNewValue}";`, ); expect(benchmark.files["fixtures/stacktrace.txt"]).toContain( `Caused by: Error: ${benchmark.expected.stackRootCause}`, ); expect(benchmark.files["fixtures/build.log"]).toContain( `ERROR build failed: ${benchmark.expected.logFailure}`, ); expect(benchmark.files["fixtures/build.log"]).toContain( `completion token: ${benchmark.expected.logTail}`, ); expect(benchmark.files["fixtures/narrative.txt"]).toContain( `middle token: ${benchmark.expected.textMiddle}`, ); }); test("requires retrieval for omitted facts while preserving structural signals", () => { const compressed = Object.fromEntries( Object.entries(benchmark.files).map(([path, content]) => [ path, __test.compressContent(content).text, ]), ); expect(compressed["fixtures/data.json"]).not.toContain( benchmark.expected.jsonCode, ); expect(compressed["fixtures/search.txt"]).not.toContain( benchmark.expected.searchNeedle, ); expect(compressed["fixtures/narrative.txt"]).not.toContain( benchmark.expected.textMiddle, ); expect(compressed["fixtures/change.diff"]).toContain( benchmark.expected.diffNewValue, ); expect(compressed["fixtures/stacktrace.txt"]).toContain( benchmark.expected.stackRootCause, ); expect(compressed["fixtures/build.log"]).toContain( benchmark.expected.logFailure, ); expect(compressed["fixtures/build.log"]).toContain( benchmark.expected.logTail, ); }); test("hard-scores exact and fenced JSON answers", () => { const exact = JSON.stringify(benchmark.expected); const fenced = `\`\`\`json\n${exact}\n\`\`\``; expect(scoreCandidate(exact, benchmark.expected).score).toBe(100); expect(scoreCandidate(fenced, benchmark.expected).score).toBe(100); const wrong = { ...benchmark.expected, textMiddle: "wrong" }; const score = scoreCandidate(JSON.stringify(wrong), benchmark.expected); expect(score.correct).toBe(Object.keys(benchmark.expected).length - 1); expect(score.score).toBeLessThan(100); }); test("compares modified runs with the latest persisted controls", () => { const result = { case: "modified", subject: { usage: { totalTokens: 60 }, hardScore: { score: 100 } }, judge: { result: { score: 90 } }, }; const history = [ { case: "current", subject: { usage: { totalTokens: 100 }, hardScore: { score: 90 } }, judge: { result: { score: 80 } }, }, { case: "baseline", subject: { usage: { totalTokens: 120 }, hardScore: { score: 100 } }, judge: { result: { score: 100 } }, }, ]; expect(compareWithHistory(result, history)).toEqual([ { case: "baseline", tokenDelta: -60, tokenDeltaPercent: -50, hardDelta: 0, judgeDelta: -10, }, { case: "current", tokenDelta: -40, tokenDeltaPercent: -40, hardDelta: 10, judgeDelta: 10, }, ]); }); test("summarizes provider usage, compression, retrieval, and final answer", () => { const events = [ { type: "message_end", message: { role: "assistant", provider: "test", model: "luna", content: [{ type: "text", text: "working" }], usage: { input: 100, output: 10, cacheRead: 20, cacheWrite: 5, totalTokens: 135, }, }, }, { type: "tool_execution_end", toolName: "read", result: { content: [{ type: "text", text: "summary" }], details: { cmprss: { originalBytes: 30_000, compressedBytes: 1_000 }, }, }, }, { type: "tool_execution_end", toolName: "cmprss_retrieve", result: { content: [{ type: "text", text: "retrieved" }], details: { returnedBytes: 9 }, }, }, { type: "message_end", message: { role: "assistant", provider: "test", model: "luna", content: [{ type: "text", text: "final" }], usage: { input: 200, output: 20, cacheRead: 40, cacheWrite: 0, totalTokens: 260, }, }, }, ]; const summary = summarizeEvents(events); expect(summary.usage).toEqual({ input: 300, output: 30, cacheRead: 60, cacheWrite: 5, totalTokens: 395, }); expect(summary.compression).toMatchObject({ blocks: 1, originalBytes: 30_000, compressedBytes: 1_000, retrievals: 1, netSavedBytes: 29_000 - Buffer.byteLength("retrieved"), }); expect(summary.finalText).toBe("final"); expect(summary.provider).toBe("test"); expect(summary.model).toBe("luna"); });});+107 / −0 text lines
MAX_RETRIEVE_BYTES, retrieveToolResult, retrievedBytes: 0, 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("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(); });+71 / −1 text lines
import { describe, expect, test } from "vitest"; test("renders every retrieval parameter and hides content until expanded", () => { let tool: any; cmprssExtension({ on() {}, registerTool(definition: unknown) { tool = definition; }, registerCommand() {}, appendEntry() {}, } as any); const call = render( tool.renderCall( { hash: "0123456789abcdef", offset: 128, limit: 256 }, theme(), {}, ), ); expect(call).toContain("0123456789abcdef"); expect(call).toContain("offset=128"); expect(call).toContain("limit=256"); const result = { content: [{ type: "text", text: "secret retrieved content" }], details: { hash: "0123456789abcdef", offset: 128, nextOffset: 384, returnedBytes: 256, totalBytes: 1_024, hasMore: true, }, }; const collapsed = render( tool.renderResult( result, { expanded: false, isPartial: false }, theme(), {}, ), ); const expanded = render( tool.renderResult( result, { expanded: true, isPartial: false }, theme(), {}, ), ); expect(collapsed).toContain("256B"); expect(collapsed).toContain("128-383 of 1024"); expect(collapsed).not.toContain("secret retrieved content"); expect(expanded).toContain("secret retrieved content"); });+171 / −13 text lines
keyHint,import { Text } from "@earendil-works/pi-tui"; | { op: "block"; meta: BlockMeta; originalText: string; at: number }; stats: { blocks: number; originalBytes: number; compressedBytes: number }; stats: { blocks: 0, originalBytes: 0, compressedBytes: 0 }, runtime.stats = { blocks: 0, originalBytes: 0, compressedBytes: 0 }; if (["edit", "write"].includes(tool)) return false; if (["cmprss_retrieve", "edit", "write"].includes(tool)) return false; const marker = `[cmprss: ${String(event.toolName)} ${originalBytes}B → ${bytes(compression.text)}B, saved ~${Math.max(0, Math.floor((originalBytes - bytes(compression.text)) / 4))}t, hash=${hash}]\nUse cmprss_retrieve(hash="${hash}") for exact original text.`; const marker = `[cmprss: ${String(event.toolName)} ${originalBytes}B → ${bytes(compression.text)}B, saved ~${Math.max(0, Math.floor((originalBytes - bytes(compression.text)) / 4))}t, hash=${hash}]\nUse cmprss_retrieve(hash="${hash}") for bounded exact UTF-8 ranges.`;export function retrieveToolResult( runtime: Runtime, hash: string, offset = 0, limit = MAX_RETRIEVE_BYTES,): { content: [{ type: "text"; text: string }]; details: RetrieveDetails;} { if (!Number.isInteger(offset) || offset < 0) throw new Error("cmprss: offset must be a non-negative integer"); if (!Number.isInteger(limit) || limit < 1) throw new Error("cmprss: limit must be a positive integer"); if (limit > MAX_RETRIEVE_BYTES) throw new Error(`cmprss: limit must be at most ${MAX_RETRIEVE_BYTES}`); const original = Buffer.from(runtime.retrieve(hash), "utf8"); if (offset >= original.length) throw new Error( `cmprss: offset ${offset} is beyond end of block (${original.length} bytes)`, ); if (offset > 0 && isUtf8Continuation(original[offset])) throw new Error("cmprss: offset must be a UTF-8 boundary"); let nextOffset = Math.min(offset + limit, original.length); while ( nextOffset > offset && nextOffset < original.length && isUtf8Continuation(original[nextOffset]) ) nextOffset--; if (nextOffset === offset) throw new Error("cmprss: limit must include a complete UTF-8 character"); const chunk = original.subarray(offset, nextOffset).toString("utf8"); const hasMore = nextOffset < original.length; const continuation = hasMore ? `\n\n[cmprss: bytes ${offset}-${nextOffset - 1} of ${original.length}. Continue with cmprss_retrieve(hash="${hash}", offset=${nextOffset}, limit=${limit}).]` : ""; const text = `${chunk}${continuation}`; const contextBytes = bytes(text); const at = Date.now(); record(runtime, { op: "retrieve", hash, contextBytes, at }); return { content: [{ type: "text", text }], details: { hash, offset, nextOffset, limit, returnedBytes: nextOffset - offset, totalBytes: original.length, hasMore, }, };} (runtime.stats.originalBytes - runtime.stats.compressedBytes) / 4, description: "Retrieve exact original text for a cmprss hash.", description: `Retrieve an exact UTF-8 byte range from a cmprss block. Returns at most ${MAX_RETRIEVE_BYTES} bytes and includes the next offset when more remains.`, offset: Type.Optional( Type.Integer({ description: "UTF-8 byte offset, starting at 0", minimum: 0, }), ), limit: Type.Optional( Type.Integer({ description: `Maximum bytes to return, defaults to ${MAX_RETRIEVE_BYTES}`, minimum: 1, maximum: MAX_RETRIEVE_BYTES, }), ), renderCall(args, theme) { const offset = args.offset ?? 0; const limit = args.limit ?? MAX_RETRIEVE_BYTES; return new Text( `${theme.fg("toolTitle", theme.bold("cmprss_retrieve"))} ${theme.fg("accent", args.hash)} ${theme.fg("dim", `offset=${offset} limit=${limit}`)}`, 0, 0, ); }, renderResult(result, { expanded }, theme, context) { const details = result.details as RetrieveDetails | undefined; const content = result.content[0]; const text = content?.type === "text" ? content.text : ""; if (!details) { return new Text( theme.fg(context.isError ? "error" : "muted", text), 0, 0, ); } const end = details.nextOffset - 1; let summary = theme.fg( "success", `✓ ${details.returnedBytes}B · ${details.offset}-${end} of ${details.totalBytes}`, ); if (!expanded) summary += ` ${theme.fg("dim", `(${keyHint("app.tools.expand", "to expand")})`)}`; else if (text) summary += `\n${theme.fg("toolOutput", text)}`; return new Text(summary, 0, 0); }, MAX_RETRIEVE_BYTES, retrieveToolResult,new file mode 100644+9 / −0 text lines
+1 / −0 text lines
+1 / −0 text lines