Skip to main content

yk_session/
lib.rs

1//! Append-only JSONL sessions, stored as a tree of entries.
2//!
3//! Every entry carries an id and a parent id. The active branch is the parent
4//! chain walked back from the last entry, so nothing is ever rewritten and a
5//! compaction is an entry that shadows what came before it.
6
7use 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/// One line of a session file.
22#[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    /// Shadows everything before it on the branch.
41    ///
42    /// A summary is an entry rather than an edit so that compaction costs one
43    /// append and the original messages stay on disk.
44    Compaction {
45        id: Id,
46        parent: Option<Id>,
47        summary: String,
48    },
49    /// Moves the head back to an earlier entry.
50    ///
51    /// Appended rather than applied by deletion, so what the model was told
52    /// before the rewind is still readable afterwards.
53    Rewind { id: Id, parent: Option<Id>, to: Id },
54    /// The model this conversation switched to, from this point on.
55    ///
56    /// An entry rather than a header field, because the model is chosen partway
57    /// through a session and the file is append-only. The last one on the active
58    /// branch is the model in force; see [`SessionLog::active_model`]. Nothing in the
59    /// conversation reads it, so [`entry_to_message`] drops it.
60    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
93/// The version of the session file format this build writes.
94///
95/// Bumped when an entry changes shape in a way an older reader would misread.
96/// A reader refuses a version above this one rather than guessing at the fields.
97pub const CURRENT_VERSION: u32 = 1;
98
99/// The first line of a session file.
100///
101/// Written when the file is created and never rewritten, because the file is
102/// append-only. It exists so a format change can be detected: without it, a
103/// build that renamed an entry field would read an old session as a different
104/// conversation rather than refusing it.
105#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
106pub struct Header {
107    /// Always `session`, and serialised as such. The tag is what tells a reader
108    /// this line is the header and not an entry.
109    kind: Kind,
110    /// The format version, which is [`CURRENT_VERSION`] for anything this build
111    /// writes.
112    pub version: u32,
113}
114
115impl Header {
116    /// A header for `version`.
117    #[must_use]
118    pub const fn new(version: u32) -> Self {
119        Self {
120            kind: Kind::Session,
121            version,
122        }
123    }
124}
125
126/// The only value [`Header::kind`] takes.
127#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
128#[serde(rename_all = "snake_case")]
129enum Kind {
130    Session,
131}
132
133/// One line of a session file, once it has been classified.
134enum Line {
135    Header(Header),
136    Entry(Entry),
137}
138
139/// Read one line as a header or an entry.
140///
141/// The two share a `kind` field, so the tag decides which shape to parse rather
142/// than a fallback that would report a corrupt entry as a corrupt header.
143///
144/// # Errors
145///
146/// [`yk_core::Error::Malformed`] naming the line number when it is not valid
147/// JSON or matches neither shape.
148fn 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
163/// A session file opened for appending.
164pub struct SessionLog {
165    path: PathBuf,
166    file: File,
167}
168
169impl SessionLog {
170    /// Where the session file lives, for diagnostics.
171    #[must_use]
172    pub fn path(&self) -> &Path {
173        &self.path
174    }
175
176    /// Open, creating the file and its parent directories if needed.
177    ///
178    /// # Errors
179    ///
180    /// Fails if the directories cannot be created or the file cannot be opened.
181    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        // A file that already holds bytes keeps them; a new or empty one gets the
190        // header first, so every session this build writes is versioned from its
191        // first line.
192        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    /// Append one entry and flush it.
218    ///
219    /// Flushing per entry is deliberate. A session log that loses its last turn
220    /// to a crash is a log of lies, and the cost is negligible next to a model
221    /// round trip.
222    ///
223    /// # Errors
224    ///
225    /// Fails if the entry cannot be written.
226    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    /// The header, if the file has one.
238    ///
239    /// `None` for a file written before the header existed. There is one version,
240    /// so reading such a file as the current one is the only answer available and
241    /// the right one.
242    ///
243    /// # Errors
244    ///
245    /// As [`SessionLog::all_entries`].
246    pub fn header(&self) -> Result<Option<Header>> {
247        Ok(self.load()?.0)
248    }
249
250    /// The header and the entries, in one pass over the file.
251    ///
252    /// # Errors
253    ///
254    /// As [`SessionLog::read`].
255    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/// Default location for session files.
291#[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/// The path for a named session.
298#[must_use]
299pub fn path_for(dir: &Path, name: &str) -> PathBuf {
300    dir.join(format!("{name}.jsonl"))
301}
302
303/// The id the next appended entry takes.
304///
305/// Sequential rather than random so a session file is diffable and a resumed
306/// conversation is reproducible. One writer, so collisions cannot happen.
307pub(crate) fn next_id(existing: usize) -> Id {
308    format!("e{}", existing.saturating_add(1))
309}
310
311/// A name no other session has: the second it was made, and the process id.
312///
313/// The process id is what makes two launches in the same second distinct. It is
314/// not a uuid, and two processes sharing a pid in the same second would collide,
315/// which is not worth a dependency to prevent.
316#[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/// One session file, and when it was last written.
325#[derive(Clone, Debug, Eq, PartialEq)]
326pub struct SessionFile {
327    /// Where the file is.
328    pub path: PathBuf,
329    /// When it was last written. This is what orders the list.
330    pub modified: SystemTime,
331}
332
333/// The sessions in `dir`, newest first.
334///
335/// One reader of the directory, so `--continue` and the session picker cannot
336/// disagree about what is there.
337///
338/// Not fallible, and that is a decision rather than an omission: a directory that
339/// cannot be read holds no sessions as far as the interface is concerned, and a
340/// first run has no directory at all. Returning nothing is the truth in both
341/// cases, and an error would only be a second thing for the caller to render.
342#[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            // A directory or a dangling link can carry the extension, and neither
356            // is a conversation. Listing one would hand the picker a row that
357            // `/session` then refuses, which is a worse answer than not
358            // listing it. #119.
359            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    // Newest first, so the picker opens on the session someone most likely wants
368    // and the cursor starts where the eye already is.
369    found.sort_by_key(|session| std::cmp::Reverse(session.modified));
370    found
371}
372
373/// The name of a session file, without the directory or the extension.
374#[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)]
383// Test code is exempt from the panic-shaped lints on purpose: the rules exist so
384// product code has no reachable panic path, and a test that threads Result
385// through every assertion is a worse test. Product code gets none of this.
386mod 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    /// A session path inside a scratch directory, removed on drop.
400    ///
401    /// The caller holds the `TempDir` so the directory outlives the path.
402    /// `tempfile` rather than a fixed path under `std::env::temp_dir`, which
403    /// collided between test binaries.
404    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        // The first line must be valid, so the failure is unambiguously line 2.
441        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        // Every file written before the header existed. There is one version, so
493        // reading it as the current one is the only answer and the right one.
494        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    /// Set a file's modification time, so an ordering test does not sleep.
563    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}