-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.test.ts
More file actions
2002 lines (1803 loc) · 76.2 KB
/
Copy pathcli.test.ts
File metadata and controls
2002 lines (1803 loc) · 76.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 { RunContext } from '../src/lib/types.ts'
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
import { mkdir, mkdtemp, readdir, readFile, stat, symlink, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { Readable } from 'node:stream'
// eslint-disable-next-line test/no-import-node-test -- This repo uses node:test as the runner.
import { test } from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { codexBackfillFiles, createCodexAdapter } from '../src/adapters/codex.ts'
import { run, syncLocalRunnerEntryArgs } from '../src/cli.ts'
import { ensureLocalMachineId, machineIdPath, readConfig, writeConfig } from '../src/lib/config.ts'
import { writeFileAtomic } from '../src/lib/fs.ts'
test('detect reports installed Codex hook', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
await run(['install', '--target', 'codex', '--home', home], testContext())
let output = ''
const exitCode = await run(['detect', '--json', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const parsed = JSON.parse(output)
const codex = parsed.targets.find((target: { id: string }) => target.id === 'codex')
assert.equal(codex.installed, true)
})
test('detect only marks Codex installed when codetime hook exists', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
await mkdir(path.join(home, '.codex'), { recursive: true })
await writeFile(path.join(home, '.codex', 'hooks.json'), JSON.stringify({ hooks: {} }), 'utf8')
let output = ''
const exitCode = await run(['detect', '--json', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const parsed = JSON.parse(output)
const codex = parsed.targets.find((target: { id: string }) => target.id === 'codex')
assert.equal(codex.detected, true)
assert.equal(codex.installed, false)
})
test('install writes Codex hook without a skill', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const exitCode = await run(['install', '--target', 'codex', '--home', home], testContext())
assert.equal(exitCode, 0)
const skillPath = path.join(home, '.codex', 'skills', 'codetime', 'SKILL.md')
const hooksPath = path.join(home, '.codex', 'hooks.json')
const hooks = JSON.parse(await readFile(hooksPath, 'utf8'))
await assert.rejects(readFile(skillPath, 'utf8'), { code: 'ENOENT' })
assert.equal(hooks.hooks.SessionStart[0].hooks[0].command, 'codetime hook --agent codex')
assert.equal(hooks.hooks.PreToolUse[0].hooks[0].command, 'codetime hook --agent codex')
assert.equal(hooks.hooks.PostToolUse[0].hooks[0].command, 'codetime hook --agent codex')
assert.equal(hooks.hooks.Stop[0].hooks[0].command, 'codetime hook --agent codex')
})
test('hook triggers a sync-local-runner without parsing the payload', async () => {
// Verifies the trigger contract: the hook spawns sync-local-runner (the
// real upload path) and persists state/lock files. Payload contents are
// not inspected — backfill re-derives all events from session files.
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const spawns: Array<{ command: string, args: string[] }> = []
const stdin = Readable.from([JSON.stringify({
hook_event_name: 'PostToolUse',
tool_name: 'apply_patch',
cwd: path.join(home, 'project'),
session_id: 's1',
})])
const exitCode = await run(['hook', '--agent', 'codex', '--home', home], testContext({
stdin,
spawn: ((command: string, args: string[]) => {
spawns.push({ command, args })
return { pid: 43_210, unref() {} } as never
}) as unknown as RunContext['spawn'],
}))
assert.equal(exitCode, 0)
assert.equal(spawns.length, 1)
assert.equal(spawns[0].args.includes('sync-local-runner'), true)
const state = JSON.parse(await readFile(path.join(home, '.codetime', 'sync-local-trigger.json'), 'utf8'))
const lock = JSON.parse(await readFile(path.join(home, '.codetime', 'sync-local-trigger.lock'), 'utf8'))
assert.equal(typeof state.lastTriggeredAt, 'string')
assert.equal(lock.pid, 43_210)
})
test('hook --dry-run echoes the payload without triggering backfill', async () => {
const spawns: number[] = []
const stdin = Readable.from([JSON.stringify({
hook_event_name: 'PostToolUse',
tool_name: 'Read',
tool_input: { file_path: 'src/index.ts' },
})])
let output = ''
const exitCode = await run(['hook', '--agent', 'claude', '--dry-run'], testContext({
stdin,
spawn: () => {
spawns.push(1)
return { pid: 1, unref() {} } as never
},
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
assert.equal(spawns.length, 0, 'dry-run must not spawn anything')
const result = JSON.parse(output)
assert.equal(result.agent, 'claude')
assert.equal(result.wouldTrigger, 'backfill')
assert.equal(result.received.hook_event_name, 'PostToolUse')
assert.equal(result.received.tool_name, 'Read')
})
test('sync-local-runner entry args use the bin entrypoint for built output', () => {
assert.deepEqual(syncLocalRunnerEntryArgs('/repo/packages/cli/src/cli.ts'), [
'--import',
'tsx',
'/repo/packages/cli/src/cli.ts',
])
assert.deepEqual(syncLocalRunnerEntryArgs('/repo/packages/cli/dist/cli.js'), [
'/repo/packages/cli/bin/codetime.mjs',
])
})
test('sync-local-trigger throttles repeated triggers', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
await mkdir(path.join(home, '.codetime'), { recursive: true })
await writeFile(path.join(home, '.codetime', 'sync-local-trigger.json'), JSON.stringify({
version: 1,
lastTriggeredAt: new Date().toISOString(),
}), 'utf8')
let output = ''
const exitCode = await run(['sync-local-trigger', '--home', home, '--min-interval', '60', '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.status, 'throttled')
})
test('sync-local-trigger detects an already running sync', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
await mkdir(path.join(home, '.codetime'), { recursive: true })
await writeFile(path.join(home, '.codetime', 'sync-local-trigger.lock'), JSON.stringify({
pid: process.pid,
startedAt: '2026-05-02T00:00:00.000Z',
}), 'utf8')
let output = ''
const exitCode = await run(['sync-local-trigger', '--home', home, '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.status, 'already-running')
assert.equal(result.pid, process.pid)
})
test('sync-local-runner honors explicit state and lock file paths', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const statePath = path.join(home, 'custom-state.json')
const lockPath = path.join(home, 'custom.lock')
const exitCode = await run([
'sync-local-runner',
'--home',
home,
'--lock-file',
lockPath,
'--state-file',
statePath,
'--json',
], testContext({
stdout: { write() {} },
fetch: async (_url, init) => {
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
const state = JSON.parse(await readFile(statePath, 'utf8'))
assert.equal(typeof state.lastStartedAt, 'string')
assert.equal(typeof state.lastCompletedAt, 'string')
assert.equal(state.lastExitCode, 0)
await assert.rejects(readFile(lockPath, 'utf8'), { code: 'ENOENT' })
})
test('backfill dry-run reports local history candidates without importing', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
await mkdir(path.join(home, '.codex', 'sessions'), { recursive: true })
await writeFile(path.join(home, '.codex', 'sessions', 'session.jsonl'), JSON.stringify({
type: 'session_meta',
timestamp: '2026-04-29T00:00:00.000Z',
payload: {
id: 's1',
cwd: path.join(home, 'project'),
model_provider: 'openai',
},
}), 'utf8')
let output = ''
const exitCode = await run(['backfill', 'plan', '--source', 'codex', '--dry-run', '--json', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.importRun.source, 'codex')
assert.equal(result.candidates[0].exists, true)
assert.match(result.plannedEvents[0].eventId, /^evt_[0-9a-f]{24}$/)
assert.match(result.plannedEvents[0].payloadHash, /^sha256:/)
})
test('backfill plan parses Codex sessions without leaking transcript text', async () => {
const home = await createCodexBackfillHome()
let output = ''
const exitCode = await run(['backfill', 'plan', '--source', 'codex', '--dry-run', '--json', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
assert.equal(output.includes('secret prompt'), false)
assert.equal(output.includes('secret command'), false)
assert.equal(output.includes('secret diff'), false)
const result = JSON.parse(output)
const types = new Set(result.plannedEvents.map((event: { type: string }) => event.type))
assert.ok(types.has('session.started'))
assert.ok(types.has('prompt.submitted'))
assert.ok(types.has('model.usage'))
assert.ok(types.has('command.completed'))
assert.ok(types.has('file.read'))
assert.ok(types.has('file.changed'))
})
test('backfill plan text output is bounded', async () => {
const home = await createCodexBackfillHome()
let output = ''
const exitCode = await run(['backfill', 'plan', '--source', 'codex', '--dry-run', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
assert.match(output, /planned \d+/)
assert.match(output, /events codex:/)
assert.match(output, /sample/)
assert.match(output, /use --json for full details/)
assert.equal(output.includes('secret prompt'), false)
assert.equal(output.split('\n').length < 20, true)
})
test('backfill plan honors the limit option', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions')
await mkdir(sessionsDir, { recursive: true })
await writeFile(path.join(sessionsDir, 'a.jsonl'), JSON.stringify({
timestamp: '2026-04-29T00:00:00.000Z',
type: 'session_meta',
payload: { id: 'a', cwd: path.join(home, 'project-a') },
}), 'utf8')
await writeFile(path.join(sessionsDir, 'b.jsonl'), JSON.stringify({
timestamp: '2026-04-29T00:00:00.000Z',
type: 'session_meta',
payload: { id: 'b', cwd: path.join(home, 'project-b') },
}), 'utf8')
let output = ''
const exitCode = await run(['backfill', 'plan', '--source', 'codex', '--dry-run', '--json', '--home', home, '--limit', '1'], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.candidates[0].entries, 2)
assert.equal(result.plannedEvents.length, 1)
})
test('Codex parser dedupes consecutive token_count events with identical last_token_usage', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions')
await mkdir(sessionsDir, { recursive: true })
const dupUsage = {
info: {
model_context_window: 128_000,
last_token_usage: {
input_tokens: 100,
cached_input_tokens: 0,
output_tokens: 20,
reasoning_output_tokens: 0,
total_tokens: 120,
},
},
}
const freshUsage = {
info: {
model_context_window: 128_000,
last_token_usage: {
input_tokens: 150,
cached_input_tokens: 50,
output_tokens: 30,
reasoning_output_tokens: 0,
total_tokens: 180,
},
},
}
await writeFile(path.join(sessionsDir, 'dup.jsonl'), [
{ timestamp: '2026-04-29T00:00:00.000Z', type: 'session_meta', payload: { id: 's-dup', cwd: path.join(home, 'project'), model_provider: 'openai' } },
{ timestamp: '2026-04-29T00:00:01.000Z', type: 'event_msg', payload: { type: 'token_count', ...dupUsage } },
{ timestamp: '2026-04-29T00:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', ...dupUsage } },
{ timestamp: '2026-04-29T00:00:03.000Z', type: 'event_msg', payload: { type: 'token_count', ...dupUsage } },
{ timestamp: '2026-04-29T00:00:04.000Z', type: 'event_msg', payload: { type: 'token_count', ...freshUsage } },
].map(item => JSON.stringify(item)).join('\n'), 'utf8')
let capturedBody = ''
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test'], testContext({
fetch: async (_url, init) => {
capturedBody = String(init?.body)
const rollups = JSON.parse(capturedBody).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
const rollup = JSON.parse(capturedBody).rollups[0]
const modelRollup = rollup.modelRollups[0]
assert.equal(modelRollup.callCount, 2)
assert.equal(modelRollup.inputTokens, 100 + 150)
assert.equal(modelRollup.outputTokens, 20 + 30)
assert.equal(modelRollup.totalTokens, 120 + 180)
})
test('Codex parser ignores replayed parent session_meta in forked rollouts', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions')
await mkdir(sessionsDir, { recursive: true })
await writeFile(path.join(sessionsDir, 'fork.jsonl'), [
{ timestamp: '2026-04-29T00:00:00.000Z', type: 'session_meta', payload: { id: 'child-id', forked_from_id: 'parent-id', cwd: path.join(home, 'project'), model_provider: 'openai' } },
{ timestamp: '2026-04-29T00:00:01.000Z', type: 'event_msg', payload: { type: 'task_started', turn_id: 't1' } },
{ timestamp: '2026-04-29T00:00:02.000Z', type: 'event_msg', payload: { type: 'token_count', info: { model_context_window: 128_000, last_token_usage: { input_tokens: 10, cached_input_tokens: 0, output_tokens: 4, reasoning_output_tokens: 0, total_tokens: 14 } } } },
{ timestamp: '2026-04-29T00:00:03.000Z', type: 'session_meta', payload: { id: 'parent-id', cwd: path.join(home, 'project'), model_provider: 'openai' } },
{ timestamp: '2026-04-29T00:00:04.000Z', type: 'event_msg', payload: { type: 'task_complete', turn_id: 't1', duration_ms: 4000 } },
].map(item => JSON.stringify(item)).join('\n'), 'utf8')
let capturedBody = ''
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test'], testContext({
fetch: async (_url, init) => {
capturedBody = String(init?.body)
const rollups = JSON.parse(capturedBody).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
const rollups = JSON.parse(capturedBody).rollups
assert.equal(rollups.length, 1)
assert.equal(rollups[0].sessionId, 'child-id')
})
test('backfill import --force is non-destructive: re-imports without purging server rollups', async () => {
const home = await createCodexBackfillHome()
const calls: Array<{ method: string, url: string }> = []
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--force', '--json'], testContext({
stdout: { write: () => {} },
fetch: async (url, init) => {
const method = (init?.method || 'GET').toUpperCase()
calls.push({ method, url: String(url) })
if (method === 'DELETE') {
return Response.json({ deleted: 3 }, { status: 200 })
}
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
// No DELETE (purge) is issued — the rollups are overwritten in place instead.
assert.equal(calls.some(c => c.method === 'DELETE'), false)
// The import still ran: an ingest POST was made.
assert.equal(calls.some(c => c.method === 'POST' && /\/v3\/agent\/ingest$/.test(c.url)), true)
})
test('backfill import --purge deletes this machine\'s rollups before re-importing', async () => {
const home = await createCodexBackfillHome()
const calls: Array<{ method: string, url: string }> = []
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--purge', '--json'], testContext({
stdout: { write: () => {} },
fetch: async (url, init) => {
const method = (init?.method || 'GET').toUpperCase()
calls.push({ method, url: String(url) })
if (method === 'DELETE') {
return Response.json({ deleted: 3 }, { status: 200 })
}
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
assert.equal(calls.some(c => c.method === 'DELETE' && /\/v3\/agent\/sessions\?source=codex$/.test(c.url)), true)
})
test('codexBackfillFiles discovers archived_sessions and prefers the active copy on collision', async () => {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessions = path.join(home, '.codex', 'sessions')
const archived = path.join(home, '.codex', 'archived_sessions')
await mkdir(sessions, { recursive: true })
await mkdir(archived, { recursive: true })
await writeFile(path.join(sessions, 'a.jsonl'), '{}', 'utf8')
await writeFile(path.join(archived, 'a.jsonl'), '{}', 'utf8') // same relative path — active wins
await writeFile(path.join(archived, 'b.jsonl'), '{}', 'utf8') // archived-only — kept
const discovered = await codexBackfillFiles(undefined, home, undefined)
const files = new Set(discovered.map(f => f.path))
assert.equal(files.has(path.join(sessions, 'a.jsonl')), true)
assert.equal(files.has(path.join(archived, 'b.jsonl')), true)
assert.equal(files.has(path.join(archived, 'a.jsonl')), false) // deduped in favor of active
})
test('symlinked Codex home yields the same rollup identity as the real path', async () => {
const home = await createCodexBackfillHome()
// Multi-account setups point CODEX_HOME at a shadow dir that symlinks the
// real ~/.codex; a hook-triggered sync sees the shadow path while a manual
// sync sees the real one. Both must resolve to one rollup identity.
const shadowCodexHome = path.join(home, '.codex-shadow')
await symlink(path.join(home, '.codex'), shadowCodexHome, 'dir')
const importOnce = async (env: Record<string, string>) => {
let body = ''
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--force', '--json'], testContext({
env: { HOME: home, ...env },
fetch: async (_url, init) => {
body = String(init?.body)
const rollups = JSON.parse(body).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
return JSON.parse(body).rollups
}
const direct = await importOnce({})
const viaSymlink = await importOnce({ CODEX_HOME: shadowCodexHome })
assert.equal(direct.length, 1)
assert.equal(viaSymlink.length, 1)
assert.equal(viaSymlink[0].rollupKey, direct[0].rollupKey)
})
test('backfill import sends parsed Codex events and counts API results', async () => {
const home = await createCodexBackfillHome()
const calls: Array<{ url: string, body: string }> = []
let output = ''
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
fetch: async (url, init) => {
const body = String(init?.body)
const rollups = JSON.parse(body).rollups
calls.push({ url: String(url), body })
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
assert.equal(calls.length, 1)
assert.match(calls[0].url, /\/v3\/agent\/ingest$/)
assert.equal(calls.some(call => call.body.includes('secret prompt')), false)
assert.equal(calls.some(call => call.body.includes('secret command')), false)
assert.equal(calls.some(call => call.body.includes('secret diff')), false)
const rollups = JSON.parse(calls[0].body).rollups
const result = JSON.parse(output)
assert.equal(result.planned, rollups.length)
assert.equal(result.sourceEvents > rollups.length, true)
assert.equal(result.inserted, rollups.length)
assert.equal(result.skipped, 0)
const rollup = rollups[0]
assert.equal(rollup.fileRollups.some((file: { displayPath: string }) => file.displayPath === 'src/secret.ts'), true)
assert.equal(rollup.fileRollups.some((file: { displayPath: string }) => file.displayPath === 'src/readme.ts'), true)
const changedFile = rollup.fileRollups.find((file: { displayPath: string }) => file.displayPath === 'src/secret.ts')
assert.equal(changedFile.linesAdded, 1)
assert.equal(changedFile.linesRemoved, 1)
})
test('backfill import text output reports bounded progress', async () => {
const home = await createCodexBackfillHome()
let output = ''
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--batch-size', '2'], testContext({
stdout: { write: (text: string) => {
output += text
} },
fetch: async (_url, init) => {
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
// Progress now renders as a bar (one line per source, overwritten via
// \r), so we assert on the per-source label and the data the bar's
// tick/finalize messages embed rather than the old text milestones.
assert.match(output, /codex\s+\[.+\] 100% · \d+\/\d+ files, \d+ events/)
assert.match(output, /rollup \d+ from \d+ events/)
assert.match(output, /upload\s+\[.+\] 100% · \d+\/\d+ batches, inserted \d+/)
assert.match(output, /inserted \d+/)
assert.equal(output.split('\n').length < 30, true)
})
test('backfill import can skip API conflicts', async () => {
const home = await createCodexBackfillHome()
let sawReplace = true
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--skip-conflicts'], testContext({
fetch: async (_url, init) => {
const body = JSON.parse(String(init?.body))
sawReplace = body.replace === true
const rollups = body.rollups
return Response.json({ inserted: 0, skipped: 0, conflicts: rollups.length, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
assert.equal(sawReplace, false)
})
test('backfill import replaces conflicts by default for rollup uploads', async () => {
const home = await createCodexBackfillHome()
let sawReplace = false
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test'], testContext({
fetch: async (_url, init) => {
const body = JSON.parse(String(init?.body))
sawReplace = body.replace === true
const rollups = body.rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
assert.equal(sawReplace, true)
})
test('backfill import handles large Codex event batches', async () => {
const home = await createLargeCodexBackfillHome(3, 50_000)
let output = ''
let batches = 0
const exitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--batch-size', '50000', '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
fetch: async (_url, init) => {
batches += 1
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.planned, 3)
assert.equal(result.sourceEvents, 150_000)
assert.equal(result.inserted, 3)
assert.equal(batches, 1)
})
test('backfill import skips unchanged session files after the watermark advances', async () => {
const home = await createIncrementalCodexBackfillHome()
const calls: Array<{ url: string, body: string }> = []
const fetch: RunContext['fetch'] = async (url, init) => {
calls.push({ url: String(url), body: String(init?.body) })
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
}
const firstExitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({ fetch }))
assert.equal(firstExitCode, 0)
assert.equal(calls.length, 1)
assert.equal(JSON.parse(calls[0].body).rollups.length, 2)
calls.length = 0
const secondExitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({ fetch }))
assert.equal(secondExitCode, 0)
assert.equal(calls.length, 0)
})
test('backfill import reparses a changed session file from its earliest event', async () => {
const home = await createIncrementalCodexBackfillHome()
const calls: Array<{ url: string, body: string }> = []
const fetch: RunContext['fetch'] = async (url, init) => {
calls.push({ url: String(url), body: String(init?.body) })
const rollups = JSON.parse(String(init?.body)).rollups
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
}
const firstExitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({ fetch }))
assert.equal(firstExitCode, 0)
calls.length = 0
const sessionPath = path.join(home, '.codex', 'sessions', '2026', '04', '29', 'rollout-b.jsonl')
await writeFile(sessionPath, [
{
timestamp: '2026-04-28T23:59:58.000Z',
type: 'session_meta',
payload: {
id: 'session-b',
cwd: path.join(home, 'project-b'),
model_provider: 'openai',
},
},
{
timestamp: '2026-04-29T00:01:01.000Z',
type: 'event_msg',
payload: {
type: 'task_started',
turn_id: 'turn-b',
},
},
{
timestamp: '2026-04-29T00:01:02.000Z',
type: 'event_msg',
payload: {
type: 'user_message',
message: 'prompt b',
},
},
{
timestamp: '2026-04-29T00:01:03.000Z',
type: 'event_msg',
payload: {
type: 'task_complete',
turn_id: 'turn-b',
duration_ms: 2000,
},
},
].map(item => JSON.stringify(item)).join('\n'), 'utf8')
await utimes(sessionPath, new Date('2026-04-29T00:10:00.000Z'), new Date('2026-04-29T00:10:00.000Z'))
const secondExitCode = await run(['backfill', 'import', '--source', 'codex', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({ fetch }))
assert.equal(secondExitCode, 0)
assert.equal(calls.length, 1)
const rollups = JSON.parse(calls[0].body).rollups
assert.equal(rollups.length, 1)
assert.equal(rollups[0].sessionId, 'session-b')
assert.equal(rollups[0].startedAt, '2026-04-28T23:59:58.000Z')
})
test('backfill plan parses Claude Code sessions without leaking transcript text', async () => {
const home = await createClaudeBackfillHome()
let output = ''
const exitCode = await run(['backfill', 'plan', '--source', 'claude-code', '--dry-run', '--json', '--home', home], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
assert.equal(output.includes('secret prompt'), false)
assert.equal(output.includes('secret command'), false)
assert.equal(output.includes('secret file content'), false)
assert.equal(output.includes('secret subagent prompt'), false)
const result = JSON.parse(output)
assert.equal(result.importRun.source, 'claude-code')
const types = new Set(result.plannedEvents.map((event: { type: string }) => event.type))
assert.ok(types.has('session.started'))
assert.ok(types.has('prompt.submitted'))
assert.ok(types.has('model.usage'))
assert.ok(types.has('tool.started'))
assert.ok(types.has('tool.completed'))
assert.ok(types.has('command.completed'))
assert.ok(types.has('file.read'))
assert.ok(types.has('file.changed'))
assert.ok(types.has('subagent.started'))
assert.ok(types.has('subagent.ended'))
})
test('backfill import sends parsed Claude Code events and counts API results', async () => {
const home = await createClaudeBackfillHome()
const calls: Array<{ url: string, body: string }> = []
let output = ''
const exitCode = await run(['backfill', 'import', '--source', 'claude-code', '--home', home, '--api-url', 'http://example.test', '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
fetch: async (url, init) => {
const body = String(init?.body)
const rollups = JSON.parse(body).rollups
calls.push({ url: String(url), body })
return Response.json({ inserted: rollups.length, skipped: 0, conflicts: 0, conflictIds: [] }, { status: 200 })
},
}))
assert.equal(exitCode, 0)
assert.equal(calls.length, 1)
assert.match(calls[0].url, /\/v3\/agent\/ingest$/)
assert.equal(calls[0].body.includes('secret prompt'), false)
assert.equal(calls[0].body.includes('secret command'), false)
assert.equal(calls[0].body.includes('secret file content'), false)
assert.equal(calls[0].body.includes('secret subagent prompt'), false)
const rollups = JSON.parse(calls[0].body).rollups
const result = JSON.parse(output)
assert.equal(result.source, 'claude-code')
assert.equal(result.planned, rollups.length)
assert.equal(result.inserted, rollups.length)
const rollup = rollups[0]
assert.equal(rollup.project, 'codetime')
assert.equal(rollup.fileRollups.some((file: { displayPath: string }) => file.displayPath === 'src/readme.ts'), true)
const fileChanged = rollup.fileRollups.find((file: { displayPath: string }) => file.displayPath === 'src/generated.ts')
assert.equal(fileChanged.linesAdded, 2)
const modelRollup = rollup.modelRollups[0]
assert.equal(modelRollup.inputTokens, 17)
assert.equal(modelRollup.cachedInputTokens, 7)
assert.equal(modelRollup.cacheCreationInputTokens, 2)
assert.equal(modelRollup.cacheReadInputTokens, 5)
assert.equal(modelRollup.outputTokens, 4)
assert.equal(modelRollup.totalTokens, 21)
})
test('backfill verify reports placeholder status for import runs', async () => {
let output = ''
const exitCode = await run(['backfill', 'verify', '--import-run', 'import_123', '--json'], testContext({
stdout: { write: (text: string) => {
output += text
} },
}))
assert.equal(exitCode, 0)
const result = JSON.parse(output)
assert.equal(result.importRunId, 'import_123')
assert.equal(result.status, 'not-implemented')
})
async function createCodexBackfillHome() {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions', '2026', '04', '29')
await mkdir(sessionsDir, { recursive: true })
await writeFile(path.join(sessionsDir, 'rollout-2026-04-29T00-00-00-000Z-12345678-1234-1234-1234-123456789abc.jsonl'), [
{
timestamp: '2026-04-29T00:00:00.000Z',
type: 'session_meta',
payload: {
id: '12345678-1234-1234-1234-123456789abc',
cwd: path.join(home, 'project'),
model_provider: 'openai',
},
},
{
timestamp: '2026-04-29T00:00:01.000Z',
type: 'event_msg',
payload: {
type: 'task_started',
turn_id: 'turn-1',
},
},
{
timestamp: '2026-04-29T00:00:02.000Z',
type: 'event_msg',
payload: {
type: 'user_message',
message: 'secret prompt',
},
},
{
timestamp: '2026-04-29T00:00:03.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
model_context_window: 128_000,
last_token_usage: {
input_tokens: 10,
cached_input_tokens: 2,
output_tokens: 4,
reasoning_output_tokens: 1,
total_tokens: 14,
},
},
},
},
{
timestamp: '2026-04-29T00:00:04.000Z',
type: 'response_item',
payload: {
type: 'function_call',
name: 'shell_command',
call_id: 'call-read',
arguments: JSON.stringify({
cmd: 'sed -n \'1,20p\' src/readme.ts',
workdir: path.join(home, 'project'),
}),
},
},
{
timestamp: '2026-04-29T00:00:04.500Z',
type: 'response_item',
payload: {
type: 'function_call',
name: 'exec_command',
call_id: 'call-1',
arguments: 'secret command',
},
},
{
timestamp: '2026-04-29T00:00:05.000Z',
type: 'event_msg',
payload: {
type: 'exec_command_end',
call_id: 'call-1',
turn_id: 'turn-1',
command: ['sh', '-lc', 'secret command'],
exit_code: 0,
duration: {
secs: 1,
nanos: 250_000_000,
},
},
},
{
timestamp: '2026-04-29T00:00:06.000Z',
type: 'event_msg',
payload: {
type: 'patch_apply_end',
call_id: 'call-2',
turn_id: 'turn-1',
success: true,
changes: {
'src/secret.ts': {
type: 'update',
unified_diff: [
'--- a/src/secret.ts',
'+++ b/src/secret.ts',
'-const value = \'\'',
'+const value = \'secret diff\'',
].join('\n'),
},
},
},
},
{
timestamp: '2026-04-29T00:00:07.000Z',
type: 'event_msg',
payload: {
type: 'task_complete',
turn_id: 'turn-1',
duration_ms: 7000,
},
},
].map(item => JSON.stringify(item)).join('\n'), 'utf8')
return home
}
async function createIncrementalCodexBackfillHome() {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions', '2026', '04', '29')
await mkdir(sessionsDir, { recursive: true })
const files = [
{
name: 'rollout-a.jsonl',
mtime: '2026-04-29T00:05:00.000Z',
lines: [
{
timestamp: '2026-04-29T00:00:00.000Z',
type: 'session_meta',
payload: {
id: 'session-a',
cwd: path.join(home, 'project-a'),
model_provider: 'openai',
},
},
{
timestamp: '2026-04-29T00:00:01.000Z',
type: 'event_msg',
payload: {
type: 'task_started',
turn_id: 'turn-a',
},
},
{
timestamp: '2026-04-29T00:00:02.000Z',
type: 'event_msg',
payload: {
type: 'user_message',
message: 'prompt a',
},
},
{
timestamp: '2026-04-29T00:00:03.000Z',
type: 'event_msg',
payload: {
type: 'task_complete',
turn_id: 'turn-a',
duration_ms: 2000,
},
},
],
},
{
name: 'rollout-b.jsonl',
mtime: '2026-04-29T00:06:00.000Z',
lines: [
{
timestamp: '2026-04-29T00:01:00.000Z',
type: 'session_meta',
payload: {
id: 'session-b',
cwd: path.join(home, 'project-b'),
model_provider: 'openai',
},
},
{
timestamp: '2026-04-29T00:01:01.000Z',
type: 'event_msg',
payload: {
type: 'task_started',
turn_id: 'turn-b',
},
},
{
timestamp: '2026-04-29T00:01:02.000Z',
type: 'event_msg',
payload: {
type: 'user_message',
message: 'prompt b',
},
},
{
timestamp: '2026-04-29T00:01:03.000Z',
type: 'event_msg',
payload: {
type: 'task_complete',
turn_id: 'turn-b',
duration_ms: 2000,
},
},
],
},
]
for (const file of files) {
const filePath = path.join(sessionsDir, file.name)
await writeFile(filePath, file.lines.map(item => JSON.stringify(item)).join('\n'), 'utf8')
await utimes(filePath, new Date(file.mtime), new Date(file.mtime))
}
return home
}
async function createLargeCodexBackfillHome(fileCount: number, eventsPerFile: number) {
const home = await mkdtemp(path.join(tmpdir(), 'codetime-'))
const sessionsDir = path.join(home, '.codex', 'sessions', '2026', '04', '29')
await mkdir(sessionsDir, { recursive: true })
const line = JSON.stringify({
timestamp: '2026-04-29T00:00:00.000Z',
type: 'event_msg',