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//! # Example
105//!
106//! ```no_run
107//! use codex_wrapper::history::{self, SessionQuery};
108//!
109//! # fn example() -> codex_wrapper::Result<()> {
110//! for session in history::list(&SessionQuery::new().after(2026, 8, 1))? {
111//!     let log = history::read(&session.path)?;
112//!     println!("{} in {:?}", session.id, log.meta.and_then(|m| m.cwd));
113//! }
114//! # Ok(())
115//! # }
116//! ```
117
118use std::fs::File;
119use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
120use std::path::{Path, PathBuf};
121
122use ruzstd::decoding::StreamingDecoder;
123use serde::{Deserialize, Serialize};
124use serde_json::Value;
125
126use crate::error::{Error, Result};
127
128/// A rollout file on disk, identified without opening it.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct SessionFile {
131    /// Full path to the `.jsonl` or `.jsonl.zst` file.
132    pub path: PathBuf,
133    /// The session id, taken from the filename.
134    ///
135    /// This is the `thread_id` a resume takes.
136    pub id: String,
137    /// The date directory this file sits in, as `(year, month, day)`.
138    pub date: (u16, u8, u8),
139}
140
141/// Git metadata recorded with a session.
142#[derive(Debug, Clone, Default, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct GitMeta {
145    /// Commit the working tree was on.
146    pub commit_hash: Option<String>,
147    /// Branch name.
148    pub branch: Option<String>,
149    /// Remote URL.
150    pub repository_url: Option<String>,
151}
152
153/// The session's opening metadata.
154///
155/// Every field is optional. Older files carry a different and smaller set, and
156/// a reader that required any one of them would fail on a real history.
157#[derive(Debug, Clone, Default, PartialEq)]
158#[non_exhaustive]
159pub struct SessionMeta {
160    /// Session id as recorded inside the file.
161    pub id: Option<String>,
162    /// ISO 8601 start time.
163    pub timestamp: Option<String>,
164    /// Working directory the session ran in. Absent in legacy files.
165    pub cwd: Option<PathBuf>,
166    /// CLI version that wrote it. Absent in legacy files.
167    pub cli_version: Option<String>,
168    /// What started the session, for example `codex_cli_rs`.
169    pub originator: Option<String>,
170    /// Entry point, for example `cli`.
171    pub source: Option<String>,
172    /// Git metadata, when recorded.
173    pub git: Option<GitMeta>,
174    /// The metadata object as written, including keys not named above.
175    pub raw: Value,
176}
177
178/// One line of a session log.
179#[derive(Debug, Clone, PartialEq)]
180pub struct SessionEntry {
181    /// Envelope timestamp, when the line has an envelope.
182    pub timestamp: Option<String>,
183    /// Envelope type: `event_msg`, `response_item`, `turn_context`, and so on.
184    ///
185    /// `None` for a legacy line, which has no envelope. In that case
186    /// `payload` is the whole line.
187    pub entry_type: Option<String>,
188    /// The payload, or the whole line for a legacy entry.
189    ///
190    /// Modern envelope extensions, such as paginated `ordinal`, are not retained.
191    pub payload: Value,
192}
193
194impl SessionEntry {
195    /// The payload's own `type`, which is the useful discriminator.
196    ///
197    /// For a modern `event_msg` this is `agent_message`, `token_count`, and
198    /// so on; for a `response_item`, `message` or `reasoning`.
199    #[must_use]
200    pub fn payload_type(&self) -> Option<&str> {
201        self.payload.get("type")?.as_str()
202    }
203
204    /// What this entry means, or `None` for one this crate does not type.
205    ///
206    /// Always `None` for a legacy line without an envelope.
207    #[must_use]
208    pub fn record(&self) -> Option<SessionRecord> {
209        let payload = &self.payload;
210        let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
211        let call = |name: String, input: &str| {
212            Some(SessionRecord::ToolCall {
213                call_id: string("call_id"),
214                name,
215                namespace: string("namespace"),
216                input: payload.get(input).cloned().unwrap_or_default(),
217            })
218        };
219        let result = |output: &str| {
220            Some(SessionRecord::ToolResult {
221                call_id: string("call_id"),
222                output: payload.get(output)?.clone(),
223            })
224        };
225
226        match (self.entry_type.as_deref()?, self.payload_type()) {
227            ("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
228            ("turn_context", _) => Some(SessionRecord::TurnContext {
229                turn_id: string("turn_id"),
230                cwd: string("cwd").map(PathBuf::from),
231                model: string("model"),
232            }),
233            // A prompt is also written as a `response_item` message with the
234            // user role, but so is the context the CLI adds by itself.
235            ("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
236                turn_id: None,
237                text: string("message")?,
238            }),
239            ("event_msg", Some("item_completed")) => {
240                let item = payload.get("item")?;
241                if item.get("type")? != "UserMessage" {
242                    return None;
243                }
244                let parts = item.get("content")?.as_array()?;
245                Some(SessionRecord::Prompt {
246                    turn_id: string("turn_id"),
247                    text: parts
248                        .iter()
249                        .filter_map(|part| part.get("text")?.as_str())
250                        .collect(),
251                })
252            }
253            ("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
254                turn_id: string("turn_id"),
255                last_agent_message: string("last_agent_message"),
256                error: payload
257                    .pointer("/error/message")
258                    .and_then(Value::as_str)
259                    .map(str::to_string),
260            }),
261            ("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
262                turn_id: string("turn_id"),
263                reason: string("reason"),
264            }),
265            ("response_item", Some("function_call")) => call(string("name")?, "arguments"),
266            ("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
267            ("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
268            ("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
269            ("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
270                result("output")
271            }
272            ("response_item", Some("tool_search_output")) => result("tools"),
273            _ => None,
274        }
275    }
276}
277
278/// What a [`SessionEntry`] means.
279///
280/// The entry keeps the payload as written, for fields not named here.
281#[derive(Debug, Clone, PartialEq)]
282#[non_exhaustive]
283pub enum SessionRecord {
284    /// Session metadata. The first line of a session.
285    Meta(Box<SessionMeta>),
286    /// The settings a turn runs with.
287    #[non_exhaustive]
288    TurnContext {
289        /// The turn.
290        turn_id: Option<String>,
291        /// Working directory of the turn.
292        cwd: Option<PathBuf>,
293        /// Model of the turn.
294        model: Option<String>,
295    },
296    /// A message from the user.
297    #[non_exhaustive]
298    Prompt {
299        /// The turn it belongs to. Not recorded in `legacy` history mode.
300        turn_id: Option<String>,
301        /// The text, without images or other attachments.
302        text: String,
303    },
304    /// A tool call by the model.
305    ///
306    /// `local_shell_call` and `image_generation_call` are not typed, because
307    /// there is no captured sample of them.
308    #[non_exhaustive]
309    ToolCall {
310        /// Matches the [`ToolResult`](Self::ToolResult). A web search has
311        /// neither.
312        call_id: Option<String>,
313        /// Tool name.
314        name: String,
315        /// Where the tool comes from, such as an MCP server.
316        namespace: Option<String>,
317        /// The input as written. A function call has a string that contains
318        /// JSON.
319        input: Value,
320    },
321    /// The result of a tool call.
322    #[non_exhaustive]
323    ToolResult {
324        /// The call this answers.
325        call_id: Option<String>,
326        /// The output as written: a string, or an array of content parts.
327        output: Value,
328    },
329    /// A turn ended by itself.
330    #[non_exhaustive]
331    TurnComplete {
332        /// The turn.
333        turn_id: Option<String>,
334        /// The final answer.
335        last_agent_message: Option<String>,
336        /// Why the turn failed, if it did.
337        error: Option<String>,
338    },
339    /// A turn was interrupted.
340    #[non_exhaustive]
341    TurnAborted {
342        /// The turn.
343        turn_id: Option<String>,
344        /// The reason, such as `interrupted`.
345        reason: Option<String>,
346    },
347}
348
349/// How far a session log has been read. The default is the start.
350///
351/// Serialize it to continue in another process.
352#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
353pub struct Position {
354    offset: u64,
355    fingerprint: u64,
356}
357
358impl Position {
359    /// Bytes read so far, counted without compression.
360    #[must_use]
361    pub fn offset(&self) -> u64 {
362        self.offset
363    }
364}
365
366/// What [`read_from`] found.
367#[derive(Debug, Clone, PartialEq)]
368pub enum Continuation {
369    /// The log continues from the given position.
370    Continued {
371        /// New entries, which may be none. Unlike [`SessionLog::entries`],
372        /// they include the metadata line.
373        entries: Vec<SessionEntry>,
374        /// Where to continue.
375        position: Position,
376    },
377    /// The log is now shorter than the given position.
378    Truncated,
379    /// The log no longer has the content that was read before.
380    Replaced,
381}
382
383/// A parsed session log.
384#[derive(Debug, Clone, PartialEq)]
385pub struct SessionLog {
386    /// The file this came from.
387    pub path: PathBuf,
388    /// Opening metadata, if the file had any.
389    pub meta: Option<SessionMeta>,
390    /// Every line after the metadata, in order.
391    pub entries: Vec<SessionEntry>,
392}
393
394/// Which sessions to list.
395#[derive(Debug, Clone, Default)]
396pub struct SessionQuery {
397    after: Option<(u16, u8, u8)>,
398    before: Option<(u16, u8, u8)>,
399    cwd: Option<PathBuf>,
400}
401
402impl SessionQuery {
403    /// Every session.
404    #[must_use]
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    /// On or after this date. Filters directories, without opening files.
410    #[must_use]
411    pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
412        self.after = Some((year, month, day));
413        self
414    }
415
416    /// On or before this date. Filters directories, without opening files.
417    #[must_use]
418    pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
419        self.before = Some((year, month, day));
420        self
421    }
422
423    /// Only sessions recorded as running in this directory.
424    ///
425    /// Unlike the date filters this one has to open each candidate file to
426    /// read its metadata, and legacy files record no `cwd` so they never
427    /// match.
428    #[must_use]
429    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
430        self.cwd = Some(cwd.into());
431        self
432    }
433
434    fn matches_date(&self, date: (u16, u8, u8)) -> bool {
435        self.after.is_none_or(|after| date >= after)
436            && self.before.is_none_or(|before| date <= before)
437    }
438}
439
440/// List sessions for the current environment, newest first.
441///
442/// Honors `CODEX_HOME`, defaulting to `~/.codex`.
443pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
444    let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
445    list_in(home, query)
446}
447
448/// [`list`], but against an explicit `CODEX_HOME`.
449///
450/// A missing `sessions` directory yields an empty list rather than an error:
451/// no sessions is a normal state.
452pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
453    let root = codex_home.as_ref().join("sessions");
454    let mut found = Vec::new();
455
456    for (date, day_dir) in date_dirs(&root) {
457        if !query.matches_date(date) {
458            continue;
459        }
460        let Ok(entries) = std::fs::read_dir(&day_dir) else {
461            continue;
462        };
463        for entry in entries.filter_map(std::result::Result::ok) {
464            let path = entry.path();
465            let Some(id) = session_id_from_path(&path) else {
466                continue;
467            };
468            // Both files exist while the CLI compresses or restores a session.
469            if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
470            {
471                continue;
472            }
473            if let Some(wanted) = &query.cwd
474                && !session_ran_in(&path, wanted)
475            {
476                continue;
477            }
478            found.push(SessionFile { path, id, date });
479        }
480    }
481
482    // Newest first. The filename carries the timestamp, so it orders within a
483    // day without opening anything.
484    found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
485    Ok(found)
486}
487
488/// Read and parse one session log.
489pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
490    let path = path.as_ref();
491    let mut contents = Vec::new();
492    open(path)
493        .and_then(|log| log.reader()?.read_to_end(&mut contents))
494        .map_err(|e| read_error(path, e))?;
495
496    let mut meta = None;
497    let mut entries = Vec::new();
498
499    for value in values(&contents) {
500        if meta.is_none()
501            && let Some(found) = metadata(&value)
502        {
503            meta = Some(parse_meta(found));
504        } else {
505            entries.push(entry(value));
506        }
507    }
508
509    Ok(SessionLog {
510        path: path.to_path_buf(),
511        meta,
512        entries,
513    })
514}
515
516/// Read the entries written to a session log since `position`.
517///
518/// An incomplete last line is left for the next call. Compressing or restoring
519/// a session does not affect its position. A compressed log is decompressed
520/// from the start on every call.
521///
522/// A replaced log is found by comparing up to 4 KiB at the start and before the
523/// position, so a change between those is not reported.
524pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
525    let path = path.as_ref();
526    open(path)
527        .and_then(|log| match log {
528            Log::Plain(file) => continue_from(file, position),
529            Log::Compressed(_) => {
530                let mut contents = Vec::new();
531                log.reader()?.read_to_end(&mut contents)?;
532                continue_from(Cursor::new(contents), position)
533            }
534        })
535        .map_err(|e| read_error(path, e))
536}
537
538fn continue_from(mut log: impl Read + Seek, position: &Position) -> io::Result<Continuation> {
539    if log.seek(SeekFrom::End(0))? < position.offset {
540        return Ok(Continuation::Truncated);
541    }
542    if position.offset > 0 && fingerprint(&mut log, position.offset)? != position.fingerprint {
543        return Ok(Continuation::Replaced);
544    }
545
546    let mut contents = Vec::new();
547    log.seek(SeekFrom::Start(position.offset))?;
548    log.read_to_end(&mut contents)?;
549    let Some(end) = contents.iter().rposition(|byte| *byte == b'\n') else {
550        return Ok(Continuation::Continued {
551            entries: Vec::new(),
552            position: position.clone(),
553        });
554    };
555    let complete = &contents[..=end];
556    let offset = position.offset + complete.len() as u64;
557    Ok(Continuation::Continued {
558        entries: values(complete).map(entry).collect(),
559        position: Position {
560            offset,
561            fingerprint: fingerprint(&mut log, offset)?,
562        },
563    })
564}
565
566/// FNV-1a of the bytes at the start of a log and those before `offset`.
567///
568/// Positions are saved, so this has to give the same value in every release.
569/// `DefaultHasher` does not promise that.
570fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
571    let window = offset.min(4096);
572    let mut bytes = Vec::new();
573    for start in [0, offset - window] {
574        log.seek(SeekFrom::Start(start))?;
575        log.by_ref().take(window).read_to_end(&mut bytes)?;
576    }
577    Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
578        (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
579    }))
580}
581
582enum Log {
583    Plain(File),
584    Compressed(File),
585}
586
587impl Log {
588    fn reader(self) -> io::Result<Box<dyn Read>> {
589        Ok(match self {
590            Self::Plain(file) => Box::new(file),
591            Self::Compressed(file) => {
592                Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
593            }
594        })
595    }
596}
597
598/// Open a log under either of its two names.
599fn open(path: &Path) -> io::Result<Log> {
600    let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
601        Some(plain) => PathBuf::from(plain),
602        None => path.to_path_buf(),
603    };
604    let mut compressed = plain.clone().into_os_string();
605    compressed.push(".zst");
606
607    let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
608    match File::open(&plain) {
609        Err(e) if missing(&e) => match File::open(compressed) {
610            // Restored between the two attempts. The CLI writes the new file
611            // before it removes the old one.
612            Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
613            file => file.map(Log::Compressed),
614        },
615        file => file.map(Log::Plain),
616    }
617}
618
619fn read_error(path: &Path, source: io::Error) -> Error {
620    Error::Io {
621        message: format!("failed to read {}: {source}", path.display()),
622        source,
623        working_dir: None,
624    }
625}
626
627/// The JSON value of each line.
628///
629/// A line that will not parse is skipped rather than failing the read. These
630/// files are appended to by a long-running process and a truncated tail should
631/// not cost the caller the rest of the session.
632fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
633    contents
634        .split(|byte| *byte == b'\n')
635        .filter_map(|line| serde_json::from_slice(line).ok())
636}
637
638/// The metadata object, if the line holds one.
639///
640/// A legacy metadata line is recognised by carrying an id and no record type of
641/// its own.
642fn metadata(value: &Value) -> Option<&Value> {
643    match envelope(value) {
644        Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
645        None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
646    }
647}
648
649fn entry(value: Value) -> SessionEntry {
650    match envelope(&value) {
651        Some((timestamp, entry_type, payload)) => SessionEntry {
652            timestamp: timestamp.map(str::to_string),
653            entry_type: Some(entry_type.to_string()),
654            payload: payload.clone(),
655        },
656        None => SessionEntry {
657            timestamp: value
658                .get("timestamp")
659                .and_then(Value::as_str)
660                .map(str::to_string),
661            entry_type: None,
662            payload: value,
663        },
664    }
665}
666
667/// `(timestamp, type, payload)` for a modern envelope, `None` for a legacy
668/// line.
669fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
670    let payload = value.get("payload")?;
671    let entry_type = value.get("type")?.as_str()?;
672    Some((
673        value.get("timestamp").and_then(Value::as_str),
674        entry_type,
675        payload,
676    ))
677}
678
679fn parse_meta(value: &Value) -> SessionMeta {
680    let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
681    SessionMeta {
682        id: string("id").or_else(|| string("session_id")),
683        timestamp: string("timestamp"),
684        cwd: string("cwd").map(PathBuf::from),
685        cli_version: string("cli_version"),
686        originator: string("originator"),
687        source: string("source"),
688        git: value.get("git").and_then(|git| {
689            let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
690            let meta = GitMeta {
691                commit_hash: get("commit_hash"),
692                branch: get("branch"),
693                repository_url: get("repository_url"),
694            };
695            (meta != GitMeta::default()).then_some(meta)
696        }),
697        raw: value.clone(),
698    }
699}
700
701/// `(year, month, day)` directories under the sessions root.
702fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
703    let mut out = Vec::new();
704    for year in numeric_children(root) {
705        for month in numeric_children(&year.1) {
706            for day in numeric_children(&month.1) {
707                out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
708            }
709        }
710    }
711    out
712}
713
714/// Child directories whose names are numbers, with the parsed value.
715fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
716    let Ok(entries) = std::fs::read_dir(dir) else {
717        return Vec::new();
718    };
719    entries
720        .filter_map(std::result::Result::ok)
721        .filter_map(|entry| {
722            let name = entry.file_name().into_string().ok()?;
723            let value = name.parse::<u32>().ok()?;
724            entry.path().is_dir().then(|| (value, entry.path()))
725        })
726        .collect()
727}
728
729/// The thread id in `rollout-<ISO8601>-<thread_id>.jsonl`, compressed or not.
730///
731/// The timestamp itself contains dashes, so this takes the tail rather than
732/// splitting: a uuid is five dash-separated groups. A reverted thread's name
733/// has `_<rollout_id>` after the thread id, which a resume does not take.
734fn session_id_from_path(path: &Path) -> Option<String> {
735    let name = path.file_name()?.to_str()?;
736    let name = name.strip_suffix(".zst").unwrap_or(name);
737    let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
738    let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
739    let parts: Vec<&str> = stem.split('-').collect();
740    if parts.len() < 5 {
741        return None;
742    }
743    Some(parts[parts.len() - 5..].join("-"))
744}
745
746/// Whether a session's metadata records it as having run in `wanted`.
747fn session_ran_in(path: &Path, wanted: &Path) -> bool {
748    let Ok(reader) = open(path).and_then(Log::reader) else {
749        return false;
750    };
751    let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
752    let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
753        return false;
754    };
755    let Ok(value) = serde_json::from_str::<Value>(&first) else {
756        return false;
757    };
758    let meta = value.get("payload").unwrap_or(&value);
759    meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    fn temp_home(label: &str) -> PathBuf {
767        let dir = std::env::temp_dir().join(format!(
768            "codex-wrapper-history-{}-{label}",
769            std::process::id()
770        ));
771        let _ = std::fs::remove_dir_all(&dir);
772        dir
773    }
774
775    fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
776        let dir = home
777            .join("sessions")
778            .join(format!("{:04}", date.0))
779            .join(format!("{:02}", date.1))
780            .join(format!("{:02}", date.2));
781        std::fs::create_dir_all(&dir).unwrap();
782        let path = dir.join(name);
783        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
784        path
785    }
786
787    /// Transcribed from a real 2026 rollout: envelope of timestamp, type and
788    /// payload on every line.
789    const MODERN: &[&str] = &[
790        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"}}}"#,
791        r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
792        r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
793        r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
794    ];
795
796    /// Transcribed from a real 2025-09 rollout: no envelope at all.
797    const LEGACY: &[&str] = &[
798        r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
799        r#"{"record_type":"state"}"#,
800        r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
801    ];
802
803    #[test]
804    fn discovers_both_current_history_modes_and_preserves_their_payloads() {
805        let home = temp_home("current-history-modes");
806        for (mode, fixture, id, item_type) in [
807            (
808                "legacy",
809                include_str!("../tests/history/0.163.0-legacy.jsonl"),
810                "00000000-0000-4000-8000-000000000001",
811                "user_message",
812            ),
813            (
814                "paginated",
815                include_str!("../tests/history/0.163.0-paginated.jsonl"),
816                "00000000-0000-4000-8000-000000000002",
817                "item_completed",
818            ),
819        ] {
820            let path = write_session(
821                &home,
822                (2026, 10, 20),
823                &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
824                &fixture.lines().collect::<Vec<_>>(),
825            );
826            let log = read(&path).unwrap();
827            let meta = log.meta.unwrap();
828            assert_eq!(meta.id.as_deref(), Some(id));
829            assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
830            assert_eq!(meta.raw["history_mode"], mode);
831            assert_eq!(log.entries.len(), 4);
832            let captured: Vec<serde_json::Value> = fixture
833                .lines()
834                .map(|line| serde_json::from_str(line).unwrap())
835                .collect();
836            for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
837                assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
838                assert_eq!(entry.payload, envelope["payload"]);
839            }
840            assert_eq!(log.entries[0].payload_type(), Some(item_type));
841            assert_eq!(log.entries[2].payload_type(), Some(item_type));
842            if mode == "paginated" {
843                assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
844                assert_eq!(
845                    log.entries[0].payload["item"]["content"][0]["text"],
846                    "synthetic offline history fixture"
847                );
848            }
849        }
850        let sessions = list_in(
851            &home,
852            &SessionQuery::new()
853                .cwd("/fixture/workspace")
854                .after(2026, 10, 20),
855        )
856        .unwrap();
857        assert_eq!(sessions.len(), 2);
858        std::fs::remove_dir_all(home).unwrap();
859    }
860
861    /// Moving the tested range needs a rollout from the new version. See
862    /// `tests/history/README.md`.
863    #[test]
864    fn types_the_records_of_every_tested_cli_version() {
865        use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};
866
867        for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
868            let path = format!(
869                "{}/tests/history/{version}.jsonl",
870                env!("CARGO_MANIFEST_DIR")
871            );
872            let records: Vec<String> = follow(Path::new(&path), &Position::default())
873                .0
874                .iter()
875                .filter_map(SessionEntry::record)
876                .map(|record| match record {
877                    SessionRecord::Meta(meta) => {
878                        assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
879                        format!("meta {}", meta.cli_version.unwrap())
880                    }
881                    SessionRecord::TurnContext {
882                        turn_id,
883                        cwd,
884                        model,
885                    } => {
886                        assert!(turn_id.is_some());
887                        format!("context {} {}", cwd.unwrap().display(), model.unwrap())
888                    }
889                    SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
890                    SessionRecord::ToolCall {
891                        call_id,
892                        name,
893                        input,
894                        ..
895                    } => {
896                        assert!(input.to_string().contains("fixture"));
897                        format!("call {name} {call_id:?}")
898                    }
899                    SessionRecord::ToolResult { call_id, output } => {
900                        assert!(output.is_string() || output.is_array());
901                        format!("result {}", call_id.unwrap())
902                    }
903                    SessionRecord::TurnComplete {
904                        turn_id,
905                        last_agent_message,
906                        error,
907                    } => {
908                        assert!(turn_id.is_some());
909                        format!("complete {last_agent_message:?} {error:?}")
910                    }
911                    SessionRecord::TurnAborted { turn_id, reason } => {
912                        assert!(turn_id.is_some());
913                        format!("aborted {}", reason.unwrap())
914                    }
915                })
916                .collect();
917            assert_eq!(
918                records,
919                [
920                    format!("meta {version}").as_str(),
921                    "context /fixture/workspace gpt-5.2-codex",
922                    "prompt first prompt",
923                    r#"call exec_command Some("call_1")"#,
924                    "result call_1",
925                    r#"call apply_patch Some("call_2")"#,
926                    "result call_2",
927                    r#"call tool_search Some("call_3")"#,
928                    "result call_3",
929                    "call web_search None",
930                    r#"complete Some("fixture answer") None"#,
931                    "context /fixture/workspace gpt-5.2-codex",
932                    "prompt interrupted prompt",
933                    "aborted interrupted",
934                ],
935                "{version}"
936            );
937        }
938    }
939
940    /// The CLI leaves `action` out when the provider did not send one.
941    #[test]
942    fn a_web_search_without_an_action_is_still_a_call() {
943        let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
944        let record = values(line).map(entry).next().unwrap().record();
945        assert!(matches!(
946            record,
947            Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
948        ));
949    }
950
951    #[test]
952    fn a_failed_turn_has_its_error() {
953        let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
954        let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
955            let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
956                return None;
957            };
958            error
959        });
960        assert!(failed.unwrap().contains("intentional offline fixture"));
961    }
962
963    fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
964        match read_from(path, position).unwrap() {
965            Continuation::Continued { entries, position } => (entries, position),
966            other => panic!("expected the log to continue, got {other:?}"),
967        }
968    }
969
970    #[test]
971    fn continues_after_the_last_complete_line() {
972        let home = temp_home("continue");
973        let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
974        let (entries, position) = follow(&path, &Position::default());
975        assert_eq!(entries.len(), 2);
976        assert_eq!(
977            position.offset(),
978            std::fs::metadata(&path).unwrap().len(),
979            "everything was read"
980        );
981
982        // Cut inside a character, as a write in progress can be.
983        let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
984        let cut = line.find('é').unwrap() + 1;
985        let mut contents = std::fs::read(&path).unwrap();
986        contents.extend(&line.as_bytes()[..cut]);
987        std::fs::write(&path, &contents).unwrap();
988        assert_eq!(follow(&path, &position), (vec![], position.clone()));
989
990        contents.extend(&line.as_bytes()[cut..]);
991        contents.push(b'\n');
992        std::fs::write(&path, &contents).unwrap();
993        let saved = serde_json::to_string(&position).unwrap();
994        let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
995        assert_eq!(entries.len(), 1);
996        assert_eq!(
997            entries[0].record(),
998            Some(SessionRecord::Prompt {
999                turn_id: None,
1000                text: "é".into()
1001            })
1002        );
1003    }
1004
1005    #[test]
1006    fn reports_a_truncated_or_replaced_log() {
1007        let home = temp_home("replaced");
1008        let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1009        let (_, position) = follow(&path, &Position::default());
1010
1011        let contents = std::fs::read_to_string(&path).unwrap();
1012        std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
1013        assert_eq!(
1014            read_from(&path, &position).unwrap(),
1015            Continuation::Replaced,
1016            "same length, another session"
1017        );
1018
1019        std::fs::write(&path, MODERN[0]).unwrap();
1020        assert_eq!(
1021            read_from(&path, &position).unwrap(),
1022            Continuation::Truncated
1023        );
1024    }
1025
1026    #[test]
1027    fn a_compressed_session_is_the_same_session() {
1028        use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1029
1030        let home = temp_home("compressed");
1031        let path = write_session(
1032            &home,
1033            (2026, 8, 6),
1034            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1035            MODERN,
1036        );
1037        let query = SessionQuery::new().cwd("/repo");
1038        let log = read(&path).unwrap();
1039        let (_, position) = follow(&path, &Position::default());
1040
1041        let compressed = path.with_extension("jsonl.zst");
1042        let contents = std::fs::read(&path).unwrap();
1043        std::fs::write(
1044            &compressed,
1045            compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1046        )
1047        .unwrap();
1048        let listed = list_in(&home, &query).unwrap();
1049        assert_eq!(listed.len(), 1, "one session while both files exist");
1050        assert_eq!(listed[0].path, path);
1051
1052        std::fs::remove_file(&path).unwrap();
1053        let listed = list_in(&home, &query).unwrap();
1054        assert_eq!(listed.len(), 1);
1055        assert_eq!(listed[0].path, compressed);
1056        assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1057        assert_eq!(read(&compressed).unwrap().entries, log.entries);
1058        // A caller that still has the old path.
1059        assert_eq!(read(&path).unwrap(), log);
1060        assert_eq!(follow(&path, &position), (vec![], position.clone()));
1061
1062        // Restored, for a caller that has the compressed path.
1063        std::fs::write(&path, &contents).unwrap();
1064        std::fs::remove_file(&compressed).unwrap();
1065        assert_eq!(follow(&compressed, &position), (vec![], position));
1066    }
1067
1068    #[test]
1069    fn a_missing_sessions_directory_is_empty_not_an_error() {
1070        let home = temp_home("empty");
1071        assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
1072    }
1073
1074    #[test]
1075    fn lists_sessions_newest_first() {
1076        let home = temp_home("order");
1077        write_session(
1078            &home,
1079            (2026, 8, 1),
1080            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1081            MODERN,
1082        );
1083        write_session(
1084            &home,
1085            (2026, 8, 6),
1086            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1087            MODERN,
1088        );
1089        write_session(
1090            &home,
1091            (2025, 9, 1),
1092            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1093            LEGACY,
1094        );
1095
1096        let found = list_in(&home, &SessionQuery::new()).unwrap();
1097        let dates: Vec<_> = found.iter().map(|s| s.date).collect();
1098        assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
1099        assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1100    }
1101
1102    #[test]
1103    fn date_filters_narrow_the_listing() {
1104        let home = temp_home("dates");
1105        write_session(
1106            &home,
1107            (2026, 8, 1),
1108            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1109            MODERN,
1110        );
1111        write_session(
1112            &home,
1113            (2026, 8, 6),
1114            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1115            MODERN,
1116        );
1117
1118        let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
1119        assert_eq!(after.len(), 1);
1120        assert_eq!(after[0].date, (2026, 8, 6));
1121
1122        let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
1123        assert_eq!(before.len(), 1);
1124        assert_eq!(before[0].date, (2026, 8, 1));
1125
1126        let between = list_in(
1127            &home,
1128            &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
1129        )
1130        .unwrap();
1131        assert_eq!(between.len(), 2);
1132    }
1133
1134    #[test]
1135    fn cwd_filter_matches_the_recorded_directory() {
1136        let home = temp_home("cwd");
1137        write_session(
1138            &home,
1139            (2026, 8, 6),
1140            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1141            MODERN,
1142        );
1143
1144        assert_eq!(
1145            list_in(&home, &SessionQuery::new().cwd("/repo"))
1146                .unwrap()
1147                .len(),
1148            1
1149        );
1150        assert_eq!(
1151            list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
1152                .unwrap()
1153                .len(),
1154            0
1155        );
1156    }
1157
1158    #[test]
1159    fn reads_a_modern_session() {
1160        let home = temp_home("modern");
1161        let path = write_session(
1162            &home,
1163            (2026, 8, 6),
1164            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1165            MODERN,
1166        );
1167
1168        let log = read(&path).unwrap();
1169        let meta = log.meta.unwrap();
1170        assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
1171        assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
1172        assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
1173
1174        // The metadata line is not also an entry.
1175        assert_eq!(log.entries.len(), 3);
1176        assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
1177        assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
1178    }
1179
1180    /// The whole point of the two-generation handling: a parser written for
1181    /// the modern envelope returns nothing here, silently.
1182    #[test]
1183    fn reads_a_legacy_session_without_an_envelope() {
1184        let home = temp_home("legacy");
1185        let path = write_session(
1186            &home,
1187            (2025, 9, 1),
1188            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1189            LEGACY,
1190        );
1191
1192        let log = read(&path).unwrap();
1193        let meta = log.meta.expect("the first line is the metadata");
1194        assert_eq!(
1195            meta.id.as_deref(),
1196            Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
1197        );
1198        assert_eq!(meta.cli_version, None, "legacy files record no version");
1199        assert_eq!(meta.cwd, None, "legacy files record no cwd");
1200        assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
1201
1202        assert_eq!(log.entries.len(), 2);
1203        // No envelope, so the whole line is the payload.
1204        assert_eq!(log.entries[0].entry_type, None);
1205        assert_eq!(log.entries[1].payload_type(), Some("message"));
1206    }
1207
1208    /// These files are appended to by a running process, so a truncated last
1209    /// line must not cost the caller the rest of the session.
1210    #[test]
1211    fn a_truncated_tail_does_not_lose_the_rest() {
1212        let home = temp_home("truncated");
1213        let mut lines = MODERN.to_vec();
1214        lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
1215        let path = write_session(
1216            &home,
1217            (2026, 8, 6),
1218            "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
1219            &lines,
1220        );
1221
1222        let log = read(&path).unwrap();
1223        assert!(log.meta.is_some());
1224        assert_eq!(log.entries.len(), 3, "the good lines survive");
1225    }
1226
1227    /// The timestamp in the filename also contains dashes, so the id has to be
1228    /// taken from the tail rather than by splitting on the first one.
1229    #[test]
1230    fn session_id_comes_from_the_uuid_tail() {
1231        assert_eq!(
1232            session_id_from_path(Path::new(
1233                "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
1234            )),
1235            Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
1236        );
1237        assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
1238    }
1239
1240    /// Name format from `codex-rs/rollout/src/rollout_file_name.rs` at
1241    /// `rust-v0.167.0`.
1242    #[test]
1243    fn a_reverted_thread_is_identified_by_its_thread_id() {
1244        for extension in ["jsonl", "jsonl.zst"] {
1245            let name = format!(
1246                "/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
1247            );
1248            assert_eq!(
1249                session_id_from_path(Path::new(&name)).as_deref(),
1250                Some("aaaaaaaa-1111-2222-3333-444444444444"),
1251                "{extension}"
1252            );
1253        }
1254    }
1255
1256    #[test]
1257    fn unknown_entry_types_are_kept_rather_than_dropped() {
1258        let home = temp_home("unknown");
1259        let path = write_session(
1260            &home,
1261            (2026, 8, 6),
1262            "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
1263            &[
1264                MODERN[0],
1265                r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
1266            ],
1267        );
1268
1269        let log = read(&path).unwrap();
1270        assert_eq!(log.entries.len(), 1);
1271        assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
1272        assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
1273    }
1274}