Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2
3import {
4 initialCodexScanState,
5 parseClaudeLine,
6 parseCodexLine,
7 parseOpenCodeMessage,
8 totalTokens,
9} from "./usageTranscripts.ts";
10
11/** Shaped after a real Claude Code assistant record. */
12function claudeLine(overrides: {
13 messageId: string;
14 contentType: string;
15 model?: string;
16 outputTokens?: number;
17}): string {
18 return JSON.stringify({
19 type: "assistant",
20 timestamp: "2026-08-07T04:05:13.944Z",
21 sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
22 cwd: "/home/theo/project",
23 message: {
24 id: overrides.messageId,
25 role: "assistant",
26 model: overrides.model ?? "claude-fable-5",
27 content: [{ type: overrides.contentType }],
28 usage: {
29 input_tokens: 2,
30 cache_creation_input_tokens: 66818,
31 cache_read_input_tokens: 1000,
32 output_tokens: overrides.outputTokens ?? 286,
33 },
34 },
35 });
36}
37
38describe("parseClaudeLine", () => {
39 it("extracts token totals and a dedupe key", () => {
40 const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
41
42 expect(record).not.toBeNull();
43 expect(record?.provider).toBe("claude");
44 expect(record?.model).toBe("claude-fable-5");
45 expect(record?.totals).toEqual({
46 uncachedInputTokens: 2,
47 cachedInputTokens: 1000,
48 cacheCreationTokens: 66818,
49 outputTokens: 286,
50 reasoningTokens: 0,
51 });
52 expect(record?.dedupeKey).toBe("msg_1:");
53 });
54
55 it("gives every content block of one message the same dedupe key", () => {
56 // T3 Code writes one record per content block, each repeating the parent
57 // message's full usage. Summing them would overcount ~2.4x on real data.
58 const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
59 const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
60
61 expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
62 expect(text?.totals).toEqual(toolUse?.totals);
63 });
64
65 it("ignores records that are not assistant messages", () => {
66 expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
67 expect(parseClaudeLine("not json")).toBeNull();
68 });
69});
70
71describe("parseCodexLine", () => {
72 const sessionMeta = JSON.stringify({
73 type: "session_meta",
74 timestamp: "2026-08-01T05:17:41.289Z",
75 payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
76 });
77 const turnContext = JSON.stringify({
78 type: "turn_context",
79 timestamp: "2026-08-01T05:17:42.694Z",
80 payload: { type: "turn_context", model: "gpt-5.6-sol" },
81 });
82 const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
83 JSON.stringify({
84 type: "event_msg",
85 timestamp: "2026-08-01T05:17:49.919Z",
86 payload: {
87 type: "token_count",
88 info: {
89 last_token_usage: {
90 input_tokens: inputTokens,
91 cached_input_tokens: cached,
92 cache_write_input_tokens: 0,
93 output_tokens: output,
94 reasoning_output_tokens: reasoning,
95 },
96 },
97 },
98 });
99
100 it("attributes usage to the model from the preceding turn context", () => {
101 const state = initialCodexScanState();
102 parseCodexLine(sessionMeta, state);
103 parseCodexLine(turnContext, state);
104 const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
105
106 expect(record?.provider).toBe("codex");
107 expect(record?.model).toBe("gpt-5.6-sol");
108 expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
109 // Codex reports input_tokens inclusive of the cached portion.
110 expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
111 expect(record?.totals.cachedInputTokens).toBe(11008);
112 expect(record?.totals.reasoningTokens).toBe(116);
113 });
114
115 it("skips a repeated token_count so deltas are not double counted", () => {
116 const state = initialCodexScanState();
117 parseCodexLine(turnContext, state);
118 const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
119 const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
120
121 expect(first).not.toBeNull();
122 expect(repeat).toBeNull();
123 });
124
125 it("drops usage that arrives before any model is known", () => {
126 const state = initialCodexScanState();
127 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
128 });
129
130 it("does not let a pre-model event poison the duplicate signature", () => {
131 // A token_count before its turn_context is dropped; the identical event
132 // re-emitted once the model is known must still be counted.
133 const state = initialCodexScanState();
134 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
135 parseCodexLine(turnContext, state);
136 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
137 });
138
139 // A forked/subagent rollout opens with the parent's history copied in and
140 // every line re-stamped to the fork instant, then the ancestors' session
141 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
142 describe("forked rollouts", () => {
143 const meta = (overrides: {
144 id: string;
145 timestamp: string;
146 forkedFromId?: string;
147 spawnParentId?: string;
148 }) =>
149 JSON.stringify({
150 type: "session_meta",
151 timestamp: overrides.timestamp,
152 payload: {
153 type: "session_meta",
154 id: overrides.id,
155 ...(overrides.forkedFromId === undefined
156 ? {}
157 : { forked_from_id: overrides.forkedFromId }),
158 ...(overrides.spawnParentId === undefined
159 ? {}
160 : {
161 source: {
162 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
163 },
164 }),
165 },
166 });
167 const stamped = (timestamp: string, line: string) => {
168 const parsed = JSON.parse(line) as { timestamp: string };
169 parsed.timestamp = timestamp;
170 return JSON.stringify(parsed);
171 };
172
173 it("keeps the child session id over copied ancestor metas", () => {
174 const state = initialCodexScanState();
175 parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
176 parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
177 parseCodexLine(turnContext, state);
178 const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
179
180 expect(record?.sessionId).toBe("child");
181 });
182
183 it("drops the re-stamped copied burst and keeps the first real event", () => {
184 const state = initialCodexScanState();
185 const forkInstant = "2026-08-01T05:00:00.000Z";
186 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
187 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
188 parseCodexLine(stamped(forkInstant, turnContext), state);
189
190 // Copied history: written in one burst at the fork instant.
191 expect(
192 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
193 ).toBeNull();
194 expect(
195 parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
196 ).toBeNull();
197
198 // The child's first genuine turn lands seconds later and must count.
199 const real = parseCodexLine(
200 stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
201 state,
202 );
203 expect(real).not.toBeNull();
204 expect(real?.totals.outputTokens).toBe(30);
205
206 // Suppression never restarts, even for closely spaced later events.
207 const next = parseCodexLine(
208 stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
209 state,
210 );
211 expect(next).not.toBeNull();
212 });
213
214 it("recognizes subagent spawns without forked_from_id", () => {
215 const state = initialCodexScanState();
216 const spawnInstant = "2026-08-01T05:00:00.000Z";
217 parseCodexLine(
218 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
219 state,
220 );
221 parseCodexLine(stamped(spawnInstant, turnContext), state);
222 expect(
223 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
224 ).toBeNull();
225 });
226
227 it("does not suppress anything in a rollout that is not a fork", () => {
228 const state = initialCodexScanState();
229 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
230 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
231 const record = parseCodexLine(
232 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
233 state,
234 );
235 expect(record).not.toBeNull();
236 });
237 });
238});
239
240describe("totalTokens", () => {
241 it("does not add reasoning on top of output", () => {
242 expect(
243 totalTokens({
244 uncachedInputTokens: 10,
245 cachedInputTokens: 20,
246 cacheCreationTokens: 30,
247 outputTokens: 40,
248 reasoningTokens: 25,
249 }),
250 ).toBe(100);
251 });
252});
253
254describe("parseOpenCodeMessage", () => {
255 /** Shaped after a real OpenCode assistant message in the `message` table. */
256 function row(overrides: Record<string, unknown> = {}): {
257 readonly id: string;
258 readonly sessionId: string;
259 readonly timeCreatedMs: number;
260 readonly data: string;
261 } {
262 return {
263 id: "msg_1",
264 sessionId: "ses_1",
265 timeCreatedMs: 1_785_000_000_000,
266 data: JSON.stringify({
267 parentID: "msg_0",
268 role: "assistant",
269 mode: "build",
270 cost: 0.00368793,
271 tokens: {
272 total: 8193,
273 input: 7908,
274 output: 209,
275 reasoning: 76,
276 cache: { write: 0, read: 0 },
277 },
278 modelID: "deepseek-v4-pro",
279 providerID: "opencode-go",
280 time: { created: 1_785_000_000_000, completed: 1_785_000_001_000 },
281 finish: "tool-calls",
282 ...overrides,
283 }),
284 };
285 }
286
287 it("extracts totals, the qualified model and the reported cost", () => {
288 const record = parseOpenCodeMessage(row());
289
290 expect(record).not.toBeNull();
291 expect(record?.provider).toBe("opencode");
292 expect(record?.model).toBe("opencode-go/deepseek-v4-pro");
293 expect(record?.sessionId).toBe("ses_1");
294 expect(record?.timestampMs).toBe(1_785_000_000_000);
295 expect(record?.reportedCostUsd).toBeCloseTo(0.00368793, 9);
296 expect(record?.dedupeKey).toBeNull();
297 // reasoning is a subset of output, never added on top.
298 expect(record?.totals).toEqual({
299 uncachedInputTokens: 7908,
300 cachedInputTokens: 0,
301 cacheCreationTokens: 0,
302 outputTokens: 209,
303 reasoningTokens: 76,
304 });
305 });
306
307 it("maps cache reads and writes to their own totals", () => {
308 const record = parseOpenCodeMessage(
309 row({
310 cost: 0.000390311,
311 tokens: {
312 total: 8703,
313 input: 193,
314 output: 277,
315 reasoning: 41,
316 cache: { write: 0, read: 8192 },
317 },
318 }),
319 );
320
321 expect(record?.totals).toEqual({
322 uncachedInputTokens: 193,
323 cachedInputTokens: 8192,
324 cacheCreationTokens: 0,
325 outputTokens: 277,
326 reasoningTokens: 41,
327 });
328 });
329
330 it("reads the legacy nested model shape", () => {
331 const record = parseOpenCodeMessage(
332 row({
333 model: { providerID: "opencode", modelID: "deepseek-v4-flash" },
334 modelID: undefined,
335 providerID: undefined,
336 }),
337 );
338
339 expect(record?.model).toBe("opencode/deepseek-v4-flash");
340 });
341
342 it("falls back to the row timestamp when the message has none", () => {
343 const record = parseOpenCodeMessage(row({ time: {} }));
344
345 expect(record?.timestampMs).toBe(1_785_000_000_000);
346 });
347
348 it("ignores non-assistant messages, missing models and zero-token rows", () => {
349 expect(parseOpenCodeMessage(row({ role: "user" }))).toBeNull();
350 expect(parseOpenCodeMessage(row({ modelID: undefined }))).toBeNull();
351 expect(
352 parseOpenCodeMessage(
353 row({
354 tokens: { total: 0, input: 0, output: 0, reasoning: 0, cache: { write: 0, read: 0 } },
355 }),
356 ),
357 ).toBeNull();
358 expect(parseOpenCodeMessage({ ...row(), data: "not json" })).toBeNull();
359 });
360});