Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageTranscriptReader.test.ts

663 lines26.8 KB

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 NodeChildProcess from "node:child_process";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeZlib from "node:zlib";
9​
10import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
11import { totalTokens, type TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as Schema from "effect/Schema";
14​
15import { TEST_FORMATS } from "./usageTestFormats.ts";
16import {
17 listTranscriptFiles,
18 physicalSourceIdOf,
19 readPhysicalSourceId,
20 readTranscriptRecords,
21 transcriptLineGate,
22} from "./usageTranscriptReader.ts";
23​
24let dir: string;
25​
26beforeEach(async () => {
27 dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-reader-test-"));
28});
29​
30afterEach(async () => {
31 await NodeFSP.rm(dir, { recursive: true, force: true });
32});
33​
34function claudeLine(id: number, outputTokens: number): string {
35 return `${JSON.stringify({
36 type: "assistant",
37 timestamp: "2026-08-01T10:00:00Z",
38 requestId: `req_${id}`,
39 sessionId: "session-1",
40 message: {
41 id: `msg_${id}`,
42 model: "claude-fable-5",
43 usage: { input_tokens: 10, output_tokens: outputTokens },
44 },
45 })}\n`;
47​
48function codexMetaLine(): string {
49 return `${JSON.stringify({
50 type: "session_meta",
51 timestamp: "2026-08-01T10:00:00Z",
52 payload: { type: "session_meta", id: "codex-session-1" },
53 })}\n`;
55​
56function codexModelLine(model: string): string {
57 return `${JSON.stringify({
58 type: "turn_context",
59 timestamp: "2026-08-01T10:00:01Z",
60 payload: { type: "turn_context", model },
61 })}\n`;
63​
64function codexTierLine(serviceTier: string): string {
65 return `${JSON.stringify({
66 type: "event_msg",
67 timestamp: "2026-08-01T10:00:01Z",
68 payload: { type: "thread_settings_applied", thread_settings: { service_tier: serviceTier } },
69 })}\n`;
71​
72function codexUsageLine(outputTokens: number, secondsOffset: number): string {
73 return `${JSON.stringify({
74 type: "event_msg",
75 timestamp: `2026-08-01T10:00:${String(secondsOffset).padStart(2, "0")}Z`,
76 payload: {
77 type: "token_count",
78 info: { last_token_usage: { input_tokens: 100, output_tokens: outputTokens } },
79 },
80 })}\n`;
82​
83describe("compressed transcripts", () => {
84 it("discovers nested plain and zstd JSONL files within the requested window", async () => {
85 const nested = NodePath.join(dir, "nested");
86 await NodeFSP.mkdir(nested);
87 const plain = NodePath.join(dir, "active.jsonl");
88 const compressed = NodePath.join(nested, "archived.jsonl.zst");
89 const old = NodePath.join(nested, "old.jsonl.zst");
90 await NodeFSP.writeFile(plain, claudeLine(1, 5));
91 await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(claudeLine(2, 7)));
92 await NodeFSP.writeFile(old, NodeZlib.zstdCompressSync(claudeLine(3, 11)));
93 await NodeFSP.writeFile(NodePath.join(nested, "unrelated.zst"), "ignored");
94 await NodeFSP.writeFile(NodePath.join(nested, "partial.jsonl.zst.tmp"), "ignored");
95 await NodeFSP.utimes(old, 1, 1);
96​
97 const listed = await listTranscriptFiles(dir, Date.parse("2026-01-01T00:00:00Z"));
98 assert.deepStrictEqual(
99 listed.files.map((file) => file.path).sort(),
100 [plain, compressed].sort(),
101 );
102 assert.strictEqual(listed.failedPaths, 0);
103 assert.isAbove(listed.files.find((file) => file.path === compressed)?.size ?? 0, 0);
104 });
105​
106 it.skipIf(HostProcess.Platform.defaultValue() === "win32")(
107 "skips transcript-named entries that are not regular files",
108 async () => {
109 const ordinary = NodePath.join(dir, "ordinary.jsonl");
110 await NodeFSP.writeFile(ordinary, claudeLine(1, 5));
111 // Opening a FIFO without a writer blocks forever, so a queued one hangs the scan.
112 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "session.jsonl")]);
113​
114 const listed = await listTranscriptFiles(dir, 0);
115 assert.deepStrictEqual(
116 listed.files.map((file) => file.path),
117 [ordinary],
118 );
119 },
120 );
121​
122 it("lists files in directory order when more directories wait than it reads at once", async () => {
123 for (let index = 0; index < 40; index += 1) {
124 const nested = NodePath.join(dir, `project-${index}`, "sessions");
125 await NodeFSP.mkdir(nested, { recursive: true });
126 await NodeFSP.writeFile(NodePath.join(nested, "a.jsonl"), "");
127 await NodeFSP.writeFile(NodePath.join(nested, "..", "b.jsonl"), "");
128 }
129 // Usage that two transcripts share counts in the first one listed, so the order is part of the result.
130 const inOrder = async (folder: string): Promise<string[]> => {
131 const paths: string[] = [];
132 for (const entry of await NodeFSP.readdir(folder, { withFileTypes: true })) {
133 const child = NodePath.join(folder, entry.name);
134 if (entry.isDirectory()) paths.push(...(await inOrder(child)));
135 else paths.push(child);
136 }
137 return paths;
138 };
139 const listed = await listTranscriptFiles(dir, 0);
140 assert.deepStrictEqual(
141 listed.files.map((file) => file.path),
142 await inOrder(dir),
143 );
144 });
145​
146 it.each([
147 { parser: "native", streamingThresholdBytes: undefined },
148 { parser: "projected", streamingThresholdBytes: 1024 },
149 ])(
150 "matches plain Codex records and unfinished tails through long lines ($parser)",
151 async ({ streamingThresholdBytes }) => {
152 const plain = NodePath.join(dir, "rollout.jsonl");
153 const compressed = plain + ".zst";
154 const large = codexUsageLine(9, 5).replace(
155 '"payload":',
156 '"padding":' + JSON.stringify("日本語 é".repeat(128 * 1024)) + ',"payload":',
157 );
158 const content =
159 codexMetaLine() +
160 codexModelLine("gpt-6-astra") +
161 codexTierLine("ultrafast") +
162 large +
163 codexUsageLine(13, 6).replace('"output_tokens":13', '"output_tokens":"invalid"') +
164 codexUsageLine(21, 8).trimEnd();
165 await NodeFSP.writeFile(plain, content);
166 await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(content));
167​
168 const options =
169 streamingThresholdBytes === undefined ? undefined : { streamingThresholdBytes };
170 const expected = await readTranscriptRecords(plain, TEST_FORMATS.codex, undefined, options);
171 const actual = await readTranscriptRecords(
172 compressed,
173 TEST_FORMATS.codex,
174 undefined,
175 options,
176 );
177 assert.isNotNull(expected);
178 assert.isNotNull(actual);
179 assert.strictEqual(expected.records.length, 1);
180 assert.strictEqual(expected.tailRecords.length, 1);
181 assert.deepStrictEqual(actual.records, expected.records);
182 assert.deepStrictEqual(actual.tailRecords, expected.tailRecords);
183 assert.strictEqual(expected.malformedRecords.length, 1);
184 assert.deepStrictEqual(actual.malformedRecords, expected.malformedRecords);
185 assert.strictEqual(actual.records[0]?.speed, "ultrafast");
186 assert.isFalse(actual.resumed);
187 assert.strictEqual(actual.position.resumeOffset, 0);
188 },
189 );
190​
191 it("ignores a prior resume position and rereads compressed rollouts from their start", async () => {
192 const plain = NodePath.join(dir, "rollout.jsonl");
193 const content = codexMetaLine() + codexModelLine("gpt-6-astra") + codexUsageLine(9, 5);
194 await NodeFSP.writeFile(plain, content);
195 const first = await readTranscriptRecords(plain, TEST_FORMATS.codex);
196 assert.isNotNull(first);
197​
198 const compressed = plain + ".zst";
199 await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(content + codexUsageLine(21, 8)));
200 const actual = await readTranscriptRecords(compressed, TEST_FORMATS.codex, first.position);
201 assert.isNotNull(actual);
202 assert.isFalse(actual.resumed);
203 assert.deepStrictEqual(
204 actual.records.map((record) => record.totals.outputTokens),
205 [9, 21],
206 );
207 const repeated = await readTranscriptRecords(compressed, TEST_FORMATS.codex, actual.position);
208 assert.isNotNull(repeated);
209 assert.isFalse(repeated.resumed);
210 assert.deepStrictEqual(repeated.records, actual.records);
211 });
212​
213 it("returns null for zstd decoder errors rather than caching an empty parse", async () => {
214 const path = NodePath.join(dir, "corrupt.jsonl.zst");
215 await NodeFSP.writeFile(path, "not a zstd frame");
216 assert.isNull(await readTranscriptRecords(path, TEST_FORMATS.claude));
217 });
218});
219​
220describe("readTranscriptRecords resume", () => {
221 it.each([
222 { mode: "buffered", streamingThresholdBytes: Infinity },
223 { mode: "streaming", streamingThresholdBytes: 0 },
224 ])("counts malformed tails once across $mode reads and resume", async (options) => {
225 const format: TranscriptUsageFormat<{ errors: number }> = {
226 ...TEST_FORMATS.claude,
227 selectFields: { ...TEST_FORMATS.claude.selectFields, usage: true },
228 state: {
229 initial: () => ({ errors: 0 }),
230 schema: Schema.Struct({ errors: Schema.Number }),
231 },
232 parseLine(line, state) {
233 return this.parseProjected(JSON.parse(line), state);
234 },
235 parseProjected(value, state) {
236 if (
237 typeof value === "object" &&
238 value !== null &&
239 "usage" in value &&
240 value.usage === "malformed"
241 ) {
242 state.errors += 1;
243 return [];
244 }
245 return TEST_FORMATS.claude.parseProjected(value, undefined);
246 },
247 readMalformedRecords: (state: { errors: number }) => Array(state.errors).fill(0),
248 };
249 const path = NodePath.join(dir, "diagnostics.jsonl");
250 const malformed = JSON.stringify({ usage: "malformed" });
251 // Completed lines enter the projected parser only when they cross a stream chunk.
252 const committed = `${JSON.stringify({ usage: "malformed", padding: "x".repeat(256 * 1024) })}\n${claudeLine(1, 5)}`;
253 await NodeFSP.writeFile(path, committed + malformed);
254​
255 const first = await readTranscriptRecords(path, format, undefined, options);
256 assert.isNotNull(first);
257 assert.deepStrictEqual(
258 first.records.map((record) => record.totals.outputTokens),
259 [5],
260 );
261 assert.deepStrictEqual(first.tailRecords, []);
262 assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed));
263 assert.deepStrictEqual(first.position.state, { errors: 1 });
264 assert.strictEqual(first.malformedRecords.length, 2);
265​
266 const savedPosition = JSON.parse(JSON.stringify(first.position));
267 await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`);
268 const resumed = await readTranscriptRecords(path, format, savedPosition, options);
269 assert.isNotNull(resumed);
270 assert.isTrue(resumed.resumed);
271 assert.deepStrictEqual(
272 resumed.records.map((record) => record.totals.outputTokens),
273 [7],
274 );
275 assert.deepStrictEqual(resumed.position.state, { errors: 3 });
276 assert.strictEqual(resumed.malformedRecords.length, 3);
277​
278 const full = await readTranscriptRecords(path, format, undefined, options);
279 assert.isNotNull(full);
280 assert.deepStrictEqual([...first.records, ...resumed.records], full.records);
281 assert.deepStrictEqual(resumed.tailRecords, full.tailRecords);
282 assert.deepStrictEqual(resumed.position, full.position);
283 assert.deepStrictEqual(resumed.malformedRecords, full.malformedRecords);
284 });
285​
286 it("parses only appended lines when resuming a grown file", async () => {
287 const path = NodePath.join(dir, "claude.jsonl");
288 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
289 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
290 assert.isNotNull(first);
291 assert.strictEqual(first.records.length, 2);
292 assert.isFalse(first.resumed);
293 assert.deepStrictEqual(first.malformedRecords, []);
294​
295 await NodeFSP.appendFile(path, claudeLine(3, 11));
296 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
297 assert.isNotNull(second);
298 assert.isTrue(second.resumed);
299 assert.strictEqual(second.records.length, 1);
300 assert.strictEqual(second.records[0]?.totals.outputTokens, 11);
301​
302 const full = await readTranscriptRecords(path, TEST_FORMATS.claude);
303 assert.isNotNull(full);
304 assert.deepStrictEqual([...first.records, ...second.records], [...full.records]);
305 });
306​
307 it("carries the Codex reducer state across the resume boundary", async () => {
308 const path = NodePath.join(dir, "rollout.jsonl");
309 await NodeFSP.writeFile(
310 path,
311 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"),
312 );
313 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
314 assert.isNotNull(first);
315 assert.strictEqual(first.records.length, 0);
316​
317 await NodeFSP.appendFile(path, codexUsageLine(9, 5));
318 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
319 assert.isNotNull(second);
320 assert.isTrue(second.resumed);
321 assert.strictEqual(second.records.length, 1);
322 assert.strictEqual(second.records[0]?.model, "gpt-5.2-codex");
323 assert.strictEqual(second.records[0]?.speed, "ultrafast");
324 assert.strictEqual(second.records[0]?.sessionId, "codex-session-1");
325 });
326​
327 it("suppresses a Codex duplicate usage event that straddles the boundary", async () => {
328 const path = NodePath.join(dir, "rollout.jsonl");
329 await NodeFSP.writeFile(
330 path,
331 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexUsageLine(9, 5),
332 );
333 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
334 assert.isNotNull(first);
335 assert.strictEqual(first.records.length, 1);
336​
337 // Codex duplicates token_count at stream boundaries, including after resume points.
338 await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
339 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
340 assert.isNotNull(second);
341 assert.isTrue(second.resumed);
342 assert.deepStrictEqual(
343 second.records.map((record) => record.totals.outputTokens),
344 [21],
345 );
346 });
347​
348 it("defers an unterminated trailing line to tailRecords, then consumes it once terminated", async () => {
349 const path = NodePath.join(dir, "claude.jsonl");
350 const unterminated = claudeLine(2, 7).trimEnd();
351 await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
352 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
353 assert.isNotNull(first);
354 assert.strictEqual(first.records.length, 1);
355 assert.strictEqual(first.tailRecords.length, 1);
356 assert.strictEqual(first.tailRecords[0]?.totals.outputTokens, 7);
357​
358 await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
359 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
360 assert.isNotNull(second);
361 assert.isTrue(second.resumed);
362 assert.deepStrictEqual(
363 second.records.map((record) => record.totals.outputTokens),
364 [7, 11],
365 );
366 assert.strictEqual(second.tailRecords.length, 0);
367 });
368​
369 it.each([
370 { mode: "buffered", streamingThresholdBytes: Infinity },
371 { mode: "streaming", streamingThresholdBytes: 0 },
372 ])(
373 "resumes an initial Codex carried-total tail without rebilling it ($mode)",
374 async (options) => {
375 const path = NodePath.join(dir, "continuation.jsonl");
376 const usage = (input: number, output: number) => ({
377 input_tokens: input,
378 output_tokens: output,
379 });
380 const event = (last: unknown, cumulative: unknown) =>
381 JSON.stringify({
382 type: "event_msg",
383 timestamp: "2026-08-01T10:00:05Z",
384 payload: {
385 type: "token_count",
386 info: { last_token_usage: last, total_token_usage: cumulative },
387 },
388 });
389 const firstLine = event(usage(100, 20), usage(500, 60));
390 await NodeFSP.writeFile(
391 path,
392 codexMetaLine() + codexModelLine("gpt-6-astra") + codexTierLine("ultrafast") + firstLine,
393 );
394 const first = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options);
395 assert.isNotNull(first);
396 assert.strictEqual(first.records.length, 0);
397 assert.deepStrictEqual(
398 first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]),
399 [[20, "ultrafast"]],
400 );
401 assert.deepStrictEqual(first.malformedRecords, []);
402​
403 await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`);
404 const resumed = await readTranscriptRecords(
405 path,
406 TEST_FORMATS.codex,
407 JSON.parse(JSON.stringify(first.position)),
408 options,
409 );
410 const full = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options);
411 assert.isNotNull(resumed);
412 assert.isNotNull(full);
413 assert.isTrue(resumed.resumed);
414 assert.deepStrictEqual(resumed.records, full.records);
415 assert.deepStrictEqual(
416 resumed.records.map((r) => [r.totals.outputTokens, r.speed]),
417 [
418 [20, "ultrafast"],
419 [2, "ultrafast"],
420 ],
421 );
422 assert.deepStrictEqual(resumed.tailRecords, []);
423 assert.deepStrictEqual(resumed.malformedRecords, []);
424 assert.deepStrictEqual(resumed.position, full.position);
425 },
426 );
427​
428 it.each([
429 { mode: "buffered", streamingThresholdBytes: Infinity },
430 { mode: "streaming", streamingThresholdBytes: 0 },
431 ])(
432 "bills a Codex request whose turn was interrupted before its token_count ($mode)",
433 async (options) => {
434 const path = NodePath.join(dir, "rollout.jsonl");
435 const usage = (input: number, output: number) => ({
436 input_tokens: input,
437 cached_input_tokens: 0,
438 cache_write_input_tokens: 0,
439 output_tokens: output,
440 reasoning_output_tokens: 0,
441 total_tokens: input + output,
442 });
443 const context = (turn: number) => ({
444 type: "turn_context",
445 timestamp: `2026-11-02T10:00:0${turn * 4 - 4}.000Z`,
446 payload: { turn_id: `turn-${turn}`, model: "gpt-6-sol" },
447 });
448 const request = (turn: number, id: number, timestamp: string, last: unknown) => ({
449 type: "token_usage_record",
450 timestamp,
451 payload: { turn_id: `turn-${turn}`, response_id: `resp_${id}`, usage: last },
452 });
453 const tokenCount = (timestamp: string, last: unknown, total: unknown) => ({
454 type: "event_msg",
455 timestamp,
456 payload: {
457 type: "token_count",
458 info: { last_token_usage: last, total_token_usage: total },
459 },
460 });
461 const lines = [
462 {
463 type: "session_meta",
464 timestamp: "2026-11-02T10:00:00.000Z",
465 payload: { id: "aborted-turn-repro", model_provider: "openai" },
466 },
467 context(1),
468 request(1, 1, "2026-11-02T10:00:01.000Z", usage(100, 20)),
469 tokenCount("2026-11-02T10:00:01.001Z", usage(100, 20), usage(100, 20)),
470 // Interrupted after this request finished: no token_count reports it.
471 request(1, 2, "2026-11-02T10:00:02.000Z", usage(150, 10)),
472 {
473 type: "event_msg",
474 timestamp: "2026-11-02T10:00:03.000Z",
475 payload: { type: "turn_aborted", turn_id: "turn-1", reason: "interrupted" },
476 },
477 context(2),
478 request(2, 3, "2026-11-02T10:00:05.000Z", usage(200, 30)),
479 tokenCount("2026-11-02T10:00:05.001Z", usage(200, 30), usage(450, 60)),
480 ];
481 // Lines longer than a read chunk take the projected path when streaming.
482 const padding = "x".repeat(256 * 1024);
483 await NodeFSP.writeFile(
484 path,
485 lines.map((line) => `${JSON.stringify({ padding, ...line })}\n`).join(""),
486 );
487​
488 const result = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options);
489 assert.isNotNull(result);
490 const requests = [...result.records, ...result.tailRecords]
491 .map((record) => totalTokens(record.totals))
492 .toSorted((a, b) => a - b);
493 assert.deepStrictEqual(
494 {
495 billedTokens: requests.reduce((sum, tokens) => sum + tokens, 0),
496 requests,
497 malformedRecords: result.malformedRecords.length,
498 },
499 { billedTokens: 510, requests: [120, 160, 230], malformedRecords: 0 },
500 );
501 },
502 );
503​
504 it("re-parses from the start when the guard bytes no longer match", async () => {
505 const path = NodePath.join(dir, "claude.jsonl");
506 await NodeFSP.writeFile(path, claudeLine(1, 5));
507 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
508 assert.isNotNull(first);
509​
510 await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
511 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
512 assert.isNotNull(second);
513 assert.isFalse(second.resumed);
514 assert.deepStrictEqual(
515 second.records.map((record) => record.totals.outputTokens),
516 [13, 17],
517 );
518 });
519​
520 it("re-parses a grown replacement file even when its guard bytes match", async () => {
521 const path = NodePath.join(dir, "claude.jsonl");
522 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
523 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
524 assert.isNotNull(first);
525​
526 const replacement = NodePath.join(dir, "claude.jsonl.tmp");
527 await NodeFSP.writeFile(replacement, claudeLine(1, 9) + claudeLine(2, 7) + claudeLine(3, 13));
528 await NodeFSP.rename(replacement, path);
529 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
530 assert.isNotNull(second);
531 assert.isFalse(second.resumed);
532 assert.deepStrictEqual(
533 second.records.map((record) => record.totals.outputTokens),
534 [9, 7, 13],
535 );
536 });
537​
538 it("re-parses from the start when the file shrank below the resume point", async () => {
539 const path = NodePath.join(dir, "claude.jsonl");
540 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
541 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
542 assert.isNotNull(first);
543​
544 await NodeFSP.writeFile(path, claudeLine(3, 11));
545 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
546 assert.isNotNull(second);
547 assert.isFalse(second.resumed);
548 assert.deepStrictEqual(
549 second.records.map((record) => record.totals.outputTokens),
550 [11],
551 );
552 });
553​
554 it("parses a line larger than one stream chunk", async () => {
555 const path = NodePath.join(dir, "claude.jsonl");
556 const bigLine = `${JSON.stringify({
557 type: "assistant",
558 timestamp: "2026-08-01T10:00:00Z",
559 requestId: "req_big",
560 sessionId: "session-1",
561 padding: "x".repeat(512 * 1024),
562 message: {
563 id: "msg_big",
564 model: "claude-fable-5",
565 usage: { input_tokens: 10, output_tokens: 42 },
566 },
567 })}\n`;
568 await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
569​
570 const parsed = await readTranscriptRecords(path, TEST_FORMATS.claude);
571 assert.isNotNull(parsed);
572 assert.deepStrictEqual(
573 parsed.records.map((record) => record.totals.outputTokens),
574 [42, 7],
575 );
576 });
577​
578 it("keeps a CRLF Codex reducer line whose marker straddles a stream chunk", async () => {
579 const path = NodePath.join(dir, "rollout.jsonl");
580 const crlf = (line: string) => line.replace("\n", "\r\n");
581 const modelLine = crlf(codexModelLine("gpt-5.2-codex"));
582 const head = crlf(codexMetaLine());
583 const fillerBytes =
584 256 * 1024 - Buffer.byteLength(head) - modelLine.indexOf("turn_context") - 4;
585 const fillerEnvelope = crlf(`${JSON.stringify({ type: "response_item", output: "" })}\n`);
586 const padding = "é".repeat((fillerBytes - Buffer.byteLength(fillerEnvelope)) / 2);
587 const filler = crlf(`${JSON.stringify({ type: "response_item", output: padding })}\n`);
588 const content = head + filler + modelLine + crlf(codexUsageLine(40, 2));
589 await NodeFSP.writeFile(path, content);
590​
591 const result = await readTranscriptRecords(path, TEST_FORMATS.codex);
592 assert.isNotNull(result);
593 assert.strictEqual(result.records.length, 1);
594 assert.strictEqual(result.records[0]?.model, "gpt-5.2-codex");
595 assert.strictEqual(result.records[0]?.sessionId, "codex-session-1");
596 assert.strictEqual(result.position.resumeOffset, Buffer.byteLength(content));
597 });
598});
599​
600describe("transcriptLineGate", () => {
601 const gates = {
602 one: transcriptLineGate(['"usage"']),
603 several: transcriptLineGate(['"token_count"', '"session_meta"', '"a.b(c)"']),
604 };
605 const markers = { one: ['"usage"'], several: ['"token_count"', '"session_meta"', '"a.b(c)"'] };
606​
607 it("matches markers beside multi-byte and malformed UTF-8", () => {
608 const invalid = Buffer.from([0xff, 0xc3]);
609 for (const kind of ["one", "several"] as const) {
610 for (const marker of markers[kind]) {
611 assert.isTrue(gates[kind](Buffer.from(`{"text":"日本語 é",${marker}:1}`)));
612 assert.isTrue(gates[kind](Buffer.concat([invalid, Buffer.from(marker), invalid])));
613 assert.isFalse(gates[kind](Buffer.from(`{"text":"日本語 é ${marker.slice(1, -1)}"}`)));
614 }
615 }
616 });
617});
618​
619describe("readPhysicalSourceId", () => {
620 const scope = "0123456789abcdef0123456789abcdef";
621 const windowsPath = "C:\\Users\\User\\.claude\\projects";
622​
623 // One NTFS directory the Windows server reads natively and the WSL server
624 // through drvfs. The temp dir stands in for the drive's mount point.
625 async function drvfsFixture(extraMounts: (escapedMountPoint: string) => string = () => "") {
626 const mountPoint = NodePath.join(dir, "drive c");
627 await NodeFSP.mkdir(NodePath.join(mountPoint, "Users", "User", ".claude", "projects"), {
628 recursive: true,
629 });
630 const escaped = mountPoint.replaceAll(" ", "\\040");
631 const mountInfoPath = NodePath.join(dir, "mountinfo");
632 await NodeFSP.writeFile(
633 mountInfoPath,
634 [
635 "24 1 8:32 / / rw,relatime shared:1 - ext4 /dev/sdc rw,discard",
636 `81 24 0:61 / ${escaped} rw,noatime shared:2 - 9p C:\\134 rw,dirsync,aname=drvfs;path=C:\\;uid=1000;gid=1000;symlinkroot=/mnt/,mmap,access=client,msize=65536,trans=fd`,
637 extraMounts(escaped),
638 ].join("\n"),
639 );
640 return { mountPoint, mountInfoPath };
641 }
642​
643 it("names a drvfs directory as the Windows server names it, whatever its typed case", async () => {
644 const { mountPoint, mountInfoPath } = await drvfsFixture();
645 const wslId = await readPhysicalSourceId(
646 `${mountPoint}/users/user/.claude/projects`,
647 scope,
648 "linux",
649 mountInfoPath,
650 );
651 assert.strictEqual(wslId, physicalSourceIdOf(scope, windowsPath));
652 });
653​
654 it("gives no identity to native or shadowing Linux mounts, or without a desktop scope", async () => {
655 const { mountPoint, mountInfoPath } = await drvfsFixture(
656 (escaped) => `90 81 8:48 / ${escaped}/Users rw,relatime - ext4 /dev/sdd rw`,
657 );
658 const projects = `${mountPoint}/Users/User/.claude/projects`;
659 assert.isUndefined(await readPhysicalSourceId(projects, scope, "linux", mountInfoPath));
660 assert.isUndefined(await readPhysicalSourceId(dir, scope, "linux", mountInfoPath));
661 assert.isUndefined(await readPhysicalSourceId(projects, undefined, "linux", mountInfoPath));
662 });
663});