1use std::fs::{self, File, OpenOptions};
8use std::io::{BufRead, BufReader, Write};
9use std::path::{Path, PathBuf};
10use std::time::SystemTime;
11
12mod session;
13mod tree;
14
15pub use session::Session;
16pub use tree::{entry_to_message, summary_message};
17
18use serde::{Deserialize, Serialize};
19use yk_core::{Id, Message, Result, ToolResult, Turn};
20
21#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
23#[serde(tag = "kind", rename_all = "snake_case")]
24pub enum Entry {
25 Message {
26 id: Id,
27 parent: Option<Id>,
28 message: Message,
29 },
30 Assistant {
31 id: Id,
32 parent: Option<Id>,
33 turn: Turn,
34 },
35 Result {
36 id: Id,
37 parent: Option<Id>,
38 result: ToolResult,
39 },
40 Compaction {
45 id: Id,
46 parent: Option<Id>,
47 summary: String,
48 },
49 Rewind { id: Id, parent: Option<Id>, to: Id },
54 Model {
61 id: Id,
62 parent: Option<Id>,
63 model: String,
64 },
65}
66
67impl Entry {
68 #[must_use]
69 pub const fn id(&self) -> &Id {
70 match self {
71 Self::Message { id, .. }
72 | Self::Assistant { id, .. }
73 | Self::Result { id, .. }
74 | Self::Compaction { id, .. }
75 | Self::Model { id, .. }
76 | Self::Rewind { id, .. } => id,
77 }
78 }
79
80 #[must_use]
81 pub const fn parent(&self) -> Option<&Id> {
82 match self {
83 Self::Message { parent, .. }
84 | Self::Assistant { parent, .. }
85 | Self::Result { parent, .. }
86 | Self::Compaction { parent, .. }
87 | Self::Model { parent, .. }
88 | Self::Rewind { parent, .. } => parent.as_ref(),
89 }
90 }
91}
92
93pub const CURRENT_VERSION: u32 = 1;
98
99#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
106pub struct Header {
107 kind: Kind,
110 pub version: u32,
113}
114
115impl Header {
116 #[must_use]
118 pub const fn new(version: u32) -> Self {
119 Self {
120 kind: Kind::Session,
121 version,
122 }
123 }
124}
125
126#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
128#[serde(rename_all = "snake_case")]
129enum Kind {
130 Session,
131}
132
133enum Line {
135 Header(Header),
136 Entry(Entry),
137}
138
139fn parse_line(line: &str, number: usize) -> Result<Line> {
149 let value: serde_json::Value = serde_json::from_str(line)
150 .map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))?;
151
152 if value.get("kind").and_then(serde_json::Value::as_str) == Some("session") {
153 serde_json::from_value(value)
154 .map(Line::Header)
155 .map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))
156 } else {
157 serde_json::from_value(value)
158 .map(Line::Entry)
159 .map_err(|error| yk_core::Error::Malformed(format!("line {number}: {error}")))
160 }
161}
162
163pub struct SessionLog {
165 path: PathBuf,
166 file: File,
167}
168
169impl SessionLog {
170 #[must_use]
172 pub fn path(&self) -> &Path {
173 &self.path
174 }
175
176 pub fn open(path: impl Into<PathBuf>) -> Result<Self> {
182 let path = path.into();
183 if let Some(parent) = path.parent() {
184 fs::create_dir_all(parent).map_err(|source| yk_core::Error::Write {
185 path: parent.display().to_string(),
186 source,
187 })?;
188 }
189 let fresh = fs::metadata(&path).map_or(0, |meta| meta.len()) == 0;
193
194 let mut file = OpenOptions::new()
195 .create(true)
196 .append(true)
197 .open(&path)
198 .map_err(|source| yk_core::Error::Write {
199 path: path.display().to_string(),
200 source,
201 })?;
202
203 if fresh {
204 let line = serde_json::to_string(&Header::new(CURRENT_VERSION))
205 .map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
206 writeln!(file, "{line}")
207 .and_then(|()| file.flush())
208 .map_err(|source| yk_core::Error::Write {
209 path: path.display().to_string(),
210 source,
211 })?;
212 }
213
214 Ok(Self { path, file })
215 }
216
217 pub fn append(&mut self, entry: &Entry) -> Result<()> {
227 let line =
228 serde_json::to_string(entry).map_err(|e| yk_core::Error::Malformed(e.to_string()))?;
229 writeln!(self.file, "{line}")
230 .and_then(|()| self.file.flush())
231 .map_err(|source| yk_core::Error::Write {
232 path: self.path.display().to_string(),
233 source,
234 })
235 }
236
237 pub fn header(&self) -> Result<Option<Header>> {
247 Ok(self.load()?.0)
248 }
249
250 fn load(&self) -> Result<(Option<Header>, Vec<Entry>)> {
256 let file = File::open(&self.path).map_err(|source| yk_core::Error::Read {
257 path: self.path.display().to_string(),
258 source,
259 })?;
260
261 let mut header = None;
262 let mut entries = Vec::new();
263 for (number, line) in BufReader::new(file).lines().enumerate() {
264 let line = line.map_err(|source| yk_core::Error::Read {
265 path: self.path.display().to_string(),
266 source,
267 })?;
268 if line.trim().is_empty() {
269 continue;
270 }
271
272 match parse_line(&line, number.saturating_add(1))? {
273 Line::Header(found) => {
274 if found.version > CURRENT_VERSION {
275 return Err(yk_core::Error::Malformed(format!(
276 "session file is version {}, but this build writes {CURRENT_VERSION}",
277 found.version
278 )));
279 }
280 header = Some(found);
281 }
282 Line::Entry(entry) => entries.push(entry),
283 }
284 }
285
286 Ok((header, entries))
287 }
288}
289
290#[must_use]
292pub fn default_dir() -> PathBuf {
293 let home = std::env::var_os("HOME").map_or_else(|| PathBuf::from("."), PathBuf::from);
294 home.join(".yk").join("sessions")
295}
296
297#[must_use]
299pub fn path_for(dir: &Path, name: &str) -> PathBuf {
300 dir.join(format!("{name}.jsonl"))
301}
302
303pub(crate) fn next_id(existing: usize) -> Id {
308 format!("e{}", existing.saturating_add(1))
309}
310
311#[must_use]
317pub fn new_session_name() -> String {
318 let seconds = std::time::SystemTime::now()
319 .duration_since(std::time::UNIX_EPOCH)
320 .map_or(0, |elapsed| elapsed.as_secs());
321 format!("{seconds}-{}", std::process::id())
322}
323
324#[derive(Clone, Debug, Eq, PartialEq)]
326pub struct SessionFile {
327 pub path: PathBuf,
329 pub modified: SystemTime,
331}
332
333#[must_use]
343pub fn list_sessions(dir: &Path) -> Vec<SessionFile> {
344 let Ok(entries) = std::fs::read_dir(dir) else {
345 return Vec::new();
346 };
347
348 let mut found: Vec<SessionFile> = entries
349 .flatten()
350 .filter_map(|entry| {
351 let path = entry.path();
352 if path.extension().and_then(std::ffi::OsStr::to_str) != Some("jsonl") {
353 return None;
354 }
355 if !path.is_file() {
360 return None;
361 }
362 let modified = entry.metadata().ok()?.modified().ok()?;
363 Some(SessionFile { path, modified })
364 })
365 .collect();
366
367 found.sort_by_key(|session| std::cmp::Reverse(session.modified));
370 found
371}
372
373#[must_use]
375pub fn session_name_of(path: &Path) -> String {
376 path.file_stem().map_or_else(
377 || path.display().to_string(),
378 |stem| stem.to_string_lossy().into_owned(),
379 )
380}
381
382#[cfg(test)]
383mod tests {
387 #![allow(
388 clippy::unwrap_used,
389 clippy::expect_used,
390 clippy::indexing_slicing,
391 clippy::as_conversions,
392 clippy::arithmetic_side_effects
393 )]
394
395 use super::{Entry, SessionLog, list_sessions, path_for, session_name_of};
396 use std::fs;
397 use yk_core::{Message, ToolResult};
398
399 fn temp_path(tag: &str) -> (tempfile::TempDir, std::path::PathBuf) {
405 let dir = tempfile::TempDir::with_prefix(tag).expect("temp dir");
406 let path = path_for(dir.path(), "s");
407 (dir, path)
408 }
409
410 #[test]
411 fn appends_and_reads_back_in_order() {
412 let (_dir, path) = temp_path("order");
413
414 let mut store = SessionLog::open(&path).expect("opens");
415 store
416 .append(&Entry::Message {
417 id: "a".to_owned(),
418 parent: None,
419 message: Message::user("hello"),
420 })
421 .expect("appends");
422 store
423 .append(&Entry::Result {
424 id: "b".to_owned(),
425 parent: Some("a".to_owned()),
426 result: ToolResult::ok("call-1", "done"),
427 })
428 .expect("appends");
429
430 let entries = store.all_entries().expect("reads");
431 assert_eq!(entries.len(), 2);
432 assert_eq!(entries[0].id(), "a");
433 assert_eq!(entries[0].parent(), None);
434 assert_eq!(entries[1].parent(), Some(&"a".to_owned()));
435 }
436
437 #[test]
438 fn a_corrupt_line_is_reported_rather_than_skipped() {
439 let (_dir, path) = temp_path("corrupt");
440 let good = Entry::Message {
442 id: "a".to_owned(),
443 parent: None,
444 message: Message::user("hello"),
445 };
446 let json = serde_json::to_string(&good).expect("serialises");
447 fs::write(&path, format!("{json}\nnot json\n")).expect("writes");
448
449 let store = SessionLog::open(&path).expect("opens");
450 let error = store
451 .all_entries()
452 .expect_err("a bad line must not be skipped");
453
454 assert!(
455 error.to_string().contains("line 2"),
456 "unhelpful error: {error}"
457 );
458 }
459
460 #[test]
461 fn a_new_session_file_starts_with_a_version_header() {
462 let (_dir, path) = temp_path("header");
463 let store = SessionLog::open(&path).expect("opens");
464
465 assert_eq!(
466 store.header().expect("reads the header"),
467 Some(super::Header::new(super::CURRENT_VERSION))
468 );
469 assert!(
470 store.all_entries().expect("reads").is_empty(),
471 "the header must not read back as an entry"
472 );
473 }
474
475 #[test]
476 fn a_header_from_a_newer_build_is_refused() {
477 let (_dir, path) = temp_path("newer");
478 let header = super::Header::new(super::CURRENT_VERSION.saturating_add(1));
479 let line = serde_json::to_string(&header).expect("serialises");
480 fs::write(&path, format!("{line}\n")).expect("writes");
481
482 let store = SessionLog::open(&path).expect("opens");
483 let error = store
484 .all_entries()
485 .expect_err("must refuse a newer version");
486
487 assert!(error.to_string().contains("version"), "{error}");
488 }
489
490 #[test]
491 fn a_file_without_a_header_still_reads() {
492 let (_dir, path) = temp_path("legacy");
495 let entry = Entry::Message {
496 id: "e1".to_owned(),
497 parent: None,
498 message: Message::user("old"),
499 };
500 fs::write(
501 &path,
502 format!("{}\n", serde_json::to_string(&entry).expect("serialises")),
503 )
504 .expect("writes");
505
506 let store = SessionLog::open(&path).expect("opens");
507
508 assert!(store.header().expect("reads").is_none());
509 assert_eq!(store.all_entries().expect("reads").len(), 1);
510 }
511
512 #[test]
513 fn sessions_are_listed_newest_first() {
514 let (dir, _) = temp_path("sessions-order");
515 for (name, seconds) in [("oldest", 1_000), ("newest", 3_000), ("middle", 2_000)] {
516 let path = dir.path().join(format!("{name}.jsonl"));
517 fs::write(&path, "").expect("writes");
518 stamp(&path, seconds);
519 }
520
521 let names: Vec<String> = list_sessions(dir.path())
522 .iter()
523 .map(|session| session_name_of(&session.path))
524 .collect();
525
526 assert_eq!(names, ["newest", "middle", "oldest"]);
527 }
528
529 #[test]
530 fn a_session_that_is_not_jsonl_is_not_a_session() {
531 let (dir, _) = temp_path("sessions-filter");
532 fs::write(dir.path().join("real.jsonl"), "").expect("writes");
533 fs::write(dir.path().join("notes.txt"), "").expect("writes");
534
535 let found = list_sessions(dir.path());
536
537 assert_eq!(found.len(), 1);
538 assert_eq!(session_name_of(&found[0].path), "real");
539 }
540
541 #[test]
542 fn a_directory_that_is_not_there_holds_no_sessions() {
543 let (dir, path) = temp_path("sessions-absent");
544 let missing = path.parent().expect("a parent").join("nope");
545
546 assert!(
547 list_sessions(&missing).is_empty(),
548 "and that is not an error"
549 );
550 assert!(list_sessions(dir.path()).is_empty());
551 }
552
553 #[test]
554 fn a_name_is_the_stem_and_nothing_else() {
555 assert_eq!(
556 session_name_of(std::path::Path::new("/a/b/17-99.jsonl")),
557 "17-99"
558 );
559 assert_eq!(session_name_of(std::path::Path::new("bare")), "bare");
560 }
561
562 fn stamp(path: &std::path::Path, seconds: u64) {
564 let file = fs::File::options().write(true).open(path).expect("opens");
565 let at = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds);
566 file.set_times(fs::FileTimes::new().set_modified(at))
567 .expect("sets the stamp");
568 }
569}