Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - resume coverage writes, appends
2// to, and truncates real transcript files byte-exactly, mirroring the reader's
3// own deliberate node:fs usage.
4import * as NodeFSP from "node:fs/promises";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7
8import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
9
10import { TEST_FORMATS } from "./usageTestFormats.ts";
11import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts";
12
13let dir: string;
14
15beforeEach(async () => {
16 dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-reader-test-"));
17});
18
19afterEach(async () => {
20 await NodeFSP.rm(dir, { recursive: true, force: true });
21});
22
23function claudeLine(id: number, outputTokens: number): string {
24 return `${JSON.stringify({
25 type: "assistant",
26 timestamp: "2026-08-01T10:00:00Z",
27 requestId: `req_${id}`,
28 sessionId: "session-1",
29 message: {
30 id: `msg_${id}`,
31 model: "claude-fable-5",
32 usage: { input_tokens: 10, output_tokens: outputTokens },
33 },
34 })}\n`;
35}
36
37function codexMetaLine(): string {
38 return `${JSON.stringify({
39 type: "session_meta",
40 timestamp: "2026-08-01T10:00:00Z",
41 payload: { type: "session_meta", id: "codex-session-1" },
42 })}\n`;
43}
44
45function codexModelLine(model: string): string {
46 return `${JSON.stringify({
47 type: "turn_context",
48 timestamp: "2026-08-01T10:00:01Z",
49 payload: { type: "turn_context", model },
50 })}\n`;
51}
52
53function codexTierLine(serviceTier: string): string {
54 return `${JSON.stringify({
55 type: "event_msg",
56 timestamp: "2026-08-01T10:00:01Z",
57 payload: { type: "thread_settings_applied", thread_settings: { service_tier: serviceTier } },
58 })}\n`;
59}
60
61function codexUsageLine(outputTokens: number, secondsOffset: number): string {
62 return `${JSON.stringify({
63 type: "event_msg",
64 timestamp: `2026-08-01T10:00:${String(secondsOffset).padStart(2, "0")}Z`,
65 payload: {
66 type: "token_count",
67 info: { last_token_usage: { input_tokens: 100, output_tokens: outputTokens } },
68 },
69 })}\n`;
70}
71
72describe("readTranscriptRecords resume", () => {
73 it("parses only appended lines when resuming a grown file", async () => {
74 const path = NodePath.join(dir, "claude.jsonl");
75 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
76 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
77 assert.isNotNull(first);
78 assert.strictEqual(first.records.length, 2);
79 assert.isFalse(first.resumed);
80
81 await NodeFSP.appendFile(path, claudeLine(3, 11));
82 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
83 assert.isNotNull(second);
84 assert.isTrue(second.resumed);
85 assert.strictEqual(second.records.length, 1);
86 assert.strictEqual(second.records[0]?.totals.outputTokens, 11);
87
88 const full = await readTranscriptRecords(path, TEST_FORMATS.claude);
89 assert.isNotNull(full);
90 assert.deepStrictEqual([...first.records, ...second.records], [...full.records]);
91 });
92
93 it("carries the Codex reducer state across the resume boundary", async () => {
94 const path = NodePath.join(dir, "rollout.jsonl");
95 await NodeFSP.writeFile(
96 path,
97 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"),
98 );
99 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
100 assert.isNotNull(first);
101 assert.strictEqual(first.records.length, 0);
102
103 await NodeFSP.appendFile(path, codexUsageLine(9, 5));
104 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
105 assert.isNotNull(second);
106 assert.isTrue(second.resumed);
107 assert.strictEqual(second.records.length, 1);
108 assert.strictEqual(second.records[0]?.model, "gpt-5.2-codex");
109 assert.strictEqual(second.records[0]?.speed, "ultrafast");
110 assert.strictEqual(second.records[0]?.sessionId, "codex-session-1");
111 });
112
113 it("suppresses a Codex duplicate usage event that straddles the boundary", async () => {
114 const path = NodePath.join(dir, "rollout.jsonl");
115 await NodeFSP.writeFile(
116 path,
117 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexUsageLine(9, 5),
118 );
119 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
120 assert.isNotNull(first);
121 assert.strictEqual(first.records.length, 1);
122
123 // Codex re-emits an unchanged token_count on stream boundaries; the copy
124 // lands after the resume point and must still be dropped.
125 await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
126 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
127 assert.isNotNull(second);
128 assert.isTrue(second.resumed);
129 assert.deepStrictEqual(
130 second.records.map((record) => record.totals.outputTokens),
131 [21],
132 );
133 });
134
135 it("defers an unterminated trailing line to tailRecords, then consumes it once terminated", async () => {
136 const path = NodePath.join(dir, "claude.jsonl");
137 const unterminated = claudeLine(2, 7).trimEnd();
138 await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
139 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
140 assert.isNotNull(first);
141 assert.strictEqual(first.records.length, 1);
142 assert.strictEqual(first.tailRecords.length, 1);
143 assert.strictEqual(first.tailRecords[0]?.totals.outputTokens, 7);
144
145 await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
146 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
147 assert.isNotNull(second);
148 assert.isTrue(second.resumed);
149 assert.deepStrictEqual(
150 second.records.map((record) => record.totals.outputTokens),
151 [7, 11],
152 );
153 assert.strictEqual(second.tailRecords.length, 0);
154 });
155
156 it("re-parses from the start when the guard bytes no longer match", async () => {
157 const path = NodePath.join(dir, "claude.jsonl");
158 await NodeFSP.writeFile(path, claudeLine(1, 5));
159 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
160 assert.isNotNull(first);
161
162 await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
163 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
164 assert.isNotNull(second);
165 assert.isFalse(second.resumed);
166 assert.deepStrictEqual(
167 second.records.map((record) => record.totals.outputTokens),
168 [13, 17],
169 );
170 });
171
172 it("re-parses from the start when the file shrank below the resume point", async () => {
173 const path = NodePath.join(dir, "claude.jsonl");
174 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
175 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
176 assert.isNotNull(first);
177
178 await NodeFSP.writeFile(path, claudeLine(3, 11));
179 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
180 assert.isNotNull(second);
181 assert.isFalse(second.resumed);
182 assert.deepStrictEqual(
183 second.records.map((record) => record.totals.outputTokens),
184 [11],
185 );
186 });
187
188 it("parses a line larger than one stream chunk", async () => {
189 const path = NodePath.join(dir, "claude.jsonl");
190 const bigLine = `${JSON.stringify({
191 type: "assistant",
192 timestamp: "2026-08-01T10:00:00Z",
193 requestId: "req_big",
194 sessionId: "session-1",
195 padding: "x".repeat(512 * 1024),
196 message: {
197 id: "msg_big",
198 model: "claude-fable-5",
199 usage: { input_tokens: 10, output_tokens: 42 },
200 },
201 })}\n`;
202 await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
203
204 const parsed = await readTranscriptRecords(path, TEST_FORMATS.claude);
205 assert.isNotNull(parsed);
206 assert.deepStrictEqual(
207 parsed.records.map((record) => record.totals.outputTokens),
208 [42, 7],
209 );
210 });
211
212 it("keeps a CRLF Codex reducer line whose marker straddles a stream chunk", async () => {
213 const path = NodePath.join(dir, "rollout.jsonl");
214 const crlf = (line: string) => line.replace("\n", "\r\n");
215 const modelLine = crlf(codexModelLine("gpt-5.2-codex"));
216 const head = crlf(codexMetaLine());
217 const fillerBytes =
218 256 * 1024 - Buffer.byteLength(head) - modelLine.indexOf("turn_context") - 4;
219 const fillerEnvelope = crlf(`${JSON.stringify({ type: "response_item", output: "" })}\n`);
220 const padding = "é".repeat((fillerBytes - Buffer.byteLength(fillerEnvelope)) / 2);
221 const filler = crlf(`${JSON.stringify({ type: "response_item", output: padding })}\n`);
222 const content = head + filler + modelLine + crlf(codexUsageLine(40, 2));
223 await NodeFSP.writeFile(path, content);
224
225 const result = await readTranscriptRecords(path, TEST_FORMATS.codex);
226 assert.isNotNull(result);
227 assert.strictEqual(result.records.length, 1);
228 assert.strictEqual(result.records[0]?.model, "gpt-5.2-codex");
229 assert.strictEqual(result.records[0]?.sessionId, "codex-session-1");
230 assert.strictEqual(result.position.resumeOffset, Buffer.byteLength(content));
231 });
232
233 it("returns null for an unreadable file", async () => {
234 assert.isNull(
235 await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), TEST_FORMATS.claude),
236 );
237 });
238});
239
240describe("transcriptLineGate", () => {
241 const gates = {
242 one: transcriptLineGate(['"usage"']),
243 several: transcriptLineGate(['"token_count"', '"session_meta"', '"a.b(c)"']),
244 };
245 const markers = { one: ['"usage"'], several: ['"token_count"', '"session_meta"', '"a.b(c)"'] };
246
247 it("passes only lines containing one of its markers", () => {
248 for (const kind of ["one", "several"] as const) {
249 for (const marker of markers[kind]) {
250 assert.isTrue(gates[kind](Buffer.from(`{"payload":{${marker}:1}}`)));
251 assert.isFalse(gates[kind](Buffer.from(`{"text":"see ${marker.slice(1, -1)} here"}`)));
252 assert.isFalse(gates[kind](Buffer.from(`{${marker.replace(/[._]|usage/, "x")}:1}`)));
253 }
254 assert.isFalse(gates[kind](Buffer.alloc(0)));
255 }
256 });
257
258 it("matches markers beside multi-byte and malformed UTF-8", () => {
259 const invalid = Buffer.from([0xff, 0xc3]);
260 for (const kind of ["one", "several"] as const) {
261 for (const marker of markers[kind]) {
262 assert.isTrue(gates[kind](Buffer.from(`{"text":"日本語 é",${marker}:1}`)));
263 assert.isTrue(gates[kind](Buffer.concat([invalid, Buffer.from(marker), invalid])));
264 assert.isFalse(gates[kind](Buffer.from(`{"text":"日本語 é ${marker.slice(1, -1)}"}`)));
265 }
266 }
267 });
268});