use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use ruzstd::decoding::StreamingDecoder;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionFile {
pub path: PathBuf,
pub id: String,
pub date: (u16, u8, u8),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct GitMeta {
pub commit_hash: Option<String>,
pub branch: Option<String>,
pub repository_url: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct SessionMeta {
pub id: Option<String>,
pub timestamp: Option<String>,
pub cwd: Option<PathBuf>,
pub cli_version: Option<String>,
pub originator: Option<String>,
pub source: Option<String>,
pub git: Option<GitMeta>,
pub raw: Value,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SessionEntry {
pub timestamp: Option<String>,
pub entry_type: Option<String>,
pub payload: Value,
}
impl SessionEntry {
#[must_use]
pub fn payload_type(&self) -> Option<&str> {
self.payload.get("type")?.as_str()
}
#[must_use]
pub fn record(&self) -> Option<SessionRecord> {
let payload = &self.payload;
let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
let call = |name: String, input: &str| {
Some(SessionRecord::ToolCall {
call_id: string("call_id"),
name,
namespace: string("namespace"),
input: payload.get(input).cloned().unwrap_or_default(),
})
};
let result = |output: &str| {
Some(SessionRecord::ToolResult {
call_id: string("call_id"),
output: payload.get(output)?.clone(),
})
};
match (self.entry_type.as_deref()?, self.payload_type()) {
("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
("turn_context", _) => Some(SessionRecord::TurnContext {
turn_id: string("turn_id"),
cwd: string("cwd").map(PathBuf::from),
model: string("model"),
}),
("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
turn_id: None,
text: string("message")?,
}),
("event_msg", Some("item_completed")) => {
let item = payload.get("item")?;
if item.get("type")? != "UserMessage" {
return None;
}
let parts = item.get("content")?.as_array()?;
Some(SessionRecord::Prompt {
turn_id: string("turn_id"),
text: parts
.iter()
.filter_map(|part| part.get("text")?.as_str())
.collect(),
})
}
("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
turn_id: string("turn_id"),
last_agent_message: string("last_agent_message"),
error: payload
.pointer("/error/message")
.and_then(Value::as_str)
.map(str::to_string),
}),
("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
turn_id: string("turn_id"),
reason: string("reason"),
}),
("response_item", Some("function_call")) => call(string("name")?, "arguments"),
("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
result("output")
}
("response_item", Some("tool_search_output")) => result("tools"),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SessionRecord {
Meta(Box<SessionMeta>),
#[non_exhaustive]
TurnContext {
turn_id: Option<String>,
cwd: Option<PathBuf>,
model: Option<String>,
},
#[non_exhaustive]
Prompt {
turn_id: Option<String>,
text: String,
},
#[non_exhaustive]
ToolCall {
call_id: Option<String>,
name: String,
namespace: Option<String>,
input: Value,
},
#[non_exhaustive]
ToolResult {
call_id: Option<String>,
output: Value,
},
#[non_exhaustive]
TurnComplete {
turn_id: Option<String>,
last_agent_message: Option<String>,
error: Option<String>,
},
#[non_exhaustive]
TurnAborted {
turn_id: Option<String>,
reason: Option<String>,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Position {
offset: u64,
fingerprint: u64,
}
impl Position {
#[must_use]
pub fn offset(&self) -> u64 {
self.offset
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Continuation {
Continued {
entries: Vec<SessionEntry>,
position: Position,
},
Truncated,
Replaced,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SessionLog {
pub path: PathBuf,
pub meta: Option<SessionMeta>,
pub entries: Vec<SessionEntry>,
}
#[derive(Debug, Clone, Default)]
pub struct SessionQuery {
after: Option<(u16, u8, u8)>,
before: Option<(u16, u8, u8)>,
cwd: Option<PathBuf>,
}
impl SessionQuery {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
self.after = Some((year, month, day));
self
}
#[must_use]
pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
self.before = Some((year, month, day));
self
}
#[must_use]
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
fn matches_date(&self, date: (u16, u8, u8)) -> bool {
self.after.is_none_or(|after| date >= after)
&& self.before.is_none_or(|before| date <= before)
}
}
pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
list_in(home, query)
}
pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
let root = codex_home.as_ref().join("sessions");
let mut found = Vec::new();
for (date, day_dir) in date_dirs(&root) {
if !query.matches_date(date) {
continue;
}
let Ok(entries) = std::fs::read_dir(&day_dir) else {
continue;
};
for entry in entries.filter_map(std::result::Result::ok) {
let path = entry.path();
let Some(id) = session_id_from_path(&path) else {
continue;
};
if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
{
continue;
}
if let Some(wanted) = &query.cwd
&& !session_ran_in(&path, wanted)
{
continue;
}
found.push(SessionFile { path, id, date });
}
}
found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
Ok(found)
}
pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
let path = path.as_ref();
let mut contents = Vec::new();
open(path)
.and_then(|log| log.reader()?.read_to_end(&mut contents))
.map_err(|e| read_error(path, e))?;
let mut meta = None;
let mut entries = Vec::new();
for value in values(&contents) {
if meta.is_none()
&& let Some(found) = metadata(&value)
{
meta = Some(parse_meta(found));
} else {
entries.push(entry(value));
}
}
Ok(SessionLog {
path: path.to_path_buf(),
meta,
entries,
})
}
pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
let path = path.as_ref();
open(path)
.and_then(|log| match log {
Log::Plain(file) => continue_from(file, position),
Log::Compressed(_) => {
let mut contents = Vec::new();
log.reader()?.read_to_end(&mut contents)?;
continue_from(Cursor::new(contents), position)
}
})
.map_err(|e| read_error(path, e))
}
fn continue_from(mut log: impl Read + Seek, position: &Position) -> io::Result<Continuation> {
if log.seek(SeekFrom::End(0))? < position.offset {
return Ok(Continuation::Truncated);
}
if position.offset > 0 && fingerprint(&mut log, position.offset)? != position.fingerprint {
return Ok(Continuation::Replaced);
}
let mut contents = Vec::new();
log.seek(SeekFrom::Start(position.offset))?;
log.read_to_end(&mut contents)?;
let Some(end) = contents.iter().rposition(|byte| *byte == b'\n') else {
return Ok(Continuation::Continued {
entries: Vec::new(),
position: position.clone(),
});
};
let complete = &contents[..=end];
let offset = position.offset + complete.len() as u64;
Ok(Continuation::Continued {
entries: values(complete).map(entry).collect(),
position: Position {
offset,
fingerprint: fingerprint(&mut log, offset)?,
},
})
}
fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
let window = offset.min(4096);
let mut bytes = Vec::new();
for start in [0, offset - window] {
log.seek(SeekFrom::Start(start))?;
log.by_ref().take(window).read_to_end(&mut bytes)?;
}
Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
}))
}
enum Log {
Plain(File),
Compressed(File),
}
impl Log {
fn reader(self) -> io::Result<Box<dyn Read>> {
Ok(match self {
Self::Plain(file) => Box::new(file),
Self::Compressed(file) => {
Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
}
})
}
}
fn open(path: &Path) -> io::Result<Log> {
let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
Some(plain) => PathBuf::from(plain),
None => path.to_path_buf(),
};
let mut compressed = plain.clone().into_os_string();
compressed.push(".zst");
let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
match File::open(&plain) {
Err(e) if missing(&e) => match File::open(compressed) {
Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
file => file.map(Log::Compressed),
},
file => file.map(Log::Plain),
}
}
fn read_error(path: &Path, source: io::Error) -> Error {
Error::Io {
message: format!("failed to read {}: {source}", path.display()),
source,
working_dir: None,
}
}
fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
contents
.split(|byte| *byte == b'\n')
.filter_map(|line| serde_json::from_slice(line).ok())
}
fn metadata(value: &Value) -> Option<&Value> {
match envelope(value) {
Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
}
}
fn entry(value: Value) -> SessionEntry {
match envelope(&value) {
Some((timestamp, entry_type, payload)) => SessionEntry {
timestamp: timestamp.map(str::to_string),
entry_type: Some(entry_type.to_string()),
payload: payload.clone(),
},
None => SessionEntry {
timestamp: value
.get("timestamp")
.and_then(Value::as_str)
.map(str::to_string),
entry_type: None,
payload: value,
},
}
}
fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
let payload = value.get("payload")?;
let entry_type = value.get("type")?.as_str()?;
Some((
value.get("timestamp").and_then(Value::as_str),
entry_type,
payload,
))
}
fn parse_meta(value: &Value) -> SessionMeta {
let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
SessionMeta {
id: string("id").or_else(|| string("session_id")),
timestamp: string("timestamp"),
cwd: string("cwd").map(PathBuf::from),
cli_version: string("cli_version"),
originator: string("originator"),
source: string("source"),
git: value.get("git").and_then(|git| {
let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
let meta = GitMeta {
commit_hash: get("commit_hash"),
branch: get("branch"),
repository_url: get("repository_url"),
};
(meta != GitMeta::default()).then_some(meta)
}),
raw: value.clone(),
}
}
fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
let mut out = Vec::new();
for year in numeric_children(root) {
for month in numeric_children(&year.1) {
for day in numeric_children(&month.1) {
out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
}
}
}
out
}
fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.filter_map(std::result::Result::ok)
.filter_map(|entry| {
let name = entry.file_name().into_string().ok()?;
let value = name.parse::<u32>().ok()?;
entry.path().is_dir().then(|| (value, entry.path()))
})
.collect()
}
fn session_id_from_path(path: &Path) -> Option<String> {
let name = path.file_name()?.to_str()?;
let name = name.strip_suffix(".zst").unwrap_or(name);
let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
let parts: Vec<&str> = stem.split('-').collect();
if parts.len() < 5 {
return None;
}
Some(parts[parts.len() - 5..].join("-"))
}
fn session_ran_in(path: &Path, wanted: &Path) -> bool {
let Ok(reader) = open(path).and_then(Log::reader) else {
return false;
};
let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
return false;
};
let Ok(value) = serde_json::from_str::<Value>(&first) else {
return false;
};
let meta = value.get("payload").unwrap_or(&value);
meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_home(label: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"codex-wrapper-history-{}-{label}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
let dir = home
.join("sessions")
.join(format!("{:04}", date.0))
.join(format!("{:02}", date.1))
.join(format!("{:02}", date.2));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
path
}
const MODERN: &[&str] = &[
r#"{"timestamp":"2026-08-06T10:11:24Z","type":"session_meta","payload":{"session_id":"019fd80e-eb27-70e3-ad2e-ed939930901a","id":"019fd80e-eb27-70e3-ad2e-ed939930901a","timestamp":"2026-08-06T10:11:24Z","cwd":"/repo","originator":"codex_cli_rs","cli_version":"0.145.0","source":"cli","git":{"commit_hash":"abc123","branch":"main","repository_url":"git@example.com:o/r.git"}}}"#,
r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
];
const LEGACY: &[&str] = &[
r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
r#"{"record_type":"state"}"#,
r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
];
#[test]
fn discovers_both_current_history_modes_and_preserves_their_payloads() {
let home = temp_home("current-history-modes");
for (mode, fixture, id, item_type) in [
(
"legacy",
include_str!("../tests/history/0.163.0-legacy.jsonl"),
"00000000-0000-4000-8000-000000000001",
"user_message",
),
(
"paginated",
include_str!("../tests/history/0.163.0-paginated.jsonl"),
"00000000-0000-4000-8000-000000000002",
"item_completed",
),
] {
let path = write_session(
&home,
(2026, 10, 20),
&format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
&fixture.lines().collect::<Vec<_>>(),
);
let log = read(&path).unwrap();
let meta = log.meta.unwrap();
assert_eq!(meta.id.as_deref(), Some(id));
assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
assert_eq!(meta.raw["history_mode"], mode);
assert_eq!(log.entries.len(), 4);
let captured: Vec<serde_json::Value> = fixture
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
assert_eq!(entry.payload, envelope["payload"]);
}
assert_eq!(log.entries[0].payload_type(), Some(item_type));
assert_eq!(log.entries[2].payload_type(), Some(item_type));
if mode == "paginated" {
assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
assert_eq!(
log.entries[0].payload["item"]["content"][0]["text"],
"synthetic offline history fixture"
);
}
}
let sessions = list_in(
&home,
&SessionQuery::new()
.cwd("/fixture/workspace")
.after(2026, 10, 20),
)
.unwrap();
assert_eq!(sessions.len(), 2);
std::fs::remove_dir_all(home).unwrap();
}
#[test]
fn types_the_records_of_every_tested_cli_version() {
use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};
for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
let path = format!(
"{}/tests/history/{version}.jsonl",
env!("CARGO_MANIFEST_DIR")
);
let records: Vec<String> = follow(Path::new(&path), &Position::default())
.0
.iter()
.filter_map(SessionEntry::record)
.map(|record| match record {
SessionRecord::Meta(meta) => {
assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
format!("meta {}", meta.cli_version.unwrap())
}
SessionRecord::TurnContext {
turn_id,
cwd,
model,
} => {
assert!(turn_id.is_some());
format!("context {} {}", cwd.unwrap().display(), model.unwrap())
}
SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
SessionRecord::ToolCall {
call_id,
name,
input,
..
} => {
assert!(input.to_string().contains("fixture"));
format!("call {name} {call_id:?}")
}
SessionRecord::ToolResult { call_id, output } => {
assert!(output.is_string() || output.is_array());
format!("result {}", call_id.unwrap())
}
SessionRecord::TurnComplete {
turn_id,
last_agent_message,
error,
} => {
assert!(turn_id.is_some());
format!("complete {last_agent_message:?} {error:?}")
}
SessionRecord::TurnAborted { turn_id, reason } => {
assert!(turn_id.is_some());
format!("aborted {}", reason.unwrap())
}
})
.collect();
assert_eq!(
records,
[
format!("meta {version}").as_str(),
"context /fixture/workspace gpt-5.2-codex",
"prompt first prompt",
r#"call exec_command Some("call_1")"#,
"result call_1",
r#"call apply_patch Some("call_2")"#,
"result call_2",
r#"call tool_search Some("call_3")"#,
"result call_3",
"call web_search None",
r#"complete Some("fixture answer") None"#,
"context /fixture/workspace gpt-5.2-codex",
"prompt interrupted prompt",
"aborted interrupted",
],
"{version}"
);
}
}
#[test]
fn a_web_search_without_an_action_is_still_a_call() {
let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
let record = values(line).map(entry).next().unwrap().record();
assert!(matches!(
record,
Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
));
}
#[test]
fn a_failed_turn_has_its_error() {
let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
return None;
};
error
});
assert!(failed.unwrap().contains("intentional offline fixture"));
}
fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
match read_from(path, position).unwrap() {
Continuation::Continued { entries, position } => (entries, position),
other => panic!("expected the log to continue, got {other:?}"),
}
}
#[test]
fn continues_after_the_last_complete_line() {
let home = temp_home("continue");
let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
let (entries, position) = follow(&path, &Position::default());
assert_eq!(entries.len(), 2);
assert_eq!(
position.offset(),
std::fs::metadata(&path).unwrap().len(),
"everything was read"
);
let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
let cut = line.find('é').unwrap() + 1;
let mut contents = std::fs::read(&path).unwrap();
contents.extend(&line.as_bytes()[..cut]);
std::fs::write(&path, &contents).unwrap();
assert_eq!(follow(&path, &position), (vec![], position.clone()));
contents.extend(&line.as_bytes()[cut..]);
contents.push(b'\n');
std::fs::write(&path, &contents).unwrap();
let saved = serde_json::to_string(&position).unwrap();
let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].record(),
Some(SessionRecord::Prompt {
turn_id: None,
text: "é".into()
})
);
}
#[test]
fn reports_a_truncated_or_replaced_log() {
let home = temp_home("replaced");
let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
let (_, position) = follow(&path, &Position::default());
let contents = std::fs::read_to_string(&path).unwrap();
std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
assert_eq!(
read_from(&path, &position).unwrap(),
Continuation::Replaced,
"same length, another session"
);
std::fs::write(&path, MODERN[0]).unwrap();
assert_eq!(
read_from(&path, &position).unwrap(),
Continuation::Truncated
);
}
#[test]
fn a_compressed_session_is_the_same_session() {
use ruzstd::encoding::{CompressionLevel, compress_to_vec};
let home = temp_home("compressed");
let path = write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
MODERN,
);
let query = SessionQuery::new().cwd("/repo");
let log = read(&path).unwrap();
let (_, position) = follow(&path, &Position::default());
let compressed = path.with_extension("jsonl.zst");
let contents = std::fs::read(&path).unwrap();
std::fs::write(
&compressed,
compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
)
.unwrap();
let listed = list_in(&home, &query).unwrap();
assert_eq!(listed.len(), 1, "one session while both files exist");
assert_eq!(listed[0].path, path);
std::fs::remove_file(&path).unwrap();
let listed = list_in(&home, &query).unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].path, compressed);
assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
assert_eq!(read(&compressed).unwrap().entries, log.entries);
assert_eq!(read(&path).unwrap(), log);
assert_eq!(follow(&path, &position), (vec![], position.clone()));
std::fs::write(&path, &contents).unwrap();
std::fs::remove_file(&compressed).unwrap();
assert_eq!(follow(&compressed, &position), (vec![], position));
}
#[test]
fn a_missing_sessions_directory_is_empty_not_an_error() {
let home = temp_home("empty");
assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
}
#[test]
fn lists_sessions_newest_first() {
let home = temp_home("order");
write_session(
&home,
(2026, 8, 1),
"rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
MODERN,
);
write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
MODERN,
);
write_session(
&home,
(2025, 9, 1),
"rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
LEGACY,
);
let found = list_in(&home, &SessionQuery::new()).unwrap();
let dates: Vec<_> = found.iter().map(|s| s.date).collect();
assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
}
#[test]
fn date_filters_narrow_the_listing() {
let home = temp_home("dates");
write_session(
&home,
(2026, 8, 1),
"rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
MODERN,
);
write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
MODERN,
);
let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
assert_eq!(after.len(), 1);
assert_eq!(after[0].date, (2026, 8, 6));
let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
assert_eq!(before.len(), 1);
assert_eq!(before[0].date, (2026, 8, 1));
let between = list_in(
&home,
&SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
)
.unwrap();
assert_eq!(between.len(), 2);
}
#[test]
fn cwd_filter_matches_the_recorded_directory() {
let home = temp_home("cwd");
write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
MODERN,
);
assert_eq!(
list_in(&home, &SessionQuery::new().cwd("/repo"))
.unwrap()
.len(),
1
);
assert_eq!(
list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
.unwrap()
.len(),
0
);
}
#[test]
fn reads_a_modern_session() {
let home = temp_home("modern");
let path = write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
MODERN,
);
let log = read(&path).unwrap();
let meta = log.meta.unwrap();
assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
assert_eq!(log.entries.len(), 3);
assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
}
#[test]
fn reads_a_legacy_session_without_an_envelope() {
let home = temp_home("legacy");
let path = write_session(
&home,
(2025, 9, 1),
"rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
LEGACY,
);
let log = read(&path).unwrap();
let meta = log.meta.expect("the first line is the metadata");
assert_eq!(
meta.id.as_deref(),
Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
);
assert_eq!(meta.cli_version, None, "legacy files record no version");
assert_eq!(meta.cwd, None, "legacy files record no cwd");
assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
assert_eq!(log.entries.len(), 2);
assert_eq!(log.entries[0].entry_type, None);
assert_eq!(log.entries[1].payload_type(), Some("message"));
}
#[test]
fn a_truncated_tail_does_not_lose_the_rest() {
let home = temp_home("truncated");
let mut lines = MODERN.to_vec();
lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
let path = write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
&lines,
);
let log = read(&path).unwrap();
assert!(log.meta.is_some());
assert_eq!(log.entries.len(), 3, "the good lines survive");
}
#[test]
fn session_id_comes_from_the_uuid_tail() {
assert_eq!(
session_id_from_path(Path::new(
"/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
)),
Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
);
assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
}
#[test]
fn a_reverted_thread_is_identified_by_its_thread_id() {
for extension in ["jsonl", "jsonl.zst"] {
let name = format!(
"/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
);
assert_eq!(
session_id_from_path(Path::new(&name)).as_deref(),
Some("aaaaaaaa-1111-2222-3333-444444444444"),
"{extension}"
);
}
}
#[test]
fn unknown_entry_types_are_kept_rather_than_dropped() {
let home = temp_home("unknown");
let path = write_session(
&home,
(2026, 8, 6),
"rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
&[
MODERN[0],
r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
],
);
let log = read(&path).unwrap();
assert_eq!(log.entries.len(), 1);
assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
}
}