codex-wrapper 0.5.2

A type-safe Codex CLI wrapper for Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
//! Read-side access to the CLI's on-disk session logs.
//!
//! Read-only. Mutation goes through the CLI, via
//! [`ArchiveCommand`](crate::ArchiveCommand) and
//! [`DeleteCommand`](crate::DeleteCommand).
//!
//! # On-disk layout
//!
//! ```text
//! $CODEX_HOME/sessions/<YYYY>/<MM>/<DD>/rollout-<ISO8601>-<uuid>.jsonl
//! ```
//!
//! A reverted thread's file is named `rollout-<ISO8601>-<uuid>_<uuid>.jsonl`:
//! the thread id, then the id of that rollout.
//!
//! The CLI compresses older sessions to `.jsonl.zst`, and restores the plain
//! file when one is resumed. Either path reads whichever of the two exists.
//!
//! The date partitioning is why [`SessionQuery::after`] and
//! [`SessionQuery::before`] are cheap: they filter directories, without opening
//! a file.
//!
//! # Two envelope generations
//!
//! A real machine holds sessions written by many CLI versions, and the line
//! format changed. Both were found on one machine while writing this, 205
//! files spanning both:
//!
//! **Modern**, from around 0.47 onward. Every line is an envelope:
//!
//! ```json
//! {"timestamp":"...","type":"session_meta","payload":{"id":"...","cwd":"..."}}
//! {"timestamp":"...","type":"response_item","payload":{"type":"message","role":"user"}}
//! ```
//!
//! **Legacy**, older files. No envelope at all: the first line *is* the
//! metadata, and later lines are bare records.
//!
//! ```json
//! {"id":"...","timestamp":"...","git":{},"instructions":null}
//! {"id":"...","type":"message","role":"user","content":[]}
//! ```
//!
//! A parser written against only the modern shape returns nothing at all for
//! the older half of a real history, silently. [`SessionEntry::entry_type`] is
//! `None` for a legacy line, and its `payload` is the whole line.
//!
//! Field-level drift is handled the same way: every metadata field is
//! optional, because older files carry no `cli_version`, no `cwd`, and a
//! different `instructions` key. [`SessionMeta::raw`] keeps whatever this
//! crate does not name.
//!
//! # Coverage of current history modes
//!
//! CLI 0.163.0 writes materialized, persistent `legacy` and `paginated` threads
//! under the layout above. Both use the modern envelope; the current
//! `history_mode: "legacy"` setting is distinct from the older bare-line format.
//! [`SessionMeta::raw`] preserves `history_mode`. Paginated `item_completed`
//! payloads are retained as written, including their nested item.
//!
//! This is a file reader, not the provider's logical thread-history view.
//! Discovery does not include archived sessions, ephemeral or unmaterialized
//! threads, or a server's other storage roots. It does not query the state
//! database. Entries are not normalized into turns, replayed, or deduplicated.
//! Envelope fields other than `timestamp`, `type`, and `payload` (including
//! paginated `ordinal`) are not exposed. Invalid JSON lines are skipped.
//!
//! For the provider's view, enable `app-server` and use
//! `AppServerHandle::request` with `thread/read`, `thread/turns/list`, or
//! `thread/items/list`. In an isolated 0.163.0 capture, `thread/read` and
//! cursor-paginated `thread/turns/list` worked for both materialized modes.
//! `thread/items/list` worked for paginated history and rejected legacy history.
//! Continue each method's opaque `nextCursor` until absent; do not derive a
//! cursor from rollout ordinals or treat one page as complete history.
//! Availability depends on CLI version, mode, and materialization. These probes
//! used failed offline turns and do not qualify every item kind or history
//! recovery scenario. Versioned fixture provenance ships in `tests/history/`.
//!
//! # Following a live session
//!
//! [`read_from`] continues from a [`Position`], and [`SessionEntry::record`]
//! gives typed access to the entries it returns.
//!
//! ```no_run
//! use codex_wrapper::history::{self, Continuation, Position, SessionRecord};
//!
//! # fn example(path: &std::path::Path, mut position: Position) -> codex_wrapper::Result<()> {
//! match history::read_from(path, &position)? {
//!     Continuation::Continued { entries, position: next } => {
//!         for entry in &entries {
//!             if let Some(SessionRecord::Prompt { text, .. }) = entry.record() {
//!                 println!("{text}");
//!             }
//!         }
//!         position = next;
//!     }
//!     // Not the file that was being followed, so start again.
//!     Continuation::Truncated | Continuation::Replaced => position = Position::default(),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Example
//!
//! ```no_run
//! use codex_wrapper::history::{self, SessionQuery};
//!
//! # fn example() -> codex_wrapper::Result<()> {
//! for session in history::list(&SessionQuery::new().after(2026, 8, 1))? {
//!     let log = history::read(&session.path)?;
//!     println!("{} in {:?}", session.id, log.meta.and_then(|m| m.cwd));
//! }
//! # Ok(())
//! # }
//! ```

use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use ruzstd::decoding::StreamingDecoder;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::{Error, Result};

/// A rollout file on disk, identified without opening it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionFile {
    /// Full path to the `.jsonl` or `.jsonl.zst` file.
    pub path: PathBuf,
    /// The session id, taken from the filename.
    ///
    /// This is the `thread_id` a resume takes.
    pub id: String,
    /// The date directory this file sits in, as `(year, month, day)`.
    pub date: (u16, u8, u8),
}

/// Git metadata recorded with a session.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct GitMeta {
    /// Commit the working tree was on.
    pub commit_hash: Option<String>,
    /// Branch name.
    pub branch: Option<String>,
    /// Remote URL.
    pub repository_url: Option<String>,
}

/// The session's opening metadata.
///
/// Every field is optional. Older files carry a different and smaller set, and
/// a reader that required any one of them would fail on a real history.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct SessionMeta {
    /// Session id as recorded inside the file.
    pub id: Option<String>,
    /// ISO 8601 start time.
    pub timestamp: Option<String>,
    /// Working directory the session ran in. Absent in legacy files.
    pub cwd: Option<PathBuf>,
    /// CLI version that wrote it. Absent in legacy files.
    pub cli_version: Option<String>,
    /// What started the session, for example `codex_cli_rs`.
    pub originator: Option<String>,
    /// Entry point, for example `cli`.
    pub source: Option<String>,
    /// Git metadata, when recorded.
    pub git: Option<GitMeta>,
    /// The metadata object as written, including keys not named above.
    pub raw: Value,
}

/// One line of a session log.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionEntry {
    /// Envelope timestamp, when the line has an envelope.
    pub timestamp: Option<String>,
    /// Envelope type: `event_msg`, `response_item`, `turn_context`, and so on.
    ///
    /// `None` for a legacy line, which has no envelope. In that case
    /// `payload` is the whole line.
    pub entry_type: Option<String>,
    /// The payload, or the whole line for a legacy entry.
    ///
    /// Modern envelope extensions, such as paginated `ordinal`, are not retained.
    pub payload: Value,
}

impl SessionEntry {
    /// The payload's own `type`, which is the useful discriminator.
    ///
    /// For a modern `event_msg` this is `agent_message`, `token_count`, and
    /// so on; for a `response_item`, `message` or `reasoning`.
    #[must_use]
    pub fn payload_type(&self) -> Option<&str> {
        self.payload.get("type")?.as_str()
    }

    /// What this entry means, or `None` for one this crate does not type.
    ///
    /// Always `None` for a legacy line without an envelope.
    #[must_use]
    pub fn record(&self) -> Option<SessionRecord> {
        let payload = &self.payload;
        let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
        let call = |name: String, input: &str| {
            Some(SessionRecord::ToolCall {
                call_id: string("call_id"),
                name,
                namespace: string("namespace"),
                input: payload.get(input).cloned().unwrap_or_default(),
            })
        };
        let result = |output: &str| {
            Some(SessionRecord::ToolResult {
                call_id: string("call_id"),
                output: payload.get(output)?.clone(),
            })
        };

        match (self.entry_type.as_deref()?, self.payload_type()) {
            ("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
            ("turn_context", _) => Some(SessionRecord::TurnContext {
                turn_id: string("turn_id"),
                cwd: string("cwd").map(PathBuf::from),
                model: string("model"),
            }),
            // A prompt is also written as a `response_item` message with the
            // user role, but so is the context the CLI adds by itself.
            ("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
                turn_id: None,
                text: string("message")?,
            }),
            ("event_msg", Some("item_completed")) => {
                let item = payload.get("item")?;
                if item.get("type")? != "UserMessage" {
                    return None;
                }
                let parts = item.get("content")?.as_array()?;
                Some(SessionRecord::Prompt {
                    turn_id: string("turn_id"),
                    text: parts
                        .iter()
                        .filter_map(|part| part.get("text")?.as_str())
                        .collect(),
                })
            }
            ("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
                turn_id: string("turn_id"),
                last_agent_message: string("last_agent_message"),
                error: payload
                    .pointer("/error/message")
                    .and_then(Value::as_str)
                    .map(str::to_string),
            }),
            ("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
                turn_id: string("turn_id"),
                reason: string("reason"),
            }),
            ("response_item", Some("function_call")) => call(string("name")?, "arguments"),
            ("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
            ("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
            ("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
            ("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
                result("output")
            }
            ("response_item", Some("tool_search_output")) => result("tools"),
            _ => None,
        }
    }
}

/// What a [`SessionEntry`] means.
///
/// The entry keeps the payload as written, for fields not named here.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SessionRecord {
    /// Session metadata. The first line of a session.
    Meta(Box<SessionMeta>),
    /// The settings a turn runs with.
    #[non_exhaustive]
    TurnContext {
        /// The turn.
        turn_id: Option<String>,
        /// Working directory of the turn.
        cwd: Option<PathBuf>,
        /// Model of the turn.
        model: Option<String>,
    },
    /// A message from the user.
    #[non_exhaustive]
    Prompt {
        /// The turn it belongs to. Not recorded in `legacy` history mode.
        turn_id: Option<String>,
        /// The text, without images or other attachments.
        text: String,
    },
    /// A tool call by the model.
    ///
    /// `local_shell_call` and `image_generation_call` are not typed, because
    /// there is no captured sample of them.
    #[non_exhaustive]
    ToolCall {
        /// Matches the [`ToolResult`](Self::ToolResult). A web search has
        /// neither.
        call_id: Option<String>,
        /// Tool name.
        name: String,
        /// Where the tool comes from, such as an MCP server.
        namespace: Option<String>,
        /// The input as written. A function call has a string that contains
        /// JSON.
        input: Value,
    },
    /// The result of a tool call.
    #[non_exhaustive]
    ToolResult {
        /// The call this answers.
        call_id: Option<String>,
        /// The output as written: a string, or an array of content parts.
        output: Value,
    },
    /// A turn ended by itself.
    #[non_exhaustive]
    TurnComplete {
        /// The turn.
        turn_id: Option<String>,
        /// The final answer.
        last_agent_message: Option<String>,
        /// Why the turn failed, if it did.
        error: Option<String>,
    },
    /// A turn was interrupted.
    #[non_exhaustive]
    TurnAborted {
        /// The turn.
        turn_id: Option<String>,
        /// The reason, such as `interrupted`.
        reason: Option<String>,
    },
}

/// How far a session log has been read. The default is the start.
///
/// Serialize it to continue in another process.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Position {
    offset: u64,
    fingerprint: u64,
}

impl Position {
    /// Bytes read so far, counted without compression.
    #[must_use]
    pub fn offset(&self) -> u64 {
        self.offset
    }
}

/// What [`read_from`] found.
#[derive(Debug, Clone, PartialEq)]
pub enum Continuation {
    /// The log continues from the given position.
    Continued {
        /// New entries, which may be none. Unlike [`SessionLog::entries`],
        /// they include the metadata line.
        entries: Vec<SessionEntry>,
        /// Where to continue.
        position: Position,
    },
    /// The log is now shorter than the given position.
    Truncated,
    /// The log no longer has the content that was read before.
    Replaced,
}

/// A parsed session log.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionLog {
    /// The file this came from.
    pub path: PathBuf,
    /// Opening metadata, if the file had any.
    pub meta: Option<SessionMeta>,
    /// Every line after the metadata, in order.
    pub entries: Vec<SessionEntry>,
}

/// Which sessions to list.
#[derive(Debug, Clone, Default)]
pub struct SessionQuery {
    after: Option<(u16, u8, u8)>,
    before: Option<(u16, u8, u8)>,
    cwd: Option<PathBuf>,
}

impl SessionQuery {
    /// Every session.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// On or after this date. Filters directories, without opening files.
    #[must_use]
    pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
        self.after = Some((year, month, day));
        self
    }

    /// On or before this date. Filters directories, without opening files.
    #[must_use]
    pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
        self.before = Some((year, month, day));
        self
    }

    /// Only sessions recorded as running in this directory.
    ///
    /// Unlike the date filters this one has to open each candidate file to
    /// read its metadata, and legacy files record no `cwd` so they never
    /// match.
    #[must_use]
    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.cwd = Some(cwd.into());
        self
    }

    fn matches_date(&self, date: (u16, u8, u8)) -> bool {
        self.after.is_none_or(|after| date >= after)
            && self.before.is_none_or(|before| date <= before)
    }
}

/// List sessions for the current environment, newest first.
///
/// Honors `CODEX_HOME`, defaulting to `~/.codex`.
pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
    let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
    list_in(home, query)
}

/// [`list`], but against an explicit `CODEX_HOME`.
///
/// A missing `sessions` directory yields an empty list rather than an error:
/// no sessions is a normal state.
pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
    let root = codex_home.as_ref().join("sessions");
    let mut found = Vec::new();

    for (date, day_dir) in date_dirs(&root) {
        if !query.matches_date(date) {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&day_dir) else {
            continue;
        };
        for entry in entries.filter_map(std::result::Result::ok) {
            let path = entry.path();
            let Some(id) = session_id_from_path(&path) else {
                continue;
            };
            // Both files exist while the CLI compresses or restores a session.
            if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
            {
                continue;
            }
            if let Some(wanted) = &query.cwd
                && !session_ran_in(&path, wanted)
            {
                continue;
            }
            found.push(SessionFile { path, id, date });
        }
    }

    // Newest first. The filename carries the timestamp, so it orders within a
    // day without opening anything.
    found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
    Ok(found)
}

/// Read and parse one session log.
pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
    let path = path.as_ref();
    let mut contents = Vec::new();
    open(path)
        .and_then(|log| log.reader()?.read_to_end(&mut contents))
        .map_err(|e| read_error(path, e))?;

    let mut meta = None;
    let mut entries = Vec::new();

    for value in values(&contents) {
        if meta.is_none()
            && let Some(found) = metadata(&value)
        {
            meta = Some(parse_meta(found));
        } else {
            entries.push(entry(value));
        }
    }

    Ok(SessionLog {
        path: path.to_path_buf(),
        meta,
        entries,
    })
}

/// Read the entries written to a session log since `position`.
///
/// An incomplete last line is left for the next call. Compressing or restoring
/// a session does not affect its position. A compressed log is decompressed
/// from the start on every call.
///
/// A replaced log is found by comparing up to 4 KiB at the start and before the
/// position, so a change between those is not reported.
pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
    let path = path.as_ref();
    open(path)
        .and_then(|log| match log {
            Log::Plain(file) => continue_from(file, position),
            Log::Compressed(_) => {
                let mut contents = Vec::new();
                log.reader()?.read_to_end(&mut contents)?;
                continue_from(Cursor::new(contents), position)
            }
        })
        .map_err(|e| read_error(path, e))
}

fn continue_from(mut log: impl Read + Seek, position: &Position) -> io::Result<Continuation> {
    if log.seek(SeekFrom::End(0))? < position.offset {
        return Ok(Continuation::Truncated);
    }
    if position.offset > 0 && fingerprint(&mut log, position.offset)? != position.fingerprint {
        return Ok(Continuation::Replaced);
    }

    let mut contents = Vec::new();
    log.seek(SeekFrom::Start(position.offset))?;
    log.read_to_end(&mut contents)?;
    let Some(end) = contents.iter().rposition(|byte| *byte == b'\n') else {
        return Ok(Continuation::Continued {
            entries: Vec::new(),
            position: position.clone(),
        });
    };
    let complete = &contents[..=end];
    let offset = position.offset + complete.len() as u64;
    Ok(Continuation::Continued {
        entries: values(complete).map(entry).collect(),
        position: Position {
            offset,
            fingerprint: fingerprint(&mut log, offset)?,
        },
    })
}

/// FNV-1a of the bytes at the start of a log and those before `offset`.
///
/// Positions are saved, so this has to give the same value in every release.
/// `DefaultHasher` does not promise that.
fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
    let window = offset.min(4096);
    let mut bytes = Vec::new();
    for start in [0, offset - window] {
        log.seek(SeekFrom::Start(start))?;
        log.by_ref().take(window).read_to_end(&mut bytes)?;
    }
    Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
    }))
}

enum Log {
    Plain(File),
    Compressed(File),
}

impl Log {
    fn reader(self) -> io::Result<Box<dyn Read>> {
        Ok(match self {
            Self::Plain(file) => Box::new(file),
            Self::Compressed(file) => {
                Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
            }
        })
    }
}

/// Open a log under either of its two names.
fn open(path: &Path) -> io::Result<Log> {
    let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
        Some(plain) => PathBuf::from(plain),
        None => path.to_path_buf(),
    };
    let mut compressed = plain.clone().into_os_string();
    compressed.push(".zst");

    let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
    match File::open(&plain) {
        Err(e) if missing(&e) => match File::open(compressed) {
            // Restored between the two attempts. The CLI writes the new file
            // before it removes the old one.
            Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
            file => file.map(Log::Compressed),
        },
        file => file.map(Log::Plain),
    }
}

fn read_error(path: &Path, source: io::Error) -> Error {
    Error::Io {
        message: format!("failed to read {}: {source}", path.display()),
        source,
        working_dir: None,
    }
}

/// The JSON value of each line.
///
/// A line that will not parse is skipped rather than failing the read. These
/// files are appended to by a long-running process and a truncated tail should
/// not cost the caller the rest of the session.
fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
    contents
        .split(|byte| *byte == b'\n')
        .filter_map(|line| serde_json::from_slice(line).ok())
}

/// The metadata object, if the line holds one.
///
/// A legacy metadata line is recognised by carrying an id and no record type of
/// its own.
fn metadata(value: &Value) -> Option<&Value> {
    match envelope(value) {
        Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
        None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
    }
}

fn entry(value: Value) -> SessionEntry {
    match envelope(&value) {
        Some((timestamp, entry_type, payload)) => SessionEntry {
            timestamp: timestamp.map(str::to_string),
            entry_type: Some(entry_type.to_string()),
            payload: payload.clone(),
        },
        None => SessionEntry {
            timestamp: value
                .get("timestamp")
                .and_then(Value::as_str)
                .map(str::to_string),
            entry_type: None,
            payload: value,
        },
    }
}

/// `(timestamp, type, payload)` for a modern envelope, `None` for a legacy
/// line.
fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
    let payload = value.get("payload")?;
    let entry_type = value.get("type")?.as_str()?;
    Some((
        value.get("timestamp").and_then(Value::as_str),
        entry_type,
        payload,
    ))
}

fn parse_meta(value: &Value) -> SessionMeta {
    let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
    SessionMeta {
        id: string("id").or_else(|| string("session_id")),
        timestamp: string("timestamp"),
        cwd: string("cwd").map(PathBuf::from),
        cli_version: string("cli_version"),
        originator: string("originator"),
        source: string("source"),
        git: value.get("git").and_then(|git| {
            let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
            let meta = GitMeta {
                commit_hash: get("commit_hash"),
                branch: get("branch"),
                repository_url: get("repository_url"),
            };
            (meta != GitMeta::default()).then_some(meta)
        }),
        raw: value.clone(),
    }
}

/// `(year, month, day)` directories under the sessions root.
fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
    let mut out = Vec::new();
    for year in numeric_children(root) {
        for month in numeric_children(&year.1) {
            for day in numeric_children(&month.1) {
                out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
            }
        }
    }
    out
}

/// Child directories whose names are numbers, with the parsed value.
fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .filter_map(std::result::Result::ok)
        .filter_map(|entry| {
            let name = entry.file_name().into_string().ok()?;
            let value = name.parse::<u32>().ok()?;
            entry.path().is_dir().then(|| (value, entry.path()))
        })
        .collect()
}

/// The thread id in `rollout-<ISO8601>-<thread_id>.jsonl`, compressed or not.
///
/// The timestamp itself contains dashes, so this takes the tail rather than
/// splitting: a uuid is five dash-separated groups. A reverted thread's name
/// has `_<rollout_id>` after the thread id, which a resume does not take.
fn session_id_from_path(path: &Path) -> Option<String> {
    let name = path.file_name()?.to_str()?;
    let name = name.strip_suffix(".zst").unwrap_or(name);
    let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
    let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
    let parts: Vec<&str> = stem.split('-').collect();
    if parts.len() < 5 {
        return None;
    }
    Some(parts[parts.len() - 5..].join("-"))
}

/// Whether a session's metadata records it as having run in `wanted`.
fn session_ran_in(path: &Path, wanted: &Path) -> bool {
    let Ok(reader) = open(path).and_then(Log::reader) else {
        return false;
    };
    let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
    let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
        return false;
    };
    let Ok(value) = serde_json::from_str::<Value>(&first) else {
        return false;
    };
    let meta = value.get("payload").unwrap_or(&value);
    meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn temp_home(label: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "codex-wrapper-history-{}-{label}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        dir
    }

    fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
        let dir = home
            .join("sessions")
            .join(format!("{:04}", date.0))
            .join(format!("{:02}", date.1))
            .join(format!("{:02}", date.2));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(name);
        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
        path
    }

    /// Transcribed from a real 2026 rollout: envelope of timestamp, type and
    /// payload on every line.
    const MODERN: &[&str] = &[
        r#"{"timestamp":"2026-08-06T10:11:24Z","type":"session_meta","payload":{"session_id":"019fd80e-eb27-70e3-ad2e-ed939930901a","id":"019fd80e-eb27-70e3-ad2e-ed939930901a","timestamp":"2026-08-06T10:11:24Z","cwd":"/repo","originator":"codex_cli_rs","cli_version":"0.145.0","source":"cli","git":{"commit_hash":"abc123","branch":"main","repository_url":"git@example.com:o/r.git"}}}"#,
        r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
        r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
        r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
    ];

    /// Transcribed from a real 2025-09 rollout: no envelope at all.
    const LEGACY: &[&str] = &[
        r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
        r#"{"record_type":"state"}"#,
        r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
    ];

    #[test]
    fn discovers_both_current_history_modes_and_preserves_their_payloads() {
        let home = temp_home("current-history-modes");
        for (mode, fixture, id, item_type) in [
            (
                "legacy",
                include_str!("../tests/history/0.163.0-legacy.jsonl"),
                "00000000-0000-4000-8000-000000000001",
                "user_message",
            ),
            (
                "paginated",
                include_str!("../tests/history/0.163.0-paginated.jsonl"),
                "00000000-0000-4000-8000-000000000002",
                "item_completed",
            ),
        ] {
            let path = write_session(
                &home,
                (2026, 10, 20),
                &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
                &fixture.lines().collect::<Vec<_>>(),
            );
            let log = read(&path).unwrap();
            let meta = log.meta.unwrap();
            assert_eq!(meta.id.as_deref(), Some(id));
            assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
            assert_eq!(meta.raw["history_mode"], mode);
            assert_eq!(log.entries.len(), 4);
            let captured: Vec<serde_json::Value> = fixture
                .lines()
                .map(|line| serde_json::from_str(line).unwrap())
                .collect();
            for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
                assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
                assert_eq!(entry.payload, envelope["payload"]);
            }
            assert_eq!(log.entries[0].payload_type(), Some(item_type));
            assert_eq!(log.entries[2].payload_type(), Some(item_type));
            if mode == "paginated" {
                assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
                assert_eq!(
                    log.entries[0].payload["item"]["content"][0]["text"],
                    "synthetic offline history fixture"
                );
            }
        }
        let sessions = list_in(
            &home,
            &SessionQuery::new()
                .cwd("/fixture/workspace")
                .after(2026, 10, 20),
        )
        .unwrap();
        assert_eq!(sessions.len(), 2);
        std::fs::remove_dir_all(home).unwrap();
    }

    /// Moving the tested range needs a rollout from the new version. See
    /// `tests/history/README.md`.
    #[test]
    fn types_the_records_of_every_tested_cli_version() {
        use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};

        for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
            let path = format!(
                "{}/tests/history/{version}.jsonl",
                env!("CARGO_MANIFEST_DIR")
            );
            let records: Vec<String> = follow(Path::new(&path), &Position::default())
                .0
                .iter()
                .filter_map(SessionEntry::record)
                .map(|record| match record {
                    SessionRecord::Meta(meta) => {
                        assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
                        format!("meta {}", meta.cli_version.unwrap())
                    }
                    SessionRecord::TurnContext {
                        turn_id,
                        cwd,
                        model,
                    } => {
                        assert!(turn_id.is_some());
                        format!("context {} {}", cwd.unwrap().display(), model.unwrap())
                    }
                    SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
                    SessionRecord::ToolCall {
                        call_id,
                        name,
                        input,
                        ..
                    } => {
                        assert!(input.to_string().contains("fixture"));
                        format!("call {name} {call_id:?}")
                    }
                    SessionRecord::ToolResult { call_id, output } => {
                        assert!(output.is_string() || output.is_array());
                        format!("result {}", call_id.unwrap())
                    }
                    SessionRecord::TurnComplete {
                        turn_id,
                        last_agent_message,
                        error,
                    } => {
                        assert!(turn_id.is_some());
                        format!("complete {last_agent_message:?} {error:?}")
                    }
                    SessionRecord::TurnAborted { turn_id, reason } => {
                        assert!(turn_id.is_some());
                        format!("aborted {}", reason.unwrap())
                    }
                })
                .collect();
            assert_eq!(
                records,
                [
                    format!("meta {version}").as_str(),
                    "context /fixture/workspace gpt-5.2-codex",
                    "prompt first prompt",
                    r#"call exec_command Some("call_1")"#,
                    "result call_1",
                    r#"call apply_patch Some("call_2")"#,
                    "result call_2",
                    r#"call tool_search Some("call_3")"#,
                    "result call_3",
                    "call web_search None",
                    r#"complete Some("fixture answer") None"#,
                    "context /fixture/workspace gpt-5.2-codex",
                    "prompt interrupted prompt",
                    "aborted interrupted",
                ],
                "{version}"
            );
        }
    }

    /// The CLI leaves `action` out when the provider did not send one.
    #[test]
    fn a_web_search_without_an_action_is_still_a_call() {
        let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
        let record = values(line).map(entry).next().unwrap().record();
        assert!(matches!(
            record,
            Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
        ));
    }

    #[test]
    fn a_failed_turn_has_its_error() {
        let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
        let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
            let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
                return None;
            };
            error
        });
        assert!(failed.unwrap().contains("intentional offline fixture"));
    }

    fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
        match read_from(path, position).unwrap() {
            Continuation::Continued { entries, position } => (entries, position),
            other => panic!("expected the log to continue, got {other:?}"),
        }
    }

    #[test]
    fn continues_after_the_last_complete_line() {
        let home = temp_home("continue");
        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
        let (entries, position) = follow(&path, &Position::default());
        assert_eq!(entries.len(), 2);
        assert_eq!(
            position.offset(),
            std::fs::metadata(&path).unwrap().len(),
            "everything was read"
        );

        // Cut inside a character, as a write in progress can be.
        let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
        let cut = line.find('é').unwrap() + 1;
        let mut contents = std::fs::read(&path).unwrap();
        contents.extend(&line.as_bytes()[..cut]);
        std::fs::write(&path, &contents).unwrap();
        assert_eq!(follow(&path, &position), (vec![], position.clone()));

        contents.extend(&line.as_bytes()[cut..]);
        contents.push(b'\n');
        std::fs::write(&path, &contents).unwrap();
        let saved = serde_json::to_string(&position).unwrap();
        let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0].record(),
            Some(SessionRecord::Prompt {
                turn_id: None,
                text: "é".into()
            })
        );
    }

    #[test]
    fn reports_a_truncated_or_replaced_log() {
        let home = temp_home("replaced");
        let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
        let (_, position) = follow(&path, &Position::default());

        let contents = std::fs::read_to_string(&path).unwrap();
        std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
        assert_eq!(
            read_from(&path, &position).unwrap(),
            Continuation::Replaced,
            "same length, another session"
        );

        std::fs::write(&path, MODERN[0]).unwrap();
        assert_eq!(
            read_from(&path, &position).unwrap(),
            Continuation::Truncated
        );
    }

    #[test]
    fn a_compressed_session_is_the_same_session() {
        use ruzstd::encoding::{CompressionLevel, compress_to_vec};

        let home = temp_home("compressed");
        let path = write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );
        let query = SessionQuery::new().cwd("/repo");
        let log = read(&path).unwrap();
        let (_, position) = follow(&path, &Position::default());

        let compressed = path.with_extension("jsonl.zst");
        let contents = std::fs::read(&path).unwrap();
        std::fs::write(
            &compressed,
            compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
        )
        .unwrap();
        let listed = list_in(&home, &query).unwrap();
        assert_eq!(listed.len(), 1, "one session while both files exist");
        assert_eq!(listed[0].path, path);

        std::fs::remove_file(&path).unwrap();
        let listed = list_in(&home, &query).unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].path, compressed);
        assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
        assert_eq!(read(&compressed).unwrap().entries, log.entries);
        // A caller that still has the old path.
        assert_eq!(read(&path).unwrap(), log);
        assert_eq!(follow(&path, &position), (vec![], position.clone()));

        // Restored, for a caller that has the compressed path.
        std::fs::write(&path, &contents).unwrap();
        std::fs::remove_file(&compressed).unwrap();
        assert_eq!(follow(&compressed, &position), (vec![], position));
    }

    #[test]
    fn a_missing_sessions_directory_is_empty_not_an_error() {
        let home = temp_home("empty");
        assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
    }

    #[test]
    fn lists_sessions_newest_first() {
        let home = temp_home("order");
        write_session(
            &home,
            (2026, 8, 1),
            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );
        write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );
        write_session(
            &home,
            (2025, 9, 1),
            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
            LEGACY,
        );

        let found = list_in(&home, &SessionQuery::new()).unwrap();
        let dates: Vec<_> = found.iter().map(|s| s.date).collect();
        assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
        assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
    }

    #[test]
    fn date_filters_narrow_the_listing() {
        let home = temp_home("dates");
        write_session(
            &home,
            (2026, 8, 1),
            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );
        write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );

        let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
        assert_eq!(after.len(), 1);
        assert_eq!(after[0].date, (2026, 8, 6));

        let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
        assert_eq!(before.len(), 1);
        assert_eq!(before[0].date, (2026, 8, 1));

        let between = list_in(
            &home,
            &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
        )
        .unwrap();
        assert_eq!(between.len(), 2);
    }

    #[test]
    fn cwd_filter_matches_the_recorded_directory() {
        let home = temp_home("cwd");
        write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );

        assert_eq!(
            list_in(&home, &SessionQuery::new().cwd("/repo"))
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
                .unwrap()
                .len(),
            0
        );
    }

    #[test]
    fn reads_a_modern_session() {
        let home = temp_home("modern");
        let path = write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
            MODERN,
        );

        let log = read(&path).unwrap();
        let meta = log.meta.unwrap();
        assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
        assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
        assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));

        // The metadata line is not also an entry.
        assert_eq!(log.entries.len(), 3);
        assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
        assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
    }

    /// The whole point of the two-generation handling: a parser written for
    /// the modern envelope returns nothing here, silently.
    #[test]
    fn reads_a_legacy_session_without_an_envelope() {
        let home = temp_home("legacy");
        let path = write_session(
            &home,
            (2025, 9, 1),
            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
            LEGACY,
        );

        let log = read(&path).unwrap();
        let meta = log.meta.expect("the first line is the metadata");
        assert_eq!(
            meta.id.as_deref(),
            Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
        );
        assert_eq!(meta.cli_version, None, "legacy files record no version");
        assert_eq!(meta.cwd, None, "legacy files record no cwd");
        assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));

        assert_eq!(log.entries.len(), 2);
        // No envelope, so the whole line is the payload.
        assert_eq!(log.entries[0].entry_type, None);
        assert_eq!(log.entries[1].payload_type(), Some("message"));
    }

    /// These files are appended to by a running process, so a truncated last
    /// line must not cost the caller the rest of the session.
    #[test]
    fn a_truncated_tail_does_not_lose_the_rest() {
        let home = temp_home("truncated");
        let mut lines = MODERN.to_vec();
        lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
        let path = write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
            &lines,
        );

        let log = read(&path).unwrap();
        assert!(log.meta.is_some());
        assert_eq!(log.entries.len(), 3, "the good lines survive");
    }

    /// The timestamp in the filename also contains dashes, so the id has to be
    /// taken from the tail rather than by splitting on the first one.
    #[test]
    fn session_id_comes_from_the_uuid_tail() {
        assert_eq!(
            session_id_from_path(Path::new(
                "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
            )),
            Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
        );
        assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
    }

    /// Name format from `codex-rs/rollout/src/rollout_file_name.rs` at
    /// `rust-v0.167.0`.
    #[test]
    fn a_reverted_thread_is_identified_by_its_thread_id() {
        for extension in ["jsonl", "jsonl.zst"] {
            let name = format!(
                "/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
            );
            assert_eq!(
                session_id_from_path(Path::new(&name)).as_deref(),
                Some("aaaaaaaa-1111-2222-3333-444444444444"),
                "{extension}"
            );
        }
    }

    #[test]
    fn unknown_entry_types_are_kept_rather_than_dropped() {
        let home = temp_home("unknown");
        let path = write_session(
            &home,
            (2026, 8, 6),
            "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
            &[
                MODERN[0],
                r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
            ],
        );

        let log = read(&path).unwrap();
        assert_eq!(log.entries.len(), 1);
        assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
        assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
    }
}