use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
mod session;
mod tree;
pub use session::Session;
pub use tree::{entry_to_message, summary_message};
use serde::{Deserialize, Serialize};
use yk_core::{Id, Message, Result, ToolResult, Turn};
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Entry {
Message {
id: Id,
parent: Option<Id>,
message: Message,
},
Assistant {
id: Id,
parent: Option<Id>,
turn: Turn,
},
Result {
id: Id,
parent: Option<Id>,
result: ToolResult,
},
Compaction {
id: Id,
parent: Option<Id>,
summary: String,
},
Rewind { id: Id, parent: Option<Id>, to: Id },
Model {
id: Id,
parent: Option<Id>,
model: String,
},
}
impl Entry {
#[must_use]
pub const fn id(&self) -> &Id {
match self {
Self::Message { id, .. }
| Self::Assistant { id, .. }
| Self::Result { id, .. }
| Self::Compaction { id, .. }
| Self::Model { id, .. }
| Self::Rewind { id, .. } => id,
}
}
#[must_use]
pub const fn parent(&self) -> Option<&Id> {
match self {
Self::Message { parent, .. }
| Self::Assistant { parent, .. }
| Self::Result { parent, .. }
| Self::Compaction { parent, .. }
| Self::Model { parent, .. }
| Self::Rewind { parent, .. } => parent.as_ref(),
}
}
}
pub const CURRENT_VERSION: u32 = 1;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Header {
kind: Kind,
pub version: u32,
}
impl Header {
#[must_use]
pub const fn new(version: u32) -> Self {
Self {
kind: Kind::Session,
version,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
enum Kind {
Session,
}
enum Line {
Header(Header),
Entry(Entry),
}
fn parse_line(line: &str, number: usize) -> Result<Line> {
let value: serde_json::Value = serde_json::from_str(line)
.map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))?;
if value.get("kind").and_then(serde_json::Value::as_str) == Some("session") {
serde_json::from_value(value)
.map(Line::Header)
.map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))
} else {
serde_json::from_value(value)
.map(Line::Entry)
.map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))
}
}
pub struct SessionLog {
path: PathBuf,
file: File,
}
impl SessionLog {
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn open(path: impl Into<PathBuf>) -> Result<Self> {
let path = path.into();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|source| yk_core::Error::Write {
path: parent.display().to_string(),
source,
})?;
}
let fresh = fs::metadata(&path).map_or(0, |meta| meta.len()) == 0;
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|source| yk_core::Error::Write {
path: path.display().to_string(),
source,
})?;
if fresh {
let line = serde_json::to_string(&Header::new(CURRENT_VERSION))
.map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
writeln!(file, "{line}")
.and_then(|()| file.flush())
.map_err(|source| yk_core::Error::Write {
path: path.display().to_string(),
source,
})?;
}
Ok(Self { path, file })
}
pub fn append(&mut self, entry: &Entry) -> Result<()> {
let line =
serde_json::to_string(entry).map_err(|e| yk_core::Error::Malformed(e.to_string()))?;
writeln!(self.file, "{line}")
.and_then(|()| self.file.flush())
.map_err(|source| yk_core::Error::Write {
path: self.path.display().to_string(),
source,
})
}
pub fn header(&self) -> Result<Option<Header>> {
Ok(self.load()?.0)
}
fn load(&self) -> Result<(Option<Header>, Vec<Entry>)> {
let file = File::open(&self.path).map_err(|source| yk_core::Error::Read {
path: self.path.display().to_string(),
source,
})?;
let mut header = None;
let mut entries = Vec::new();
for (number, line) in BufReader::new(file).lines().enumerate() {
let line = line.map_err(|source| yk_core::Error::Read {
path: self.path.display().to_string(),
source,
})?;
if line.trim().is_empty() {
continue;
}
match parse_line(&line, number.saturating_add(1))? {
Line::Header(found) => {
if found.version > CURRENT_VERSION {
return Err(yk_core::Error::Malformed(format!(
"session file is version {}, but this build writes {CURRENT_VERSION}",
found.version
)));
}
header = Some(found);
}
Line::Entry(entry) => entries.push(entry),
}
}
Ok((header, entries))
}
}
#[must_use]
pub fn default_dir() -> PathBuf {
let home = std::env::var_os("HOME").map_or_else(|| PathBuf::from("."), PathBuf::from);
home.join(".yk").join("sessions")
}
#[must_use]
pub fn path_for(dir: &Path, name: &str) -> PathBuf {
dir.join(format!("{name}.jsonl"))
}
pub(crate) fn next_id(existing: usize) -> Id {
format!("e{}", existing.saturating_add(1))
}
#[must_use]
pub fn new_session_name() -> String {
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs());
format!("{seconds}-{}", std::process::id())
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionFile {
pub path: PathBuf,
pub modified: SystemTime,
}
#[must_use]
pub fn list_sessions(dir: &Path) -> Vec<SessionFile> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut found: Vec<SessionFile> = entries
.flatten()
.filter_map(|entry| {
let path = entry.path();
if path.extension().and_then(std::ffi::OsStr::to_str) != Some("jsonl") {
return None;
}
if !path.is_file() {
return None;
}
let modified = entry.metadata().ok()?.modified().ok()?;
Some(SessionFile { path, modified })
})
.collect();
found.sort_by_key(|session| std::cmp::Reverse(session.modified));
found
}
#[must_use]
pub fn session_name_of(path: &Path) -> String {
path.file_stem().map_or_else(
|| path.display().to_string(),
|stem| stem.to_string_lossy().into_owned(),
)
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use super::{Entry, SessionLog, list_sessions, path_for, session_name_of};
use std::fs;
use yk_core::{Message, ToolResult};
fn temp_path(tag: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::TempDir::with_prefix(tag).expect("temp dir");
let path = path_for(dir.path(), "s");
(dir, path)
}
#[test]
fn appends_and_reads_back_in_order() {
let (_dir, path) = temp_path("order");
let mut store = SessionLog::open(&path).expect("opens");
store
.append(&Entry::Message {
id: "a".to_owned(),
parent: None,
message: Message::user("hello"),
})
.expect("appends");
store
.append(&Entry::Result {
id: "b".to_owned(),
parent: Some("a".to_owned()),
result: ToolResult::ok("call-1", "done"),
})
.expect("appends");
let entries = store.all_entries().expect("reads");
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].id(), "a");
assert_eq!(entries[0].parent(), None);
assert_eq!(entries[1].parent(), Some(&"a".to_owned()));
}
#[test]
fn a_corrupt_line_is_reported_rather_than_skipped() {
let (_dir, path) = temp_path("corrupt");
let good = Entry::Message {
id: "a".to_owned(),
parent: None,
message: Message::user("hello"),
};
let json = serde_json::to_string(&good).expect("serialises");
fs::write(&path, format!("{json}\nnot json\n")).expect("writes");
let store = SessionLog::open(&path).expect("opens");
let error = store
.all_entries()
.expect_err("a bad line must not be skipped");
assert!(
error.to_string().contains("line 2"),
"unhelpful error: {error}"
);
}
#[test]
fn a_new_session_file_starts_with_a_version_header() {
let (_dir, path) = temp_path("header");
let store = SessionLog::open(&path).expect("opens");
assert_eq!(
store.header().expect("reads the header"),
Some(super::Header::new(super::CURRENT_VERSION))
);
assert!(
store.all_entries().expect("reads").is_empty(),
"the header must not read back as an entry"
);
}
#[test]
fn a_header_from_a_newer_build_is_refused() {
let (_dir, path) = temp_path("newer");
let header = super::Header::new(super::CURRENT_VERSION.saturating_add(1));
let line = serde_json::to_string(&header).expect("serialises");
fs::write(&path, format!("{line}\n")).expect("writes");
let store = SessionLog::open(&path).expect("opens");
let error = store
.all_entries()
.expect_err("must refuse a newer version");
assert!(error.to_string().contains("version"), "{error}");
}
#[test]
fn a_file_without_a_header_still_reads() {
let (_dir, path) = temp_path("legacy");
let entry = Entry::Message {
id: "e1".to_owned(),
parent: None,
message: Message::user("old"),
};
fs::write(
&path,
format!("{}\n", serde_json::to_string(&entry).expect("serialises")),
)
.expect("writes");
let store = SessionLog::open(&path).expect("opens");
assert!(store.header().expect("reads").is_none());
assert_eq!(store.all_entries().expect("reads").len(), 1);
}
#[test]
fn sessions_are_listed_newest_first() {
let (dir, _) = temp_path("sessions-order");
for (name, seconds) in [("oldest", 1_000), ("newest", 3_000), ("middle", 2_000)] {
let path = dir.path().join(format!("{name}.jsonl"));
fs::write(&path, "").expect("writes");
stamp(&path, seconds);
}
let names: Vec<String> = list_sessions(dir.path())
.iter()
.map(|session| session_name_of(&session.path))
.collect();
assert_eq!(names, ["newest", "middle", "oldest"]);
}
#[test]
fn a_session_that_is_not_jsonl_is_not_a_session() {
let (dir, _) = temp_path("sessions-filter");
fs::write(dir.path().join("real.jsonl"), "").expect("writes");
fs::write(dir.path().join("notes.txt"), "").expect("writes");
let found = list_sessions(dir.path());
assert_eq!(found.len(), 1);
assert_eq!(session_name_of(&found[0].path), "real");
}
#[test]
fn a_directory_that_is_not_there_holds_no_sessions() {
let (dir, path) = temp_path("sessions-absent");
let missing = path.parent().expect("a parent").join("nope");
assert!(
list_sessions(&missing).is_empty(),
"and that is not an error"
);
assert!(list_sessions(dir.path()).is_empty());
}
#[test]
fn a_name_is_the_stem_and_nothing_else() {
assert_eq!(
session_name_of(std::path::Path::new("/a/b/17-99.jsonl")),
"17-99"
);
assert_eq!(session_name_of(std::path::Path::new("bare")), "bare");
}
fn stamp(path: &std::path::Path, seconds: u64) {
let file = fs::File::options().write(true).open(path).expect("opens");
let at = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds);
file.set_times(fs::FileTimes::new().set_modified(at))
.expect("sets the stamp");
}
}