//! Append-only JSONL session tree. Each entry has `id` + `parent`; the head is the last appended id. //! Forking = appending with an older parent. Resume = walk parents from the head. use hx_ai::Message; use serde::{Deserialize, Serialize}; use std::io::{BufRead, Write}; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Entry { pub id: u64, pub parent: Option, pub message: Message, /// Model that produced an assistant message (absent in older files). #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, /// API usage of the request that produced this assistant message (absent in older files). #[serde(default, skip_serializing_if = "Option::is_none")] pub usage: Option, /// Tool-result masking boundary (assistant turns) of the request that produced this assistant /// message; absent in older files, where the stepwise rule applied. #[serde(default, skip_serializing_if = "Option::is_none")] pub mask: Option, } pub struct Session { path: PathBuf, entries: Vec, head: Option, } impl Session { /// Open (or create) a session file; head = last entry. pub fn open(path: impl AsRef) -> std::io::Result { let path = path.as_ref().to_path_buf(); if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; } let mut entries = vec![]; if let Ok(f) = std::fs::File::open(&path) { for l in std::io::BufReader::new(f).lines() { let l = l?; // skip a torn last line from a crash rather than losing the session if let Ok(e) = serde_json::from_str::(&l) { entries.push(e); } } } let head = entries.last().map(|e| e.id); Ok(Self { path, entries, head, }) } pub fn path(&self) -> &Path { &self.path } pub fn head(&self) -> Option { self.head } pub fn append(&mut self, message: Message) -> std::io::Result { self.append_by(message, None) } /// Append, recording which model produced it. pub fn append_by(&mut self, message: Message, model: Option) -> std::io::Result { self.append_full(message, model, None) } /// Append an assistant message with the model and request usage that produced it. pub fn append_full( &mut self, message: Message, model: Option, usage: Option, ) -> std::io::Result { self.append_masked(message, model, usage, None) } /// Like `append_full`, also recording the masking boundary the request used. pub fn append_masked( &mut self, message: Message, model: Option, usage: Option, mask: Option, ) -> std::io::Result { let id = self.entries.last().map_or(0, |e| e.id + 1); let e = Entry { id, parent: self.head, message, model, usage, mask, }; let mut f = std::fs::OpenOptions::new() .create(true) .append(true) .open(&self.path)?; writeln!( f, "{}", serde_json::to_string(&e).map_err(std::io::Error::other)? )?; self.entries.push(e); self.head = Some(id); Ok(id) } /// Start a new root with `msgs` (used by compaction). Old entries stay in the file. pub fn rebase(&mut self, msgs: Vec) -> std::io::Result<()> { self.head = None; for m in msgs { self.append(m)?; } Ok(()) } /// Move head to `id` so the next append branches from it. pub fn fork(&mut self, id: u64) -> bool { let ok = self.entries.iter().any(|e| e.id == id); if ok { self.head = Some(id); } ok } /// Per-request usage rows (entry id, tool results bytes in the request's input, usage), in file order. pub fn usages(&self) -> Vec<(u64, &hx_ai::Usage)> { self.entries .iter() .filter_map(|e| e.usage.as_ref().map(|u| (e.id, u))) .collect() } /// Model and usage of every request, in file order (entries from before models were logged have none). pub fn model_usages(&self) -> Vec<(Option<&str>, &hx_ai::Usage)> { self.entries .iter() .filter_map(|e| e.usage.as_ref().map(|u| (e.model.as_deref(), u))) .collect() } fn branch(&self) -> Vec<&Entry> { let mut out = vec![]; let mut cur = self.head; while let Some(id) = cur { let Some(e) = self.entries.iter().find(|e| e.id == id) else { break; }; out.push(e); cur = e.parent; } out.reverse(); out } /// Messages on the path root..=head. pub fn messages(&self) -> Vec { self.branch() .into_iter() .map(|e| e.message.clone()) .collect() } /// Recorded masking boundary per message on the path (aligned with `messages()`). pub fn masks(&self) -> Vec> { self.branch().into_iter().map(|e| e.mask).collect() } } /// `/sessions/`. pub fn dir(home: &Path, cwd: &Path) -> PathBuf { let slug: String = cwd .to_string_lossy() .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) .collect(); home.join("sessions").join(slug.trim_matches('-')) } /// A fresh, not yet created session file in `dir` (created on first append). pub fn new_path(dir: &Path) -> PathBuf { let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_millis(); let mut p = dir.join(format!("{ts}.jsonl")); let mut n = 0; while p.exists() { n += 1; p = dir.join(format!("{ts}-{n}.jsonl")); } p } #[derive(Debug, Clone, PartialEq)] pub struct Meta { pub path: PathBuf, /// First line of the first user prompt; "(untitled)" when there is none. pub title: String, pub modified: std::time::SystemTime, /// Messages on the head path. pub messages: usize, /// Model of the last assistant entry that recorded one. pub model: Option, /// Leaf entries: >1 means forks or compactions. pub branches: usize, /// Session dir name (project slug). pub project: String, } pub const UNTITLED: &str = "(untitled)"; /// Title of a conversation: first line of the first user text, ≤80 chars. pub fn title(msgs: &[Message]) -> Option { msgs.iter() .filter(|m| m.role == hx_ai::Role::User) .map(|m| m.text()) .find(|t| !t.trim().is_empty()) .map(|t| { t.trim() .lines() .next() .unwrap_or_default() .chars() .take(80) .collect() }) } impl Session { pub fn meta(&self) -> Meta { let all: Vec = self.entries.iter().map(|e| e.message.clone()).collect(); let parents: std::collections::HashSet = self.entries.iter().filter_map(|e| e.parent).collect(); Meta { path: self.path.clone(), title: title(&all).unwrap_or_else(|| UNTITLED.into()), modified: std::fs::metadata(&self.path) .and_then(|m| m.modified()) .unwrap_or(std::time::UNIX_EPOCH), messages: self.messages().len(), model: self.entries.iter().rev().find_map(|e| e.model.clone()), branches: self .entries .iter() .filter(|e| !parents.contains(&e.id)) .count(), project: self .path .parent() .and_then(|d| d.file_name()) .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(), } } } /// Sessions in `dir`, newest first. Empty files are skipped. // ponytail: parses every file on each call; fine for hundreds of sessions, add an index beyond that. pub fn list(dir: &Path) -> Vec { let mut v: Vec = std::fs::read_dir(dir) .into_iter() .flatten() .flatten() .map(|e| e.path()) .filter(|p| p.extension().is_some_and(|x| x == "jsonl")) .filter_map(|p| Session::open(&p).ok()) .filter(|s| !s.entries.is_empty()) .map(|s| s.meta()) .collect(); // equal mtimes (coarse clocks): newer timestamped file name wins v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path))); v } /// Sessions of every project under `/sessions`, newest first. pub fn list_all(root: &Path) -> Vec { let mut v: Vec = std::fs::read_dir(root) .into_iter() .flatten() .flatten() .filter(|e| e.path().is_dir()) .flat_map(|e| list(&e.path())) .collect(); // equal mtimes (coarse clocks): newer timestamped file name wins v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path))); v } #[cfg(test)] mod tests { use super::*; #[test] fn branch_and_resume() { let d = tempfile::tempdir().unwrap(); let p = d.path().join("s/a.jsonl"); let mut s = Session::open(&p).unwrap(); let a = s.append(Message::user("a")).unwrap(); s.append(Message::user("b")).unwrap(); assert!(s.fork(a)); s.append(Message::user("c")).unwrap(); let txt = |s: &Session| s.messages().iter().map(|m| m.text()).collect::>(); assert_eq!(txt(&s), ["a", "c"]); std::fs::OpenOptions::new() .append(true) .open(&p) .unwrap() .write_all(b"{torn") .unwrap(); let s2 = Session::open(&p).unwrap(); assert_eq!(txt(&s2), ["a", "c"]); assert!(!Session::open(&p).unwrap().fork(99)); } #[test] fn listing() { let d = tempfile::tempdir().unwrap(); let proj = d.path().join("sessions/proj"); let mut a = Session::open(proj.join("1.jsonl")).unwrap(); // first user message is only a tool result: title comes from the next prompt a.append(Message { role: hx_ai::Role::User, content: vec![hx_ai::ContentBlock::ToolResult { tool_use_id: "x".into(), content: "r".into(), is_error: false, }], }) .unwrap(); let root = a.append(Message::user(" fix parser\nmore")).unwrap(); a.append_by( Message { role: hx_ai::Role::Assistant, content: vec![hx_ai::ContentBlock::Text { text: "ok".into() }], }, Some("opus".into()), ) .unwrap(); a.fork(root); a.append(Message::user("other")).unwrap(); std::fs::write(proj.join("empty.jsonl"), "").unwrap(); std::thread::sleep(std::time::Duration::from_millis(20)); let mut b = Session::open(d.path().join("sessions/other/2.jsonl")).unwrap(); b.append(Message::user("newer")).unwrap(); std::fs::OpenOptions::new() .append(true) .open(b.path()) .unwrap() .write_all(b"{torn") .unwrap(); let l = list(&proj); assert_eq!(l.len(), 1, "empty file skipped"); let m = &l[0]; assert_eq!(m.title, "fix parser"); assert_eq!((m.messages, m.branches), (3, 2)); assert_eq!(m.model.as_deref(), Some("opus")); assert_eq!(m.project, "proj"); let all = list_all(&d.path().join("sessions")); let t: Vec<_> = all .iter() .map(|m| (m.title.as_str(), m.project.as_str())) .collect(); assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]); assert_eq!( dir(Path::new("/h"), Path::new("/a/b c")), Path::new("/h/sessions/a-b-c") ); let n = new_path(&proj); assert!(n.starts_with(&proj) && !n.exists()); // old files without `model` still load assert!( serde_json::from_str::( r#"{"id":0,"parent":null,"message":{"role":"user","content":[]}}"# ) .is_ok() ); } }