yk-session 0.1.0

Append-only JSONL sessions as a tree of entries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Append-only JSONL sessions, stored as a tree of entries.
//!
//! Every entry carries an id and a parent id. The active branch is the parent
//! chain walked back from the last entry, so nothing is ever rewritten and a
//! compaction is an entry that shadows what came before it.

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};

/// One line of a session file.
#[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,
    },
    /// Shadows everything before it on the branch.
    ///
    /// A summary is an entry rather than an edit so that compaction costs one
    /// append and the original messages stay on disk.
    Compaction {
        id: Id,
        parent: Option<Id>,
        summary: String,
    },
    /// Moves the head back to an earlier entry.
    ///
    /// Appended rather than applied by deletion, so what the model was told
    /// before the rewind is still readable afterwards.
    Rewind { id: Id, parent: Option<Id>, to: Id },
    /// The model this conversation switched to, from this point on.
    ///
    /// An entry rather than a header field, because the model is chosen partway
    /// through a session and the file is append-only. The last one on the active
    /// branch is the model in force; see [`SessionLog::active_model`]. Nothing in the
    /// conversation reads it, so [`entry_to_message`] drops it.
    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(),
        }
    }
}

/// The version of the session file format this build writes.
///
/// Bumped when an entry changes shape in a way an older reader would misread.
/// A reader refuses a version above this one rather than guessing at the fields.
pub const CURRENT_VERSION: u32 = 1;

/// The first line of a session file.
///
/// Written when the file is created and never rewritten, because the file is
/// append-only. It exists so a format change can be detected: without it, a
/// build that renamed an entry field would read an old session as a different
/// conversation rather than refusing it.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Header {
    /// Always `session`, and serialised as such. The tag is what tells a reader
    /// this line is the header and not an entry.
    kind: Kind,
    /// The format version, which is [`CURRENT_VERSION`] for anything this build
    /// writes.
    pub version: u32,
}

impl Header {
    /// A header for `version`.
    #[must_use]
    pub const fn new(version: u32) -> Self {
        Self {
            kind: Kind::Session,
            version,
        }
    }
}

/// The only value [`Header::kind`] takes.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
enum Kind {
    Session,
}

/// One line of a session file, once it has been classified.
enum Line {
    Header(Header),
    Entry(Entry),
}

/// Read one line as a header or an entry.
///
/// The two share a `kind` field, so the tag decides which shape to parse rather
/// than a fallback that would report a corrupt entry as a corrupt header.
///
/// # Errors
///
/// [`yk_core::Error::Malformed`] naming the line number when it is not valid
/// JSON or matches neither shape.
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}")))
    }
}

/// A session file opened for appending.
pub struct SessionLog {
    path: PathBuf,
    file: File,
}

impl SessionLog {
    /// Where the session file lives, for diagnostics.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Open, creating the file and its parent directories if needed.
    ///
    /// # Errors
    ///
    /// Fails if the directories cannot be created or the file cannot be opened.
    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,
            })?;
        }
        // A file that already holds bytes keeps them; a new or empty one gets the
        // header first, so every session this build writes is versioned from its
        // first line.
        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 })
    }

    /// Append one entry and flush it.
    ///
    /// Flushing per entry is deliberate. A session log that loses its last turn
    /// to a crash is a log of lies, and the cost is negligible next to a model
    /// round trip.
    ///
    /// # Errors
    ///
    /// Fails if the entry cannot be written.
    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,
            })
    }

    /// The header, if the file has one.
    ///
    /// `None` for a file written before the header existed. There is one version,
    /// so reading such a file as the current one is the only answer available and
    /// the right one.
    ///
    /// # Errors
    ///
    /// As [`SessionLog::all_entries`].
    pub fn header(&self) -> Result<Option<Header>> {
        Ok(self.load()?.0)
    }

    /// The header and the entries, in one pass over the file.
    ///
    /// # Errors
    ///
    /// As [`SessionLog::read`].
    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))
    }
}

/// Default location for session files.
#[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")
}

/// The path for a named session.
#[must_use]
pub fn path_for(dir: &Path, name: &str) -> PathBuf {
    dir.join(format!("{name}.jsonl"))
}

/// The id the next appended entry takes.
///
/// Sequential rather than random so a session file is diffable and a resumed
/// conversation is reproducible. One writer, so collisions cannot happen.
pub(crate) fn next_id(existing: usize) -> Id {
    format!("e{}", existing.saturating_add(1))
}

/// A name no other session has: the second it was made, and the process id.
///
/// The process id is what makes two launches in the same second distinct. It is
/// not a uuid, and two processes sharing a pid in the same second would collide,
/// which is not worth a dependency to prevent.
#[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())
}

/// One session file, and when it was last written.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionFile {
    /// Where the file is.
    pub path: PathBuf,
    /// When it was last written. This is what orders the list.
    pub modified: SystemTime,
}

/// The sessions in `dir`, newest first.
///
/// One reader of the directory, so `--continue` and the session picker cannot
/// disagree about what is there.
///
/// Not fallible, and that is a decision rather than an omission: a directory that
/// cannot be read holds no sessions as far as the interface is concerned, and a
/// first run has no directory at all. Returning nothing is the truth in both
/// cases, and an error would only be a second thing for the caller to render.
#[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;
            }
            // A directory or a dangling link can carry the extension, and neither
            // is a conversation. Listing one would hand the picker a row that
            // `/session` then refuses, which is a worse answer than not
            // listing it. #119.
            if !path.is_file() {
                return None;
            }
            let modified = entry.metadata().ok()?.modified().ok()?;
            Some(SessionFile { path, modified })
        })
        .collect();

    // Newest first, so the picker opens on the session someone most likely wants
    // and the cursor starts where the eye already is.
    found.sort_by_key(|session| std::cmp::Reverse(session.modified));
    found
}

/// The name of a session file, without the directory or the extension.
#[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)]
// Test code is exempt from the panic-shaped lints on purpose: the rules exist so
// product code has no reachable panic path, and a test that threads Result
// through every assertion is a worse test. Product code gets none of this.
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};

    /// A session path inside a scratch directory, removed on drop.
    ///
    /// The caller holds the `TempDir` so the directory outlives the path.
    /// `tempfile` rather than a fixed path under `std::env::temp_dir`, which
    /// collided between test binaries.
    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");
        // The first line must be valid, so the failure is unambiguously line 2.
        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() {
        // Every file written before the header existed. There is one version, so
        // reading it as the current one is the only answer and the right one.
        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");
    }

    /// Set a file's modification time, so an ordering test does not sleep.
    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");
    }
}