Skip to main content

codex_wrapper/
history.rs

1//! Read-side access to the CLI's on-disk session logs.
2//!
3//! Read-only. Mutation goes through the CLI, via
4//! [`ArchiveCommand`](crate::ArchiveCommand) and
5//! [`DeleteCommand`](crate::DeleteCommand).
6//!
7//! # On-disk layout
8//!
9//! ```text
10//! $CODEX_HOME/sessions/<YYYY>/<MM>/<DD>/rollout-<ISO8601>-<uuid>.jsonl
11//! ```
12//!
13//! A reverted thread's file is named `rollout-<ISO8601>-<uuid>_<uuid>.jsonl`:
14//! the thread id, then the id of that rollout.
15//!
16//! The CLI compresses older sessions to `.jsonl.zst`, and restores the plain
17//! file when one is resumed. Either path reads whichever of the two exists.
18//!
19//! The date partitioning is why [`SessionQuery::after`] and
20//! [`SessionQuery::before`] are cheap: they filter directories, without opening
21//! a file.
22//!
23//! # Two envelope generations
24//!
25//! A real machine holds sessions written by many CLI versions, and the line
26//! format changed. Both were found on one machine while writing this, 205
27//! files spanning both:
28//!
29//! **Modern**, from around 0.47 onward. Every line is an envelope:
30//!
31//! ```json
32//! {"timestamp":"...","type":"session_meta","payload":{"id":"...","cwd":"..."}}
33//! {"timestamp":"...","type":"response_item","payload":{"type":"message","role":"user"}}
34//! ```
35//!
36//! **Legacy**, older files. No envelope at all: the first line *is* the
37//! metadata, and later lines are bare records.
38//!
39//! ```json
40//! {"id":"...","timestamp":"...","git":{},"instructions":null}
41//! {"id":"...","type":"message","role":"user","content":[]}
42//! ```
43//!
44//! A parser written against only the modern shape returns nothing at all for
45//! the older half of a real history, silently. [`SessionEntry::entry_type`] is
46//! `None` for a legacy line, and its `payload` is the whole line.
47//!
48//! Field-level drift is handled the same way: every metadata field is
49//! optional, because older files carry no `cli_version`, no `cwd`, and a
50//! different `instructions` key. [`SessionMeta::raw`] keeps whatever this
51//! crate does not name.
52//!
53//! # Coverage of current history modes
54//!
55//! CLI 0.163.0 writes materialized, persistent `legacy` and `paginated` threads
56//! under the layout above. Both use the modern envelope; the current
57//! `history_mode: "legacy"` setting is distinct from the older bare-line format.
58//! [`SessionMeta::raw`] preserves `history_mode`. Paginated `item_completed`
59//! payloads are retained as written, including their nested item.
60//!
61//! This is a file reader, not the provider's logical thread-history view.
62//! Discovery does not include archived sessions, ephemeral or unmaterialized
63//! threads, or a server's other storage roots. It does not query the state
64//! database. Entries are not normalized into turns, replayed, or deduplicated.
65//! Envelope fields other than `timestamp`, `type`, and `payload` (including
66//! paginated `ordinal`) are not exposed. Invalid JSON lines are skipped.
67//!
68//! For the provider's view, enable `app-server` and use
69//! `AppServerHandle::request` with `thread/read`, `thread/turns/list`, or
70//! `thread/items/list`. In an isolated 0.163.0 capture, `thread/read` and
71//! cursor-paginated `thread/turns/list` worked for both materialized modes.
72//! `thread/items/list` worked for paginated history and rejected legacy history.
73//! Continue each method's opaque `nextCursor` until absent; do not derive a
74//! cursor from rollout ordinals or treat one page as complete history.
75//! Availability depends on CLI version, mode, and materialization. These probes
76//! used failed offline turns and do not qualify every item kind or history
77//! recovery scenario. Versioned fixture provenance ships in `tests/history/`.
78//!
79//! # Following a live session
80//!
81//! [`read_from`] continues from a [`Position`], and [`SessionEntry::record`]
82//! gives typed access to the entries it returns.
83//!
84//! ```no_run
85//! use codex_wrapper::history::{self, Continuation, Position, SessionRecord};
86//!
87//! # fn example(path: &std::path::Path, mut position: Position) -> codex_wrapper::Result<()> {
88//! match history::read_from(path, &position)? {
89//!     Continuation::Continued { entries, position: next } => {
90//!         for entry in &entries {
91//!             if let Some(SessionRecord::Prompt { text, .. }) = entry.record() {
92//!                 println!("{text}");
93//!             }
94//!         }
95//!         position = next;
96//!     }
97//!     // Not the file that was being followed, so start again.
98//!     Continuation::Truncated | Continuation::Replaced => position = Position::default(),
99//! }
100//! # Ok(())
101//! # }
102//! ```
103//!
104//! To attach to a long session, start at [`Position::before_end`] and use
105//! [`read_chunk`], which can limit a read and gives the offset of each entry.
106//!
107//! # Example
108//!
109//! ```no_run
110//! use codex_wrapper::history::{self, SessionQuery};
111//!
112//! # fn example() -> codex_wrapper::Result<()> {
113//! for session in history::list(&SessionQuery::new().after(2026, 8, 1))? {
114//!     let log = history::read(&session.path)?;
115//!     println!("{} in {:?}", session.id, log.meta.and_then(|m| m.cwd));
116//! }
117//! # Ok(())
118//! # }
119//! ```
120
121use std::fs::File;
122use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
123use std::path::{Path, PathBuf};
124
125use ruzstd::decoding::StreamingDecoder;
126use serde::{Deserialize, Serialize};
127use serde_json::Value;
128
129use crate::error::{Error, Result};
130
131/// A rollout file on disk, identified without opening it.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct SessionFile {
134    /// Full path to the `.jsonl` or `.jsonl.zst` file.
135    pub path: PathBuf,
136    /// The session id, taken from the filename.
137    ///
138    /// This is the `thread_id` a resume takes.
139    pub id: String,
140    /// The date directory this file sits in, as `(year, month, day)`.
141    pub date: (u16, u8, u8),
142}
143
144/// Git metadata recorded with a session.
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146#[non_exhaustive]
147pub struct GitMeta {
148    /// Commit the working tree was on.
149    pub commit_hash: Option<String>,
150    /// Branch name.
151    pub branch: Option<String>,
152    /// Remote URL.
153    pub repository_url: Option<String>,
154}
155
156/// The session's opening metadata.
157///
158/// Every field is optional. Older files carry a different and smaller set, and
159/// a reader that required any one of them would fail on a real history.
160#[derive(Debug, Clone, Default, PartialEq)]
161#[non_exhaustive]
162pub struct SessionMeta {
163    /// Session id as recorded inside the file.
164    pub id: Option<String>,
165    /// ISO 8601 start time.
166    pub timestamp: Option<String>,
167    /// Working directory the session ran in. Absent in legacy files.
168    pub cwd: Option<PathBuf>,
169    /// CLI version that wrote it. Absent in legacy files.
170    pub cli_version: Option<String>,
171    /// What started the session, for example `codex_cli_rs`.
172    pub originator: Option<String>,
173    /// Entry point, for example `cli`.
174    pub source: Option<String>,
175    /// Git metadata, when recorded.
176    pub git: Option<GitMeta>,
177    /// The metadata object as written, including keys not named above.
178    pub raw: Value,
179}
180
181/// One line of a session log.
182#[derive(Debug, Clone, PartialEq)]
183pub struct SessionEntry {
184    /// Envelope timestamp, when the line has an envelope.
185    pub timestamp: Option<String>,
186    /// Envelope type: `event_msg`, `response_item`, `turn_context`, and so on.
187    ///
188    /// `None` for a legacy line, which has no envelope. In that case
189    /// `payload` is the whole line.
190    pub entry_type: Option<String>,
191    /// The payload, or the whole line for a legacy entry.
192    ///
193    /// Modern envelope extensions, such as paginated `ordinal`, are not retained.
194    pub payload: Value,
195}
196
197impl SessionEntry {
198    /// The payload's own `type`, which is the useful discriminator.
199    ///
200    /// For a modern `event_msg` this is `agent_message`, `token_count`, and
201    /// so on; for a `response_item`, `message` or `reasoning`.
202    #[must_use]
203    pub fn payload_type(&self) -> Option<&str> {
204        self.payload.get("type")?.as_str()
205    }
206
207    /// What this entry means, or `None` for one this crate does not type.
208    ///
209    /// Always `None` for a legacy line without an envelope.
210    #[must_use]
211    pub fn record(&self) -> Option<SessionRecord> {
212        let payload = &self.payload;
213        let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
214        let call = |name: String, input: &str| {
215            Some(SessionRecord::ToolCall {
216                call_id: string("call_id"),
217                name,
218                namespace: string("namespace"),
219                input: payload.get(input).cloned().unwrap_or_default(),
220            })
221        };
222        let result = |output: &str| {
223            Some(SessionRecord::ToolResult {
224                call_id: string("call_id"),
225                output: payload.get(output)?.clone(),
226            })
227        };
228
229        match (self.entry_type.as_deref()?, self.payload_type()) {
230            ("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
231            ("turn_context", _) => Some(SessionRecord::TurnContext {
232                turn_id: string("turn_id"),
233                cwd: string("cwd").map(PathBuf::from),
234                model: string("model"),
235            }),
236            // A prompt is also written as a `response_item` message with the
237            // user role, but so is the context the CLI adds by itself.
238            ("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
239                turn_id: None,
240                text: string("message")?,
241            }),
242            ("event_msg", Some("item_completed")) => {
243                let item = payload.get("item")?;
244                if item.get("type")? != "UserMessage" {
245                    return None;
246                }
247                let parts = item.get("content")?.as_array()?;
248                Some(SessionRecord::Prompt {
249                    turn_id: string("turn_id"),
250                    text: parts
251                        .iter()
252                        .filter_map(|part| part.get("text")?.as_str())
253                        .collect(),
254                })
255            }
256            ("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
257                turn_id: string("turn_id"),
258                last_agent_message: string("last_agent_message"),
259                error: payload
260                    .pointer("/error/message")
261                    .and_then(Value::as_str)
262                    .map(str::to_string),
263            }),
264            ("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
265                turn_id: string("turn_id"),
266                reason: string("reason"),
267            }),
268            ("response_item", Some("function_call")) => call(string("name")?, "arguments"),
269            ("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
270            ("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
271            ("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
272            ("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
273                result("output")
274            }
275            ("response_item", Some("tool_search_output")) => result("tools"),
276            _ => None,
277        }
278    }
279}
280
281/// What a [`SessionEntry`] means.
282///
283/// The entry keeps the payload as written, for fields not named here.
284#[derive(Debug, Clone, PartialEq)]
285#[non_exhaustive]
286pub enum SessionRecord {
287    /// Session metadata. The first line of a session.
288    Meta(Box<SessionMeta>),
289    /// The settings a turn runs with.
290    #[non_exhaustive]
291    TurnContext {
292        /// The turn.
293        turn_id: Option<String>,
294        /// Working directory of the turn.
295        cwd: Option<PathBuf>,
296        /// Model of the turn.
297        model: Option<String>,
298    },
299    /// A message from the user.
300    #[non_exhaustive]
301    Prompt {
302        /// The turn it belongs to. Not recorded in `legacy` history mode.
303        turn_id: Option<String>,
304        /// The text, without images or other attachments.
305        text: String,
306    },
307    /// A tool call by the model.
308    ///
309    /// `local_shell_call` and `image_generation_call` are not typed, because
310    /// there is no captured sample of them.
311    #[non_exhaustive]
312    ToolCall {
313        /// Matches the [`ToolResult`](Self::ToolResult). A web search has
314        /// neither.
315        call_id: Option<String>,
316        /// Tool name.
317        name: String,
318        /// Where the tool comes from, such as an MCP server.
319        namespace: Option<String>,
320        /// The input as written. A function call has a string that contains
321        /// JSON.
322        input: Value,
323    },
324    /// The result of a tool call.
325    #[non_exhaustive]
326    ToolResult {
327        /// The call this answers.
328        call_id: Option<String>,
329        /// The output as written: a string, or an array of content parts.
330        output: Value,
331    },
332    /// A turn ended by itself.
333    #[non_exhaustive]
334    TurnComplete {
335        /// The turn.
336        turn_id: Option<String>,
337        /// The final answer.
338        last_agent_message: Option<String>,
339        /// Why the turn failed, if it did.
340        error: Option<String>,
341    },
342    /// A turn was interrupted.
343    #[non_exhaustive]
344    TurnAborted {
345        /// The turn.
346        turn_id: Option<String>,
347        /// The reason, such as `interrupted`.
348        reason: Option<String>,
349    },
350}
351
352/// How far a session log has been read. The default is the start.
353///
354/// Serialize it to continue in another process.
355#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
356pub struct Position {
357    offset: u64,
358    fingerprint: u64,
359}
360
361impl Position {
362    /// The position at a byte offset, counted without compression, such as
363    /// [`ChunkEntry::offset`].
364    ///
365    /// From a place inside an entry, reading starts at the next one. Reading
366    /// from an offset past the end gives `Truncated`, or `Replaced` if the log
367    /// has grown past it since.
368    ///
369    /// This does not check that the log is the one the offset came from. Save
370    /// the position instead of the offset to have later reads check that.
371    ///
372    /// A compressed log is decompressed to find the position.
373    pub fn at_offset(path: impl AsRef<Path>, offset: u64) -> Result<Self> {
374        Self::locate(path.as_ref(), |_| offset)
375    }
376
377    /// The position `bytes` before the end of a log, counted without
378    /// compression, or the start of a shorter log.
379    ///
380    /// From a place inside an entry, reading starts at the next one, so there
381    /// may be nothing to read if the last entry is longer than `bytes`.
382    ///
383    /// A compressed log is decompressed to find the position.
384    pub fn before_end(path: impl AsRef<Path>, bytes: u64) -> Result<Self> {
385        Self::locate(path.as_ref(), |end| end.saturating_sub(bytes))
386    }
387
388    fn locate(path: &Path, offset: impl FnOnce(u64) -> u64) -> Result<Self> {
389        open(path)
390            .and_then(|log| {
391                let mut log = log.seekable()?;
392                let offset = offset(log.seek(SeekFrom::End(0))?);
393                Self::new(&mut log, offset)
394            })
395            .map_err(|e| read_error(path, e))
396    }
397
398    fn new(log: &mut (impl Read + Seek), offset: u64) -> io::Result<Self> {
399        Ok(Self {
400            offset,
401            fingerprint: fingerprint(log, offset)?,
402        })
403    }
404
405    /// Where reading continues, counted in bytes without compression.
406    #[must_use]
407    pub fn offset(&self) -> u64 {
408        self.offset
409    }
410}
411
412/// What [`read_from`] found.
413#[derive(Debug, Clone, PartialEq)]
414pub enum Continuation {
415    /// The log continues from the given position.
416    Continued {
417        /// New entries, which may be none. Unlike [`SessionLog::entries`],
418        /// they include the metadata line.
419        entries: Vec<SessionEntry>,
420        /// Where to continue.
421        position: Position,
422    },
423    /// The log is now shorter than the given position.
424    Truncated,
425    /// The log no longer has the content that was read before.
426    Replaced,
427}
428
429/// What [`read_chunk`] found.
430#[derive(Debug, Clone, PartialEq)]
431pub enum Chunk {
432    /// The log continues from the given position.
433    Continued {
434        /// New entries, including the metadata line. There are none only when
435        /// the end of the log was reached.
436        entries: Vec<ChunkEntry>,
437        /// Where to continue.
438        position: Position,
439    },
440    /// The log is now shorter than the given position.
441    Truncated,
442    /// The log no longer has the content that was read before.
443    Replaced,
444}
445
446/// An entry and its place in the log.
447#[derive(Debug, Clone, PartialEq)]
448#[non_exhaustive]
449pub struct ChunkEntry {
450    /// Where the entry starts, counted in bytes without compression.
451    ///
452    /// [`Position::at_offset`] reads from here again.
453    pub offset: u64,
454    /// The entry.
455    pub entry: SessionEntry,
456}
457
458/// A parsed session log.
459#[derive(Debug, Clone, PartialEq)]
460pub struct SessionLog {
461    /// The file this came from.
462    pub path: PathBuf,
463    /// Opening metadata, if the file had any.
464    pub meta: Option<SessionMeta>,
465    /// Every line after the metadata, in order.
466    pub entries: Vec<SessionEntry>,
467}
468
469/// Which sessions to list.
470#[derive(Debug, Clone, Default)]
471pub struct SessionQuery {
472    after: Option<(u16, u8, u8)>,
473    before: Option<(u16, u8, u8)>,
474    cwd: Option<PathBuf>,
475}
476
477impl SessionQuery {
478    /// Every session.
479    #[must_use]
480    pub fn new() -> Self {
481        Self::default()
482    }
483
484    /// On or after this date. Filters directories, without opening files.
485    #[must_use]
486    pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
487        self.after = Some((year, month, day));
488        self
489    }
490
491    /// On or before this date. Filters directories, without opening files.
492    #[must_use]
493    pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
494        self.before = Some((year, month, day));
495        self
496    }
497
498    /// Only sessions recorded as running in this directory.
499    ///
500    /// Unlike the date filters this one has to open each candidate file to
501    /// read its metadata, and legacy files record no `cwd` so they never
502    /// match.
503    #[must_use]
504    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
505        self.cwd = Some(cwd.into());
506        self
507    }
508
509    fn matches_date(&self, date: (u16, u8, u8)) -> bool {
510        self.after.is_none_or(|after| date >= after)
511            && self.before.is_none_or(|before| date <= before)
512    }
513}
514
515/// List sessions for the current environment, newest first.
516///
517/// Honors `CODEX_HOME`, defaulting to `~/.codex`.
518pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
519    let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
520    list_in(home, query)
521}
522
523/// [`list`], but against an explicit `CODEX_HOME`.
524///
525/// A missing `sessions` directory yields an empty list rather than an error:
526/// no sessions is a normal state.
527pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
528    let root = codex_home.as_ref().join("sessions");
529    let mut found = Vec::new();
530
531    for (date, day_dir) in date_dirs(&root) {
532        if !query.matches_date(date) {
533            continue;
534        }
535        let Ok(entries) = std::fs::read_dir(&day_dir) else {
536            continue;
537        };
538        for entry in entries.filter_map(std::result::Result::ok) {
539            let path = entry.path();
540            let Some(id) = session_id_from_path(&path) else {
541                continue;
542            };
543            // Both files exist while the CLI compresses or restores a session.
544            if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
545            {
546                continue;
547            }
548            if let Some(wanted) = &query.cwd
549                && !session_ran_in(&path, wanted)
550            {
551                continue;
552            }
553            found.push(SessionFile { path, id, date });
554        }
555    }
556
557    // Newest first. The filename carries the timestamp, so it orders within a
558    // day without opening anything.
559    found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
560    Ok(found)
561}
562
563/// Read and parse one session log.
564pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
565    let path = path.as_ref();
566    let mut contents = Vec::new();
567    open(path)
568        .and_then(|log| log.reader()?.read_to_end(&mut contents))
569        .map_err(|e| read_error(path, e))?;
570
571    let mut meta = None;
572    let mut entries = Vec::new();
573
574    for value in values(&contents) {
575        if meta.is_none()
576            && let Some(found) = metadata(&value)
577        {
578            meta = Some(parse_meta(found));
579        } else {
580            entries.push(entry(value));
581        }
582    }
583
584    Ok(SessionLog {
585        path: path.to_path_buf(),
586        meta,
587        entries,
588    })
589}
590
591/// Read the entries written to a session log since `position`.
592///
593/// An incomplete last line is left for the next call. Compressing or restoring
594/// a session does not affect its position. A compressed log is decompressed
595/// from the start on every call.
596///
597/// A replaced log is found by comparing up to 4 KiB at the start and before the
598/// position, so a change between those is not reported.
599pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
600    Ok(match read_chunk(path, position, None)? {
601        Chunk::Continued { entries, position } => Continuation::Continued {
602            entries: entries.into_iter().map(|found| found.entry).collect(),
603            position,
604        },
605        Chunk::Truncated => Continuation::Truncated,
606        Chunk::Replaced => Continuation::Replaced,
607    })
608}
609
610/// [`read_from`], with the offset of each entry and an optional limit.
611///
612/// With `max_bytes`, a read stops before the entry that would exceed it. The
613/// first entry is returned whatever its size, so repeated calls always reach
614/// the end of the log.
615///
616/// The limit does not apply to a compressed log, where one call returns
617/// everything up to the end. Each call has to decompress the log from the
618/// start, so reading it in parts would repeat that for every part.
619pub fn read_chunk(
620    path: impl AsRef<Path>,
621    position: &Position,
622    max_bytes: Option<u64>,
623) -> Result<Chunk> {
624    let path = path.as_ref();
625    open(path)
626        .and_then(|log| {
627            let max_bytes = match log {
628                Log::Plain(_) => max_bytes,
629                Log::Compressed(_) => None,
630            };
631            continue_from(log.seekable()?, position, max_bytes.unwrap_or(u64::MAX))
632        })
633        .map_err(|e| read_error(path, e))
634}
635
636fn continue_from(
637    mut log: impl Read + Seek,
638    position: &Position,
639    max_bytes: u64,
640) -> io::Result<Chunk> {
641    if log.seek(SeekFrom::End(0))? < position.offset {
642        return Ok(Chunk::Truncated);
643    }
644    if fingerprint(&mut log, position.offset)? != position.fingerprint {
645        return Ok(Chunk::Replaced);
646    }
647
648    let mut inside_entry = false;
649    if let Some(before) = position.offset.checked_sub(1) {
650        let mut byte = [0];
651        log.seek(SeekFrom::Start(before))?;
652        log.read_exact(&mut byte)?;
653        inside_entry = byte != *b"\n";
654    } else {
655        log.seek(SeekFrom::Start(0))?;
656    }
657
658    let mut reader = BufReader::new(&mut log);
659    let mut offset = position.offset;
660    let mut entries = Vec::new();
661    let mut line = Vec::new();
662    loop {
663        let left = if entries.is_empty() {
664            u64::MAX
665        } else {
666            max_bytes.saturating_sub(offset - position.offset)
667        };
668        line.clear();
669        reader.by_ref().take(left).read_until(b'\n', &mut line)?;
670        if line.last() != Some(&b'\n') {
671            break;
672        }
673        if !inside_entry && let Some(value) = values(&line).next() {
674            entries.push(ChunkEntry {
675                offset,
676                entry: entry(value),
677            });
678        }
679        inside_entry = false;
680        offset += line.len() as u64;
681    }
682    Ok(Chunk::Continued {
683        entries,
684        position: Position::new(&mut log, offset)?,
685    })
686}
687
688/// FNV-1a of the bytes at the start of a log and those before `offset`.
689///
690/// Positions are saved, so this has to give the same value in every release.
691/// `DefaultHasher` does not promise that.
692fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
693    if offset == 0 {
694        return Ok(Position::default().fingerprint);
695    }
696    let window = offset.min(4096);
697    let mut bytes = Vec::new();
698    for start in [0, offset - window] {
699        log.seek(SeekFrom::Start(start))?;
700        log.by_ref().take(window).read_to_end(&mut bytes)?;
701    }
702    Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
703        (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
704    }))
705}
706
707enum Log {
708    Plain(File),
709    Compressed(File),
710}
711
712trait ReadSeek: Read + Seek {}
713
714impl<T: Read + Seek> ReadSeek for T {}
715
716impl Log {
717    fn reader(self) -> io::Result<Box<dyn Read>> {
718        Ok(match self {
719            Self::Plain(file) => Box::new(file),
720            Self::Compressed(file) => {
721                Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
722            }
723        })
724    }
725
726    /// The log without compression. A compressed one is held in memory.
727    fn seekable(self) -> io::Result<Box<dyn ReadSeek>> {
728        Ok(match self {
729            Self::Plain(file) => Box::new(file),
730            Self::Compressed(_) => {
731                let mut contents = Vec::new();
732                self.reader()?.read_to_end(&mut contents)?;
733                Box::new(Cursor::new(contents))
734            }
735        })
736    }
737}
738
739/// Open a log under either of its two names.
740fn open(path: &Path) -> io::Result<Log> {
741    let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
742        Some(plain) => PathBuf::from(plain),
743        None => path.to_path_buf(),
744    };
745    let mut compressed = plain.clone().into_os_string();
746    compressed.push(".zst");
747
748    let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
749    match File::open(&plain) {
750        Err(e) if missing(&e) => match File::open(compressed) {
751            // Restored between the two attempts. The CLI writes the new file
752            // before it removes the old one.
753            Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
754            file => file.map(Log::Compressed),
755        },
756        file => file.map(Log::Plain),
757    }
758}
759
760fn read_error(path: &Path, source: io::Error) -> Error {
761    Error::Io {
762        message: format!("failed to read {}: {source}", path.display()),
763        source,
764        working_dir: None,
765    }
766}
767
768/// The JSON value of each line.
769///
770/// A line that will not parse is skipped rather than failing the read. These
771/// files are appended to by a long-running process and a truncated tail should
772/// not cost the caller the rest of the session.
773fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
774    contents
775        .split(|byte| *byte == b'\n')
776        .filter_map(|line| serde_json::from_slice(line).ok())
777}
778
779/// The metadata object, if the line holds one.
780///
781/// A legacy metadata line is recognised by carrying an id and no record type of
782/// its own.
783fn metadata(value: &Value) -> Option<&Value> {
784    match envelope(value) {
785        Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
786        None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
787    }
788}
789
790fn entry(value: Value) -> SessionEntry {
791    match envelope(&value) {
792        Some((timestamp, entry_type, payload)) => SessionEntry {
793            timestamp: timestamp.map(str::to_string),
794            entry_type: Some(entry_type.to_string()),
795            payload: payload.clone(),
796        },
797        None => SessionEntry {
798            timestamp: value
799                .get("timestamp")
800                .and_then(Value::as_str)
801                .map(str::to_string),
802            entry_type: None,
803            payload: value,
804        },
805    }
806}
807
808/// `(timestamp, type, payload)` for a modern envelope, `None` for a legacy
809/// line.
810fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
811    let payload = value.get("payload")?;
812    let entry_type = value.get("type")?.as_str()?;
813    Some((
814        value.get("timestamp").and_then(Value::as_str),
815        entry_type,
816        payload,
817    ))
818}
819
820fn parse_meta(value: &Value) -> SessionMeta {
821    let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
822    SessionMeta {
823        id: string("id").or_else(|| string("session_id")),
824        timestamp: string("timestamp"),
825        cwd: string("cwd").map(PathBuf::from),
826        cli_version: string("cli_version"),
827        originator: string("originator"),
828        source: string("source"),
829        git: value.get("git").and_then(|git| {
830            let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
831            let meta = GitMeta {
832                commit_hash: get("commit_hash"),
833                branch: get("branch"),
834                repository_url: get("repository_url"),
835            };
836            (meta != GitMeta::default()).then_some(meta)
837        }),
838        raw: value.clone(),
839    }
840}
841
842/// `(year, month, day)` directories under the sessions root.
843fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
844    let mut out = Vec::new();
845    for year in numeric_children(root) {
846        for month in numeric_children(&year.1) {
847            for day in numeric_children(&month.1) {
848                out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
849            }
850        }
851    }
852    out
853}
854
855/// Child directories whose names are numbers, with the parsed value.
856fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
857    let Ok(entries) = std::fs::read_dir(dir) else {
858        return Vec::new();
859    };
860    entries
861        .filter_map(std::result::Result::ok)
862        .filter_map(|entry| {
863            let name = entry.file_name().into_string().ok()?;
864            let value = name.parse::<u32>().ok()?;
865            entry.path().is_dir().then(|| (value, entry.path()))
866        })
867        .collect()
868}
869
870/// The thread id in `rollout-<ISO8601>-<thread_id>.jsonl`, compressed or not.
871///
872/// The timestamp itself contains dashes, so this takes the tail rather than
873/// splitting: a uuid is five dash-separated groups. A reverted thread's name
874/// has `_<rollout_id>` after the thread id, which a resume does not take.
875fn session_id_from_path(path: &Path) -> Option<String> {
876    let name = path.file_name()?.to_str()?;
877    let name = name.strip_suffix(".zst").unwrap_or(name);
878    let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
879    let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
880    let parts: Vec<&str> = stem.split('-').collect();
881    if parts.len() < 5 {
882        return None;
883    }
884    Some(parts[parts.len() - 5..].join("-"))
885}
886
887/// Whether a session's metadata records it as having run in `wanted`.
888fn session_ran_in(path: &Path, wanted: &Path) -> bool {
889    let Ok(reader) = open(path).and_then(Log::reader) else {
890        return false;
891    };
892    let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
893    let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
894        return false;
895    };
896    let Ok(value) = serde_json::from_str::<Value>(&first) else {
897        return false;
898    };
899    let meta = value.get("payload").unwrap_or(&value);
900    meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
901}
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906
907    fn temp_home(label: &str) -> PathBuf {
908        let dir = std::env::temp_dir().join(format!(
909            "codex-wrapper-history-{}-{label}",
910            std::process::id()
911        ));
912        let _ = std::fs::remove_dir_all(&dir);
913        dir
914    }
915
916    fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
917        let dir = home
918            .join("sessions")
919            .join(format!("{:04}", date.0))
920            .join(format!("{:02}", date.1))
921            .join(format!("{:02}", date.2));
922        std::fs::create_dir_all(&dir).unwrap();
923        let path = dir.join(name);
924        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
925        path
926    }
927
928    /// Transcribed from a real 2026 rollout: envelope of timestamp, type and
929    /// payload on every line.
930    const MODERN: &[&str] = &[
931        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"}}}"#,
932        r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
933        r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
934        r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
935    ];
936
937    /// Transcribed from a real 2025-09 rollout: no envelope at all.
938    const LEGACY: &[&str] = &[
939        r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
940        r#"{"record_type":"state"}"#,
941        r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
942    ];
943
944    #[test]
945    fn discovers_both_current_history_modes_and_preserves_their_payloads() {
946        let home = temp_home("current-history-modes");
947        for (mode, fixture, id, item_type) in [
948            (
949                "legacy",
950                include_str!("../tests/history/0.163.0-legacy.jsonl"),
951                "00000000-0000-4000-8000-000000000001",
952                "user_message",
953            ),
954            (
955                "paginated",
956                include_str!("../tests/history/0.163.0-paginated.jsonl"),
957                "00000000-0000-4000-8000-000000000002",
958                "item_completed",
959            ),
960        ] {
961            let path = write_session(
962                &home,
963                (2026, 10, 20),
964                &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
965                &fixture.lines().collect::<Vec<_>>(),
966            );
967            let log = read(&path).unwrap();
968            let meta = log.meta.unwrap();
969            assert_eq!(meta.id.as_deref(), Some(id));
970            assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
971            assert_eq!(meta.raw["history_mode"], mode);
972            assert_eq!(log.entries.len(), 4);
973            let captured: Vec<serde_json::Value> = fixture
974                .lines()
975                .map(|line| serde_json::from_str(line).unwrap())
976                .collect();
977            for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
978                assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
979                assert_eq!(entry.payload, envelope["payload"]);
980            }
981            assert_eq!(log.entries[0].payload_type(), Some(item_type));
982            assert_eq!(log.entries[2].payload_type(), Some(item_type));
983            if mode == "paginated" {
984                assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
985                assert_eq!(
986                    log.entries[0].payload["item"]["content"][0]["text"],
987                    "synthetic offline history fixture"
988                );
989            }
990        }
991        let sessions = list_in(
992            &home,
993            &SessionQuery::new()
994                .cwd("/fixture/workspace")
995                .after(2026, 10, 20),
996        )
997        .unwrap();
998        assert_eq!(sessions.len(), 2);
999        std::fs::remove_dir_all(home).unwrap();
1000    }
1001
1002    /// Moving the tested range needs a rollout from the new version. See
1003    /// `tests/history/README.md`.
1004    #[test]
1005    fn types_the_records_of_every_tested_cli_version() {
1006        use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};
1007
1008        for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
1009            let path = format!(
1010                "{}/tests/history/{version}.jsonl",
1011                env!("CARGO_MANIFEST_DIR")
1012            );
1013            let records: Vec<String> = follow(Path::new(&path), &Position::default())
1014                .0
1015                .iter()
1016                .filter_map(SessionEntry::record)
1017                .map(|record| match record {
1018                    SessionRecord::Meta(meta) => {
1019                        assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
1020                        format!("meta {}", meta.cli_version.unwrap())
1021                    }
1022                    SessionRecord::TurnContext {
1023                        turn_id,
1024                        cwd,
1025                        model,
1026                    } => {
1027                        assert!(turn_id.is_some());
1028                        format!("context {} {}", cwd.unwrap().display(), model.unwrap())
1029                    }
1030                    SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
1031                    SessionRecord::ToolCall {
1032                        call_id,
1033                        name,
1034                        input,
1035                        ..
1036                    } => {
1037                        assert!(input.to_string().contains("fixture"));
1038                        format!("call {name} {call_id:?}")
1039                    }
1040                    SessionRecord::ToolResult { call_id, output } => {
1041                        assert!(output.is_string() || output.is_array());
1042                        format!("result {}", call_id.unwrap())
1043                    }
1044                    SessionRecord::TurnComplete {
1045                        turn_id,
1046                        last_agent_message,
1047                        error,
1048                    } => {
1049                        assert!(turn_id.is_some());
1050                        format!("complete {last_agent_message:?} {error:?}")
1051                    }
1052                    SessionRecord::TurnAborted { turn_id, reason } => {
1053                        assert!(turn_id.is_some());
1054                        format!("aborted {}", reason.unwrap())
1055                    }
1056                })
1057                .collect();
1058            assert_eq!(
1059                records,
1060                [
1061                    format!("meta {version}").as_str(),
1062                    "context /fixture/workspace gpt-5.2-codex",
1063                    "prompt first prompt",
1064                    r#"call exec_command Some("call_1")"#,
1065                    "result call_1",
1066                    r#"call apply_patch Some("call_2")"#,
1067                    "result call_2",
1068                    r#"call tool_search Some("call_3")"#,
1069                    "result call_3",
1070                    "call web_search None",
1071                    r#"complete Some("fixture answer") None"#,
1072                    "context /fixture/workspace gpt-5.2-codex",
1073                    "prompt interrupted prompt",
1074                    "aborted interrupted",
1075                ],
1076                "{version}"
1077            );
1078        }
1079    }
1080
1081    /// The CLI leaves `action` out when the provider did not send one.
1082    #[test]
1083    fn a_web_search_without_an_action_is_still_a_call() {
1084        let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
1085        let record = values(line).map(entry).next().unwrap().record();
1086        assert!(matches!(
1087            record,
1088            Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
1089        ));
1090    }
1091
1092    #[test]
1093    fn a_failed_turn_has_its_error() {
1094        let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
1095        let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
1096            let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
1097                return None;
1098            };
1099            error
1100        });
1101        assert!(failed.unwrap().contains("intentional offline fixture"));
1102    }
1103
1104    fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
1105        match read_from(path, position).unwrap() {
1106            Continuation::Continued { entries, position } => (entries, position),
1107            other => panic!("expected the log to continue, got {other:?}"),
1108        }
1109    }
1110
1111    #[test]
1112    fn continues_after_the_last_complete_line() {
1113        let home = temp_home("continue");
1114        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
1115        let (entries, position) = follow(&path, &Position::default());
1116        assert_eq!(entries.len(), 2);
1117        assert_eq!(
1118            position.offset(),
1119            std::fs::metadata(&path).unwrap().len(),
1120            "everything was read"
1121        );
1122
1123        // Cut inside a character, as a write in progress can be.
1124        let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
1125        let cut = line.find('é').unwrap() + 1;
1126        let mut contents = std::fs::read(&path).unwrap();
1127        contents.extend(&line.as_bytes()[..cut]);
1128        std::fs::write(&path, &contents).unwrap();
1129        assert_eq!(follow(&path, &position), (vec![], position.clone()));
1130
1131        contents.extend(&line.as_bytes()[cut..]);
1132        contents.push(b'\n');
1133        std::fs::write(&path, &contents).unwrap();
1134        let saved = serde_json::to_string(&position).unwrap();
1135        let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
1136        assert_eq!(entries.len(), 1);
1137        assert_eq!(
1138            entries[0].record(),
1139            Some(SessionRecord::Prompt {
1140                turn_id: None,
1141                text: "é".into()
1142            })
1143        );
1144    }
1145
1146    #[test]
1147    fn reports_a_truncated_or_replaced_log() {
1148        let home = temp_home("replaced");
1149        let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1150        let (_, position) = follow(&path, &Position::default());
1151
1152        let contents = std::fs::read_to_string(&path).unwrap();
1153        std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
1154        assert_eq!(
1155            read_from(&path, &position).unwrap(),
1156            Continuation::Replaced,
1157            "same length, another session"
1158        );
1159
1160        std::fs::write(&path, MODERN[0]).unwrap();
1161        assert_eq!(
1162            read_from(&path, &position).unwrap(),
1163            Continuation::Truncated
1164        );
1165    }
1166
1167    fn chunk(
1168        path: &Path,
1169        position: &Position,
1170        max_bytes: Option<u64>,
1171    ) -> (Vec<(u64, SessionEntry)>, Position) {
1172        match read_chunk(path, position, max_bytes).unwrap() {
1173            Chunk::Continued { entries, position } => (
1174                entries.into_iter().map(|e| (e.offset, e.entry)).collect(),
1175                position,
1176            ),
1177            other => panic!("expected the log to continue, got {other:?}"),
1178        }
1179    }
1180
1181    /// Every entry of `MODERN` with the offset of its line.
1182    fn modern_entries() -> Vec<(u64, SessionEntry)> {
1183        let mut offset = 0;
1184        MODERN
1185            .iter()
1186            .map(|line| {
1187                let start = offset;
1188                offset += line.len() as u64 + 1;
1189                (start, entry(serde_json::from_str(line).unwrap()))
1190            })
1191            .collect()
1192    }
1193
1194    #[test]
1195    fn starts_at_the_first_entry_after_a_place() {
1196        let home = temp_home("place");
1197        let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1198        let end = std::fs::metadata(&path).unwrap().len();
1199        let all = modern_entries();
1200
1201        for offset in 0..=end {
1202            let expected: Vec<_> = all.iter().filter(|e| e.0 >= offset).cloned().collect();
1203            let position = Position::at_offset(&path, offset).unwrap();
1204            assert_eq!(position.offset(), offset);
1205            assert_eq!(Position::before_end(&path, end - offset).unwrap(), position);
1206            let (entries, next) = chunk(&path, &position, None);
1207            assert_eq!(entries, expected, "from {offset}");
1208            assert_eq!(next.offset(), end);
1209            assert_eq!(follow(&path, &position).0.len(), expected.len());
1210        }
1211        assert_eq!(
1212            Position::before_end(&path, end + 1).unwrap(),
1213            Position::default()
1214        );
1215    }
1216
1217    #[test]
1218    fn an_incomplete_entry_is_skipped_from_a_place_inside_it() {
1219        let home = temp_home("place-incomplete");
1220        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..1]);
1221        let complete = std::fs::read_to_string(&path).unwrap();
1222        std::fs::write(&path, format!("{complete}{}", &MODERN[1][..20])).unwrap();
1223
1224        let position = Position::before_end(&path, 5).unwrap();
1225        assert_eq!(chunk(&path, &position, None), (vec![], position.clone()));
1226
1227        std::fs::write(&path, format!("{}\n", MODERN.join("\n"))).unwrap();
1228        assert_eq!(chunk(&path, &position, None).0, modern_entries()[2..]);
1229    }
1230
1231    #[test]
1232    fn a_place_past_the_end_is_not_in_the_log() {
1233        let home = temp_home("place-past-end");
1234        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..1]);
1235        let end = std::fs::metadata(&path).unwrap().len();
1236        let position = Position::at_offset(&path, end + 1).unwrap();
1237        assert_eq!(
1238            read_chunk(&path, &position, None).unwrap(),
1239            Chunk::Truncated
1240        );
1241        std::fs::write(&path, format!("{}\n", MODERN.join("\n"))).unwrap();
1242        assert_eq!(read_chunk(&path, &position, None).unwrap(), Chunk::Replaced);
1243    }
1244
1245    #[test]
1246    fn a_limited_read_returns_at_least_one_entry() {
1247        let home = temp_home("limit");
1248        // A line that will not parse is not an entry.
1249        let mut lines = vec!["not json"];
1250        lines.extend(MODERN);
1251        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &lines);
1252        let end = std::fs::metadata(&path).unwrap().len();
1253        let all = chunk(&path, &Position::default(), None).0;
1254        assert_eq!(all.len(), MODERN.len());
1255
1256        for max_bytes in 0..=end {
1257            let mut position = Position::default();
1258            let mut read = Vec::new();
1259            loop {
1260                let (entries, next) = chunk(&path, &position, Some(max_bytes));
1261                if entries.is_empty() {
1262                    break;
1263                }
1264                assert!(
1265                    entries.len() == 1 || next.offset() - position.offset() <= max_bytes,
1266                    "{} entries with a limit of {max_bytes}",
1267                    entries.len()
1268                );
1269                read.extend(entries);
1270                position = next;
1271            }
1272            assert_eq!(read, all, "limit {max_bytes}");
1273            assert_eq!(position.offset(), end);
1274        }
1275
1276        // Exactly two entries fit, and one byte less leaves the second.
1277        let two = all[2].0;
1278        assert_eq!(chunk(&path, &Position::default(), Some(two)).0, all[..2]);
1279        assert_eq!(
1280            chunk(&path, &Position::default(), Some(two - 1)).0,
1281            all[..1]
1282        );
1283    }
1284
1285    #[test]
1286    fn a_compressed_log_has_the_same_places_and_no_limit() {
1287        use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1288
1289        let home = temp_home("compressed-places");
1290        let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1291        let all = modern_entries();
1292        let at = Position::at_offset(&path, all[1].0).unwrap();
1293        let before = Position::before_end(&path, 10).unwrap();
1294
1295        let contents = std::fs::read(&path).unwrap();
1296        std::fs::write(
1297            path.with_extension("jsonl.zst"),
1298            compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1299        )
1300        .unwrap();
1301        std::fs::remove_file(&path).unwrap();
1302
1303        assert_eq!(Position::at_offset(&path, all[1].0).unwrap(), at);
1304        assert_eq!(Position::before_end(&path, 10).unwrap(), before);
1305        assert_eq!(chunk(&path, &at, Some(1)).0, all[1..]);
1306    }
1307
1308    #[test]
1309    fn a_compressed_session_is_the_same_session() {
1310        use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1311
1312        let home = temp_home("compressed");
1313        let path = write_session(
1314            &home,
1315            (2026, 8, 6),
1316            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1317            MODERN,
1318        );
1319        let query = SessionQuery::new().cwd("/repo");
1320        let log = read(&path).unwrap();
1321        let (_, position) = follow(&path, &Position::default());
1322
1323        let compressed = path.with_extension("jsonl.zst");
1324        let contents = std::fs::read(&path).unwrap();
1325        std::fs::write(
1326            &compressed,
1327            compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1328        )
1329        .unwrap();
1330        let listed = list_in(&home, &query).unwrap();
1331        assert_eq!(listed.len(), 1, "one session while both files exist");
1332        assert_eq!(listed[0].path, path);
1333
1334        std::fs::remove_file(&path).unwrap();
1335        let listed = list_in(&home, &query).unwrap();
1336        assert_eq!(listed.len(), 1);
1337        assert_eq!(listed[0].path, compressed);
1338        assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1339        assert_eq!(read(&compressed).unwrap().entries, log.entries);
1340        // A caller that still has the old path.
1341        assert_eq!(read(&path).unwrap(), log);
1342        assert_eq!(follow(&path, &position), (vec![], position.clone()));
1343
1344        // Restored, for a caller that has the compressed path.
1345        std::fs::write(&path, &contents).unwrap();
1346        std::fs::remove_file(&compressed).unwrap();
1347        assert_eq!(follow(&compressed, &position), (vec![], position));
1348    }
1349
1350    #[test]
1351    fn a_missing_sessions_directory_is_empty_not_an_error() {
1352        let home = temp_home("empty");
1353        assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
1354    }
1355
1356    #[test]
1357    fn lists_sessions_newest_first() {
1358        let home = temp_home("order");
1359        write_session(
1360            &home,
1361            (2026, 8, 1),
1362            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1363            MODERN,
1364        );
1365        write_session(
1366            &home,
1367            (2026, 8, 6),
1368            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1369            MODERN,
1370        );
1371        write_session(
1372            &home,
1373            (2025, 9, 1),
1374            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1375            LEGACY,
1376        );
1377
1378        let found = list_in(&home, &SessionQuery::new()).unwrap();
1379        let dates: Vec<_> = found.iter().map(|s| s.date).collect();
1380        assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
1381        assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1382    }
1383
1384    #[test]
1385    fn date_filters_narrow_the_listing() {
1386        let home = temp_home("dates");
1387        write_session(
1388            &home,
1389            (2026, 8, 1),
1390            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1391            MODERN,
1392        );
1393        write_session(
1394            &home,
1395            (2026, 8, 6),
1396            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1397            MODERN,
1398        );
1399
1400        let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
1401        assert_eq!(after.len(), 1);
1402        assert_eq!(after[0].date, (2026, 8, 6));
1403
1404        let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
1405        assert_eq!(before.len(), 1);
1406        assert_eq!(before[0].date, (2026, 8, 1));
1407
1408        let between = list_in(
1409            &home,
1410            &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
1411        )
1412        .unwrap();
1413        assert_eq!(between.len(), 2);
1414    }
1415
1416    #[test]
1417    fn cwd_filter_matches_the_recorded_directory() {
1418        let home = temp_home("cwd");
1419        write_session(
1420            &home,
1421            (2026, 8, 6),
1422            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1423            MODERN,
1424        );
1425
1426        assert_eq!(
1427            list_in(&home, &SessionQuery::new().cwd("/repo"))
1428                .unwrap()
1429                .len(),
1430            1
1431        );
1432        assert_eq!(
1433            list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
1434                .unwrap()
1435                .len(),
1436            0
1437        );
1438    }
1439
1440    #[test]
1441    fn reads_a_modern_session() {
1442        let home = temp_home("modern");
1443        let path = write_session(
1444            &home,
1445            (2026, 8, 6),
1446            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1447            MODERN,
1448        );
1449
1450        let log = read(&path).unwrap();
1451        let meta = log.meta.unwrap();
1452        assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
1453        assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
1454        assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
1455
1456        // The metadata line is not also an entry.
1457        assert_eq!(log.entries.len(), 3);
1458        assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
1459        assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
1460    }
1461
1462    /// The whole point of the two-generation handling: a parser written for
1463    /// the modern envelope returns nothing here, silently.
1464    #[test]
1465    fn reads_a_legacy_session_without_an_envelope() {
1466        let home = temp_home("legacy");
1467        let path = write_session(
1468            &home,
1469            (2025, 9, 1),
1470            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1471            LEGACY,
1472        );
1473
1474        let log = read(&path).unwrap();
1475        let meta = log.meta.expect("the first line is the metadata");
1476        assert_eq!(
1477            meta.id.as_deref(),
1478            Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
1479        );
1480        assert_eq!(meta.cli_version, None, "legacy files record no version");
1481        assert_eq!(meta.cwd, None, "legacy files record no cwd");
1482        assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
1483
1484        assert_eq!(log.entries.len(), 2);
1485        // No envelope, so the whole line is the payload.
1486        assert_eq!(log.entries[0].entry_type, None);
1487        assert_eq!(log.entries[1].payload_type(), Some("message"));
1488    }
1489
1490    /// These files are appended to by a running process, so a truncated last
1491    /// line must not cost the caller the rest of the session.
1492    #[test]
1493    fn a_truncated_tail_does_not_lose_the_rest() {
1494        let home = temp_home("truncated");
1495        let mut lines = MODERN.to_vec();
1496        lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
1497        let path = write_session(
1498            &home,
1499            (2026, 8, 6),
1500            "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
1501            &lines,
1502        );
1503
1504        let log = read(&path).unwrap();
1505        assert!(log.meta.is_some());
1506        assert_eq!(log.entries.len(), 3, "the good lines survive");
1507    }
1508
1509    /// The timestamp in the filename also contains dashes, so the id has to be
1510    /// taken from the tail rather than by splitting on the first one.
1511    #[test]
1512    fn session_id_comes_from_the_uuid_tail() {
1513        assert_eq!(
1514            session_id_from_path(Path::new(
1515                "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
1516            )),
1517            Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
1518        );
1519        assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
1520    }
1521
1522    /// Name format from `codex-rs/rollout/src/rollout_file_name.rs` at
1523    /// `rust-v0.167.0`.
1524    #[test]
1525    fn a_reverted_thread_is_identified_by_its_thread_id() {
1526        for extension in ["jsonl", "jsonl.zst"] {
1527            let name = format!(
1528                "/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
1529            );
1530            assert_eq!(
1531                session_id_from_path(Path::new(&name)).as_deref(),
1532                Some("aaaaaaaa-1111-2222-3333-444444444444"),
1533                "{extension}"
1534            );
1535        }
1536    }
1537
1538    #[test]
1539    fn unknown_entry_types_are_kept_rather_than_dropped() {
1540        let home = temp_home("unknown");
1541        let path = write_session(
1542            &home,
1543            (2026, 8, 6),
1544            "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
1545            &[
1546                MODERN[0],
1547                r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
1548            ],
1549        );
1550
1551        let log = read(&path).unwrap();
1552        assert_eq!(log.entries.len(), 1);
1553        assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
1554        assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
1555    }
1556}