Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Raw filesystem access for transcript scanning.
4 *
5 * Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
6 * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
7 * across ~1,500 files, and buffer-level streaming is roughly an order of
8 * magnitude cheaper than materialising each file. The equivalent Effect stream
9 * pipeline is idiomatic but not fast enough to sit behind a page load.
10 *
11 * Transcripts are append-only, so a parse also reports the byte position it
12 * stopped at. A later scan of the same file resumes from that position and
13 * parses only the appended bytes, which is what keeps a warm scan cheap while a
14 * session is actively writing a multi-hundred-megabyte rollout.
15 *
16 * @module usageTranscriptReader
17 */
18import * as NodeFSP from "node:fs/promises";
19import * as NodePath from "node:path";
20import type * as NodeFS from "node:fs";
21
22import type { UsageProviderKind } from "@t3tools/contracts";
23
24import {
25 initialCodexScanState,
26 mightCarryUsage,
27 parseClaudeLine,
28 parseCodexLine,
29 parseDevinCanonicalLogLine,
30 parseGrokLine,
31 type CodexScanState,
32 type UsageRecord,
33} from "./usageTranscripts.ts";
34
35export interface TranscriptFile {
36 readonly path: string;
37 readonly size: number;
38 readonly mtimeMs: number;
39}
40
41/**
42 * Where a parse stopped, with enough state to continue from there.
43 *
44 * The guard hash fingerprints the bytes immediately before `resumeOffset`. A
45 * resume only proceeds when those bytes still match: transcripts are
46 * append-only by design, but a rotated or rewritten file silently mis-parsed
47 * from the middle would corrupt usage totals. The window is a cheap tripwire
48 * for those realistic failure shapes, all of which disturb the file's tail at
49 * that exact offset; it deliberately does not hash the whole prefix, which
50 * would cost the full re-read the resume exists to avoid.
51 */
52export interface TranscriptParsePosition {
53 /** Byte offset just past the last newline-terminated line consumed. */
54 readonly resumeOffset: number;
55 /** Length of the fingerprinted window ending at `resumeOffset`. */
56 readonly guardLength: number;
57 /** FNV-1a hash of that window. */
58 readonly guardHash: number;
59 /** Codex reducer state as of `resumeOffset`; `null` for stateless providers. */
60 readonly codexState: CodexScanState | null;
61}
62
63export interface TranscriptParseResult {
64 /** Records from newline-terminated lines at or after the parse start. */
65 readonly records: readonly UsageRecord[];
66 /**
67 * Records from a trailing segment the writer has not newline-terminated yet.
68 * Kept out of `records` because `position` deliberately excludes that
69 * segment: the next scan re-reads it once the writer finishes the line.
70 */
71 readonly tailRecords: readonly UsageRecord[];
72 readonly position: TranscriptParsePosition;
73 /** Whether the parse continued from `resumeFrom` rather than byte 0. */
74 readonly resumed: boolean;
75}
76
77/** 64 bytes of JSONL tail is ample to distinguish a replaced file. */
78export const GUARD_LENGTH = 64;
79const NEWLINE = 0x0a;
80const CARRIAGE_RETURN = 0x0d;
81
82function fnv1a(buffer: Buffer): number {
83 let hash = 0x811c9dc5;
84 for (let index = 0; index < buffer.length; index += 1) {
85 hash ^= buffer[index]!;
86 hash = Math.imul(hash, 0x01000193);
87 }
88 return hash >>> 0;
89}
90
91/**
92 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
93 *
94 * Errors on individual entries are swallowed: session files rotate and get
95 * removed while the walk is in flight, and a partial listing is far better than
96 * failing the page.
97 *
98 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
99 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
100 * never carry usage, so the basename filter keeps a cold scan off those files.
101 */
102export async function listTranscriptFiles(
103 root: string,
104 sinceMs: number,
105 options?: { readonly fileName?: string },
106): Promise<readonly TranscriptFile[]> {
107 const found: TranscriptFile[] = [];
108 const fileName = options?.fileName;
109
110 const walk = async (dir: string): Promise<void> => {
111 let entries;
112 try {
113 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
114 } catch {
115 return;
116 }
117 for (const entry of entries) {
118 const child = NodePath.join(dir, entry.name);
119 if (entry.isDirectory()) {
120 await walk(child);
121 continue;
122 }
123 if (fileName !== undefined) {
124 if (entry.name !== fileName) continue;
125 } else if (!entry.name.endsWith(".jsonl")) {
126 continue;
127 }
128 try {
129 const stats = await NodeFSP.stat(child);
130 if (stats.mtimeMs >= sinceMs) {
131 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
132 }
133 } catch {
134 // Vanished between readdir and stat.
135 }
136 }
137 };
138
139 await walk(root);
140 return found;
141}
142
143/**
144 * Lists T3 provider event logs (`events.<thread>.log`) and their rotated
145 * siblings. Event logs are intentionally kept flat in one provider directory,
146 * unlike CLI transcripts which use nested session folders.
147 */
148export async function listProviderEventLogFiles(
149 root: string,
150 baseName: string,
151 sinceMs = Number.NEGATIVE_INFINITY,
152): Promise<readonly TranscriptFile[]> {
153 const found: TranscriptFile[] = [];
154 let entries: ReadonlyArray<NodeFS.Dirent>;
155 try {
156 entries = await NodeFSP.readdir(root, { withFileTypes: true });
157 } catch {
158 return found;
159 }
160
161 const prefix = `${baseName}.`;
162 for (const entry of entries) {
163 if (
164 !entry.isFile() ||
165 !entry.name.startsWith(prefix) ||
166 !/\.log(?:\.\d+)?$/u.test(entry.name)
167 ) {
168 continue;
169 }
170 const child = NodePath.join(root, entry.name);
171 try {
172 const stats = await NodeFSP.stat(child);
173 if (stats.mtimeMs >= sinceMs) {
174 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
175 }
176 } catch {
177 // Rotated logs may disappear between readdir and stat.
178 }
179 }
180
181 return found;
182}
183
184/**
185 * Filesystem identity of a directory, as `device:inode`.
186 *
187 * Used to tell "two servers reading the same transcript directory" apart from
188 * "two machines whose hostname and home path happen to match". Returns an empty
189 * string when the directory cannot be stat'd.
190 */
191export async function readDirectoryVolumeId(path: string): Promise<string> {
192 try {
193 const stats = await NodeFSP.stat(path);
194 return `${stats.dev}:${stats.ino}`;
195 } catch {
196 return "";
197 }
198}
199
200async function guardMatches(
201 handle: NodeFSP.FileHandle,
202 position: TranscriptParsePosition,
203): Promise<boolean> {
204 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
205 try {
206 const window = Buffer.alloc(position.guardLength);
207 const { bytesRead } = await handle.read(
208 window,
209 0,
210 position.guardLength,
211 position.resumeOffset - position.guardLength,
212 );
213 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
214 } catch {
215 return false;
216 }
217}
218
219/**
220 * Streams one transcript and returns the usage records it contains, or `null`
221 * when the file could not be read.
222 *
223 * The distinction matters to the caller's cache: a genuinely empty transcript
224 * is a stable fact worth memoising, while a transient read failure memoised
225 * under the same `(size, mtime)` key would silently drop that file's usage
226 * until the file next changes.
227 *
228 * With `resumeFrom`, parsing continues from that position when its guard bytes
229 * still match, so only appended lines are read; otherwise the whole file is
230 * re-parsed from the start and `resumed` reports `false`.
231 *
232 * Codex carries the active model on `turn_context` lines that hold no usage of
233 * their own, so those still have to pass through the reducer to keep model
234 * attribution correct.
235 */
236export async function readTranscriptRecords(
237 filePath: string,
238 provider: UsageProviderKind,
239 resumeFrom?: TranscriptParsePosition,
240): Promise<TranscriptParseResult | null> {
241 let handle: NodeFSP.FileHandle;
242 try {
243 handle = await NodeFSP.open(filePath, "r");
244 } catch {
245 return null;
246 }
247
248 try {
249 let codexState = initialCodexScanState();
250 let resumed = false;
251 let start = 0;
252 if (
253 resumeFrom !== undefined &&
254 resumeFrom.resumeOffset > 0 &&
255 (provider !== "codex" || resumeFrom.codexState !== null) &&
256 (await guardMatches(handle, resumeFrom))
257 ) {
258 if (resumeFrom.codexState !== null) codexState = { ...resumeFrom.codexState };
259 start = resumeFrom.resumeOffset;
260 resumed = true;
261 }
262
263 const parseLine = (line: string, state: CodexScanState, out: UsageRecord[]): void => {
264 if (provider === "devin") {
265 // Canonical event logs also contain native ACP and orchestration
266 // records. Avoid parsing those as JSON unless this line could be one
267 // of Devin's normalized usage events.
268 if (!line.includes('"thread.token-usage.updated"') || !line.includes('"devin"')) {
269 return;
270 }
271 const record = parseDevinCanonicalLogLine(line);
272 if (record !== null) out.push(record);
273 return;
274 }
275
276 if (provider === "codex") {
277 if (
278 !mightCarryUsage(line, provider) &&
279 !line.includes('"turn_context"') &&
280 !line.includes('"session_meta"')
281 ) {
282 return;
283 }
284 const record = parseCodexLine(line, state);
285 if (record !== null) out.push(record);
286 return;
287 }
288 if (!mightCarryUsage(line, provider)) return;
289 if (provider === "grok") {
290 for (const grokRecord of parseGrokLine(line)) out.push(grokRecord);
291 return;
292 }
293 const record = parseClaudeLine(line);
294 if (record !== null) out.push(record);
295 };
296
297 const toLineString = (lineBuffer: Buffer): string => {
298 const content =
299 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
300 ? lineBuffer.subarray(0, -1)
301 : lineBuffer;
302 return content.toString("utf8");
303 };
304
305 const records: UsageRecord[] = [];
306 // Buffer-level line splitting rather than `readline`, because resuming
307 // needs byte-exact offsets and decoded strings cannot provide them.
308 // Newline-free chunks are collected rather than concatenated as they
309 // arrive, so a single huge line costs one copy instead of one per chunk.
310 let resumeOffset = start;
311 let pendingChunks: Buffer[] = [];
312 const stream = handle.createReadStream({
313 start,
314 autoClose: false,
315 }) as AsyncIterable<Buffer>;
316 for await (const chunk of stream) {
317 if (!chunk.includes(NEWLINE)) {
318 pendingChunks.push(chunk);
319 continue;
320 }
321 const buffer: Buffer =
322 pendingChunks.length === 0 ? chunk : Buffer.concat([...pendingChunks, chunk]);
323 pendingChunks = [];
324 let lineStart = 0;
325 for (;;) {
326 const newlineIndex = buffer.indexOf(NEWLINE, lineStart);
327 if (newlineIndex === -1) break;
328 parseLine(toLineString(buffer.subarray(lineStart, newlineIndex)), codexState, records);
329 lineStart = newlineIndex + 1;
330 }
331 resumeOffset += lineStart;
332 if (lineStart < buffer.length) pendingChunks.push(buffer.subarray(lineStart));
333 }
334
335 // A trailing segment without its newline is parsed for this result but not
336 // consumed: a writer may still be appending to it, and counting a half
337 // record now and its full form later would double count.
338 const tailRecords: UsageRecord[] = [];
339 if (pendingChunks.length > 0) {
340 const pending = pendingChunks.length === 1 ? pendingChunks[0]! : Buffer.concat(pendingChunks);
341 if (pending.length > 0) parseLine(toLineString(pending), { ...codexState }, tailRecords);
342 }
343
344 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
345 let guardHash = 0;
346 if (guardLength > 0) {
347 const window = Buffer.alloc(guardLength);
348 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
349 guardHash = fnv1a(window);
350 }
351
352 return {
353 records,
354 tailRecords,
355 position: {
356 resumeOffset,
357 guardLength,
358 guardHash,
359 codexState: provider === "codex" ? codexState : null,
360 },
361 resumed,
362 };
363 } catch {
364 return null;
365 } finally {
366 await handle.close().catch(() => undefined);
367 }
368}