The best way to control Claude Code, Codex and more from any computer or phone

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