1use std::fs::File;
122use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
123use std::path::{Path, PathBuf};
124
125use ruzstd::decoding::StreamingDecoder;
126use serde::{Deserialize, Serialize};
127use serde_json::Value;
128
129use crate::error::{Error, Result};
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct SessionFile {
134 pub path: PathBuf,
136 pub id: String,
140 pub date: (u16, u8, u8),
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
146#[non_exhaustive]
147pub struct GitMeta {
148 pub commit_hash: Option<String>,
150 pub branch: Option<String>,
152 pub repository_url: Option<String>,
154}
155
156#[derive(Debug, Clone, Default, PartialEq)]
161#[non_exhaustive]
162pub struct SessionMeta {
163 pub id: Option<String>,
165 pub timestamp: Option<String>,
167 pub cwd: Option<PathBuf>,
169 pub cli_version: Option<String>,
171 pub originator: Option<String>,
173 pub source: Option<String>,
175 pub git: Option<GitMeta>,
177 pub raw: Value,
179}
180
181#[derive(Debug, Clone, PartialEq)]
183pub struct SessionEntry {
184 pub timestamp: Option<String>,
186 pub entry_type: Option<String>,
191 pub payload: Value,
195}
196
197impl SessionEntry {
198 #[must_use]
203 pub fn payload_type(&self) -> Option<&str> {
204 self.payload.get("type")?.as_str()
205 }
206
207 #[must_use]
211 pub fn record(&self) -> Option<SessionRecord> {
212 let payload = &self.payload;
213 let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
214 let call = |name: String, input: &str| {
215 Some(SessionRecord::ToolCall {
216 call_id: string("call_id"),
217 name,
218 namespace: string("namespace"),
219 input: payload.get(input).cloned().unwrap_or_default(),
220 })
221 };
222 let result = |output: &str| {
223 Some(SessionRecord::ToolResult {
224 call_id: string("call_id"),
225 output: payload.get(output)?.clone(),
226 })
227 };
228
229 match (self.entry_type.as_deref()?, self.payload_type()) {
230 ("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
231 ("turn_context", _) => Some(SessionRecord::TurnContext {
232 turn_id: string("turn_id"),
233 cwd: string("cwd").map(PathBuf::from),
234 model: string("model"),
235 }),
236 ("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
239 turn_id: None,
240 text: string("message")?,
241 }),
242 ("event_msg", Some("item_completed")) => {
243 let item = payload.get("item")?;
244 if item.get("type")? != "UserMessage" {
245 return None;
246 }
247 let parts = item.get("content")?.as_array()?;
248 Some(SessionRecord::Prompt {
249 turn_id: string("turn_id"),
250 text: parts
251 .iter()
252 .filter_map(|part| part.get("text")?.as_str())
253 .collect(),
254 })
255 }
256 ("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
257 turn_id: string("turn_id"),
258 last_agent_message: string("last_agent_message"),
259 error: payload
260 .pointer("/error/message")
261 .and_then(Value::as_str)
262 .map(str::to_string),
263 }),
264 ("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
265 turn_id: string("turn_id"),
266 reason: string("reason"),
267 }),
268 ("response_item", Some("function_call")) => call(string("name")?, "arguments"),
269 ("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
270 ("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
271 ("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
272 ("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
273 result("output")
274 }
275 ("response_item", Some("tool_search_output")) => result("tools"),
276 _ => None,
277 }
278 }
279}
280
281#[derive(Debug, Clone, PartialEq)]
285#[non_exhaustive]
286pub enum SessionRecord {
287 Meta(Box<SessionMeta>),
289 #[non_exhaustive]
291 TurnContext {
292 turn_id: Option<String>,
294 cwd: Option<PathBuf>,
296 model: Option<String>,
298 },
299 #[non_exhaustive]
301 Prompt {
302 turn_id: Option<String>,
304 text: String,
306 },
307 #[non_exhaustive]
312 ToolCall {
313 call_id: Option<String>,
316 name: String,
318 namespace: Option<String>,
320 input: Value,
323 },
324 #[non_exhaustive]
326 ToolResult {
327 call_id: Option<String>,
329 output: Value,
331 },
332 #[non_exhaustive]
334 TurnComplete {
335 turn_id: Option<String>,
337 last_agent_message: Option<String>,
339 error: Option<String>,
341 },
342 #[non_exhaustive]
344 TurnAborted {
345 turn_id: Option<String>,
347 reason: Option<String>,
349 },
350}
351
352#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
356pub struct Position {
357 offset: u64,
358 fingerprint: u64,
359}
360
361impl Position {
362 pub fn at_offset(path: impl AsRef<Path>, offset: u64) -> Result<Self> {
374 Self::locate(path.as_ref(), |_| offset)
375 }
376
377 pub fn before_end(path: impl AsRef<Path>, bytes: u64) -> Result<Self> {
385 Self::locate(path.as_ref(), |end| end.saturating_sub(bytes))
386 }
387
388 fn locate(path: &Path, offset: impl FnOnce(u64) -> u64) -> Result<Self> {
389 open(path)
390 .and_then(|log| {
391 let mut log = log.seekable()?;
392 let offset = offset(log.seek(SeekFrom::End(0))?);
393 Self::new(&mut log, offset)
394 })
395 .map_err(|e| read_error(path, e))
396 }
397
398 fn new(log: &mut (impl Read + Seek), offset: u64) -> io::Result<Self> {
399 Ok(Self {
400 offset,
401 fingerprint: fingerprint(log, offset)?,
402 })
403 }
404
405 #[must_use]
407 pub fn offset(&self) -> u64 {
408 self.offset
409 }
410}
411
412#[derive(Debug, Clone, PartialEq)]
414pub enum Continuation {
415 Continued {
417 entries: Vec<SessionEntry>,
420 position: Position,
422 },
423 Truncated,
425 Replaced,
427}
428
429#[derive(Debug, Clone, PartialEq)]
431pub enum Chunk {
432 Continued {
434 entries: Vec<ChunkEntry>,
437 position: Position,
439 },
440 Truncated,
442 Replaced,
444}
445
446#[derive(Debug, Clone, PartialEq)]
448#[non_exhaustive]
449pub struct ChunkEntry {
450 pub offset: u64,
454 pub entry: SessionEntry,
456}
457
458#[derive(Debug, Clone, PartialEq)]
460pub struct SessionLog {
461 pub path: PathBuf,
463 pub meta: Option<SessionMeta>,
465 pub entries: Vec<SessionEntry>,
467}
468
469#[derive(Debug, Clone, Default)]
471pub struct SessionQuery {
472 after: Option<(u16, u8, u8)>,
473 before: Option<(u16, u8, u8)>,
474 cwd: Option<PathBuf>,
475}
476
477impl SessionQuery {
478 #[must_use]
480 pub fn new() -> Self {
481 Self::default()
482 }
483
484 #[must_use]
486 pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
487 self.after = Some((year, month, day));
488 self
489 }
490
491 #[must_use]
493 pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
494 self.before = Some((year, month, day));
495 self
496 }
497
498 #[must_use]
504 pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
505 self.cwd = Some(cwd.into());
506 self
507 }
508
509 fn matches_date(&self, date: (u16, u8, u8)) -> bool {
510 self.after.is_none_or(|after| date >= after)
511 && self.before.is_none_or(|before| date <= before)
512 }
513}
514
515pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
519 let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
520 list_in(home, query)
521}
522
523pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
528 let root = codex_home.as_ref().join("sessions");
529 let mut found = Vec::new();
530
531 for (date, day_dir) in date_dirs(&root) {
532 if !query.matches_date(date) {
533 continue;
534 }
535 let Ok(entries) = std::fs::read_dir(&day_dir) else {
536 continue;
537 };
538 for entry in entries.filter_map(std::result::Result::ok) {
539 let path = entry.path();
540 let Some(id) = session_id_from_path(&path) else {
541 continue;
542 };
543 if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
545 {
546 continue;
547 }
548 if let Some(wanted) = &query.cwd
549 && !session_ran_in(&path, wanted)
550 {
551 continue;
552 }
553 found.push(SessionFile { path, id, date });
554 }
555 }
556
557 found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
560 Ok(found)
561}
562
563pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
565 let path = path.as_ref();
566 let mut contents = Vec::new();
567 open(path)
568 .and_then(|log| log.reader()?.read_to_end(&mut contents))
569 .map_err(|e| read_error(path, e))?;
570
571 let mut meta = None;
572 let mut entries = Vec::new();
573
574 for value in values(&contents) {
575 if meta.is_none()
576 && let Some(found) = metadata(&value)
577 {
578 meta = Some(parse_meta(found));
579 } else {
580 entries.push(entry(value));
581 }
582 }
583
584 Ok(SessionLog {
585 path: path.to_path_buf(),
586 meta,
587 entries,
588 })
589}
590
591pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
600 Ok(match read_chunk(path, position, None)? {
601 Chunk::Continued { entries, position } => Continuation::Continued {
602 entries: entries.into_iter().map(|found| found.entry).collect(),
603 position,
604 },
605 Chunk::Truncated => Continuation::Truncated,
606 Chunk::Replaced => Continuation::Replaced,
607 })
608}
609
610pub fn read_chunk(
620 path: impl AsRef<Path>,
621 position: &Position,
622 max_bytes: Option<u64>,
623) -> Result<Chunk> {
624 let path = path.as_ref();
625 open(path)
626 .and_then(|log| {
627 let max_bytes = match log {
628 Log::Plain(_) => max_bytes,
629 Log::Compressed(_) => None,
630 };
631 continue_from(log.seekable()?, position, max_bytes.unwrap_or(u64::MAX))
632 })
633 .map_err(|e| read_error(path, e))
634}
635
636fn continue_from(
637 mut log: impl Read + Seek,
638 position: &Position,
639 max_bytes: u64,
640) -> io::Result<Chunk> {
641 if log.seek(SeekFrom::End(0))? < position.offset {
642 return Ok(Chunk::Truncated);
643 }
644 if fingerprint(&mut log, position.offset)? != position.fingerprint {
645 return Ok(Chunk::Replaced);
646 }
647
648 let mut inside_entry = false;
649 if let Some(before) = position.offset.checked_sub(1) {
650 let mut byte = [0];
651 log.seek(SeekFrom::Start(before))?;
652 log.read_exact(&mut byte)?;
653 inside_entry = byte != *b"\n";
654 } else {
655 log.seek(SeekFrom::Start(0))?;
656 }
657
658 let mut reader = BufReader::new(&mut log);
659 let mut offset = position.offset;
660 let mut entries = Vec::new();
661 let mut line = Vec::new();
662 loop {
663 let left = if entries.is_empty() {
664 u64::MAX
665 } else {
666 max_bytes.saturating_sub(offset - position.offset)
667 };
668 line.clear();
669 reader.by_ref().take(left).read_until(b'\n', &mut line)?;
670 if line.last() != Some(&b'\n') {
671 break;
672 }
673 if !inside_entry && let Some(value) = values(&line).next() {
674 entries.push(ChunkEntry {
675 offset,
676 entry: entry(value),
677 });
678 }
679 inside_entry = false;
680 offset += line.len() as u64;
681 }
682 Ok(Chunk::Continued {
683 entries,
684 position: Position::new(&mut log, offset)?,
685 })
686}
687
688fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
693 if offset == 0 {
694 return Ok(Position::default().fingerprint);
695 }
696 let window = offset.min(4096);
697 let mut bytes = Vec::new();
698 for start in [0, offset - window] {
699 log.seek(SeekFrom::Start(start))?;
700 log.by_ref().take(window).read_to_end(&mut bytes)?;
701 }
702 Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
703 (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
704 }))
705}
706
707enum Log {
708 Plain(File),
709 Compressed(File),
710}
711
712trait ReadSeek: Read + Seek {}
713
714impl<T: Read + Seek> ReadSeek for T {}
715
716impl Log {
717 fn reader(self) -> io::Result<Box<dyn Read>> {
718 Ok(match self {
719 Self::Plain(file) => Box::new(file),
720 Self::Compressed(file) => {
721 Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
722 }
723 })
724 }
725
726 fn seekable(self) -> io::Result<Box<dyn ReadSeek>> {
728 Ok(match self {
729 Self::Plain(file) => Box::new(file),
730 Self::Compressed(_) => {
731 let mut contents = Vec::new();
732 self.reader()?.read_to_end(&mut contents)?;
733 Box::new(Cursor::new(contents))
734 }
735 })
736 }
737}
738
739fn open(path: &Path) -> io::Result<Log> {
741 let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
742 Some(plain) => PathBuf::from(plain),
743 None => path.to_path_buf(),
744 };
745 let mut compressed = plain.clone().into_os_string();
746 compressed.push(".zst");
747
748 let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
749 match File::open(&plain) {
750 Err(e) if missing(&e) => match File::open(compressed) {
751 Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
754 file => file.map(Log::Compressed),
755 },
756 file => file.map(Log::Plain),
757 }
758}
759
760fn read_error(path: &Path, source: io::Error) -> Error {
761 Error::Io {
762 message: format!("failed to read {}: {source}", path.display()),
763 source,
764 working_dir: None,
765 }
766}
767
768fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
774 contents
775 .split(|byte| *byte == b'\n')
776 .filter_map(|line| serde_json::from_slice(line).ok())
777}
778
779fn metadata(value: &Value) -> Option<&Value> {
784 match envelope(value) {
785 Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
786 None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
787 }
788}
789
790fn entry(value: Value) -> SessionEntry {
791 match envelope(&value) {
792 Some((timestamp, entry_type, payload)) => SessionEntry {
793 timestamp: timestamp.map(str::to_string),
794 entry_type: Some(entry_type.to_string()),
795 payload: payload.clone(),
796 },
797 None => SessionEntry {
798 timestamp: value
799 .get("timestamp")
800 .and_then(Value::as_str)
801 .map(str::to_string),
802 entry_type: None,
803 payload: value,
804 },
805 }
806}
807
808fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
811 let payload = value.get("payload")?;
812 let entry_type = value.get("type")?.as_str()?;
813 Some((
814 value.get("timestamp").and_then(Value::as_str),
815 entry_type,
816 payload,
817 ))
818}
819
820fn parse_meta(value: &Value) -> SessionMeta {
821 let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
822 SessionMeta {
823 id: string("id").or_else(|| string("session_id")),
824 timestamp: string("timestamp"),
825 cwd: string("cwd").map(PathBuf::from),
826 cli_version: string("cli_version"),
827 originator: string("originator"),
828 source: string("source"),
829 git: value.get("git").and_then(|git| {
830 let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
831 let meta = GitMeta {
832 commit_hash: get("commit_hash"),
833 branch: get("branch"),
834 repository_url: get("repository_url"),
835 };
836 (meta != GitMeta::default()).then_some(meta)
837 }),
838 raw: value.clone(),
839 }
840}
841
842fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
844 let mut out = Vec::new();
845 for year in numeric_children(root) {
846 for month in numeric_children(&year.1) {
847 for day in numeric_children(&month.1) {
848 out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
849 }
850 }
851 }
852 out
853}
854
855fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
857 let Ok(entries) = std::fs::read_dir(dir) else {
858 return Vec::new();
859 };
860 entries
861 .filter_map(std::result::Result::ok)
862 .filter_map(|entry| {
863 let name = entry.file_name().into_string().ok()?;
864 let value = name.parse::<u32>().ok()?;
865 entry.path().is_dir().then(|| (value, entry.path()))
866 })
867 .collect()
868}
869
870fn session_id_from_path(path: &Path) -> Option<String> {
876 let name = path.file_name()?.to_str()?;
877 let name = name.strip_suffix(".zst").unwrap_or(name);
878 let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
879 let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
880 let parts: Vec<&str> = stem.split('-').collect();
881 if parts.len() < 5 {
882 return None;
883 }
884 Some(parts[parts.len() - 5..].join("-"))
885}
886
887fn session_ran_in(path: &Path, wanted: &Path) -> bool {
889 let Ok(reader) = open(path).and_then(Log::reader) else {
890 return false;
891 };
892 let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
893 let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
894 return false;
895 };
896 let Ok(value) = serde_json::from_str::<Value>(&first) else {
897 return false;
898 };
899 let meta = value.get("payload").unwrap_or(&value);
900 meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
901}
902
903#[cfg(test)]
904mod tests {
905 use super::*;
906
907 fn temp_home(label: &str) -> PathBuf {
908 let dir = std::env::temp_dir().join(format!(
909 "codex-wrapper-history-{}-{label}",
910 std::process::id()
911 ));
912 let _ = std::fs::remove_dir_all(&dir);
913 dir
914 }
915
916 fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
917 let dir = home
918 .join("sessions")
919 .join(format!("{:04}", date.0))
920 .join(format!("{:02}", date.1))
921 .join(format!("{:02}", date.2));
922 std::fs::create_dir_all(&dir).unwrap();
923 let path = dir.join(name);
924 std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
925 path
926 }
927
928 const MODERN: &[&str] = &[
931 r#"{"timestamp":"2026-08-06T10:11:24Z","type":"session_meta","payload":{"session_id":"019fd80e-eb27-70e3-ad2e-ed939930901a","id":"019fd80e-eb27-70e3-ad2e-ed939930901a","timestamp":"2026-08-06T10:11:24Z","cwd":"/repo","originator":"codex_cli_rs","cli_version":"0.145.0","source":"cli","git":{"commit_hash":"abc123","branch":"main","repository_url":"git@example.com:o/r.git"}}}"#,
932 r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
933 r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
934 r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
935 ];
936
937 const LEGACY: &[&str] = &[
939 r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
940 r#"{"record_type":"state"}"#,
941 r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
942 ];
943
944 #[test]
945 fn discovers_both_current_history_modes_and_preserves_their_payloads() {
946 let home = temp_home("current-history-modes");
947 for (mode, fixture, id, item_type) in [
948 (
949 "legacy",
950 include_str!("../tests/history/0.163.0-legacy.jsonl"),
951 "00000000-0000-4000-8000-000000000001",
952 "user_message",
953 ),
954 (
955 "paginated",
956 include_str!("../tests/history/0.163.0-paginated.jsonl"),
957 "00000000-0000-4000-8000-000000000002",
958 "item_completed",
959 ),
960 ] {
961 let path = write_session(
962 &home,
963 (2026, 10, 20),
964 &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
965 &fixture.lines().collect::<Vec<_>>(),
966 );
967 let log = read(&path).unwrap();
968 let meta = log.meta.unwrap();
969 assert_eq!(meta.id.as_deref(), Some(id));
970 assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
971 assert_eq!(meta.raw["history_mode"], mode);
972 assert_eq!(log.entries.len(), 4);
973 let captured: Vec<serde_json::Value> = fixture
974 .lines()
975 .map(|line| serde_json::from_str(line).unwrap())
976 .collect();
977 for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
978 assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
979 assert_eq!(entry.payload, envelope["payload"]);
980 }
981 assert_eq!(log.entries[0].payload_type(), Some(item_type));
982 assert_eq!(log.entries[2].payload_type(), Some(item_type));
983 if mode == "paginated" {
984 assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
985 assert_eq!(
986 log.entries[0].payload["item"]["content"][0]["text"],
987 "synthetic offline history fixture"
988 );
989 }
990 }
991 let sessions = list_in(
992 &home,
993 &SessionQuery::new()
994 .cwd("/fixture/workspace")
995 .after(2026, 10, 20),
996 )
997 .unwrap();
998 assert_eq!(sessions.len(), 2);
999 std::fs::remove_dir_all(home).unwrap();
1000 }
1001
1002 #[test]
1005 fn types_the_records_of_every_tested_cli_version() {
1006 use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};
1007
1008 for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
1009 let path = format!(
1010 "{}/tests/history/{version}.jsonl",
1011 env!("CARGO_MANIFEST_DIR")
1012 );
1013 let records: Vec<String> = follow(Path::new(&path), &Position::default())
1014 .0
1015 .iter()
1016 .filter_map(SessionEntry::record)
1017 .map(|record| match record {
1018 SessionRecord::Meta(meta) => {
1019 assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
1020 format!("meta {}", meta.cli_version.unwrap())
1021 }
1022 SessionRecord::TurnContext {
1023 turn_id,
1024 cwd,
1025 model,
1026 } => {
1027 assert!(turn_id.is_some());
1028 format!("context {} {}", cwd.unwrap().display(), model.unwrap())
1029 }
1030 SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
1031 SessionRecord::ToolCall {
1032 call_id,
1033 name,
1034 input,
1035 ..
1036 } => {
1037 assert!(input.to_string().contains("fixture"));
1038 format!("call {name} {call_id:?}")
1039 }
1040 SessionRecord::ToolResult { call_id, output } => {
1041 assert!(output.is_string() || output.is_array());
1042 format!("result {}", call_id.unwrap())
1043 }
1044 SessionRecord::TurnComplete {
1045 turn_id,
1046 last_agent_message,
1047 error,
1048 } => {
1049 assert!(turn_id.is_some());
1050 format!("complete {last_agent_message:?} {error:?}")
1051 }
1052 SessionRecord::TurnAborted { turn_id, reason } => {
1053 assert!(turn_id.is_some());
1054 format!("aborted {}", reason.unwrap())
1055 }
1056 })
1057 .collect();
1058 assert_eq!(
1059 records,
1060 [
1061 format!("meta {version}").as_str(),
1062 "context /fixture/workspace gpt-5.2-codex",
1063 "prompt first prompt",
1064 r#"call exec_command Some("call_1")"#,
1065 "result call_1",
1066 r#"call apply_patch Some("call_2")"#,
1067 "result call_2",
1068 r#"call tool_search Some("call_3")"#,
1069 "result call_3",
1070 "call web_search None",
1071 r#"complete Some("fixture answer") None"#,
1072 "context /fixture/workspace gpt-5.2-codex",
1073 "prompt interrupted prompt",
1074 "aborted interrupted",
1075 ],
1076 "{version}"
1077 );
1078 }
1079 }
1080
1081 #[test]
1083 fn a_web_search_without_an_action_is_still_a_call() {
1084 let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
1085 let record = values(line).map(entry).next().unwrap().record();
1086 assert!(matches!(
1087 record,
1088 Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
1089 ));
1090 }
1091
1092 #[test]
1093 fn a_failed_turn_has_its_error() {
1094 let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
1095 let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
1096 let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
1097 return None;
1098 };
1099 error
1100 });
1101 assert!(failed.unwrap().contains("intentional offline fixture"));
1102 }
1103
1104 fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
1105 match read_from(path, position).unwrap() {
1106 Continuation::Continued { entries, position } => (entries, position),
1107 other => panic!("expected the log to continue, got {other:?}"),
1108 }
1109 }
1110
1111 #[test]
1112 fn continues_after_the_last_complete_line() {
1113 let home = temp_home("continue");
1114 let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
1115 let (entries, position) = follow(&path, &Position::default());
1116 assert_eq!(entries.len(), 2);
1117 assert_eq!(
1118 position.offset(),
1119 std::fs::metadata(&path).unwrap().len(),
1120 "everything was read"
1121 );
1122
1123 let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
1125 let cut = line.find('é').unwrap() + 1;
1126 let mut contents = std::fs::read(&path).unwrap();
1127 contents.extend(&line.as_bytes()[..cut]);
1128 std::fs::write(&path, &contents).unwrap();
1129 assert_eq!(follow(&path, &position), (vec![], position.clone()));
1130
1131 contents.extend(&line.as_bytes()[cut..]);
1132 contents.push(b'\n');
1133 std::fs::write(&path, &contents).unwrap();
1134 let saved = serde_json::to_string(&position).unwrap();
1135 let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
1136 assert_eq!(entries.len(), 1);
1137 assert_eq!(
1138 entries[0].record(),
1139 Some(SessionRecord::Prompt {
1140 turn_id: None,
1141 text: "é".into()
1142 })
1143 );
1144 }
1145
1146 #[test]
1147 fn reports_a_truncated_or_replaced_log() {
1148 let home = temp_home("replaced");
1149 let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1150 let (_, position) = follow(&path, &Position::default());
1151
1152 let contents = std::fs::read_to_string(&path).unwrap();
1153 std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
1154 assert_eq!(
1155 read_from(&path, &position).unwrap(),
1156 Continuation::Replaced,
1157 "same length, another session"
1158 );
1159
1160 std::fs::write(&path, MODERN[0]).unwrap();
1161 assert_eq!(
1162 read_from(&path, &position).unwrap(),
1163 Continuation::Truncated
1164 );
1165 }
1166
1167 fn chunk(
1168 path: &Path,
1169 position: &Position,
1170 max_bytes: Option<u64>,
1171 ) -> (Vec<(u64, SessionEntry)>, Position) {
1172 match read_chunk(path, position, max_bytes).unwrap() {
1173 Chunk::Continued { entries, position } => (
1174 entries.into_iter().map(|e| (e.offset, e.entry)).collect(),
1175 position,
1176 ),
1177 other => panic!("expected the log to continue, got {other:?}"),
1178 }
1179 }
1180
1181 fn modern_entries() -> Vec<(u64, SessionEntry)> {
1183 let mut offset = 0;
1184 MODERN
1185 .iter()
1186 .map(|line| {
1187 let start = offset;
1188 offset += line.len() as u64 + 1;
1189 (start, entry(serde_json::from_str(line).unwrap()))
1190 })
1191 .collect()
1192 }
1193
1194 #[test]
1195 fn starts_at_the_first_entry_after_a_place() {
1196 let home = temp_home("place");
1197 let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1198 let end = std::fs::metadata(&path).unwrap().len();
1199 let all = modern_entries();
1200
1201 for offset in 0..=end {
1202 let expected: Vec<_> = all.iter().filter(|e| e.0 >= offset).cloned().collect();
1203 let position = Position::at_offset(&path, offset).unwrap();
1204 assert_eq!(position.offset(), offset);
1205 assert_eq!(Position::before_end(&path, end - offset).unwrap(), position);
1206 let (entries, next) = chunk(&path, &position, None);
1207 assert_eq!(entries, expected, "from {offset}");
1208 assert_eq!(next.offset(), end);
1209 assert_eq!(follow(&path, &position).0.len(), expected.len());
1210 }
1211 assert_eq!(
1212 Position::before_end(&path, end + 1).unwrap(),
1213 Position::default()
1214 );
1215 }
1216
1217 #[test]
1218 fn an_incomplete_entry_is_skipped_from_a_place_inside_it() {
1219 let home = temp_home("place-incomplete");
1220 let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..1]);
1221 let complete = std::fs::read_to_string(&path).unwrap();
1222 std::fs::write(&path, format!("{complete}{}", &MODERN[1][..20])).unwrap();
1223
1224 let position = Position::before_end(&path, 5).unwrap();
1225 assert_eq!(chunk(&path, &position, None), (vec![], position.clone()));
1226
1227 std::fs::write(&path, format!("{}\n", MODERN.join("\n"))).unwrap();
1228 assert_eq!(chunk(&path, &position, None).0, modern_entries()[2..]);
1229 }
1230
1231 #[test]
1232 fn a_place_past_the_end_is_not_in_the_log() {
1233 let home = temp_home("place-past-end");
1234 let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..1]);
1235 let end = std::fs::metadata(&path).unwrap().len();
1236 let position = Position::at_offset(&path, end + 1).unwrap();
1237 assert_eq!(
1238 read_chunk(&path, &position, None).unwrap(),
1239 Chunk::Truncated
1240 );
1241 std::fs::write(&path, format!("{}\n", MODERN.join("\n"))).unwrap();
1242 assert_eq!(read_chunk(&path, &position, None).unwrap(), Chunk::Replaced);
1243 }
1244
1245 #[test]
1246 fn a_limited_read_returns_at_least_one_entry() {
1247 let home = temp_home("limit");
1248 let mut lines = vec!["not json"];
1250 lines.extend(MODERN);
1251 let path = write_session(&home, (2026, 8, 6), "log.jsonl", &lines);
1252 let end = std::fs::metadata(&path).unwrap().len();
1253 let all = chunk(&path, &Position::default(), None).0;
1254 assert_eq!(all.len(), MODERN.len());
1255
1256 for max_bytes in 0..=end {
1257 let mut position = Position::default();
1258 let mut read = Vec::new();
1259 loop {
1260 let (entries, next) = chunk(&path, &position, Some(max_bytes));
1261 if entries.is_empty() {
1262 break;
1263 }
1264 assert!(
1265 entries.len() == 1 || next.offset() - position.offset() <= max_bytes,
1266 "{} entries with a limit of {max_bytes}",
1267 entries.len()
1268 );
1269 read.extend(entries);
1270 position = next;
1271 }
1272 assert_eq!(read, all, "limit {max_bytes}");
1273 assert_eq!(position.offset(), end);
1274 }
1275
1276 let two = all[2].0;
1278 assert_eq!(chunk(&path, &Position::default(), Some(two)).0, all[..2]);
1279 assert_eq!(
1280 chunk(&path, &Position::default(), Some(two - 1)).0,
1281 all[..1]
1282 );
1283 }
1284
1285 #[test]
1286 fn a_compressed_log_has_the_same_places_and_no_limit() {
1287 use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1288
1289 let home = temp_home("compressed-places");
1290 let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1291 let all = modern_entries();
1292 let at = Position::at_offset(&path, all[1].0).unwrap();
1293 let before = Position::before_end(&path, 10).unwrap();
1294
1295 let contents = std::fs::read(&path).unwrap();
1296 std::fs::write(
1297 path.with_extension("jsonl.zst"),
1298 compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1299 )
1300 .unwrap();
1301 std::fs::remove_file(&path).unwrap();
1302
1303 assert_eq!(Position::at_offset(&path, all[1].0).unwrap(), at);
1304 assert_eq!(Position::before_end(&path, 10).unwrap(), before);
1305 assert_eq!(chunk(&path, &at, Some(1)).0, all[1..]);
1306 }
1307
1308 #[test]
1309 fn a_compressed_session_is_the_same_session() {
1310 use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1311
1312 let home = temp_home("compressed");
1313 let path = write_session(
1314 &home,
1315 (2026, 8, 6),
1316 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1317 MODERN,
1318 );
1319 let query = SessionQuery::new().cwd("/repo");
1320 let log = read(&path).unwrap();
1321 let (_, position) = follow(&path, &Position::default());
1322
1323 let compressed = path.with_extension("jsonl.zst");
1324 let contents = std::fs::read(&path).unwrap();
1325 std::fs::write(
1326 &compressed,
1327 compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1328 )
1329 .unwrap();
1330 let listed = list_in(&home, &query).unwrap();
1331 assert_eq!(listed.len(), 1, "one session while both files exist");
1332 assert_eq!(listed[0].path, path);
1333
1334 std::fs::remove_file(&path).unwrap();
1335 let listed = list_in(&home, &query).unwrap();
1336 assert_eq!(listed.len(), 1);
1337 assert_eq!(listed[0].path, compressed);
1338 assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1339 assert_eq!(read(&compressed).unwrap().entries, log.entries);
1340 assert_eq!(read(&path).unwrap(), log);
1342 assert_eq!(follow(&path, &position), (vec![], position.clone()));
1343
1344 std::fs::write(&path, &contents).unwrap();
1346 std::fs::remove_file(&compressed).unwrap();
1347 assert_eq!(follow(&compressed, &position), (vec![], position));
1348 }
1349
1350 #[test]
1351 fn a_missing_sessions_directory_is_empty_not_an_error() {
1352 let home = temp_home("empty");
1353 assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
1354 }
1355
1356 #[test]
1357 fn lists_sessions_newest_first() {
1358 let home = temp_home("order");
1359 write_session(
1360 &home,
1361 (2026, 8, 1),
1362 "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1363 MODERN,
1364 );
1365 write_session(
1366 &home,
1367 (2026, 8, 6),
1368 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1369 MODERN,
1370 );
1371 write_session(
1372 &home,
1373 (2025, 9, 1),
1374 "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1375 LEGACY,
1376 );
1377
1378 let found = list_in(&home, &SessionQuery::new()).unwrap();
1379 let dates: Vec<_> = found.iter().map(|s| s.date).collect();
1380 assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
1381 assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1382 }
1383
1384 #[test]
1385 fn date_filters_narrow_the_listing() {
1386 let home = temp_home("dates");
1387 write_session(
1388 &home,
1389 (2026, 8, 1),
1390 "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1391 MODERN,
1392 );
1393 write_session(
1394 &home,
1395 (2026, 8, 6),
1396 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1397 MODERN,
1398 );
1399
1400 let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
1401 assert_eq!(after.len(), 1);
1402 assert_eq!(after[0].date, (2026, 8, 6));
1403
1404 let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
1405 assert_eq!(before.len(), 1);
1406 assert_eq!(before[0].date, (2026, 8, 1));
1407
1408 let between = list_in(
1409 &home,
1410 &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
1411 )
1412 .unwrap();
1413 assert_eq!(between.len(), 2);
1414 }
1415
1416 #[test]
1417 fn cwd_filter_matches_the_recorded_directory() {
1418 let home = temp_home("cwd");
1419 write_session(
1420 &home,
1421 (2026, 8, 6),
1422 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1423 MODERN,
1424 );
1425
1426 assert_eq!(
1427 list_in(&home, &SessionQuery::new().cwd("/repo"))
1428 .unwrap()
1429 .len(),
1430 1
1431 );
1432 assert_eq!(
1433 list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
1434 .unwrap()
1435 .len(),
1436 0
1437 );
1438 }
1439
1440 #[test]
1441 fn reads_a_modern_session() {
1442 let home = temp_home("modern");
1443 let path = write_session(
1444 &home,
1445 (2026, 8, 6),
1446 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1447 MODERN,
1448 );
1449
1450 let log = read(&path).unwrap();
1451 let meta = log.meta.unwrap();
1452 assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
1453 assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
1454 assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
1455
1456 assert_eq!(log.entries.len(), 3);
1458 assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
1459 assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
1460 }
1461
1462 #[test]
1465 fn reads_a_legacy_session_without_an_envelope() {
1466 let home = temp_home("legacy");
1467 let path = write_session(
1468 &home,
1469 (2025, 9, 1),
1470 "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1471 LEGACY,
1472 );
1473
1474 let log = read(&path).unwrap();
1475 let meta = log.meta.expect("the first line is the metadata");
1476 assert_eq!(
1477 meta.id.as_deref(),
1478 Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
1479 );
1480 assert_eq!(meta.cli_version, None, "legacy files record no version");
1481 assert_eq!(meta.cwd, None, "legacy files record no cwd");
1482 assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
1483
1484 assert_eq!(log.entries.len(), 2);
1485 assert_eq!(log.entries[0].entry_type, None);
1487 assert_eq!(log.entries[1].payload_type(), Some("message"));
1488 }
1489
1490 #[test]
1493 fn a_truncated_tail_does_not_lose_the_rest() {
1494 let home = temp_home("truncated");
1495 let mut lines = MODERN.to_vec();
1496 lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
1497 let path = write_session(
1498 &home,
1499 (2026, 8, 6),
1500 "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
1501 &lines,
1502 );
1503
1504 let log = read(&path).unwrap();
1505 assert!(log.meta.is_some());
1506 assert_eq!(log.entries.len(), 3, "the good lines survive");
1507 }
1508
1509 #[test]
1512 fn session_id_comes_from_the_uuid_tail() {
1513 assert_eq!(
1514 session_id_from_path(Path::new(
1515 "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
1516 )),
1517 Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
1518 );
1519 assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
1520 }
1521
1522 #[test]
1525 fn a_reverted_thread_is_identified_by_its_thread_id() {
1526 for extension in ["jsonl", "jsonl.zst"] {
1527 let name = format!(
1528 "/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
1529 );
1530 assert_eq!(
1531 session_id_from_path(Path::new(&name)).as_deref(),
1532 Some("aaaaaaaa-1111-2222-3333-444444444444"),
1533 "{extension}"
1534 );
1535 }
1536 }
1537
1538 #[test]
1539 fn unknown_entry_types_are_kept_rather_than_dropped() {
1540 let home = temp_home("unknown");
1541 let path = write_session(
1542 &home,
1543 (2026, 8, 6),
1544 "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
1545 &[
1546 MODERN[0],
1547 r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
1548 ],
1549 );
1550
1551 let log = read(&path).unwrap();
1552 assert_eq!(log.entries.len(), 1);
1553 assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
1554 assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
1555 }
1556}