/** * smart-compact mock-harness — run with: node --test harness.ts * (Node ≥ 22.18 with built-in TypeScript type stripping.) * * Drives the extension against a mock Pi: turn_end / agent_settled / * session_compact events, controllable getContextUsage(), and a ctx.compact * recorder. Config is injected per scenario via a temp project * .pi/settings.json (all fields set, so the user's global file cannot leak * into assertions). */ import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import smartCompact from "./index.ts"; interface CtxOverrides { tokens: number | null; window: number; onCompact?: (opts: any) => void; idle?: boolean; entries?: any[]; } function load(settings: Record) { const dir = mkdtempSync(path.join(tmpdir(), "smart-compact-test-")); mkdirSync(path.join(dir, ".pi")); writeFileSync( path.join(dir, ".pi", "settings.json"), JSON.stringify({ smartCompact: settings }), ); const prevCwd = process.cwd(); process.chdir(dir); const pi: any = { handlers: {} as Record, commands: {} as Record, on(name: string, fn: any) { this.handlers[name] = fn; }, registerCommand(name: string, def: any) { this.commands[name] = def; }, }; try { smartCompact(pi); } finally { process.chdir(prevCwd); rmSync(dir, { recursive: true, force: true }); } return pi; } function makeCtx({ tokens, window, onCompact, idle = true, entries = [] }: CtxOverrides) { const calls: { compact: number; notified: string[]; overlays: { overlay?: boolean; overlayOptions?: Record }[]; components: any[]; renders: number; } = { compact: 0, notified: [], overlays: [], components: [], renders: 0 }; return { calls, ctx: { isIdle: () => idle, getContextUsage: () => ({ tokens, contextWindow: window }), sessionManager: { getEntries: () => entries }, ui: { notify: (msg: string) => calls.notified.push(msg), // Minimal ctx.ui.custom: captures overlay options, instantiates the // component, resolves the promise when done() fires. custom: (factory: any, opts?: any) => { calls.overlays.push(opts ?? {}); return new Promise((resolve) => { calls.components.push( factory( { requestRender: () => calls.renders++ }, // Identity theme: styling is a no-op so assertions see plain text. { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, {}, (result: unknown) => resolve(result), ), ); }); }, }, compact: (opts: any) => { calls.compact++; (onCompact ?? ((o: any) => o?.onComplete?.({})))(opts); }, }, }; } const fire = async (pi: any, name: string, ctx: any, event: any = { entries: [] }) => await pi.handlers[name](event, ctx); const FULL = { enabled: true, warnTokens: 60_000, forceTokens: 90_000, warnFraction: 0.55, forceFraction: 0.8 }; // With window 100k: warnAt = min(60k, 55k) = 55k, forceAt = min(90k, 80k) = 80k. test("warn fires once per cycle at the effective threshold", async () => { const pi = load(FULL); const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 }); const first = await fire(pi, "turn_end", ctx); assert.equal(first.entries.at(-1).customType, "smart-compact-notice"); assert.equal(first.entries.at(-1).display, false); assert.equal(first.continue, true); assert.match(first.entries.at(-1).content, /56k tokens/); const second = await fire(pi, "turn_end", ctx); assert.equal(second, undefined); }); test("below warn threshold: no message", async () => { const pi = load(FULL); const { ctx } = makeCtx({ tokens: 40_000, window: 100_000 }); assert.equal(await fire(pi, "turn_end", ctx), undefined); }); test("force tier never triggers from turn_end (mid-run compaction aborts work)", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 95_000, window: 100_000 }); // above forceAt await fire(pi, "turn_end", ctx); assert.equal(calls.compact, 0); }); test("force fires at agent_settled above the effective threshold", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 }); const result = await fire(pi, "agent_settled", ctx, {}); assert.equal(result, undefined); // notification event — no entries returned assert.equal(calls.compact, 1); assert.match(calls.notified.join("\n"), /85k/); }); test("force does not fire at agent_settled below the threshold", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 60_000, window: 100_000 }); // above warn, below force await fire(pi, "agent_settled", ctx, {}); assert.equal(calls.compact, 0); }); test("in-flight lock prevents a second compaction before onComplete", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: () => {} }); // never completes const first = fire(pi, "agent_settled", ctx, {}); // handler pends until a callback fires await fire(pi, "agent_settled", ctx, {}); // blocked by the in-flight lock assert.equal(calls.compact, 1); }); test("failed compaction starts the cooldown; no immediate retry", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: (o) => o?.onError?.(new Error("x")) }); await fire(pi, "agent_settled", ctx, {}); await fire(pi, "agent_settled", ctx, {}); assert.equal(calls.compact, 1); }); test("stale pre-compaction token count does not re-trigger force", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000 }); await fire(pi, "agent_settled", ctx, {}); // compacts, onComplete releases lock await fire(pi, "session_compact", { getContextUsage: () => ({ tokens: null, contextWindow: 100_000 }) }); // Usage still null right after compaction (no assistant response yet): const { ctx: nullCtx, calls: nullCalls } = makeCtx({ tokens: null, window: 100_000 }); await fire(pi, "agent_settled", nullCtx, {}); assert.equal(nullCalls.compact, 0); // cache was cleared, not stale assert.equal(calls.compact, 1); }); test("warn re-arms after session_compact starts a new cycle", async () => { const pi = load(FULL); const { ctx } = makeCtx({ tokens: 56_000, window: 100_000 }); assert.notEqual(await fire(pi, "turn_end", ctx), undefined); await fire(pi, "session_compact", {}); assert.notEqual(await fire(pi, "turn_end", ctx), undefined); }); test("invalid config values fall back per field (null ≠ 0, strings ≠ NaN)", async () => { const pi = load({ enabled: true, warnTokens: null, forceTokens: "big", warnFraction: 0, forceFraction: 1.5 } as any); // Defaults: warnAt = min(100k, .55×100k) = 55k, forceAt = min(200k, .8×100k) = 80k. const below = makeCtx({ tokens: 79_999, window: 100_000 }); await fire(pi, "agent_settled", below.ctx, {}); assert.equal(below.calls.compact, 0); const above = makeCtx({ tokens: 80_000, window: 100_000 }); await fire(pi, "agent_settled", above.ctx, {}); assert.equal(above.calls.compact, 1); // The old Math.min(null, …) → 0 bug would compact on ANY token count: const tiny = makeCtx({ tokens: 1, window: 100_000 }); await fire(pi, "agent_settled", tiny.ctx, {}); assert.equal(tiny.calls.compact, 0); }); test("invalid warn-side config falls back per field, verified via turn_end", async () => { const pi = load({ enabled: true, warnTokens: null, forceTokens: 90_000, warnFraction: "high", forceFraction: 0.8 } as any); // Defaults: warnAt = min(100k, 0.55 × window). const fracLimited = makeCtx({ tokens: 54_999, window: 100_000 }); // 0.55×100k = 55k < 100k absolute assert.equal(await fire(pi, "turn_end", fracLimited.ctx), undefined); const atFractional = makeCtx({ tokens: 55_000, window: 100_000 }); assert.notEqual(await fire(pi, "turn_end", atFractional.ctx), undefined); // New cycle + absolute-limited window: 0.55×400k = 220k > 100k absolute floor. await fire(pi, "session_compact", {}); const absLimited = makeCtx({ tokens: 99_999, window: 400_000 }); assert.equal(await fire(pi, "turn_end", absLimited.ctx), undefined); const atAbsolute = makeCtx({ tokens: 100_000, window: 400_000 }); assert.notEqual(await fire(pi, "turn_end", atAbsolute.ctx), undefined); }); test("enabled: false registers nothing", () => { const pi = load({ ...FULL, enabled: false }); assert.equal(Object.keys(pi.handlers).length, 0); assert.equal(Object.keys(pi.commands).length, 0); }); test("status command opens a centered overlay panel with thresholds", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); // let the component factory run assert.equal(calls.overlays.length, 1); assert.equal(calls.overlays[0].overlay, true); assert.deepEqual(calls.overlays[0].overlayOptions, { width: "70%", minWidth: 50, maxHeight: "85%", anchor: "center", margin: 2, }); assert.equal(calls.notified.length, 0); // overlay mode, not notify const comp = calls.components[0]; const text = comp.render(80).join("\n"); assert.match(text, /smart-compact status/); assert.match(text, /tokens now\s+56k/); assert.match(text, /window\s+100k/); assert.match(text, /56% of window/); assert.match(text, /warn threshold\s+55k \(crossed\)/); assert.match(text, /force threshold\s+80k(?!\s*\(crossed\))/); assert.match(text, /compactions\s+0/); assert.match(text, /esc\/enter\/q to close/); comp.handleInput("\x1b"); await pending; // resolves once done() fires assert.ok(calls.renders >= 1); }); test("overlay renders a bordered box of constant line width", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); const lines = calls.components[0].render(80) as string[]; assert.ok(lines.length >= 5); for (const line of lines) { assert.equal(stripAnsi(line).length, 80); // borders and padding align } assert.match(stripAnsi(lines[0]!), /^┌─+┐$/); assert.match(stripAnsi(lines.at(-1)!), /^└─+┘$/); calls.components[0].handleInput("\r"); await pending; }); test("overlay honors requested width, including degenerate narrow", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); const comp = calls.components[0]; const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); for (const line of comp.render(10) as string[]) { assert.equal(stripAnsi(line).length, 10); // never exceeds the given width } const tiny = comp.render(4) as string[]; // below border floor: plain truncation assert.ok(tiny.length >= 5); for (const line of tiny) { assert.ok(stripAnsi(line).length <= 4); assert.ok(!line.includes("┌")); // no border glyphs at degenerate widths } comp.handleInput("\x1b"); await pending; }); test("render cache: same-width hit, width-change and invalidate rebuild", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); const comp = calls.components[0]; const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); const a = comp.render(80) as string[]; assert.ok(comp.render(80) === a); // same width → cached instance const c = comp.render(60) as string[]; // width change → rebuild at 60 assert.notEqual(c, a); assert.equal(stripAnsi(c[0]!).length, 60); comp.invalidate(); // theme change → rebuild even at the same width const d = comp.render(60) as string[]; assert.notEqual(d, c); comp.handleInput("\x1b"); await pending; }); test("overlay closes on esc, enter, q, ctrl+c (legacy and kitty forms) — not on other keys", async () => { for (const key of ["\x1b", "\r", "\n", "q", "\x03", "\x1b[27u", "\x1b[27;1u", "\x1b[13u", "\x1b[13;1u", "\x1b[113u", "\x1b[113;1u", "\x1b[99;5u"]) { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); calls.components[0].handleInput(key); await pending; // must resolve } const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); let closed = false; void pending.then(() => { closed = true; }); calls.components[0].handleInput("x"); calls.components[0].handleInput("\x1b[A"); // arrow-up sequence ≠ bare esc await new Promise((r) => setImmediate(r)); assert.equal(closed, false); // still open calls.components[0].handleInput("\x1b"); await pending; }); // Primary close path in the real TUI: keybindings.matches normalizes kitty // CSI-u sequences and honors user-remapped cancel/confirm bindings. test("overlay close prefers keybindings.matches (remapped bindings honored)", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); // Swap in a custom() mock whose keybindings only cancel on "ZZ". (ctx.ui as any).custom = (factory: any, opts: any) => { calls.overlays.push(opts ?? {}); return new Promise((resolve) => { calls.components.push( factory( { requestRender: () => calls.renders++ }, { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, { matches: (data: string, id: string) => id === "tui.select.cancel" && data === "ZZ" }, (result: unknown) => resolve(result), ), ); }); }; const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); let closed = false; void pending.then(() => { closed = true; }); calls.components[0].handleInput("\x1b[27u"); // kitty esc — still closes via the CLOSE_KEYS fallback await pending; assert.equal(closed, true); // And the remapped binding closes too, even though "ZZ" is in no set. const pi2 = load(FULL); const { ctx: ctx2, calls: calls2 } = makeCtx({ tokens: 56_000, window: 100_000 }); (ctx2.ui as any).custom = (factory: any, opts: any) => { calls2.overlays.push(opts ?? {}); return new Promise((resolve) => { calls2.components.push( factory( { requestRender: () => calls2.renders++ }, { fg: (_c: string, s: string) => s, bg: (_c: string, s: string) => s, bold: (s: string) => s }, { matches: (data: string, id: string) => id === "tui.select.cancel" && data === "ZZ" }, (result: unknown) => resolve(result), ), ); }); }; const pending2 = pi2.commands["smart-compact"].handler(undefined, ctx2); await new Promise((r) => setImmediate(r)); calls2.components[0].handleInput("ZZ"); await pending2; }); test("status falls back to notify when overlay UI is unavailable", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000 }); delete (ctx.ui as any).custom; await pi.commands["smart-compact"].handler(undefined, ctx); assert.equal(calls.overlays.length, 0); const text = calls.notified.join("\n"); assert.match(text, /smart-compact status/); assert.match(text, /56k/); assert.doesNotMatch(text, /to close/); // hint is overlay-mode only }); test("status counts compactions from the session tree; in-memory fallback without sessionManager", async () => { const pi = load(FULL); const entries = [{ type: "message" }, { type: "compaction" }, { type: "message" }, { type: "compaction" }, { type: "compaction" }]; const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000, entries }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); assert.match(calls.components[0].render(80).join("\n"), /compactions\s+3/); calls.components[0].handleInput("\x1b"); await pending; // No sessionManager: fall back to compactions this process has seen. const { ctx: bareCtx, calls: bareCalls } = makeCtx({ tokens: 56_000, window: 100_000 }); delete (bareCtx as any).sessionManager; await fire(pi, "session_compact", bareCtx); const pending2 = pi.commands["smart-compact"].handler(undefined, bareCtx); await new Promise((r) => setImmediate(r)); assert.match(bareCalls.components[0].render(80).join("\n"), /compactions\s+1/); bareCalls.components[0].handleInput("\x1b"); await pending2; }); test("usage bar hidden when window is unknown", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 0 }); const pending = pi.commands["smart-compact"].handler(undefined, ctx); await new Promise((r) => setImmediate(r)); const text = calls.components[0].render(80).join("\n"); assert.match(text, /window\s+unknown/); assert.doesNotMatch(text, /% of window/); calls.components[0].handleInput("\x1b"); await pending; }); test("force does not fire when settled reports not idle", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, idle: false }); await fire(pi, "agent_settled", ctx, {}); assert.equal(calls.compact, 0); }); test("settled handler awaits compaction completion before finishing", async () => { const pi = load(FULL); let finish!: (cb: "onComplete" | "onError") => void; const { ctx, calls } = makeCtx({ tokens: 85_000, window: 100_000, onCompact: (o) => { finish = (cb) => o[cb]?.({}); }, }); const pending = fire(pi, "agent_settled", ctx, {}); let handlerDone = false; pending.then(() => { handlerDone = true; }); await new Promise((r) => setImmediate(r)); assert.equal(handlerDone, false); // handler still awaiting the compaction assert.equal(calls.compact, 1); finish("onComplete"); await pending; assert.equal(handlerDone, true); });