import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, readGenerationUsage, utcDay } from "./generationUsage"; test("the usage ledger: rows appended, the day's total read back, a torn line skipped; the daily refusal names the total", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "gen-usage-")); try { const file = path.join(dir, "sub", "usage.jsonl"); assert.deepEqual(await dayUsage(file, "2026-10-13"), { day: "2026-10-13", usd: 0, jobs: 0 }); const row = { at: "2026-10-13T10:00:00Z", day: "2026-10-13", jobId: "j1", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 3.25 }; await appendGenerationUsage(file, [row, { ...row, model: "claude-haiku-4-5", usd: 0.5 }]); await appendGenerationUsage(file, [{ ...row, jobId: "j2", day: "2026-10-12", usd: 9 }]); const { appendFile } = await import("node:fs/promises"); await appendFile(file, "{torn\n"); assert.equal((await readGenerationUsage(file)).length, 3); const today = await dayUsage(file, "2026-10-13"); assert.deepEqual(today, { day: "2026-10-13", usd: 3.75, jobs: 1 }); assert.equal(dailyCapRefusal(today, 20), null); assert.equal(dailyCapRefusal(today, 0), null, "0 = no daily cap"); assert.match(dailyCapRefusal(today, 3.75)!, /the day's Claude API spend is \$3\.75 \(2026-10-13, UTC\), at or past the \$3\.75 daily cap/); assert.equal(utcDay(new Date("2026-10-13T23:59:59Z")), "2026-10-13"); } finally { await rm(dir, { recursive: true, force: true }); } }); test("lastRunsByTask (demo epic D3): each task's newest job, its models and route; a frame scan's job is the frames task", async () => { const { lastRunsByTask } = await import("./generationUsage"); const row = (task: string, jobId: string, model: string, at: string, route?: "local") => ({ at, day: at.slice(0, 10), jobId, article: "a", iteration: 1, task, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0, ...(route ? { route } : {}) }); const out = lastRunsByTask([ row("sweep", "j1", "claude-sonnet-5-5", "2026-11-01T10:00:00Z"), row("sweep", "j1", "claude-haiku-4-5", "2026-11-01T10:00:00Z"), row("sweep", "j2", "qwen3:8b", "2026-11-02T10:00:00Z", "local"), row("narrate", "j3", "qwen3:8b", "2026-11-01T09:00:00Z", "local"), row("frame-scan", "j4", "claude-haiku-4-5", "2026-11-03T09:00:00Z"), ]); assert.deepEqual(out.sweep, { at: "2026-11-02T10:00:00Z", jobId: "j2", models: ["qwen3:8b"], route: "local" }); assert.deepEqual(out.narrate!.models, ["qwen3:8b"]); assert.deepEqual(out.frames, { at: "2026-11-03T09:00:00Z", jobId: "j4", models: ["claude-haiku-4-5"], route: "api" }); assert.equal(out["revise-report"], undefined); });