163 lines
10 KiB
JavaScript
163 lines
10 KiB
JavaScript
// node --test tools/cache-score/test/
|
||
import { test, after } from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import fs from "node:fs";
|
||
import os from "node:os";
|
||
import path from "node:path";
|
||
|
||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "cache-score-test-"));
|
||
process.env.CACHE_SCORE_DATA = path.join(tmp, "data");
|
||
after(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
||
const cs = await import("../scripts/cache-score.mjs");
|
||
|
||
const T0 = Date.parse("2026-11-10T09:00:00Z") / 1000;
|
||
const iso = (t) => new Date(t * 1000).toISOString();
|
||
let n = 0;
|
||
function call(t, { cr = 0, w1h = 0, w5m = 0, inp = 2, out = 500, model = "claude-opus-5-5", side = false, entry = "cli" } = {}) {
|
||
n++;
|
||
return { type: "assistant", isSidechain: side, timestamp: iso(t), requestId: `req_${n}`, entrypoint: entry,
|
||
message: { id: `msg_${n}`, model, usage: { input_tokens: inp, output_tokens: out, cache_read_input_tokens: cr,
|
||
cache_creation_input_tokens: w1h + w5m, cache_creation: { ephemeral_1h_input_tokens: w1h, ephemeral_5m_input_tokens: w5m } } } };
|
||
}
|
||
const prompt = (t, text = "go on") => ({ type: "user", timestamp: iso(t), entrypoint: "cli", message: { role: "user", content: text } });
|
||
const toolResult = (t) => ({ type: "user", timestamp: iso(t), message: { role: "user", content: [{ type: "tool_result", tool_use_id: "x", content: "ok" }] } });
|
||
function write(dir, name, records) {
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
const p = path.join(dir, name);
|
||
fs.writeFileSync(p, records.map((r) => JSON.stringify(r)).join("\n") + "\n");
|
||
return p;
|
||
}
|
||
|
||
// One conversation: a warm follow-up after 30 min, a cold one after 3 h, a
|
||
// tool loop, a model switch, then a /compact before a 2 h break.
|
||
const proj = path.join(tmp, "projects", "-repo");
|
||
const recs = [
|
||
{ type: "ai-title", aiTitle: "Fix the quote endpoint" },
|
||
prompt(T0), call(T0 + 5, { w1h: 100_000 }),
|
||
prompt(T0 + 1800), call(T0 + 1805, { cr: 100_000, w1h: 2_000 }), // warm after 30 min
|
||
prompt(T0 + 12_605), call(T0 + 12_610, { cr: 24_000, w1h: 80_000 }), // cold after 3 h: 78K re-written
|
||
toolResult(T0 + 12_700), call(T0 + 12_705, { cr: 104_000, w1h: 1_000 }), // tool loop, warm
|
||
prompt(T0 + 12_800), call(T0 + 12_805, { cr: 0, w1h: 105_000, model: "claude-sonnet-5-5" }), // model switch
|
||
{ type: "system", subtype: "compact_boundary", timestamp: iso(T0 + 12_900), compactMetadata: { trigger: "manual", preTokens: 105_000 } },
|
||
prompt(T0 + 20_100), call(T0 + 20_105, { cr: 20_000, w1h: 30_000, model: "claude-sonnet-5-5" }), // after the compact: not a miss
|
||
];
|
||
const main = write(proj, "aaaa.jsonl", recs);
|
||
// A fork copies the history (same message ids) and adds one warm turn.
|
||
write(proj, "bbbb.jsonl", [...recs, prompt(T0 + 20_200), call(T0 + 20_205, { cr: 50_000, w1h: 500, model: "claude-sonnet-5-5" })]);
|
||
// A subagent: spend only.
|
||
write(path.join(proj, "aaaa", "subagents"), "agent-1.jsonl", [call(T0 + 100, { w5m: 20_000, side: true, model: "claude-haiku-5-5" })]);
|
||
|
||
const NOW = T0 + 86400;
|
||
|
||
test("prices: family fallback and fast mode", () => {
|
||
assert.deepEqual(cs.priceOf("claude-opus-5-5-20261101"), [4, 20, 0.2]);
|
||
assert.deepEqual(cs.priceOf("claude-opus-9"), [4, 20, 0.2]);
|
||
assert.equal(cs.priceOf("gpt-5"), null);
|
||
const c = { model: "claude-opus-5-5", inp: 0, out: 0, cr: 1e6, cw: 0, w1h: 0, w5m: 0 };
|
||
assert.equal(cs.costOf(c), 0.2);
|
||
assert.equal(cs.costOf({ ...c, fast: true }), 0.4);
|
||
});
|
||
|
||
test("scan: cold return, model switch, compaction and a forked copy", async () => {
|
||
const scan = await cs.scanAll([path.join(tmp, "projects")], { days: 30, now: NOW });
|
||
const cold = scan.events.filter((e) => e.cause === "expired");
|
||
assert.equal(cold.length, 1, "the fork must not count the cold return twice");
|
||
assert.equal(cold[0].rewritten, 78_002); // expected 102K − 24K read
|
||
assert.equal(cold[0].ttl, 3600);
|
||
assert.equal(cold[0].title, "Fix the quote endpoint");
|
||
// 78,002 tokens × ($8 write − $0.20 read) / M
|
||
assert.ok(Math.abs(cold[0].lost - 78_002 * 7.8 / 1e6) < 1e-9);
|
||
assert.deepEqual(scan.events.filter((e) => e.cause === "model").length, 1);
|
||
assert.equal(scan.events.filter((e) => e.cause === "other").length, 0, "the post-compact call is expected to rebuild");
|
||
// follow-ups: warm (100K), cold (102K), model switch (105K), fork's warm one; the compacted one is skipped
|
||
assert.equal(scan.followups.length, 4);
|
||
assert.ok(scan.spendCalls.some(([t]) => t === T0 + 100), "subagent calls count toward spend");
|
||
});
|
||
|
||
test("summary: context-weighted score and plan share", async () => {
|
||
const scan = await cs.scanAll([path.join(tmp, "projects")], { days: 30, now: NOW });
|
||
const sum = cs.summarize(scan, { week: 12.8, h5: 2.14 });
|
||
const warmCtx = 100_002 + 105_002 + 50_002; // 30 min, model switch (within TTL), fork turn
|
||
const allCtx = warmCtx + 102_002;
|
||
assert.equal(sum.score, Math.round(100 * warmCtx / allCtx));
|
||
assert.equal(sum.cold.length, 1);
|
||
assert.ok(Math.abs(sum.pctWeek - sum.lost / 12.8) < 1e-12);
|
||
assert.equal(sum.buckets[2].n, 1, "3 h idle on a 1 h cache = 2 h late → the 2h–4h bucket");
|
||
});
|
||
|
||
test("report renders without colour codes when asked", async () => {
|
||
const scan = await cs.scanAll([path.join(tmp, "projects")], { days: 30, now: NOW });
|
||
const rates = { label: "Max 5×", week: 12.8, h5: 2.14, how: { week: "measured" } };
|
||
const out = cs.renderReport(cs.summarize(scan, rates), { acct: { label: "Team seat (Max 5× tier)" }, rates, days: 30, cal: null });
|
||
assert.match(out, /CACHE SCORE/);
|
||
assert.match(out, /1 sent to an expired cache/);
|
||
assert.match(out, /2h–4h/);
|
||
});
|
||
|
||
test("status line: warm, about to expire, cold", () => {
|
||
const now = 1_800_000_000;
|
||
const base = { model: { id: "claude-opus-5-5" } };
|
||
const pc = (left) => ({ ...base, prompt_cache: { warm: left > 0, caching_observed: true, ttl: "1h", expires_at: now + left, hit_ratio: 0.98, recache_tokens_if_cold: 331_000 } });
|
||
const rates = { week: 12.8, h5: 2.14 };
|
||
assert.equal(cs.statusSegment(pc(42 * 60), { now, rates, color: false }), "● cache 42m · hit 98 % · 331K");
|
||
assert.match(cs.statusSegment(pc(6 * 60), { now, rates, color: false }), /^● cache 6m · 331K · leaving\? \/compact now ≈ \$0\.\d\d \(else ≈ \$2\.46 when back\)$/);
|
||
assert.equal(cs.statusSegment(pc(-3600), { now, rates, color: false }),
|
||
"○ cold 2h · next msg re-sends 331K ≈ $2.46 (1.1 % 5h) · new task? /clear is free");
|
||
});
|
||
|
||
test("cold cost: context minus the warm system prompt, at the TTL's write rate", () => {
|
||
assert.ok(Math.abs(cs.coldCost(331_000, "claude-opus-5-5") - (307_000 * 8 + 24_000 * 0.2) / 1e6) < 1e-12);
|
||
assert.ok(Math.abs(cs.coldCost(331_000, "claude-opus-5-5", 300) - (307_000 * 5 + 24_000 * 0.2) / 1e6) < 1e-12);
|
||
});
|
||
|
||
test("nudge: asks once on a cold, large context, then lets the same prompt through", () => {
|
||
const dir = path.join(tmp, "nudge");
|
||
const t = write(dir, "s1.jsonl", [prompt(T0), call(T0 + 5, { w1h: 150_000 })]);
|
||
const input = { session_id: "s1", transcript_path: t, prompt: "now fix the failing test" };
|
||
const opts = { now: T0 + 2 * 3600, env: {}, rates: { week: 12.8, h5: 2.14 }, markerDir: path.join(dir, "m") };
|
||
const first = cs.nudgeDecision(input, opts);
|
||
assert.match(first, /cache expired 2 h ago: this message would re-send 151K tokens ≈ \$1\.\d\d \(0\.\d+ % of your 5-hour window\)/);
|
||
assert.equal(cs.nudgeDecision(input, opts), null, "second send goes through");
|
||
assert.ok(cs.nudgeDecision(input, opts), "and the next cold send asks again");
|
||
assert.equal(cs.nudgeDecision({ ...input, prompt: "/clear" }, opts), null);
|
||
assert.equal(cs.nudgeDecision(input, { ...opts, now: T0 + 1800 }), null, "warm");
|
||
assert.equal(cs.nudgeDecision(input, { ...opts, env: { CACHE_SCORE_NUDGE: "0" } }), null);
|
||
assert.equal(cs.nudgeDecision(input, { ...opts, env: { CACHE_SCORE_NUDGE_MIN_TOKENS: "200000" } }), null);
|
||
const headless = write(dir, "s2.jsonl", [call(T0 + 5, { w1h: 150_000, entry: "sdk-cli" })]);
|
||
assert.equal(cs.nudgeDecision({ ...input, session_id: "s2", transcript_path: headless }, opts), null, "headless runs are left alone");
|
||
assert.equal(cs.nudgeDecision(input, { ...opts, env: { CLAUDE_CODE_ENTRYPOINT: "ai-agent-sidecar" } }), null, "an app resuming a terminal session");
|
||
assert.equal(cs.nudgeDecision(input, { ...opts, env: { CLAUDE_CODE_SESSION_ATTENDED: "0" } }), null);
|
||
assert.ok(cs.nudgeDecision({ ...input, session_id: "s2", transcript_path: headless }, { ...opts, env: { CLAUDE_CODE_ENTRYPOINT: "cli" } }), "a terminal resuming an app's session");
|
||
const compacted = write(dir, "s3.jsonl", [call(T0 + 5, { w1h: 150_000 }), { type: "system", subtype: "compact_boundary", timestamp: iso(T0 + 3000) }]);
|
||
assert.equal(cs.nudgeDecision({ ...input, session_id: "s3", transcript_path: compacted }, opts), null, "idle-compacted: nothing big to re-send");
|
||
});
|
||
|
||
test("calibration: list $ between readings over the points the window rose", () => {
|
||
const spend = [[100, 5], [200, 5], [300, 10], [400, 10]];
|
||
const samples = [
|
||
{ t: 50, wk: 10, wkr: 9e9, h5: 1, h5r: 1000 },
|
||
{ t: 250, wk: 11, wkr: 9e9, h5: 6, h5r: 1000 },
|
||
{ t: 450, wk: 13, wkr: 9e9, h5: 2, h5r: 20000 }, // 5 h window reset: that step is skipped
|
||
];
|
||
const cal = cs.calibrate(spend, samples);
|
||
assert.equal(cal.week.points, 3);
|
||
assert.equal(cal.week.usdPerPct, 30 / 3);
|
||
assert.equal(cal.h5.points, 5);
|
||
assert.equal(cal.h5.usdPerPct, 10 / 5);
|
||
assert.equal(cal.week.trusted, false);
|
||
});
|
||
|
||
test("account: tier from the cached profile, a seat's own tier first", () => {
|
||
const dir = path.join(tmp, "cfg");
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
fs.writeFileSync(path.join(dir, ".claude.json"), JSON.stringify({ oauthAccount: {
|
||
organizationType: "claude_team", organizationRateLimitTier: "default_raven", userRateLimitTier: "default_claude_max_5x" } }));
|
||
const a = cs.account(dir, { CLAUDE_CONFIG_DIR: dir });
|
||
assert.equal(a.tier, "default_claude_max_5x");
|
||
assert.equal(a.label, "Team seat (Max 5× tier)");
|
||
const rates = cs.ratesFor(a, { week: { trusted: true, usdPerPct: 11, points: 20 }, h5: { trusted: false } });
|
||
assert.equal(rates.week, 11);
|
||
assert.equal(rates.h5, 2.14);
|
||
assert.equal(cs.ratesFor({ kind: "api" }, null), null);
|
||
});
|