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
//! The bridge between the loop's `Vec<Message>` and the session file.
//!
//! The loop's history is the truth while a run is happening; the session file is
//! the truth between runs. This converts one to the other and remembers how much
//! has been written, so `persist` is idempotent and never rewrites history it
//! already recorded.
//!
//! It lives here rather than in the binary because `yk acp` needs the same walk
//! to resume a session, and two copies of a file format is how a format forks.
//!
//! Ids are sequential (`e1`, `e2`, ...) rather than random. That makes a session
//! file diffable and a resumed conversation reproducible, which is worth more
//! here than the collision resistance a uuid would buy, because a session has
//! exactly one writer.

use crate::{Entry, SessionLog, next_id};
use yk_core::{Id, Message, Result, ToolResult, Turn};

/// An open session and the history it is backed by.
///
/// `Debug` is hand-written so the tests can use `expect_err`; deriving it would
/// try to print the open file handle.
pub struct Session {
    store: SessionLog,
    history: Vec<Message>,
    /// How far into `history` this session has got writing.
    written: usize,
    /// How many entries the file holds, which is not the same as `written`:
    /// a resumed session starts at zero having written nothing yet.
    on_disk: usize,
    /// The id of the last written entry, which is the next entry's parent.
    last_id: Option<Id>,
    /// The model in force, restored from the file so a resumed conversation
    /// continues on the model it was actually having.
    model: Option<String>,
}

impl std::fmt::Debug for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Session")
            .field("history", &self.history)
            .field("written", &self.written)
            .field("last_id", &self.last_id)
            .field("model", &self.model)
            .finish_non_exhaustive()
    }
}

impl Session {
    /// Where the session file is, for diagnostics.
    #[must_use]
    pub fn path(&self) -> &std::path::Path {
        self.store.path()
    }

    /// How many entries the file holds.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.on_disk
    }

    /// Whether the file holds nothing yet.
    ///
    /// Not dead weight: `clippy::len_without_is_empty` requires it beside `len`,
    /// and a reader coming to `len` expects to be able to ask the empty case.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.on_disk == 0
    }

    /// Open or create the session file and replay it into a history.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] if the file cannot be opened, and
    /// [`yk_core::Error::Malformed`] if a line cannot be read. A corrupt line is
    /// reported rather than skipped: silently dropping a message makes the model
    /// look like it forgot something, which is a much harder bug to find.
    pub fn open(path: &std::path::Path) -> Result<Self> {
        let store = SessionLog::open(path.to_path_buf())?;
        let entries = store.all_entries()?;

        // The branch walk, not every line. A forked or rewound session has
        // entries on disk that are not part of this conversation.
        let history = store.active_messages()?;

        Ok(Self {
            written: 0,
            on_disk: entries.len(),
            last_id: store.head_id()?,
            model: store.active_model()?,
            store,
            history,
        })
    }

    /// The conversation as it currently stands.
    #[must_use]
    pub fn history(&self) -> &[Message] {
        &self.history
    }

    pub const fn history_mut(&mut self) -> &mut Vec<Message> {
        &mut self.history
    }

    pub fn append_user(&mut self, prompt: &str) {
        self.history.push(Message::user(prompt));
    }

    /// The model this conversation is on, if the file says.
    #[must_use]
    pub fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    /// The model in force, or `default` when the session records none.
    ///
    /// The fallback for a new conversation and for one that never switched: the
    /// caller's configured model is the answer in both cases.
    #[must_use]
    pub fn model_or<'a>(&'a self, default: &'a str) -> &'a str {
        self.model.as_deref().unwrap_or(default)
    }

    /// Record a model switch, so a resumed conversation picks it back up.
    ///
    /// Appended rather than held only in memory: a client closes the process and
    /// reopens it, and a model that lived only in memory would be a picker that
    /// lies, reporting a switched model and then resuming on the configured one.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] if the entry cannot be written.
    pub fn set_model(&mut self, model: &str) -> Result<()> {
        let id = self.write(&Entry::Model {
            id: String::new(),
            parent: self.last_id.clone(),
            model: model.to_owned(),
        })?;
        self.last_id = Some(id);
        self.model = Some(model.to_owned());
        Ok(())
    }

    /// Replace the active branch with a summary, shadowing what came before.
    ///
    /// The summary is written as a `Compaction` entry, so the branch walk stops
    /// there and everything before it leaves the conversation without leaving the
    /// file. The in-memory history becomes the summary alone, so a run that
    /// continues from here sends the summary and not the shadowed turns.
    ///
    /// The write cursor moves with the history, because the summary is already on
    /// disk as the compaction entry and a later `persist` must not write it
    /// again.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] if the entry cannot be written.
    pub fn compact(&mut self, summary: &str) -> Result<()> {
        let id = self.write(&Entry::Compaction {
            id: String::new(),
            parent: self.last_id.clone(),
            summary: summary.to_owned(),
        })?;
        self.last_id = Some(id);

        self.history = vec![crate::summary_message(summary)];
        self.written = self.history.len();
        Ok(())
    }

    /// Append whatever the loop produced since the last call.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] if the file cannot be written. The cursor advances
    /// only for entries that were actually written, so a retry after a failure
    /// resumes rather than skipping.
    pub fn persist(&mut self) -> Result<()> {
        let pending: Vec<Message> = self
            .history
            .get(self.written..)
            .map_or_else(Vec::new, <[Message]>::to_vec);

        for message in pending {
            let id = self.write(&message_to_entry(&message, self.last_id.as_deref()))?;
            self.last_id = Some(id);
            self.written = self.written.saturating_add(1);
        }

        Ok(())
    }

    /// Append one entry, stamping the id and advancing the head.
    ///
    /// The id lives in every variant of [`Entry`] rather than beside them, so it
    /// is filled in here once instead of at each call site.
    fn write(&mut self, entry: &Entry) -> Result<Id> {
        let id = next_id(self.on_disk);
        let mut stamped = entry.clone();

        match &mut stamped {
            Entry::Message { id: slot, .. }
            | Entry::Assistant { id: slot, .. }
            | Entry::Result { id: slot, .. }
            | Entry::Compaction { id: slot, .. }
            | Entry::Model { id: slot, .. }
            | Entry::Rewind { id: slot, .. } => slot.clone_from(&id),
        }

        self.store.append(&stamped)?;
        self.on_disk = self.on_disk.saturating_add(1);
        Ok(id)
    }
}

/// Convert a history message into the entry shape the file stores.
fn message_to_entry(message: &Message, parent: Option<&str>) -> Entry {
    let parent = parent.map(ToOwned::to_owned);
    let id = String::new();

    match message {
        Message::User { content } => Entry::Message {
            id,
            parent,
            message: Message::user(content.clone()),
        },
        Message::Assistant {
            content,
            tool_calls,
        } => Entry::Assistant {
            id,
            parent,
            turn: Turn {
                text: content.clone(),
                tool_calls: tool_calls.clone(),
                usage: None,
            },
        },
        Message::Tool {
            tool_call_id,
            content,
            is_error,
        } => Entry::Result {
            id,
            parent,
            result: ToolResult {
                call_id: tool_call_id.clone(),
                output: content.clone(),
                is_error: *is_error,
            },
        },
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::as_conversions,
        clippy::arithmetic_side_effects
    )]

    use std::fs;

    use super::{Session, message_to_entry};
    use crate::Entry;
    use yk_core::{AssistantToolCall, Message};

    /// A session file 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(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::TempDir::with_prefix(name).expect("makes the directory");
        let path = dir.path().join("s.jsonl");
        (dir, path)
    }

    fn call() -> AssistantToolCall {
        AssistantToolCall {
            id: "c1".to_owned(),
            name: "read".to_owned(),
            arguments: r#"{"path":"a"}"#.to_owned(),
        }
    }

    #[test]
    fn a_fresh_session_is_empty() {
        let (_dir, path) = temp("fresh");
        let session = Session::open(&path).expect("opens");
        assert_eq!(session.len(), 0);
        assert!(session.history.is_empty());
    }

    #[test]
    fn a_persisted_history_reloads_identically() {
        let (_dir, path) = temp("roundtrip");
        {
            let mut session = Session::open(&path).expect("opens");
            session.append_user("hello");
            session.history_mut().push(Message::assistant("hi"));
            session.persist().expect("writes");
        }

        let reopened = Session::open(&path).expect("reopens");
        assert_eq!(reopened.history.len(), 2);
        assert_eq!(reopened.history[0], Message::user("hello"));
        assert_eq!(reopened.history[1], Message::assistant("hi"));
    }

    #[test]
    fn persisting_twice_does_not_duplicate() {
        let (_dir, path) = temp("idempotent");
        let mut session = Session::open(&path).expect("opens");

        session.append_user("one");
        session.persist().expect("writes");
        session.persist().expect("writes again");
        session.persist().expect("and again");

        assert_eq!(Session::open(&path).expect("reopens").len(), 1);
    }

    #[test]
    fn only_new_messages_are_written_each_time() {
        let (_dir, path) = temp("incremental");
        let mut session = Session::open(&path).expect("opens");

        session.append_user("first");
        session.persist().expect("writes");
        session.append_user("second");
        session.persist().expect("writes");

        let reopened = Session::open(&path).expect("reopens");
        assert_eq!(reopened.history.len(), 2);
        assert_eq!(reopened.history[1], Message::user("second"));
    }

    #[test]
    fn ids_continue_across_a_reopen() {
        let (_dir, path) = temp("ids");
        {
            let mut session = Session::open(&path).expect("opens");
            session.append_user("one");
            session.persist().expect("writes");
        }

        let mut reopened = Session::open(&path).expect("reopens");
        reopened.append_user("two");
        reopened.persist().expect("writes");

        let raw = fs::read_to_string(&path).expect("reads");
        let entries: Vec<serde_json::Value> = raw
            .lines()
            .map(|line| serde_json::from_str(line).expect("parses"))
            .filter(|value: &serde_json::Value| value["kind"] != "session")
            .collect();
        let second = &entries[1];

        assert_eq!(second["id"], "e2", "ids restarted: {second}");
    }

    #[test]
    fn every_entry_points_at_the_one_before_it() {
        let (_dir, path) = temp("chain");
        let mut session = Session::open(&path).expect("opens");
        session.append_user("one");
        session.history_mut().push(Message::assistant("two"));
        session.history_mut().push(Message::tool("c1", "three"));
        session.persist().expect("writes");

        let raw = fs::read_to_string(&path).expect("reads");
        let parsed: Vec<serde_json::Value> = raw
            .lines()
            .map(|line| serde_json::from_str(line).expect("parses"))
            .filter(|value: &serde_json::Value| value["kind"] != "session")
            .collect();

        assert_eq!(parsed.len(), 3);
        assert_eq!(parsed[0]["id"], "e1");
        assert_eq!(parsed[0]["parent"], serde_json::Value::Null);
        assert_eq!(parsed[1]["id"], "e2");
        assert_eq!(parsed[1]["parent"], "e1");
        assert_eq!(parsed[2]["id"], "e3");
        assert_eq!(parsed[2]["parent"], "e2");
    }

    #[test]
    fn a_tool_error_survives_the_file_even_though_the_wire_shape_drops_it() {
        let (_dir, path) = temp("toolerror");
        let message = Message::tool_result("c1", "no such file", true);

        // The provider must not see the flag.
        let wire = serde_json::to_string(&message).expect("serialises");
        assert!(
            !wire.contains("is_error"),
            "flag leaked to the wire: {wire}"
        );

        {
            let mut session = Session::open(&path).expect("opens");
            session.history_mut().push(message);
            session.persist().expect("writes");
        }

        let reopened = Session::open(&path).expect("reopens");
        assert_eq!(
            reopened.history[0],
            Message::tool_result("c1", "no such file", true),
            "the session lost the error flag"
        );
    }

    #[test]
    fn a_whole_conversation_round_trips() {
        let conversation = [
            Message::user("read a.txt"),
            Message::assistant_with_calls("one sec", vec![call()]),
            Message::tool("c1", "contents"),
            Message::assistant("done"),
        ];

        let mut seen = Vec::new();
        for message in &conversation {
            let entry = message_to_entry(message, None);
            seen.push(crate::entry_to_message(&entry));
        }

        assert_eq!(seen, conversation.into_iter().map(Some).collect::<Vec<_>>());
    }

    #[test]
    fn a_switched_model_survives_a_reopen_and_leaves_the_history_alone() {
        let (_dir, path) = temp("model");

        let fresh = Session::open(&path).expect("opens");
        assert_eq!(
            fresh.model(),
            None,
            "a session that never switched has no model"
        );

        {
            let mut session = Session::open(&path).expect("opens");
            session.append_user("hi");
            session.set_model("some/other-model").expect("writes");
            session.persist().expect("writes");
        }

        let reopened = Session::open(&path).expect("reopens");

        assert_eq!(reopened.model(), Some("some/other-model"));
        assert_eq!(reopened.history.len(), 1, "the switch became a message");
        assert_eq!(reopened.history[0], Message::user("hi"));
    }

    #[test]
    fn a_model_entry_continues_the_branch_rather_than_forking_it() {
        let (_dir, path) = temp("modelbranch");
        let mut session = Session::open(&path).expect("opens");
        session.append_user("hi");
        session.persist().expect("writes");
        session.set_model("switched").expect("writes");

        let raw = fs::read_to_string(&path).expect("reads");
        let entries: Vec<serde_json::Value> = raw
            .lines()
            .map(|line| serde_json::from_str(line).expect("parses"))
            .filter(|value: &serde_json::Value| value["kind"] != "session")
            .collect();

        assert_eq!(entries.len(), 2);
        assert_eq!(entries[1]["kind"], "model");
        assert_eq!(entries[1]["parent"], "e1");
        assert_eq!(entries[1]["model"], "switched");
    }

    #[test]
    fn a_corrupt_line_is_reported_rather_than_skipped() {
        let (_dir, path) = temp("corrupt");
        // Write before opening, so `SessionLog` never gets to repair the file.
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("makes the directory");
        }
        let good = Entry::Message {
            id: "e1".to_owned(),
            parent: None,
            message: Message::user("hi"),
        };
        fs::write(
            &path,
            format!(
                "{}\nnot json\n",
                serde_json::to_string(&good).expect("serialises")
            ),
        )
        .expect("writes");

        let error = Session::open(&path).expect_err("must fail");
        assert!(error.to_string().contains("line 2"), "{error}");
    }
}