1use std::fs::File;
119use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
120use std::path::{Path, PathBuf};
121
122use ruzstd::decoding::StreamingDecoder;
123use serde::{Deserialize, Serialize};
124use serde_json::Value;
125
126use crate::error::{Error, Result};
127
128#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct SessionFile {
131 pub path: PathBuf,
133 pub id: String,
137 pub date: (u16, u8, u8),
139}
140
141#[derive(Debug, Clone, Default, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct GitMeta {
145 pub commit_hash: Option<String>,
147 pub branch: Option<String>,
149 pub repository_url: Option<String>,
151}
152
153#[derive(Debug, Clone, Default, PartialEq)]
158#[non_exhaustive]
159pub struct SessionMeta {
160 pub id: Option<String>,
162 pub timestamp: Option<String>,
164 pub cwd: Option<PathBuf>,
166 pub cli_version: Option<String>,
168 pub originator: Option<String>,
170 pub source: Option<String>,
172 pub git: Option<GitMeta>,
174 pub raw: Value,
176}
177
178#[derive(Debug, Clone, PartialEq)]
180pub struct SessionEntry {
181 pub timestamp: Option<String>,
183 pub entry_type: Option<String>,
188 pub payload: Value,
192}
193
194impl SessionEntry {
195 #[must_use]
200 pub fn payload_type(&self) -> Option<&str> {
201 self.payload.get("type")?.as_str()
202 }
203
204 #[must_use]
208 pub fn record(&self) -> Option<SessionRecord> {
209 let payload = &self.payload;
210 let string = |key: &str| payload.get(key)?.as_str().map(str::to_string);
211 let call = |name: String, input: &str| {
212 Some(SessionRecord::ToolCall {
213 call_id: string("call_id"),
214 name,
215 namespace: string("namespace"),
216 input: payload.get(input).cloned().unwrap_or_default(),
217 })
218 };
219 let result = |output: &str| {
220 Some(SessionRecord::ToolResult {
221 call_id: string("call_id"),
222 output: payload.get(output)?.clone(),
223 })
224 };
225
226 match (self.entry_type.as_deref()?, self.payload_type()) {
227 ("session_meta", _) => Some(SessionRecord::Meta(Box::new(parse_meta(payload)))),
228 ("turn_context", _) => Some(SessionRecord::TurnContext {
229 turn_id: string("turn_id"),
230 cwd: string("cwd").map(PathBuf::from),
231 model: string("model"),
232 }),
233 ("event_msg", Some("user_message")) => Some(SessionRecord::Prompt {
236 turn_id: None,
237 text: string("message")?,
238 }),
239 ("event_msg", Some("item_completed")) => {
240 let item = payload.get("item")?;
241 if item.get("type")? != "UserMessage" {
242 return None;
243 }
244 let parts = item.get("content")?.as_array()?;
245 Some(SessionRecord::Prompt {
246 turn_id: string("turn_id"),
247 text: parts
248 .iter()
249 .filter_map(|part| part.get("text")?.as_str())
250 .collect(),
251 })
252 }
253 ("event_msg", Some("task_complete")) => Some(SessionRecord::TurnComplete {
254 turn_id: string("turn_id"),
255 last_agent_message: string("last_agent_message"),
256 error: payload
257 .pointer("/error/message")
258 .and_then(Value::as_str)
259 .map(str::to_string),
260 }),
261 ("event_msg", Some("turn_aborted")) => Some(SessionRecord::TurnAborted {
262 turn_id: string("turn_id"),
263 reason: string("reason"),
264 }),
265 ("response_item", Some("function_call")) => call(string("name")?, "arguments"),
266 ("response_item", Some("custom_tool_call")) => call(string("name")?, "input"),
267 ("response_item", Some("tool_search_call")) => call("tool_search".into(), "arguments"),
268 ("response_item", Some("web_search_call")) => call("web_search".into(), "action"),
269 ("response_item", Some("function_call_output" | "custom_tool_call_output")) => {
270 result("output")
271 }
272 ("response_item", Some("tool_search_output")) => result("tools"),
273 _ => None,
274 }
275 }
276}
277
278#[derive(Debug, Clone, PartialEq)]
282#[non_exhaustive]
283pub enum SessionRecord {
284 Meta(Box<SessionMeta>),
286 #[non_exhaustive]
288 TurnContext {
289 turn_id: Option<String>,
291 cwd: Option<PathBuf>,
293 model: Option<String>,
295 },
296 #[non_exhaustive]
298 Prompt {
299 turn_id: Option<String>,
301 text: String,
303 },
304 #[non_exhaustive]
309 ToolCall {
310 call_id: Option<String>,
313 name: String,
315 namespace: Option<String>,
317 input: Value,
320 },
321 #[non_exhaustive]
323 ToolResult {
324 call_id: Option<String>,
326 output: Value,
328 },
329 #[non_exhaustive]
331 TurnComplete {
332 turn_id: Option<String>,
334 last_agent_message: Option<String>,
336 error: Option<String>,
338 },
339 #[non_exhaustive]
341 TurnAborted {
342 turn_id: Option<String>,
344 reason: Option<String>,
346 },
347}
348
349#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
353pub struct Position {
354 offset: u64,
355 fingerprint: u64,
356}
357
358impl Position {
359 #[must_use]
361 pub fn offset(&self) -> u64 {
362 self.offset
363 }
364}
365
366#[derive(Debug, Clone, PartialEq)]
368pub enum Continuation {
369 Continued {
371 entries: Vec<SessionEntry>,
374 position: Position,
376 },
377 Truncated,
379 Replaced,
381}
382
383#[derive(Debug, Clone, PartialEq)]
385pub struct SessionLog {
386 pub path: PathBuf,
388 pub meta: Option<SessionMeta>,
390 pub entries: Vec<SessionEntry>,
392}
393
394#[derive(Debug, Clone, Default)]
396pub struct SessionQuery {
397 after: Option<(u16, u8, u8)>,
398 before: Option<(u16, u8, u8)>,
399 cwd: Option<PathBuf>,
400}
401
402impl SessionQuery {
403 #[must_use]
405 pub fn new() -> Self {
406 Self::default()
407 }
408
409 #[must_use]
411 pub fn after(mut self, year: u16, month: u8, day: u8) -> Self {
412 self.after = Some((year, month, day));
413 self
414 }
415
416 #[must_use]
418 pub fn before(mut self, year: u16, month: u8, day: u8) -> Self {
419 self.before = Some((year, month, day));
420 self
421 }
422
423 #[must_use]
429 pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
430 self.cwd = Some(cwd.into());
431 self
432 }
433
434 fn matches_date(&self, date: (u16, u8, u8)) -> bool {
435 self.after.is_none_or(|after| date >= after)
436 && self.before.is_none_or(|before| date <= before)
437 }
438}
439
440pub fn list(query: &SessionQuery) -> Result<Vec<SessionFile>> {
444 let home = crate::codex_home::resolve(&|key| std::env::var(key).ok());
445 list_in(home, query)
446}
447
448pub fn list_in(codex_home: impl AsRef<Path>, query: &SessionQuery) -> Result<Vec<SessionFile>> {
453 let root = codex_home.as_ref().join("sessions");
454 let mut found = Vec::new();
455
456 for (date, day_dir) in date_dirs(&root) {
457 if !query.matches_date(date) {
458 continue;
459 }
460 let Ok(entries) = std::fs::read_dir(&day_dir) else {
461 continue;
462 };
463 for entry in entries.filter_map(std::result::Result::ok) {
464 let path = entry.path();
465 let Some(id) = session_id_from_path(&path) else {
466 continue;
467 };
468 if path.extension().is_some_and(|ext| ext == "zst") && path.with_extension("").exists()
470 {
471 continue;
472 }
473 if let Some(wanted) = &query.cwd
474 && !session_ran_in(&path, wanted)
475 {
476 continue;
477 }
478 found.push(SessionFile { path, id, date });
479 }
480 }
481
482 found.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| b.path.cmp(&a.path)));
485 Ok(found)
486}
487
488pub fn read(path: impl AsRef<Path>) -> Result<SessionLog> {
490 let path = path.as_ref();
491 let mut contents = Vec::new();
492 open(path)
493 .and_then(|log| log.reader()?.read_to_end(&mut contents))
494 .map_err(|e| read_error(path, e))?;
495
496 let mut meta = None;
497 let mut entries = Vec::new();
498
499 for value in values(&contents) {
500 if meta.is_none()
501 && let Some(found) = metadata(&value)
502 {
503 meta = Some(parse_meta(found));
504 } else {
505 entries.push(entry(value));
506 }
507 }
508
509 Ok(SessionLog {
510 path: path.to_path_buf(),
511 meta,
512 entries,
513 })
514}
515
516pub fn read_from(path: impl AsRef<Path>, position: &Position) -> Result<Continuation> {
525 let path = path.as_ref();
526 open(path)
527 .and_then(|log| match log {
528 Log::Plain(file) => continue_from(file, position),
529 Log::Compressed(_) => {
530 let mut contents = Vec::new();
531 log.reader()?.read_to_end(&mut contents)?;
532 continue_from(Cursor::new(contents), position)
533 }
534 })
535 .map_err(|e| read_error(path, e))
536}
537
538fn continue_from(mut log: impl Read + Seek, position: &Position) -> io::Result<Continuation> {
539 if log.seek(SeekFrom::End(0))? < position.offset {
540 return Ok(Continuation::Truncated);
541 }
542 if position.offset > 0 && fingerprint(&mut log, position.offset)? != position.fingerprint {
543 return Ok(Continuation::Replaced);
544 }
545
546 let mut contents = Vec::new();
547 log.seek(SeekFrom::Start(position.offset))?;
548 log.read_to_end(&mut contents)?;
549 let Some(end) = contents.iter().rposition(|byte| *byte == b'\n') else {
550 return Ok(Continuation::Continued {
551 entries: Vec::new(),
552 position: position.clone(),
553 });
554 };
555 let complete = &contents[..=end];
556 let offset = position.offset + complete.len() as u64;
557 Ok(Continuation::Continued {
558 entries: values(complete).map(entry).collect(),
559 position: Position {
560 offset,
561 fingerprint: fingerprint(&mut log, offset)?,
562 },
563 })
564}
565
566fn fingerprint(log: &mut (impl Read + Seek), offset: u64) -> io::Result<u64> {
571 let window = offset.min(4096);
572 let mut bytes = Vec::new();
573 for start in [0, offset - window] {
574 log.seek(SeekFrom::Start(start))?;
575 log.by_ref().take(window).read_to_end(&mut bytes)?;
576 }
577 Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
578 (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
579 }))
580}
581
582enum Log {
583 Plain(File),
584 Compressed(File),
585}
586
587impl Log {
588 fn reader(self) -> io::Result<Box<dyn Read>> {
589 Ok(match self {
590 Self::Plain(file) => Box::new(file),
591 Self::Compressed(file) => {
592 Box::new(StreamingDecoder::new(BufReader::new(file)).map_err(io::Error::other)?)
593 }
594 })
595 }
596}
597
598fn open(path: &Path) -> io::Result<Log> {
600 let plain = match path.to_str().and_then(|path| path.strip_suffix(".zst")) {
601 Some(plain) => PathBuf::from(plain),
602 None => path.to_path_buf(),
603 };
604 let mut compressed = plain.clone().into_os_string();
605 compressed.push(".zst");
606
607 let missing = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
608 match File::open(&plain) {
609 Err(e) if missing(&e) => match File::open(compressed) {
610 Err(e) if missing(&e) => File::open(&plain).map(Log::Plain),
613 file => file.map(Log::Compressed),
614 },
615 file => file.map(Log::Plain),
616 }
617}
618
619fn read_error(path: &Path, source: io::Error) -> Error {
620 Error::Io {
621 message: format!("failed to read {}: {source}", path.display()),
622 source,
623 working_dir: None,
624 }
625}
626
627fn values(contents: &[u8]) -> impl Iterator<Item = Value> {
633 contents
634 .split(|byte| *byte == b'\n')
635 .filter_map(|line| serde_json::from_slice(line).ok())
636}
637
638fn metadata(value: &Value) -> Option<&Value> {
643 match envelope(value) {
644 Some((_, entry_type, payload)) => (entry_type == "session_meta").then_some(payload),
645 None => (value.get("id").is_some() && value.get("type").is_none()).then_some(value),
646 }
647}
648
649fn entry(value: Value) -> SessionEntry {
650 match envelope(&value) {
651 Some((timestamp, entry_type, payload)) => SessionEntry {
652 timestamp: timestamp.map(str::to_string),
653 entry_type: Some(entry_type.to_string()),
654 payload: payload.clone(),
655 },
656 None => SessionEntry {
657 timestamp: value
658 .get("timestamp")
659 .and_then(Value::as_str)
660 .map(str::to_string),
661 entry_type: None,
662 payload: value,
663 },
664 }
665}
666
667fn envelope(value: &Value) -> Option<(Option<&str>, &str, &Value)> {
670 let payload = value.get("payload")?;
671 let entry_type = value.get("type")?.as_str()?;
672 Some((
673 value.get("timestamp").and_then(Value::as_str),
674 entry_type,
675 payload,
676 ))
677}
678
679fn parse_meta(value: &Value) -> SessionMeta {
680 let string = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
681 SessionMeta {
682 id: string("id").or_else(|| string("session_id")),
683 timestamp: string("timestamp"),
684 cwd: string("cwd").map(PathBuf::from),
685 cli_version: string("cli_version"),
686 originator: string("originator"),
687 source: string("source"),
688 git: value.get("git").and_then(|git| {
689 let get = |key: &str| git.get(key).and_then(Value::as_str).map(str::to_string);
690 let meta = GitMeta {
691 commit_hash: get("commit_hash"),
692 branch: get("branch"),
693 repository_url: get("repository_url"),
694 };
695 (meta != GitMeta::default()).then_some(meta)
696 }),
697 raw: value.clone(),
698 }
699}
700
701fn date_dirs(root: &Path) -> Vec<((u16, u8, u8), PathBuf)> {
703 let mut out = Vec::new();
704 for year in numeric_children(root) {
705 for month in numeric_children(&year.1) {
706 for day in numeric_children(&month.1) {
707 out.push(((year.0 as u16, month.0 as u8, day.0 as u8), day.1));
708 }
709 }
710 }
711 out
712}
713
714fn numeric_children(dir: &Path) -> Vec<(u32, PathBuf)> {
716 let Ok(entries) = std::fs::read_dir(dir) else {
717 return Vec::new();
718 };
719 entries
720 .filter_map(std::result::Result::ok)
721 .filter_map(|entry| {
722 let name = entry.file_name().into_string().ok()?;
723 let value = name.parse::<u32>().ok()?;
724 entry.path().is_dir().then(|| (value, entry.path()))
725 })
726 .collect()
727}
728
729fn session_id_from_path(path: &Path) -> Option<String> {
735 let name = path.file_name()?.to_str()?;
736 let name = name.strip_suffix(".zst").unwrap_or(name);
737 let stem = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
738 let stem = stem.split_once('_').map_or(stem, |(thread, _)| thread);
739 let parts: Vec<&str> = stem.split('-').collect();
740 if parts.len() < 5 {
741 return None;
742 }
743 Some(parts[parts.len() - 5..].join("-"))
744}
745
746fn session_ran_in(path: &Path, wanted: &Path) -> bool {
748 let Ok(reader) = open(path).and_then(Log::reader) else {
749 return false;
750 };
751 let mut lines = BufReader::new(reader).lines().map_while(io::Result::ok);
752 let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
753 return false;
754 };
755 let Ok(value) = serde_json::from_str::<Value>(&first) else {
756 return false;
757 };
758 let meta = value.get("payload").unwrap_or(&value);
759 meta.get("cwd").and_then(Value::as_str) == wanted.to_str()
760}
761
762#[cfg(test)]
763mod tests {
764 use super::*;
765
766 fn temp_home(label: &str) -> PathBuf {
767 let dir = std::env::temp_dir().join(format!(
768 "codex-wrapper-history-{}-{label}",
769 std::process::id()
770 ));
771 let _ = std::fs::remove_dir_all(&dir);
772 dir
773 }
774
775 fn write_session(home: &Path, date: (u16, u8, u8), name: &str, lines: &[&str]) -> PathBuf {
776 let dir = home
777 .join("sessions")
778 .join(format!("{:04}", date.0))
779 .join(format!("{:02}", date.1))
780 .join(format!("{:02}", date.2));
781 std::fs::create_dir_all(&dir).unwrap();
782 let path = dir.join(name);
783 std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
784 path
785 }
786
787 const MODERN: &[&str] = &[
790 r#"{"timestamp":"2026-08-06T10:11:24Z","type":"session_meta","payload":{"session_id":"019fd80e-eb27-70e3-ad2e-ed939930901a","id":"019fd80e-eb27-70e3-ad2e-ed939930901a","timestamp":"2026-08-06T10:11:24Z","cwd":"/repo","originator":"codex_cli_rs","cli_version":"0.145.0","source":"cli","git":{"commit_hash":"abc123","branch":"main","repository_url":"git@example.com:o/r.git"}}}"#,
791 r#"{"timestamp":"2026-08-06T10:11:25Z","type":"turn_context","payload":{"model":"gpt-5.6-sol","cwd":"/repo"}}"#,
792 r#"{"timestamp":"2026-08-06T10:11:30Z","type":"event_msg","payload":{"type":"agent_message","message":"hello"}}"#,
793 r#"{"timestamp":"2026-08-06T10:11:31Z","type":"response_item","payload":{"type":"message","role":"assistant"}}"#,
794 ];
795
796 const LEGACY: &[&str] = &[
798 r#"{"id":"7b332612-1b8e-424b-bbb4-a239a64377fb","timestamp":"2025-09-01T19:51:34Z","instructions":null,"git":{"commit_hash":"old123"}}"#,
799 r#"{"record_type":"state"}"#,
800 r#"{"id":"item_0","type":"message","role":"user","content":[]}"#,
801 ];
802
803 #[test]
804 fn discovers_both_current_history_modes_and_preserves_their_payloads() {
805 let home = temp_home("current-history-modes");
806 for (mode, fixture, id, item_type) in [
807 (
808 "legacy",
809 include_str!("../tests/history/0.163.0-legacy.jsonl"),
810 "00000000-0000-4000-8000-000000000001",
811 "user_message",
812 ),
813 (
814 "paginated",
815 include_str!("../tests/history/0.163.0-paginated.jsonl"),
816 "00000000-0000-4000-8000-000000000002",
817 "item_completed",
818 ),
819 ] {
820 let path = write_session(
821 &home,
822 (2026, 10, 20),
823 &format!("rollout-2026-10-20T17-20-49-{id}.jsonl"),
824 &fixture.lines().collect::<Vec<_>>(),
825 );
826 let log = read(&path).unwrap();
827 let meta = log.meta.unwrap();
828 assert_eq!(meta.id.as_deref(), Some(id));
829 assert_eq!(meta.cli_version.as_deref(), Some("0.163.0"));
830 assert_eq!(meta.raw["history_mode"], mode);
831 assert_eq!(log.entries.len(), 4);
832 let captured: Vec<serde_json::Value> = fixture
833 .lines()
834 .map(|line| serde_json::from_str(line).unwrap())
835 .collect();
836 for (entry, envelope) in log.entries.iter().zip(&captured[1..]) {
837 assert_eq!(entry.entry_type.as_deref(), Some("event_msg"));
838 assert_eq!(entry.payload, envelope["payload"]);
839 }
840 assert_eq!(log.entries[0].payload_type(), Some(item_type));
841 assert_eq!(log.entries[2].payload_type(), Some(item_type));
842 if mode == "paginated" {
843 assert_eq!(log.entries[0].payload["item"]["type"], "UserMessage");
844 assert_eq!(
845 log.entries[0].payload["item"]["content"][0]["text"],
846 "synthetic offline history fixture"
847 );
848 }
849 }
850 let sessions = list_in(
851 &home,
852 &SessionQuery::new()
853 .cwd("/fixture/workspace")
854 .after(2026, 10, 20),
855 )
856 .unwrap();
857 assert_eq!(sessions.len(), 2);
858 std::fs::remove_dir_all(home).unwrap();
859 }
860
861 #[test]
864 fn types_the_records_of_every_tested_cli_version() {
865 use crate::version::{TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN};
866
867 for version in [TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX] {
868 let path = format!(
869 "{}/tests/history/{version}.jsonl",
870 env!("CARGO_MANIFEST_DIR")
871 );
872 let records: Vec<String> = follow(Path::new(&path), &Position::default())
873 .0
874 .iter()
875 .filter_map(SessionEntry::record)
876 .map(|record| match record {
877 SessionRecord::Meta(meta) => {
878 assert_eq!(meta.cwd, Some(PathBuf::from("/fixture/workspace")));
879 format!("meta {}", meta.cli_version.unwrap())
880 }
881 SessionRecord::TurnContext {
882 turn_id,
883 cwd,
884 model,
885 } => {
886 assert!(turn_id.is_some());
887 format!("context {} {}", cwd.unwrap().display(), model.unwrap())
888 }
889 SessionRecord::Prompt { text, .. } => format!("prompt {text}"),
890 SessionRecord::ToolCall {
891 call_id,
892 name,
893 input,
894 ..
895 } => {
896 assert!(input.to_string().contains("fixture"));
897 format!("call {name} {call_id:?}")
898 }
899 SessionRecord::ToolResult { call_id, output } => {
900 assert!(output.is_string() || output.is_array());
901 format!("result {}", call_id.unwrap())
902 }
903 SessionRecord::TurnComplete {
904 turn_id,
905 last_agent_message,
906 error,
907 } => {
908 assert!(turn_id.is_some());
909 format!("complete {last_agent_message:?} {error:?}")
910 }
911 SessionRecord::TurnAborted { turn_id, reason } => {
912 assert!(turn_id.is_some());
913 format!("aborted {}", reason.unwrap())
914 }
915 })
916 .collect();
917 assert_eq!(
918 records,
919 [
920 format!("meta {version}").as_str(),
921 "context /fixture/workspace gpt-5.2-codex",
922 "prompt first prompt",
923 r#"call exec_command Some("call_1")"#,
924 "result call_1",
925 r#"call apply_patch Some("call_2")"#,
926 "result call_2",
927 r#"call tool_search Some("call_3")"#,
928 "result call_3",
929 "call web_search None",
930 r#"complete Some("fixture answer") None"#,
931 "context /fixture/workspace gpt-5.2-codex",
932 "prompt interrupted prompt",
933 "aborted interrupted",
934 ],
935 "{version}"
936 );
937 }
938 }
939
940 #[test]
942 fn a_web_search_without_an_action_is_still_a_call() {
943 let line = br#"{"type":"response_item","payload":{"type":"web_search_call"}}"#;
944 let record = values(line).map(entry).next().unwrap().record();
945 assert!(matches!(
946 record,
947 Some(SessionRecord::ToolCall { name, input: Value::Null, .. }) if name == "web_search"
948 ));
949 }
950
951 #[test]
952 fn a_failed_turn_has_its_error() {
953 let log = include_str!("../tests/history/0.163.0-legacy.jsonl");
954 let failed = values(log.as_bytes()).map(entry).find_map(|entry| {
955 let SessionRecord::TurnComplete { error, .. } = entry.record()? else {
956 return None;
957 };
958 error
959 });
960 assert!(failed.unwrap().contains("intentional offline fixture"));
961 }
962
963 fn follow(path: &Path, position: &Position) -> (Vec<SessionEntry>, Position) {
964 match read_from(path, position).unwrap() {
965 Continuation::Continued { entries, position } => (entries, position),
966 other => panic!("expected the log to continue, got {other:?}"),
967 }
968 }
969
970 #[test]
971 fn continues_after_the_last_complete_line() {
972 let home = temp_home("continue");
973 let path = write_session(&home, (2026, 8, 6), "log.jsonl", &MODERN[..2]);
974 let (entries, position) = follow(&path, &Position::default());
975 assert_eq!(entries.len(), 2);
976 assert_eq!(
977 position.offset(),
978 std::fs::metadata(&path).unwrap().len(),
979 "everything was read"
980 );
981
982 let line = r#"{"type":"event_msg","payload":{"type":"user_message","message":"é"}}"#;
984 let cut = line.find('é').unwrap() + 1;
985 let mut contents = std::fs::read(&path).unwrap();
986 contents.extend(&line.as_bytes()[..cut]);
987 std::fs::write(&path, &contents).unwrap();
988 assert_eq!(follow(&path, &position), (vec![], position.clone()));
989
990 contents.extend(&line.as_bytes()[cut..]);
991 contents.push(b'\n');
992 std::fs::write(&path, &contents).unwrap();
993 let saved = serde_json::to_string(&position).unwrap();
994 let (entries, _) = follow(&path, &serde_json::from_str(&saved).unwrap());
995 assert_eq!(entries.len(), 1);
996 assert_eq!(
997 entries[0].record(),
998 Some(SessionRecord::Prompt {
999 turn_id: None,
1000 text: "é".into()
1001 })
1002 );
1003 }
1004
1005 #[test]
1006 fn reports_a_truncated_or_replaced_log() {
1007 let home = temp_home("replaced");
1008 let path = write_session(&home, (2026, 8, 6), "log.jsonl", MODERN);
1009 let (_, position) = follow(&path, &Position::default());
1010
1011 let contents = std::fs::read_to_string(&path).unwrap();
1012 std::fs::write(&path, contents.replace("019fd80e", "019fd80f")).unwrap();
1013 assert_eq!(
1014 read_from(&path, &position).unwrap(),
1015 Continuation::Replaced,
1016 "same length, another session"
1017 );
1018
1019 std::fs::write(&path, MODERN[0]).unwrap();
1020 assert_eq!(
1021 read_from(&path, &position).unwrap(),
1022 Continuation::Truncated
1023 );
1024 }
1025
1026 #[test]
1027 fn a_compressed_session_is_the_same_session() {
1028 use ruzstd::encoding::{CompressionLevel, compress_to_vec};
1029
1030 let home = temp_home("compressed");
1031 let path = write_session(
1032 &home,
1033 (2026, 8, 6),
1034 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1035 MODERN,
1036 );
1037 let query = SessionQuery::new().cwd("/repo");
1038 let log = read(&path).unwrap();
1039 let (_, position) = follow(&path, &Position::default());
1040
1041 let compressed = path.with_extension("jsonl.zst");
1042 let contents = std::fs::read(&path).unwrap();
1043 std::fs::write(
1044 &compressed,
1045 compress_to_vec(contents.as_slice(), CompressionLevel::Fastest),
1046 )
1047 .unwrap();
1048 let listed = list_in(&home, &query).unwrap();
1049 assert_eq!(listed.len(), 1, "one session while both files exist");
1050 assert_eq!(listed[0].path, path);
1051
1052 std::fs::remove_file(&path).unwrap();
1053 let listed = list_in(&home, &query).unwrap();
1054 assert_eq!(listed.len(), 1);
1055 assert_eq!(listed[0].path, compressed);
1056 assert_eq!(listed[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1057 assert_eq!(read(&compressed).unwrap().entries, log.entries);
1058 assert_eq!(read(&path).unwrap(), log);
1060 assert_eq!(follow(&path, &position), (vec![], position.clone()));
1061
1062 std::fs::write(&path, &contents).unwrap();
1064 std::fs::remove_file(&compressed).unwrap();
1065 assert_eq!(follow(&compressed, &position), (vec![], position));
1066 }
1067
1068 #[test]
1069 fn a_missing_sessions_directory_is_empty_not_an_error() {
1070 let home = temp_home("empty");
1071 assert_eq!(list_in(&home, &SessionQuery::new()).unwrap(), vec![]);
1072 }
1073
1074 #[test]
1075 fn lists_sessions_newest_first() {
1076 let home = temp_home("order");
1077 write_session(
1078 &home,
1079 (2026, 8, 1),
1080 "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1081 MODERN,
1082 );
1083 write_session(
1084 &home,
1085 (2026, 8, 6),
1086 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1087 MODERN,
1088 );
1089 write_session(
1090 &home,
1091 (2025, 9, 1),
1092 "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1093 LEGACY,
1094 );
1095
1096 let found = list_in(&home, &SessionQuery::new()).unwrap();
1097 let dates: Vec<_> = found.iter().map(|s| s.date).collect();
1098 assert_eq!(dates, vec![(2026, 8, 6), (2026, 8, 1), (2025, 9, 1)]);
1099 assert_eq!(found[0].id, "bbbbbbbb-1111-2222-3333-444444444444");
1100 }
1101
1102 #[test]
1103 fn date_filters_narrow_the_listing() {
1104 let home = temp_home("dates");
1105 write_session(
1106 &home,
1107 (2026, 8, 1),
1108 "rollout-2026-08-01T10-00-00-aaaaaaaa-1111-2222-3333-444444444444.jsonl",
1109 MODERN,
1110 );
1111 write_session(
1112 &home,
1113 (2026, 8, 6),
1114 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1115 MODERN,
1116 );
1117
1118 let after = list_in(&home, &SessionQuery::new().after(2026, 8, 5)).unwrap();
1119 assert_eq!(after.len(), 1);
1120 assert_eq!(after[0].date, (2026, 8, 6));
1121
1122 let before = list_in(&home, &SessionQuery::new().before(2026, 8, 5)).unwrap();
1123 assert_eq!(before.len(), 1);
1124 assert_eq!(before[0].date, (2026, 8, 1));
1125
1126 let between = list_in(
1127 &home,
1128 &SessionQuery::new().after(2026, 8, 1).before(2026, 8, 6),
1129 )
1130 .unwrap();
1131 assert_eq!(between.len(), 2);
1132 }
1133
1134 #[test]
1135 fn cwd_filter_matches_the_recorded_directory() {
1136 let home = temp_home("cwd");
1137 write_session(
1138 &home,
1139 (2026, 8, 6),
1140 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1141 MODERN,
1142 );
1143
1144 assert_eq!(
1145 list_in(&home, &SessionQuery::new().cwd("/repo"))
1146 .unwrap()
1147 .len(),
1148 1
1149 );
1150 assert_eq!(
1151 list_in(&home, &SessionQuery::new().cwd("/elsewhere"))
1152 .unwrap()
1153 .len(),
1154 0
1155 );
1156 }
1157
1158 #[test]
1159 fn reads_a_modern_session() {
1160 let home = temp_home("modern");
1161 let path = write_session(
1162 &home,
1163 (2026, 8, 6),
1164 "rollout-2026-08-06T10-11-24-bbbbbbbb-1111-2222-3333-444444444444.jsonl",
1165 MODERN,
1166 );
1167
1168 let log = read(&path).unwrap();
1169 let meta = log.meta.unwrap();
1170 assert_eq!(meta.cwd, Some(PathBuf::from("/repo")));
1171 assert_eq!(meta.cli_version.as_deref(), Some("0.145.0"));
1172 assert_eq!(meta.git.unwrap().branch.as_deref(), Some("main"));
1173
1174 assert_eq!(log.entries.len(), 3);
1176 assert_eq!(log.entries[0].entry_type.as_deref(), Some("turn_context"));
1177 assert_eq!(log.entries[1].payload_type(), Some("agent_message"));
1178 }
1179
1180 #[test]
1183 fn reads_a_legacy_session_without_an_envelope() {
1184 let home = temp_home("legacy");
1185 let path = write_session(
1186 &home,
1187 (2025, 9, 1),
1188 "rollout-2025-09-01T19-51-34-cccccccc-1111-2222-3333-444444444444.jsonl",
1189 LEGACY,
1190 );
1191
1192 let log = read(&path).unwrap();
1193 let meta = log.meta.expect("the first line is the metadata");
1194 assert_eq!(
1195 meta.id.as_deref(),
1196 Some("7b332612-1b8e-424b-bbb4-a239a64377fb")
1197 );
1198 assert_eq!(meta.cli_version, None, "legacy files record no version");
1199 assert_eq!(meta.cwd, None, "legacy files record no cwd");
1200 assert_eq!(meta.git.unwrap().commit_hash.as_deref(), Some("old123"));
1201
1202 assert_eq!(log.entries.len(), 2);
1203 assert_eq!(log.entries[0].entry_type, None);
1205 assert_eq!(log.entries[1].payload_type(), Some("message"));
1206 }
1207
1208 #[test]
1211 fn a_truncated_tail_does_not_lose_the_rest() {
1212 let home = temp_home("truncated");
1213 let mut lines = MODERN.to_vec();
1214 lines.push(r#"{"timestamp":"2026-08-06T10:11:32Z","type":"event_ms"#);
1215 let path = write_session(
1216 &home,
1217 (2026, 8, 6),
1218 "rollout-2026-08-06T10-11-24-dddddddd-1111-2222-3333-444444444444.jsonl",
1219 &lines,
1220 );
1221
1222 let log = read(&path).unwrap();
1223 assert!(log.meta.is_some());
1224 assert_eq!(log.entries.len(), 3, "the good lines survive");
1225 }
1226
1227 #[test]
1230 fn session_id_comes_from_the_uuid_tail() {
1231 assert_eq!(
1232 session_id_from_path(Path::new(
1233 "/x/rollout-2026-08-06T10-11-24-019fd80e-eb27-70e3-ad2e-ed939930901a.jsonl"
1234 )),
1235 Some("019fd80e-eb27-70e3-ad2e-ed939930901a".to_string())
1236 );
1237 assert_eq!(session_id_from_path(Path::new("/x/notes.txt")), None);
1238 }
1239
1240 #[test]
1243 fn a_reverted_thread_is_identified_by_its_thread_id() {
1244 for extension in ["jsonl", "jsonl.zst"] {
1245 let name = format!(
1246 "/x/rollout-2026-08-06T10-11-24-aaaaaaaa-1111-2222-3333-444444444444_bbbbbbbb-5555-6666-7777-888888888888.{extension}"
1247 );
1248 assert_eq!(
1249 session_id_from_path(Path::new(&name)).as_deref(),
1250 Some("aaaaaaaa-1111-2222-3333-444444444444"),
1251 "{extension}"
1252 );
1253 }
1254 }
1255
1256 #[test]
1257 fn unknown_entry_types_are_kept_rather_than_dropped() {
1258 let home = temp_home("unknown");
1259 let path = write_session(
1260 &home,
1261 (2026, 8, 6),
1262 "rollout-2026-08-06T10-11-24-eeeeeeee-1111-2222-3333-444444444444.jsonl",
1263 &[
1264 MODERN[0],
1265 r#"{"timestamp":"2026-08-06T10:11:40Z","type":"something_new","payload":{"type":"unheard_of"}}"#,
1266 ],
1267 );
1268
1269 let log = read(&path).unwrap();
1270 assert_eq!(log.entries.len(), 1);
1271 assert_eq!(log.entries[0].entry_type.as_deref(), Some("something_new"));
1272 assert_eq!(log.entries[0].payload_type(), Some("unheard_of"));
1273 }
1274}