-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcodex.test.ts
More file actions
1039 lines (927 loc) · 54.2 KB
/
Copy pathcodex.test.ts
File metadata and controls
1039 lines (927 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { CanonicalEvent } from '@codetime/shared'
import assert from 'node:assert/strict'
import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
// eslint-disable-next-line test/no-import-node-test -- This repo uses node:test as the runner.
import { test } from 'node:test'
import { createCodexAdapter } from '../src/adapters/codex.ts'
import { buildSessionRollups } from '../src/backfill/rollup.ts'
const adapter = createCodexAdapter()
async function parseFile(fileName: string, records: unknown[]): Promise<CanonicalEvent[]> {
const dir = await mkdtemp(path.join(tmpdir(), 'codex-'))
const file = path.join(dir, fileName)
await writeFile(file, records.map(record => JSON.stringify(record)).join('\n'), 'utf8')
return adapter.parseSessionFile!(file, { _: [] })
}
async function parse(records: unknown[]): Promise<CanonicalEvent[]> {
return parseFile('session.jsonl', records)
}
// Build a UUIDv7 whose embedded 48-bit millisecond timestamp equals the given
// instant, mirroring real Codex rollout ids. Verified against real rollouts:
// the uuid ms always precedes the file's first own event by a few ms.
function uuidv7At(iso: string): string {
const hex = Date.parse(iso).toString(16).padStart(12, '0')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7000-8000-000000000000`
}
// Real Codex rollout filenames stamp LOCAL time in the readable part while event
// timestamps are UTC (e.g. JST names run 9h ahead). Deliberately use a +9h-style
// readable part so any implementation that parses it instead of the UUIDv7 fails.
function rolloutFileName(creationIso: string): string {
return `rollout-2026-05-12T17-02-00-${uuidv7At(creationIso)}.jsonl`
}
function usageEvents(events: CanonicalEvent[]): CanonicalEvent[] {
return events.filter(event => event.type === 'model.usage')
}
function turnCompletedEvents(events: CanonicalEvent[]): CanonicalEvent[] {
return events.filter(event => event.type === 'turn.completed')
}
// Synthetic single-turn CanonicalEvent for rollup tests.
function turnEvent(sessionId: string, turnId: string, ts: string, type: CanonicalEvent['type']): CanonicalEvent {
return {
schemaVersion: '2026-04-29',
ts,
type,
source: 'codex',
agent: 'codex',
sessionId,
turnId,
refs: { sourcePathHash: `sha256:${sessionId}` },
}
}
// ── turn boundary timestamps (idle time must not inflate turn duration) ──
test('user_message closes the previous turn at that turn last event, not the new prompt', async () => {
// Two turns with a 30-minute idle gap between turn 1's last activity and the
// second prompt. The implicit close of turn 1 must carry turn 1's own last
// event ts, so the idle gap is never folded into turn 1's duration.
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'turn_context', payload: { turn_id: 'turn-1' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'first prompt' } },
{ timestamp: '2026-01-02T00:00:05.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'reply one' } },
// 30 minutes of idle, then a new turn_context + second prompt arrive.
{ timestamp: '2026-01-02T00:30:05.000Z', type: 'turn_context', payload: { turn_id: 'turn-2' } },
{ timestamp: '2026-01-02T00:30:05.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'second prompt' } },
{ timestamp: '2026-01-02T00:30:10.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'reply two' } },
])
const turn1Id = events.find(event => event.type === 'prompt.submitted')!.turnId
assert.equal(turn1Id, 'turn-1')
const turn1Completed = turnCompletedEvents(events).filter(event => event.turnId === turn1Id)
assert.equal(turn1Completed.length, 1)
// turn.completed ts equals turn 1's last activity (the agent_message), NOT the
// second prompt's ts.
assert.equal(turn1Completed[0].ts, '2026-01-02T00:00:05.000Z')
const rollup = buildSessionRollups(events)[0]
const turn1Rollup = rollup.turnRollups!.find(turn => turn.turnId === turn1Id)!
// 1s prompt→agent gap, no 30-minute idle leakage.
assert.equal(turn1Rollup.durationMs, 4000)
assert.ok(turn1Rollup.durationMs < 30 * 60 * 1000)
})
test('a turn closed by task_complete is not re-closed by the next user_message', async () => {
// task_complete closes turn-1 explicitly; the following user_message must not
// emit a second turn.completed for the same turnId.
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'turn_context', payload: { turn_id: 'turn-1' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'first prompt' } },
{ timestamp: '2026-01-02T00:00:05.000Z', type: 'event_msg', payload: { type: 'task_complete', turn_id: 'turn-1', duration_ms: 4000 } },
{ timestamp: '2026-01-02T00:10:00.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'second prompt' } },
])
const turn1Id = events.find(event => event.type === 'prompt.submitted')!.turnId
const turn1Completed = turnCompletedEvents(events).filter(event => event.turnId === turn1Id)
assert.equal(turn1Completed.length, 1)
assert.equal(turn1Completed[0].confidence, 'exact') // the task_complete one
})
// ── rollup gap-clamped turn duration ──
test('turn duration sums gap-clamped active intervals', () => {
// Four events in one turn at offsets 0, +1min, +21min (20-min gap), +23min
// (2-min gap). Raw span is 23min but the 20-min gap is clamped to 5min, so the
// active duration is 1 + 5 + 2 = 8 minutes.
const events: CanonicalEvent[] = [
turnEvent('gap-session', 'gap-turn', '2026-01-02T00:00:00.000Z', 'prompt.submitted'),
turnEvent('gap-session', 'gap-turn', '2026-01-02T00:01:00.000Z', 'agent.operation'),
turnEvent('gap-session', 'gap-turn', '2026-01-02T00:21:00.000Z', 'agent.operation'),
turnEvent('gap-session', 'gap-turn', '2026-01-02T00:23:00.000Z', 'turn.completed'),
]
const rollup = buildSessionRollups(events)[0]
const turn = rollup.turnRollups!.find(t => t.turnId === 'gap-turn')!
assert.equal(turn.durationMs, (1 + 5 + 2) * 60 * 1000)
// Real timestamps are preserved even though duration is clamped.
assert.equal(turn.startedAt, '2026-01-02T00:00:00.000Z')
assert.equal(turn.lastEventAt, '2026-01-02T00:23:00.000Z')
})
test('session rollups carry the v3 schemaVersion', () => {
const rollup = buildSessionRollups([
turnEvent('schema-session', 'schema-turn', '2026-01-02T00:00:00.000Z', 'prompt.submitted'),
turnEvent('schema-session', 'schema-turn', '2026-01-02T00:00:01.000Z', 'turn.completed'),
])[0]
assert.equal(rollup.schemaVersion, 3)
})
// Synthetic model.usage event with a metric bag (v3 modelBuckets / TTL split).
function modelUsageEvent(
ts: string,
model: string,
metrics: NonNullable<CanonicalEvent['metrics']>,
): CanonicalEvent {
return {
schemaVersion: '2026-04-29',
ts,
type: 'model.usage',
source: 'claude-code',
agent: 'claude-code',
sessionId: 'bucket-session',
model,
metrics,
refs: { sourcePathHash: 'sha256:bucket-session' },
}
}
test('rollup builds modelBuckets grouped by 15-min bucket and model, with TTL split', () => {
// Two models across two 15-min buckets (00:00 and 00:15), with a repeated
// (bucket, model) pair to exercise summing.
const rollup = buildSessionRollups([
modelUsageEvent('2026-01-02T00:01:00.000Z', 'model-a', {
tokensInput: 10,
tokensCachedInput: 7,
tokensCacheCreationInput: 300,
tokensCacheCreation5mInput: 100,
tokensCacheCreation1hInput: 200,
tokensCacheReadInput: 5,
tokensOutput: 4,
tokensReasoningOutput: 1,
tokensTotal: 21,
}),
modelUsageEvent('2026-01-02T00:14:00.000Z', 'model-a', {
tokensInput: 5,
tokensCacheCreationInput: 50,
tokensCacheCreation5mInput: 50,
tokensCacheCreation1hInput: 0,
tokensOutput: 2,
tokensTotal: 7,
}),
modelUsageEvent('2026-01-02T00:20:00.000Z', 'model-b', {
tokensInput: 8,
tokensOutput: 3,
tokensTotal: 11,
}),
])[0]
// Sorted ts ascending, then model lexicographically.
const buckets = rollup.modelBuckets!
assert.equal(buckets.length, 2)
assert.deepEqual(buckets.map(b => [b.ts, b.model]), [
['2026-01-02T00:00:00.000Z', 'model-a'],
['2026-01-02T00:15:00.000Z', 'model-b'],
])
// First bucket merges both 00:00-window model-a events.
const [a, b] = buckets
assert.equal(a.callCount, 2)
assert.equal(a.inputTokens, 15)
assert.equal(a.cacheCreationInputTokens, 350)
assert.equal(a.cacheCreation5mInputTokens, 150)
assert.equal(a.cacheCreation1hInputTokens, 200)
assert.equal(a.cacheReadInputTokens, 5)
assert.equal(a.outputTokens, 6)
assert.equal(a.reasoningOutputTokens, 1)
assert.equal(a.totalTokens, 28)
// Second bucket is the single model-b event with no TTL split reported.
assert.equal(b.callCount, 1)
assert.equal(b.inputTokens, 8)
assert.equal(b.cacheCreation5mInputTokens, 0)
assert.equal(b.cacheCreation1hInputTokens, 0)
assert.equal(b.totalTokens, 11)
// modelRollups accumulate the TTL split across buckets.
const modelA = rollup.modelRollups.find(m => m.model === 'model-a')!
assert.equal(modelA.cacheCreationInputTokens, 350)
assert.equal(modelA.cacheCreation5mInputTokens, 150)
assert.equal(modelA.cacheCreation1hInputTokens, 200)
const modelB = rollup.modelRollups.find(m => m.model === 'model-b')!
assert.equal(modelB.cacheCreation5mInputTokens, 0)
assert.equal(modelB.cacheCreation1hInputTokens, 0)
})
// ── ccusage parity ──
//
// Token values come from ccusage's Rust codex tests (adapter/codex/mod.rs).
// codetime parses `event_msg → token_count → info.last_token_usage`; ccusage's
// `last_token_usage` cases use the same per-turn values, so token counts line
// up directly. (ccusage's `total_token_usage` accumulate-and-diff and headless
// `turn.completed`/`result` cases are NOT covered — codetime doesn't parse
// those formats; see the report accompanying these tests.)
test('parity: ccusage codex last_token_usage maps straight through', async () => {
// From ccusage adapter/codex/mod.rs loads_directory_groups_… (first row).
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5', last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 50, reasoning_output_tokens: 0, total_tokens: 150 } } } },
])
const usages = usageEvents(events)
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].metrics?.tokensCachedInput, 10)
assert.equal(usages[0].metrics?.tokensOutput, 50)
assert.equal(usages[0].metrics?.tokensReasoningOutput, 0)
assert.equal(usages[0].metrics?.tokensTotal, 150)
})
test('parity: ccusage codex reports_non_cached_input_separately (codetime keeps it inclusive)', async () => {
// From ccusage adapter/codex/mod.rs reports_non_cached_codex_input_separately.
// ccusage's daily report shows inputTokens=10 (100 − 90 cached); codetime
// stores the raw cache-inclusive input (100) plus cached (90) and leaves the
// non-cached split to the dashboard. Both agree on the underlying counts.
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session-1', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5', last_token_usage: { input_tokens: 100, cached_input_tokens: 90, output_tokens: 5, reasoning_output_tokens: 0, total_tokens: 105 } } } },
])
const usages = usageEvents(events)
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100) // ccusage report: non-cached = 100 − 90 = 10
assert.equal(usages[0].metrics?.tokensCachedInput, 90)
assert.equal(usages[0].metrics?.tokensOutput, 5)
assert.equal(usages[0].metrics?.tokensTotal, 105)
})
test('parity: ccusage codex derives per-turn deltas from cumulative total_token_usage', async () => {
// token_count events carrying ONLY info.total_token_usage (no last_token_usage) —
// a real Codex shape. ccusage subtract_codex_raw_usage emits per-turn deltas
// against a running baseline; codetime must not drop them.
const usages = usageEvents(await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 's', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 100, output_tokens: 50, total_tokens: 150 } } } },
{ timestamp: '2026-01-02T00:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 300, output_tokens: 130, total_tokens: 430 } } } },
]))
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].metrics?.tokensOutput, 50)
// second turn's delta: 300-100 input, 130-50 output.
assert.equal(usages[1].metrics?.tokensInput, 200)
assert.equal(usages[1].metrics?.tokensOutput, 80)
})
test('parity: ccusage codex clamps cached_input_tokens to input_tokens', async () => {
// cached must never exceed input, else the server's non-cached (input - cached)
// goes negative. ccusage clamps cached.min(input).
const usages = usageEvents(await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 's', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 150, output_tokens: 50, total_tokens: 150 } } } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].metrics?.tokensCachedInput, 100) // clamped from 150
})
test('parity: ccusage codex dedupes consecutive identical last_token_usage', async () => {
// From ccusage adapter/codex/loader.rs dedupes_matching_codex_usage_events.
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session-a', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5', last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 50, total_tokens: 160 } } } },
{ timestamp: '2026-01-02T00:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5', last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 50, total_tokens: 160 } } } },
])
assert.equal(usageEvents(events).length, 1)
})
test('parity: ccusage codex skips repeated last_token_usage when the cumulative total is unchanged', async () => {
// From ccusage adapter/codex/loader.rs
// skips_repeated_last_usage_when_cumulative_total_is_unchanged (#1435).
const info = {
model: 'gpt-5.5',
last_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 },
total_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 },
}
const events = await parse([
{ timestamp: '2026-07-10T08:00:00.000Z', type: 'session_meta', payload: { id: 'session-a', cwd: '/w', model_provider: 'gpt-5.5' } },
{ timestamp: '2026-07-10T08:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info } },
{ timestamp: '2026-07-10T08:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', info } },
])
assert.equal(usageEvents(events).length, 1)
})
test('parity: ccusage codex skips a stale last_token_usage the cumulative does not back', async () => {
// The cumulative check catches what the consecutive-duplicate dedup cannot:
// a re-emitted snapshot whose last_token_usage differs from the record right
// before it, while total_token_usage stands still. The differing value slips
// past lastTokenUsageKey, so only the cumulative proves no tokens were spent.
const events = await parse([
{ timestamp: '2026-07-10T08:00:00.000Z', type: 'session_meta', payload: { id: 'session-a', cwd: '/w', model_provider: 'gpt-5.5' } },
// Turn 1.
{ timestamp: '2026-07-10T08:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.5', last_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 }, total_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 } } } },
// Turn 2 — cumulative advances.
{ timestamp: '2026-07-10T08:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.5', last_token_usage: { input_tokens: 40, cached_input_tokens: 5, output_tokens: 7, total_tokens: 47 }, total_token_usage: { input_tokens: 140, cached_input_tokens: 25, output_tokens: 17, total_tokens: 157 } } } },
// Turn 1's snapshot re-emitted against turn 2's cumulative: no new tokens.
{ timestamp: '2026-07-10T08:00:03.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.5', last_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 }, total_token_usage: { input_tokens: 140, cached_input_tokens: 25, output_tokens: 17, total_tokens: 157 } } } },
])
const usages = usageEvents(events)
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensTotal, 110)
assert.equal(usages[1].metrics?.tokensTotal, 47)
})
test('parity: ccusage codex counts the first snapshot even when the cumulative is all zeros', async () => {
// ccusage tracks previous_totals as an Option, so the first event of a file is
// never mistaken for a repeat of a zeroed baseline.
const events = await parse([
{ timestamp: '2026-07-10T08:00:00.000Z', type: 'session_meta', payload: { id: 'session-a', cwd: '/w', model_provider: 'gpt-5.5' } },
{ timestamp: '2026-07-10T08:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.5', last_token_usage: { input_tokens: 100, cached_input_tokens: 20, output_tokens: 10, total_tokens: 110 }, total_token_usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, total_tokens: 0 } } } },
])
const usages = usageEvents(events)
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensTotal, 110)
})
// ── headless `codex exec` parity (turn.completed / result / bare data.usage) ──
test('parity: ccusage codex loads_saved_codex_exec_json_usage', async () => {
// ccusage adapter/codex/loader.rs loads_saved_codex_exec_json_usage.
const usages = usageEvents(await parse([
{ type: 'turn.completed', timestamp: '2026-01-02T03:04:05.000Z', model: 'gpt-5.2-codex', usage: { input_tokens: 120, cached_input_tokens: 20, output_tokens: 30, total_tokens: 150 } },
{ type: 'result', data: { timestamp: '2026-01-02T03:05:05.000Z', model_name: 'gpt-5.2-codex', usage: { prompt_tokens: 50, cached_tokens: 5, completion_tokens: 12 } } },
{ type: 'turn.completed', timestamp: '2026-01-02T03:06:05.000Z', model: 'gpt-5.2-codex', usage: { input_tokens: 9, output_tokens: 4, reasoning_output_tokens: 1, total_tokens: 0 } },
]))
assert.equal(usages.length, 3)
assert.equal(usages[0].metrics?.tokensInput, 120)
assert.equal(usages[0].metrics?.tokensCachedInput, 20)
assert.equal(usages[0].metrics?.tokensOutput, 30)
assert.equal(usages[0].metrics?.tokensTotal, 150)
assert.equal(usages[0].model, 'gpt-5.2-codex')
// result line: prompt_tokens/cached_tokens/completion_tokens aliases;
// total recomputed = 50 + 12 + 0 (cache not added).
assert.equal(usages[1].metrics?.tokensInput, 50)
assert.equal(usages[1].metrics?.tokensCachedInput, 5)
assert.equal(usages[1].metrics?.tokensOutput, 12)
assert.equal(usages[1].metrics?.tokensTotal, 62)
assert.equal(usages[1].model, 'gpt-5.2-codex') // from data.model_name
// total_tokens=0 is ignored; recomputed = 9 + 4 + 1.
assert.equal(usages[2].metrics?.tokensInput, 9)
// ccusage's raw output_tokens=4 excludes reasoning; codetime folds reasoning
// into billable tokensOutput → 4 + 1 = 5. tokensReasoningOutput keeps the raw 1.
assert.equal(usages[2].metrics?.tokensOutput, 5)
assert.equal(usages[2].metrics?.tokensReasoningOutput, 1)
assert.equal(usages[2].metrics?.tokensTotal, 14)
})
test('parity: ccusage codex headless tolerates non-string model/timestamp', async () => {
// ccusage adapter/codex/loader.rs loads_headless_usage_with_unexpected_noncritical_field_types.
const usages = usageEvents(await parse([
{ type: 'turn.completed', timestamp: false, model: { name: 'unexpected' }, usage: { input_tokens: 120, cached_input_tokens: 20, output_tokens: 30, total_tokens: 150 } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].model, 'gpt-5') // object model ignored → fallback
assert.equal(usages[0].metrics?.tokensInput, 120)
assert.equal(usages[0].metrics?.tokensCachedInput, 20)
assert.equal(usages[0].metrics?.tokensOutput, 30)
assert.equal(usages[0].metrics?.tokensTotal, 150)
})
test('parity: ccusage codex headless ignores unrelated content text', async () => {
// ccusage adapter/codex/loader.rs loads_headless_usage_with_token_count_text_content.
const usages = usageEvents(await parse([
{ type: 'turn.completed', timestamp: '2026-01-02T03:04:05.000Z', model: 'gpt-5.2-codex', content: 'debug token_count payload text', usage: { input_tokens: 120, cached_input_tokens: 20, output_tokens: 30, total_tokens: 150 } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].model, 'gpt-5.2-codex')
assert.equal(usages[0].metrics?.tokensInput, 120)
assert.equal(usages[0].metrics?.tokensTotal, 150)
})
test('parity: ccusage codex uses nested model_name for standalone exec usage', async () => {
// ccusage adapter/codex/loader.rs uses_nested_model_name_for_standalone_exec_usage.
const usages = usageEvents(await parse([
{ data: { timestamp: '2026-03-01T00:00:00.000Z', model_name: 'gpt-5.2-codex', usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 } } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].model, 'gpt-5.2-codex')
assert.equal(usages[0].metrics?.tokensInput, 10)
assert.equal(usages[0].metrics?.tokensOutput, 5)
assert.equal(usages[0].metrics?.tokensTotal, 15)
})
// ── forked subagent replay (parent token history re-stamped at creation second) ──
test('parity: ccusage codex skips replayed parent token history in thread_spawn subagent files', async () => {
// From ccusage loader.rs skips_replayed_parent_token_history_in_thread_spawn_subagent_files.
// The subagent file opens with its own session_meta (thread_spawn), the parent's
// session_meta, then the parent's token history replayed at the creation second
// (08:03:00), then the subagent's own usage at later seconds. Only the latter counts.
const usages = usageEvents(await parse([
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'subagent-abc', source: { subagent: { thread_spawn: { parent_thread_id: 'parent-xyz' } } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'parent-xyz' } },
// replayed parent history — all stamped at the subagent creation second
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 1000, cached_input_tokens: 100, output_tokens: 200, total_tokens: 1200 }, total_token_usage: { input_tokens: 1000, cached_input_tokens: 100, output_tokens: 200, total_tokens: 1200 } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 500, cached_input_tokens: 50, output_tokens: 100, total_tokens: 600 }, total_token_usage: { input_tokens: 1500, cached_input_tokens: 150, output_tokens: 300, total_tokens: 1800 } } } },
// subagent's own entries — later seconds
{ timestamp: '2026-05-12T08:04:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.2', last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 120 } } } },
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 50, cached_input_tokens: 5, output_tokens: 10, total_tokens: 60 } } } },
]))
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].metrics?.tokensCachedInput, 10)
assert.equal(usages[0].metrics?.tokensOutput, 20)
assert.equal(usages[1].metrics?.tokensInput, 50)
assert.equal(usages[1].metrics?.tokensOutput, 10)
})
test('parity: ccusage codex keeps_cumulative_baseline_when_skipping_subagent_replay', async () => {
// The replayed parent block (total-only, all at the creation second) is skipped
// BUT still advances the cumulative baseline, so the subagent's own first event
// (total 1600) yields delta 100 (1600 - 1500), not 1600. Mirrors ccusage's test.
const usages = usageEvents(await parse([
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'subagent', source: { subagent: { thread_spawn: { parent_thread_id: 'parent' } } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1000, output_tokens: 200, total_tokens: 1200 } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1500, output_tokens: 300, total_tokens: 1800 } } } },
{ timestamp: '2026-05-12T08:04:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.2', total_token_usage: { input_tokens: 1600, output_tokens: 320, total_tokens: 1920 } } } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].metrics?.tokensOutput, 20)
})
test('a non-subagent file whose first two token_counts share a second is NOT skipped', async () => {
// No thread_spawn marker → the same-second heuristic must not fire, so two
// genuinely distinct turns that happen to land in the same wall-clock second
// are both kept. Guards against over-eager replay skipping on normal sessions.
const usages = usageEvents(await parse([
{ timestamp: '2026-05-12T08:03:00.100Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-05-12T08:03:00.200Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 130 } } } },
{ timestamp: '2026-05-12T08:03:00.900Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 200, cached_input_tokens: 20, output_tokens: 40, total_tokens: 260 } } } },
]))
assert.equal(usages.length, 2)
})
test('a thread_spawn file whose first two token_counts differ in second is not skipped', async () => {
// thread_spawn is present, but the first two usage-bearing token_counts fall in
// DIFFERENT seconds → no re-stamped replay block, so nothing is skipped. Mirrors
// ccusage detect_subagent_replay_second returning None when the seconds diverge.
const usages = usageEvents(await parse([
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'subagent-abc', source: { subagent: { thread_spawn: { parent_thread_id: 'parent-xyz' } } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 130 } } } },
{ timestamp: '2026-05-12T08:04:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 50, cached_input_tokens: 5, output_tokens: 10, total_tokens: 60 } } } },
]))
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[1].metrics?.tokensInput, 50)
})
// ── copied branch/goal rollout history (verbatim copy, original timestamps) ──
//
// Codex branch/goal/resume forks copy the parent rollout's lines verbatim into a
// new file, keeping the ORIGINAL timestamps. The same-second replay heuristic
// above cannot catch those (nothing is re-stamped), and they escape the
// consecutive-identical dedupe too. The file's own events can only be stamped
// after its creation instant, which the filename's UUIDv7 carries in UTC — so any
// event_msg/response_item older than that instant is copied history. Mirrors the
// coverage of ccusage's cross-file dedupe (dedupes_copied_branch_history_across_
// session_files), but works on a single file, so incremental re-parses of the
// live branch file alone stay correct without the parent in memory.
test('parity: ccusage codex dedupes_copied_branch_history — pre-creation events are skipped via the UUIDv7 anchor', async () => {
const creation = '2026-05-12T08:02:00.000Z'
const events = await parseFile(rolloutFileName(creation), [
// copied verbatim from the parent rollout — original (pre-creation) timestamps
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'turn_context', payload: { model: 'gpt-5.2' } },
{ timestamp: '2026-05-12T08:01:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1000, cached_input_tokens: 100, output_tokens: 200, reasoning_output_tokens: 20, total_tokens: 1200 } } } },
// the branch's own usage — cumulative continues from the copied baseline
{ timestamp: '2026-05-12T08:02:30.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1600, cached_input_tokens: 300, output_tokens: 450, reasoning_output_tokens: 40, total_tokens: 2050 } } } },
])
// Only the branch's own delta is counted, measured against the copied
// baseline (1600-1000 etc.), matching ccusage's expected branch totals.
const usages = usageEvents(events)
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 600)
assert.equal(usages[0].metrics?.tokensCachedInput, 200)
assert.equal(usages[0].metrics?.tokensOutput, 250)
assert.equal(usages[0].metrics?.tokensReasoningOutput, 20)
assert.equal(usages[0].metrics?.tokensTotal, 850)
})
test('copied pre-creation activity events (prompts/tools) are dropped, not just token_counts', async () => {
// The copied block contains the parent's prompts and tool calls too. Counting
// them would double the parent's prompts, toolCalls, and active duration.
const creation = '2026-05-12T08:02:00.000Z'
const events = await parseFile(rolloutFileName(creation), [
{ timestamp: '2026-05-12T07:50:00.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'copied parent prompt' } },
{ timestamp: '2026-05-12T07:51:00.000Z', type: 'response_item', payload: { type: 'function_call', name: 'shell', call_id: 'copied-call', arguments: '{"command":"ls"}' } },
{ timestamp: '2026-05-12T07:51:05.000Z', type: 'response_item', payload: { type: 'function_call_output', call_id: 'copied-call' } },
// the branch's own activity
{ timestamp: '2026-05-12T08:02:10.000Z', type: 'event_msg', payload: { type: 'user_message', message: 'own prompt' } },
{ timestamp: '2026-05-12T08:02:20.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 120 } } } },
])
const prompts = events.filter(event => event.type === 'prompt.submitted')
assert.equal(prompts.length, 1)
assert.equal(prompts[0].ts, '2026-05-12T08:02:10.000Z')
assert.equal(events.filter(event => event.type === 'tool.started').length, 0)
assert.equal(events.filter(event => event.type === 'tool.completed').length, 0)
assert.equal(usageEvents(events).length, 1)
})
test('a normal rollout file keeps every event at or after its UUIDv7 creation instant', async () => {
// Guard against over-eager dropping: events stamped exactly AT the creation
// millisecond and later are the file's own and must all survive.
const creation = '2026-05-12T08:02:00.000Z'
const usages = usageEvents(await parseFile(rolloutFileName(creation), [
{ timestamp: creation, type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'gpt-5' } },
{ timestamp: '2026-05-12T08:02:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 130 } } } },
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 200, cached_input_tokens: 20, output_tokens: 40, total_tokens: 260 } } } },
]))
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[1].metrics?.tokensInput, 200)
})
test('files without a UUIDv7 rollout name never trigger the creation anchor', async () => {
// Same copied-history shape as the parity test, but in a plain-named file
// (headless logs, history.jsonl, tests): no anchor → nothing is dropped.
const usages = usageEvents(await parse([
{ timestamp: '2026-05-12T08:01:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1000, cached_input_tokens: 100, output_tokens: 200, total_tokens: 1200 } } } },
{ timestamp: '2026-05-12T08:02:30.000Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 1600, cached_input_tokens: 300, output_tokens: 450, total_tokens: 2050 } } } },
]))
assert.equal(usages.length, 2)
assert.equal(usages[0].metrics?.tokensInput, 1000)
assert.equal(usages[1].metrics?.tokensInput, 600)
})
test('the same-second thread_spawn replay skip still works in a UUIDv7-named file', async () => {
// Re-stamped replays are stamped AT the creation second — at or after the
// uuid instant, so the anchor cannot catch them; the layer-1 same-second
// heuristic must keep firing unchanged alongside the anchor.
const creation = '2026-05-12T08:03:00.000Z'
const usages = usageEvents(await parseFile(rolloutFileName(creation), [
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'subagent-abc', source: { subagent: { thread_spawn: { parent_thread_id: 'parent-xyz' } } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'session_meta', payload: { id: 'parent-xyz' } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 1000, cached_input_tokens: 100, output_tokens: 200, total_tokens: 1200 } } } },
{ timestamp: '2026-05-12T08:03:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 500, cached_input_tokens: 50, output_tokens: 100, total_tokens: 600 } } } },
{ timestamp: '2026-05-12T08:04:00.000Z', type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 120 } } } },
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100)
})
// ── forked replay matched against the parent rollout's own stream ──
//
// The same-second heuristic above only holds when the whole replay burst lands in
// one second. Long replays span several seconds and nested forks replay a stream
// that was itself a replay, so Codex-rewritten timestamps cannot anchor them. The
// token counts, though, are copied verbatim and in order: match the leading usage
// against the parent's own stream instead. Mirrors ccusage CodexReplayPlan
// (adapter/codex/replay.rs, #1435).
// Rollout filenames embed the session id; the readable stamp is LOCAL time and is
// deliberately inconsistent with the UTC event timestamps, as in real rollouts.
function rolloutNameFor(sessionId: string): string {
return `rollout-2026-05-12T17-02-00-${sessionId}.jsonl`
}
// Write several rollouts into one sessions directory, then parse one of them, so
// a fork can find the parent log it replayed.
async function parseAmongRollouts(
targetSessionId: string,
rollouts: { sessionId: string, records: unknown[] }[],
): Promise<CanonicalEvent[]> {
const dir = await mkdtemp(path.join(tmpdir(), 'codex-sessions-'))
for (const rollout of rollouts) {
await writeFile(
path.join(dir, rolloutNameFor(rollout.sessionId)),
rollout.records.map(record => JSON.stringify(record)).join('\n'),
'utf8',
)
}
return adapter.parseSessionFile!(path.join(dir, rolloutNameFor(targetSessionId)), { _: [] })
}
function usageLine(ts: string, usage: Record<string, number>): unknown {
return { timestamp: ts, type: 'event_msg', payload: { type: 'token_count', info: { model: 'gpt-5.2', last_token_usage: usage } } }
}
const USAGE_A = { input_tokens: 100, cached_input_tokens: 10, output_tokens: 20, total_tokens: 130 }
const USAGE_B = { input_tokens: 200, cached_input_tokens: 20, output_tokens: 40, total_tokens: 260 }
const USAGE_C = { input_tokens: 300, cached_input_tokens: 30, output_tokens: 60, total_tokens: 390 }
const USAGE_OWN = { input_tokens: 7, cached_input_tokens: 1, output_tokens: 3, total_tokens: 11 }
test('a replay burst spanning several seconds is matched against the parent stream', async () => {
// The case the same-second heuristic misses: a long parent history takes more
// than a second to replay, so the rewritten stamps span three seconds and
// detectSubagentReplaySecond bails out. Before the parent-stream match this
// counted the parent's whole history a second time.
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
usageLine('2026-05-12T08:00:03.000Z', USAGE_C),
],
},
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', source: { subagent: { thread_spawn: { parent_thread_id: parent } } } } },
// Replayed parent history, re-stamped across three distinct seconds.
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
usageLine('2026-05-12T08:05:03.000Z', USAGE_C),
// The subagent's own turn.
usageLine('2026-05-12T08:05:10.000Z', USAGE_OWN),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 7)
})
test('parity: ccusage codex skips_nested_replays_against_immutable_parent_streams', async () => {
// The child replays the parent's WHOLE stream, including the history the parent
// had itself copied from the grandparent. The prefix only lines up when the
// parent is read unfiltered, which is why the parent stream is loaded with no
// replay filtering of its own.
const grandparent = uuidv7At('2026-05-12T08:00:00.000Z')
const parent = uuidv7At('2026-05-12T08:05:00.000Z')
const child = uuidv7At('2026-05-12T08:10:00.000Z')
const rollouts = [
{
sessionId: grandparent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: grandparent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
],
},
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w', forked_from_id: grandparent } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
usageLine('2026-05-12T08:05:30.000Z', USAGE_C),
],
},
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:10:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', forked_from_id: parent } },
usageLine('2026-05-12T08:10:01.000Z', USAGE_A),
usageLine('2026-05-12T08:10:02.000Z', USAGE_B),
usageLine('2026-05-12T08:10:03.000Z', USAGE_C),
usageLine('2026-05-12T08:10:20.000Z', USAGE_OWN),
],
},
]
const childUsages = usageEvents(await parseAmongRollouts(child, rollouts))
assert.equal(childUsages.length, 1)
assert.equal(childUsages[0].metrics?.tokensInput, 7)
// The middle session keeps only its own turn too.
const parentUsages = usageEvents(await parseAmongRollouts(parent, rollouts))
assert.equal(parentUsages.length, 1)
assert.equal(parentUsages[0].metrics?.tokensInput, 300)
})
test('parity: ccusage codex keeps_child_usage_matching_parent_event_after_fork', async () => {
// Usage the parent recorded AFTER the fork was never replayed, so it must not
// mask the child's own events — even when the child's real turn happens to carry
// exactly the same token counts.
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
// Written after the child forked.
usageLine('2026-05-12T08:09:00.000Z', USAGE_B),
],
},
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', forked_from_id: parent } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
// Real child usage that happens to equal the parent's post-fork event.
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 200)
})
test('parity: ccusage codex bounds_the_replay_at_a_numeric_fork_timestamp', async () => {
// session_meta timestamps are sometimes epoch numbers rather than RFC3339.
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:09:00.000Z', USAGE_B),
],
},
{
sessionId: child,
// Epoch seconds for 2026-05-12T08:05:00Z.
records: [
{ timestamp: Date.parse('2026-05-12T08:05:00.000Z') / 1000, type: 'session_meta', payload: { id: child, cwd: '/w', forked_from_id: parent } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 200)
})
test('parity: ccusage codex falls_back_to_rewritten_second_when_the_replay_starts_mid_parent_stream', async () => {
// Codex replayed a compacted history, so it does not line up with the start of
// the parent stream. Nothing matched, so the same-second burst decides instead.
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
usageLine('2026-05-12T08:00:03.000Z', USAGE_C),
],
},
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', source: { subagent: { thread_spawn: { parent_thread_id: parent } } } } },
// Compacted replay: starts mid-stream, so USAGE_A never appears.
usageLine('2026-05-12T08:05:01.000Z', USAGE_B),
usageLine('2026-05-12T08:05:01.500Z', USAGE_C),
usageLine('2026-05-12T08:05:10.000Z', USAGE_OWN),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 7)
})
test('parity: ccusage codex keeps_usage_of_a_session_that_lists_itself_as_its_own_parent', async () => {
// Matching a session against itself would drop every event it recorded.
const self = uuidv7At('2026-05-12T08:00:00.000Z')
const usages = usageEvents(await parseAmongRollouts(self, [
{
sessionId: self,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: self, cwd: '/w', forked_from_id: self } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
],
},
]))
assert.equal(usages.length, 2)
})
test('parity: ccusage codex keeps_full_parent_stream_when_the_parent_itself_replayed_a_missing_session', async () => {
// The grandparent log is gone, so the parent keeps its own replayed history —
// and the child, which copied that whole stream, must still match all of it.
const missingGrandparent = uuidv7At('2026-05-12T07:00:00.000Z')
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w', forked_from_id: missingGrandparent } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
],
},
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', forked_from_id: parent } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
usageLine('2026-05-12T08:05:10.000Z', USAGE_OWN),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 7)
})
test('a fork whose parent log is unavailable falls back to the same-second heuristic', async () => {
// No parent file on disk: the prefix is empty, so nothing can match and the
// rewritten-second burst decides — the pre-#1435 behavior, unchanged.
const child = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(child, [
{
sessionId: child,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: child, cwd: '/w', source: { subagent: { thread_spawn: { parent_thread_id: uuidv7At('2026-05-12T08:00:00.000Z') } } } } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:01.500Z', USAGE_B),
usageLine('2026-05-12T08:05:10.000Z', USAGE_OWN),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 7)
})
test('the UUIDv7 anchor and the parent-prefix match stay aligned on a verbatim branch copy', async () => {
// A branch fork copies the parent's lines VERBATIM, keeping the original
// timestamps, so the creation anchor drops them before the prefix match ever
// sees them. Those anchored-away events must still consume their slot in the
// parent prefix — otherwise the branch's first real turn is compared against
// the head of the prefix, and a turn that happens to repeat the parent's first
// usage would be silently deleted.
const parent = uuidv7At('2026-05-12T08:00:00.000Z')
const branch = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(branch, [
{
sessionId: parent,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: parent, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
],
},
{
sessionId: branch,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: branch, cwd: '/w', forked_from_id: parent } },
// Copied verbatim: original pre-creation timestamps, caught by the anchor.
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
// The branch's own turn, which happens to repeat the parent's first usage.
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
],
},
]))
assert.equal(usages.length, 1)
assert.equal(usages[0].metrics?.tokensInput, 100)
assert.equal(usages[0].ts, '2026-05-12T08:05:01.000Z')
})
test('a normal session that shares usage values with an unrelated rollout is untouched', async () => {
// No fork marker → no prefix matching at all, however similar the neighbours.
const other = uuidv7At('2026-05-12T08:00:00.000Z')
const own = uuidv7At('2026-05-12T08:05:00.000Z')
const usages = usageEvents(await parseAmongRollouts(own, [
{
sessionId: other,
records: [
{ timestamp: '2026-05-12T08:00:00.000Z', type: 'session_meta', payload: { id: other, cwd: '/w' } },
usageLine('2026-05-12T08:00:01.000Z', USAGE_A),
usageLine('2026-05-12T08:00:02.000Z', USAGE_B),
],
},
{
sessionId: own,
records: [
{ timestamp: '2026-05-12T08:05:00.000Z', type: 'session_meta', payload: { id: own, cwd: '/w' } },
usageLine('2026-05-12T08:05:01.000Z', USAGE_A),
usageLine('2026-05-12T08:05:02.000Z', USAGE_B),
],
},
]))
assert.equal(usages.length, 2)
})
// ── model naming ──
//
// The model that gets stored is the pricing key the backend looks up, so a
// wrong name is a silently-$0 (or silently-mispriced) row rather than a
// visible error.
// Token numbers are irrelevant to these tests — only the model stamped on
// the resulting usage event is.
function tokenCount(timestamp: string): unknown {
return {
timestamp,
type: 'event_msg',
payload: { type: 'token_count', info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 10, output_tokens: 50, total_tokens: 150 } } },
}
}
test('session_meta.model_provider is never used as the model', async () => {
// `model_provider` is the API provider id — `openai` for the real thing,
// or whatever a third-party proxy calls itself. Reading it into `model`
// is how `openai` / `crs` / `custom` used to reach the model leaderboard.
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'openai' } },
{ timestamp: '2026-01-02T00:00:01.000Z', type: 'turn_context', payload: { model: 'gpt-5.6-sol' } },
tokenCount('2026-01-02T00:00:02.000Z'),
])
assert.equal(events.every(event => event.model !== 'openai'), true)
assert.equal(usageEvents(events)[0].model, 'gpt-5.6-sol')
})
test('usage recorded before the first turn_context still carries the real model', async () => {
// The model is seeded by scanning ahead for the first turn_context, so a
// token_count that lands before it is not left model-less (or, previously,
// stamped with the provider id).
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'openai' } },
tokenCount('2026-01-02T00:00:01.000Z'),
{ timestamp: '2026-01-02T00:00:02.000Z', type: 'turn_context', payload: { model: 'gpt-5.6-sol' } },
])
assert.equal(usageEvents(events)[0].model, 'gpt-5.6-sol')
assert.equal(events.find(event => event.type === 'session.started')?.model, 'gpt-5.6-sol')
})
test('a rollout with no turn_context leaves the model unset rather than guessing', async () => {
const events = await parse([
{ timestamp: '2026-01-02T00:00:00.000Z', type: 'session_meta', payload: { id: 'session', cwd: '/w', model_provider: 'crs' } },
tokenCount('2026-01-02T00:00:01.000Z'),
])
assert.equal(usageEvents(events)[0].model, undefined)
})
test('the reasoning-effort parenthetical some proxies append is stripped', async () => {