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//! The date partitioning is why [`SessionQuery::after`] and
14//! [`SessionQuery::before`] are cheap: they filter directories, without opening
15//! a file.
16//!
17//! # Two envelope generations
18//!
19//! A real machine holds sessions written by many CLI versions, and the line
20//! format changed. Both were found on one machine while writing this, 205
21//! files spanning both:
22//!
23//! **Modern**, from around 0.47 onward. Every line is an envelope:
24//!
25//! ```json
26//! {"timestamp":"...","type":"session_meta","payload":{"id":"...","cwd":"..."}}
27//! {"timestamp":"...","type":"response_item","payload":{"type":"message","role":"user"}}
28//! ```
29//!
30//! **Legacy**, older files. No envelope at all: the first line *is* the
31//! metadata, and later lines are bare records.
32//!
33//! ```json
34//! {"id":"...","timestamp":"...","git":{},"instructions":null}
35//! {"id":"...","type":"message","role":"user","content":[]}
36//! ```
37//!
38//! A parser written against only the modern shape returns nothing at all for
39//! the older half of a real history, silently. [`SessionEntry::entry_type`] is
40//! `None` for a legacy line, and its `payload` is the whole line.
41//!
42//! Field-level drift is handled the same way: every metadata field is
43//! optional, because older files carry no `cli_version`, no `cwd`, and a
44//! different `instructions` key. [`SessionMeta::raw`] keeps whatever this
45//! crate does not name.
46//!
47//! # Coverage of current history modes
48//!
49//! CLI 0.163.0 writes materialized, persistent `legacy` and `paginated` threads
50//! under the layout above. Both use the modern envelope; the current
51//! `history_mode: "legacy"` setting is distinct from the older bare-line format.
52//! [`SessionMeta::raw`] preserves `history_mode`. Paginated `item_completed`
53//! payloads are retained as written, including their nested item.
54//!
55//! This is a file reader, not the provider's logical thread-history view.
56//! Discovery does not include archived sessions, ephemeral or unmaterialized
57//! threads, or a server's other storage roots. It does not query the state
58//! database. Entries are not normalized into turns, replayed, or deduplicated.
59//! Envelope fields other than `timestamp`, `type`, and `payload` (including
60//! paginated `ordinal`) are not exposed. Invalid JSON lines are skipped.
61//!
62//! For the provider's view, enable `app-server` and use
63//! `AppServerHandle::request` with `thread/read`, `thread/turns/list`, or
64//! `thread/items/list`. In an isolated 0.163.0 capture, `thread/read` and
65//! cursor-paginated `thread/turns/list` worked for both materialized modes.
66//! `thread/items/list` worked for paginated history and rejected legacy history.
67//! Continue each method's opaque `nextCursor` until absent; do not derive a
68//! cursor from rollout ordinals or treat one page as complete history.
69//! Availability depends on CLI version, mode, and materialization. These probes
70//! used failed offline turns and do not qualify every item kind or history
71//! recovery scenario. Versioned fixture provenance ships in `tests/history/`.
72//!
73//! # Example
74//!
75//! ```no_run
76//! use codex_wrapper::history::{self, SessionQuery};
77//!
78//! # fn example() -> codex_wrapper::Result<()> {
79//! for session in history::list(&SessionQuery::new().after(2026, 8, 1))? {
80//!     let log = history::read(&session.path)?;
81//!     println!("{} in {:?}", session.id, log.meta.and_then(|m| m.cwd));
82//! }
83//! # Ok(())
84//! # }
85//! ```
86
87use std::path::{Path, PathBuf};
88
89use crate::error::{Error, Result};
90
91/// A rollout file on disk, identified without opening it.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct SessionFile {
94    /// Full path to the `.jsonl` file.
95    pub path: PathBuf,
96    /// The session id, taken from the filename.
97    ///
98    /// This is the `thread_id` a resume takes.
99    pub id: String,
100    /// The date directory this file sits in, as `(year, month, day)`.
101    pub date: (u16, u8, u8),
102}
103
104/// Git metadata recorded with a session.
105#[derive(Debug, Clone, Default, PartialEq, Eq)]
106#[non_exhaustive]
107pub struct GitMeta {
108    /// Commit the working tree was on.
109    pub commit_hash: Option<String>,
110    /// Branch name.
111    pub branch: Option<String>,
112    /// Remote URL.
113    pub repository_url: Option<String>,
114}
115
116/// The session's opening metadata.
117///
118/// Every field is optional. Older files carry a different and smaller set, and
119/// a reader that required any one of them would fail on a real history.
120#[derive(Debug, Clone, Default, PartialEq)]
121#[non_exhaustive]
122pub struct SessionMeta {
123    /// Session id as recorded inside the file.
124    pub id: Option<String>,
125    /// ISO 8601 start time.
126    pub timestamp: Option<String>,
127    /// Working directory the session ran in. Absent in legacy files.
128    pub cwd: Option<PathBuf>,
129    /// CLI version that wrote it. Absent in legacy files.
130    pub cli_version: Option<String>,
131    /// What started the session, for example `codex_cli_rs`.
132    pub originator: Option<String>,
133    /// Entry point, for example `cli`.
134    pub source: Option<String>,
135    /// Git metadata, when recorded.
136    pub git: Option<GitMeta>,
137    /// The metadata object as written, including keys not named above.
138    pub raw: serde_json::Value,
139}
140
141/// One line of a session log.
142#[derive(Debug, Clone, PartialEq)]
143pub struct SessionEntry {
144    /// Envelope timestamp, when the line has an envelope.
145    pub timestamp: Option<String>,
146    /// Envelope type: `event_msg`, `response_item`, `turn_context`, and so on.
147    ///
148    /// `None` for a legacy line, which has no envelope. In that case
149    /// `payload` is the whole line.
150    pub entry_type: Option<String>,
151    /// The payload, or the whole line for a legacy entry.
152    ///
153    /// Modern envelope extensions, such as paginated `ordinal`, are not retained.
154    pub payload: serde_json::Value,
155}
156
157impl SessionEntry {
158    /// The payload's own `type`, which is the useful discriminator.
159    ///
160    /// For a modern `event_msg` this is `agent_message`, `token_count`, and
161    /// so on; for a `response_item`, `message` or `reasoning`.
162    #[must_use]
163    pub fn payload_type(&self) -> Option<&str> {
164        self.payload.get("type")?.as_str()
165    }
166}
167
168/// A parsed session log.
169#[derive(Debug, Clone, PartialEq)]
170pub struct SessionLog {
171    /// The file this came from.
172    pub path: PathBuf,
173    /// Opening metadata, if the file had any.
174    pub meta: Option<SessionMeta>,
175    /// Every line after the metadata, in order.
176    pub entries: Vec<SessionEntry>,
177}
178
179/// Which sessions to list.
180#[derive(Debug, Clone, Default)]
181pub struct SessionQuery {
182    after: Option<(u16, u8, u8)>,
183    before: Option<(u16, u8, u8)>,
184    cwd: Option<PathBuf>,
185}
186
187impl SessionQuery {
188    /// Every session.
189    #[must_use]
190    pub fn new() -> Self {
191        Self::default()
192    }
193
194    /// On or after this date. Filters directories, without opening files.
195    #[must_use]
196    pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
197        self.after = Some((year, month, day));
198        self
199    }
200
201    /// On or before this date. Filters directories, without opening files.
202    #[must_use]
203    pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
204        self.before = Some((year, month, day));
205        self
206    }
207
208    /// Only sessions recorded as running in this directory.
209    ///
210    /// Unlike the date filters this one has to open each candidate file to
211    /// read its metadata, and legacy files record no `cwd` so they never
212    /// match.
213    #[must_use]
214    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
215        self.cwd = Some(cwd.into());
216        self
217    }
218
219    fn matches_date(&self, date: (u16, u8, u8)) -> bool {
220        self.after.is_none_or(|after| date >= after)
221            && self.before.is_none_or(|before| date <= before)
222    }
223}
224
225/// List sessions for the current environment, newest first.
226///
227/// Honors `CODEX_HOME`, defaulting to `~/.codex`.
228pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
229    let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
230    list_in(home, query)
231}
232
233/// [`list`], but against an explicit `CODEX_HOME`.
234///
235/// A missing `sessions` directory yields an empty list rather than an error:
236/// no sessions is a normal state.
237pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
238    let root = codex_home.as_ref().join("sessions");
239    let mut found = Vec::new();
240
241    for (date, day_dir) in date_dirs(&root) {
242        if !query.matches_date(date) {
243            continue;
244        }
245        let Ok(entries) = std::fs::read_dir(&day_dir) else {
246            continue;
247        };
248        for entry in entries.filter_map(std::result::Result::ok) {
249            let path = entry.path();
250            let Some(id) = session_id_from_path(&path) else {
251                continue;
252            };
253            if let Some(wanted) = &query.cwd
254                && !session_ran_in(&path, wanted)
255            {
256                continue;
257            }
258            found.push(SessionFile { path, id, date });
259        }
260    }
261
262    // Newest first. The filename carries the timestamp, so it orders within a
263    // day without opening anything.
264    found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
265    Ok(found)
266}
267
268/// Read and parse one session log.
269pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
270    let path = path.as_ref();
271    let contents = std::fs::read_to_string(path).map_err(|e| Error::Io {
272        message: format!("failed to read {}: {e}", path.display()),
273        source: e,
274        working_dir: None,
275    })?;
276
277    let mut meta = None;
278    let mut entries = Vec::new();
279
280    for line in contents.lines() {
281        let line = line.trim();
282        if line.is_empty() {
283            continue;
284        }
285        // A line that will not parse is skipped rather than failing the read.
286        // These files are appended to by a long-running process and a
287        // truncated tail should not cost the caller the rest of the session.
288        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
289            continue;
290        };
291
292        match envelope(&value) {
293            Some((timestamp, entry_type, payload)) => {
294                if entry_type == "session_meta" && meta.is_none() {
295                    meta = Some(parse_meta(payload));
296                    continue;
297                }
298                entries.push(SessionEntry {
299                    timestamp: timestamp.map(str::to_string),
300                    entry_type: Some(entry_type.to_string()),
301                    payload: payload.clone(),
302                });
303            }
304            None => {
305                // Legacy: no envelope. The first such line is the metadata,
306                // recognised by carrying an id and no record type of its own.
307                if meta.is_none() && value.get("id").is_some() && value.get("type").is_none() {
308                    meta = Some(parse_meta(&value));
309                    continue;
310                }
311                entries.push(SessionEntry {
312                    timestamp: value
313                        .get("timestamp")
314                        .and_then(|v| v.as_str())
315                        .map(str::to_string),
316                    entry_type: None,
317                    payload: value,
318                });
319            }
320        }
321    }
322
323    Ok(SessionLog {
324        path: path.to_path_buf(),
325        meta,
326        entries,
327    })
328}
329
330/// `(timestamp, type, payload)` for a modern envelope, `None` for a legacy
331/// line.
332fn envelope(value: &serde_json::Value) -> Option<(Option<&str>, &str, &serde_json::Value)> {
333    let payload = value.get("payload")?;
334    let entry_type = value.get("type")?.as_str()?;
335    Some((
336        value.get("timestamp").and_then(serde_json::Value::as_str),
337        entry_type,
338        payload,
339    ))
340}
341
342fn parse_meta(value: &serde_json::Value) -> SessionMeta {
343    let string = |key: &str| {
344        value
345            .get(key)
346            .and_then(serde_json::Value::as_str)
347            .map(str::to_string)
348    };
349    SessionMeta {
350        id: string("id").or_else(|| string("session_id")),
351        timestamp: string("timestamp"),
352        cwd: string("cwd").map(PathBuf::from),
353        cli_version: string("cli_version"),
354        originator: string("originator"),
355        source: string("source"),
356        git: value.get("git").and_then(|git| {
357            let get = |key: &str| {
358                git.get(key)
359                    .and_then(serde_json::Value::as_str)
360                    .map(str::to_string)
361            };
362            let meta = GitMeta {
363                commit_hash: get("commit_hash"),
364                branch: get("branch"),
365                repository_url: get("repository_url"),
366            };
367            (meta != GitMeta::default()).then_some(meta)
368        }),
369        raw: value.clone(),
370    }
371}
372
373/// `(year, month, day)` directories under the sessions root.
374fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
375    let mut out = Vec::new();
376    for year in numeric_children(root) {
377        for month in numeric_children(&year.1) {
378            for day in numeric_children(&month.1) {
379                out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
380            }
381        }
382    }
383    out
384}
385
386/// Child directories whose names are numbers, with the parsed value.
387fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
388    let Ok(entries) = std::fs::read_dir(dir) else {
389        return Vec::new();
390    };
391    entries
392        .filter_map(std::result::Result::ok)
393        .filter_map(|entry| {
394            let name = entry.file_name().into_string().ok()?;
395            let value = name.parse::<u32>().ok()?;
396            entry.path().is_dir().then(|| (value, entry.path()))
397        })
398        .collect()
399}
400
401/// The uuid tail of `rollout-<ISO8601>-<uuid>.jsonl`.
402///
403/// The timestamp itself contains dashes, so this takes the tail rather than
404/// splitting: a uuid is five dash-separated groups.
405fn session_id_from_path(path: &Path) -> Option<String> {
406    let name = path.file_name()?.to_str()?;
407    let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
408    let parts: Vec<&str> = stem.split('-').collect();
409    if parts.len() < 5 {
410        return None;
411    }
412    Some(parts[parts.len() - 5..].join("-"))
413}
414
415/// Whether a session's metadata records it as having run in `wanted`.
416fn session_ran_in(path: &Path, wanted: &Path) -> bool {
417    let Ok(contents) = std::fs::read_to_string(path) else {
418        return false;
419    };
420    let Some(first) = contents.lines().find(|line| !line.trim().is_empty()) else {
421        return false;
422    };
423    let Ok(value) = serde_json::from_str::<serde_json::Value>(first) else {
424        return false;
425    };
426    let meta = value.get("payload").unwrap_or(&value);
427    meta.get("cwd").and_then(serde_json::Value::as_str) == wanted.to_str()
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    fn temp_home(label: &str) -> PathBuf {
435        let dir = std::env::temp_dir().join(format!(
436            "codex-wrapper-history-{}-{label}",
437            std::process::id()
438        ));
439        let _ = std::fs::remove_dir_all(&dir);
440        dir
441    }
442
443    fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
444        let dir = home
445            .join("sessions")
446            .join(format!("{:04}", date.0))
447            .join(format!("{:02}", date.1))
448            .join(format!("{:02}", date.2));
449        std::fs::create_dir_all(&dir).unwrap();
450        let path = dir.join(name);
451        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
452        path
453    }
454
455    /// Transcribed from a real 2026 rollout: envelope of timestamp, type and
456    /// payload on every line.
457    const MODERN: &[&str] = &[
458        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"}}}"#,
459        r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
460        r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
461        r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
462    ];
463
464    /// Transcribed from a real 2025-09 rollout: no envelope at all.
465    const LEGACY: &[&str] = &[
466        r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
467        r#"{"record_type":"state"}"#,
468        r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
469    ];
470
471    #[test]
472    fn discovers_both_current_history_modes_and_preserves_their_payloads() {
473        let home = temp_home("current-history-modes");
474        for (mode, fixture, id, item_type) in [
475            (
476                "legacy",
477                include_str!("../tests/history/0.163.0-legacy.jsonl"),
478                "00000000-0000-4000-8000-000000000001",
479                "user_message",
480            ),
481            (
482                "paginated",
483                include_str!("../tests/history/0.163.0-paginated.jsonl"),
484                "00000000-0000-4000-8000-000000000002",
485                "item_completed",
486            ),
487        ] {
488            let path = write_session(
489                &home,
490                (2026, 10, 20),
491                &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
492                &fixture.lines().collect::<Vec<_>>(),
493            );
494            let log = read(&path).unwrap();
495            let meta = log.meta.unwrap();
496            assert_eq!(meta.id.as_deref(), Some(id));
497            assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
498            assert_eq!(meta.raw["history_mode"], mode);
499            assert_eq!(log.entries.len(), 4);
500            let captured: Vec<serde_json::Value> = fixture
501                .lines()
502                .map(|line| serde_json::from_str(line).unwrap())
503                .collect();
504            for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
505                assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
506                assert_eq!(entry.payload, envelope["payload"]);
507            }
508            assert_eq!(log.entries[0].payload_type(), Some(item_type));
509            assert_eq!(log.entries[2].payload_type(), Some(item_type));
510            if mode == "paginated" {
511                assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
512                assert_eq!(
513                    log.entries[0].payload["item"]["content"][0]["text"],
514                    "synthetic offline history fixture"
515                );
516            }
517        }
518        let sessions = list_in(
519            &home,
520            &SessionQuery::new()
521                .cwd("/fixture/workspace")
522                .after(2026, 10, 20),
523        )
524        .unwrap();
525        assert_eq!(sessions.len(), 2);
526        std::fs::remove_dir_all(home).unwrap();
527    }
528
529    #[test]
530    fn a_missing_sessions_directory_is_empty_not_an_error() {
531        let home = temp_home("empty");
532        assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
533    }
534
535    #[test]
536    fn lists_sessions_newest_first() {
537        let home = temp_home("order");
538        write_session(
539            &home,
540            (2026, 8, 1),
541            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
542            MODERN,
543        );
544        write_session(
545            &home,
546            (2026, 8, 6),
547            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
548            MODERN,
549        );
550        write_session(
551            &home,
552            (2025, 9, 1),
553            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
554            LEGACY,
555        );
556
557        let found = list_in(&home, &SessionQuery::new()).unwrap();
558        let dates: Vec<_> = found.iter().map(|s| s.date).collect();
559        assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
560        assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
561    }
562
563    #[test]
564    fn date_filters_narrow_the_listing() {
565        let home = temp_home("dates");
566        write_session(
567            &home,
568            (2026, 8, 1),
569            "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
570            MODERN,
571        );
572        write_session(
573            &home,
574            (2026, 8, 6),
575            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
576            MODERN,
577        );
578
579        let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
580        assert_eq!(after.len(), 1);
581        assert_eq!(after[0].date, (2026, 8, 6));
582
583        let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
584        assert_eq!(before.len(), 1);
585        assert_eq!(before[0].date, (2026, 8, 1));
586
587        let between = list_in(
588            &home,
589            &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
590        )
591        .unwrap();
592        assert_eq!(between.len(), 2);
593    }
594
595    #[test]
596    fn cwd_filter_matches_the_recorded_directory() {
597        let home = temp_home("cwd");
598        write_session(
599            &home,
600            (2026, 8, 6),
601            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
602            MODERN,
603        );
604
605        assert_eq!(
606            list_in(&home, &SessionQuery::new().cwd("/repo"))
607                .unwrap()
608                .len(),
609            1
610        );
611        assert_eq!(
612            list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
613                .unwrap()
614                .len(),
615            0
616        );
617    }
618
619    #[test]
620    fn reads_a_modern_session() {
621        let home = temp_home("modern");
622        let path = write_session(
623            &home,
624            (2026, 8, 6),
625            "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
626            MODERN,
627        );
628
629        let log = read(&path).unwrap();
630        let meta = log.meta.unwrap();
631        assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
632        assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
633        assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
634
635        // The metadata line is not also an entry.
636        assert_eq!(log.entries.len(), 3);
637        assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
638        assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
639    }
640
641    /// The whole point of the two-generation handling: a parser written for
642    /// the modern envelope returns nothing here, silently.
643    #[test]
644    fn reads_a_legacy_session_without_an_envelope() {
645        let home = temp_home("legacy");
646        let path = write_session(
647            &home,
648            (2025, 9, 1),
649            "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
650            LEGACY,
651        );
652
653        let log = read(&path).unwrap();
654        let meta = log.meta.expect("the first line is the metadata");
655        assert_eq!(
656            meta.id.as_deref(),
657            Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
658        );
659        assert_eq!(meta.cli_version, None, "legacy files record no version");
660        assert_eq!(meta.cwd, None, "legacy files record no cwd");
661        assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
662
663        assert_eq!(log.entries.len(), 2);
664        // No envelope, so the whole line is the payload.
665        assert_eq!(log.entries[0].entry_type, None);
666        assert_eq!(log.entries[1].payload_type(), Some("message"));
667    }
668
669    /// These files are appended to by a running process, so a truncated last
670    /// line must not cost the caller the rest of the session.
671    #[test]
672    fn a_truncated_tail_does_not_lose_the_rest() {
673        let home = temp_home("truncated");
674        let mut lines = MODERN.to_vec();
675        lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
676        let path = write_session(
677            &home,
678            (2026, 8, 6),
679            "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
680            &lines,
681        );
682
683        let log = read(&path).unwrap();
684        assert!(log.meta.is_some());
685        assert_eq!(log.entries.len(), 3, "the good lines survive");
686    }
687
688    /// The timestamp in the filename also contains dashes, so the id has to be
689    /// taken from the tail rather than by splitting on the first one.
690    #[test]
691    fn session_id_comes_from_the_uuid_tail() {
692        assert_eq!(
693            session_id_from_path(Path::new(
694                "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
695            )),
696            Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
697        );
698        assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
699    }
700
701    #[test]
702    fn unknown_entry_types_are_kept_rather_than_dropped() {
703        let home = temp_home("unknown");
704        let path = write_session(
705            &home,
706            (2026, 8, 6),
707            "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
708            &[
709                MODERN[0],
710                r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
711            ],
712        );
713
714        let log = read(&path).unwrap();
715        assert_eq!(log.entries.len(), 1);
716        assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
717        assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
718    }
719}