Skip to main content

yk_session/
tree.rs

1//! The tree: which entries are actually in play.
2//!
3//! The file is append-only and every entry names its parent, so a session is a
4//! tree rather than a list. This module answers the only question that matters
5//! when reading one back: *given the last entry, which entries form the
6//! conversation?*
7//!
8//! Three operations make that non-obvious, and all three are append-only. None
9//! of them rewrites or deletes a line.
10//!
11//! - **A fork** appends nothing. It copies the file, and the two copies grow
12//!   apart from a common past.
13//! - **A rewind** appends a [`Entry::Rewind`] naming an earlier id. The next
14//!   append parents to that id, so the branch walk from the head never reaches
15//!   what was dropped. The dropped entries are still on disk.
16//! - **A compaction** appends a [`Entry::Compaction`]. The walk stops when it
17//!   meets one, because a summary shadows everything before it.
18//!
19//! Rewinding by deletion would be simpler and would also throw away the only
20//! record of what the model was told, which is the thing worth keeping.
21
22use std::collections::BTreeMap;
23
24use yk_core::{Id, Result};
25
26use crate::{Entry, SessionLog, next_id};
27
28impl SessionLog {
29    /// The entry the active branch ends at.
30    ///
31    /// That is the last line in the file, except when it is a rewind, in which
32    /// case it is the entry that rewind names. `None` is a file with nothing in
33    /// it, and only that: a file that cannot be read is an error, not an empty
34    /// session.
35    ///
36    /// A rewind whose target names nothing is returned as written, because this
37    /// reads the last line rather than walking the branch. [`SessionLog::active_entries`] is
38    /// the method that reports a target that names nothing.
39    ///
40    /// # Errors
41    ///
42    /// [`yk_core::Error::Read`] naming the file when it cannot be read, and
43    /// [`yk_core::Error::Malformed`] when a line cannot be parsed. Reporting the
44    /// read failure rather than turning it into `None` is the point: a caller
45    /// that got `None` back could not tell a file it could not read from one
46    /// nobody had written to.
47    pub fn head_id(&self) -> Result<Option<Id>> {
48        Ok(head_id(&self.all_entries()?))
49    }
50
51    /// The entries that make up the conversation, oldest first.
52    ///
53    /// Returns borrowed slices of the file read, which is why it is on `&self`
54    /// and why the ids inside are borrowed too. A caller that needs to mutate
55    /// the history wants [`SessionLog::active_messages`] instead.
56    ///
57    /// # Errors
58    ///
59    /// [`yk_core::Error::Read`] naming the file when it cannot be read, and
60    /// [`yk_core::Error::Malformed`] when a line cannot be parsed or a parent id
61    /// names no entry. A dangling parent is a corrupted file, and silently
62    /// stopping the walk there would truncate a conversation in a way that looks
63    /// like nothing happened.
64    pub fn active_entries(&self) -> Result<Vec<Entry>> {
65        let entries = self.all_entries()?;
66        if entries.is_empty() {
67            return Ok(Vec::new());
68        }
69
70        let by_id: BTreeMap<&Id, &Entry> =
71            entries.iter().map(|entry| (entry.id(), entry)).collect();
72
73        let head = head_id(&entries);
74        let mut current = head.as_ref();
75
76        let mut chain: Vec<&Entry> = Vec::new();
77        let mut seen: Vec<&Id> = Vec::new();
78
79        while let Some(id) = current {
80            let entry = by_id
81                .get(id)
82                .copied()
83                .ok_or_else(|| yk_core::Error::Malformed(format!("entry `{id}` is missing")))?;
84
85            // A cycle would otherwise hang the walk. Nothing writes one, and a
86            // file that contains one is not a tree.
87            if seen.contains(&id) {
88                return Err(yk_core::Error::Malformed(format!(
89                    "entry `{id}` is its own ancestor"
90                )));
91            }
92            seen.push(id);
93
94            match entry {
95                // Everything before a summary is shadowed by it.
96                Entry::Compaction { .. } => {
97                    chain.push(entry);
98                    break;
99                }
100                Entry::Rewind { .. } => {
101                    return Err(yk_core::Error::Malformed(format!(
102                        "entry `{id}` is a rewind and cannot be part of a branch"
103                    )));
104                }
105                _ => chain.push(entry),
106            }
107
108            current = entry.parent();
109        }
110
111        chain.reverse();
112        Ok(chain.into_iter().cloned().collect())
113    }
114
115    /// The conversation as messages, oldest first.
116    ///
117    /// # Errors
118    ///
119    /// As [`SessionLog::active_entries`].
120    pub fn active_messages(&self) -> Result<Vec<yk_core::Message>> {
121        Ok(self
122            .active_entries()?
123            .iter()
124            .filter_map(entry_to_message)
125            .collect())
126    }
127
128    /// Every entry in the file, in the order written.
129    ///
130    /// The header is not an entry and is not returned. A corrupt line is
131    /// reported rather than skipped, because a session that silently loses turns
132    /// is worse than one that refuses to load.
133    ///
134    /// # Errors
135    ///
136    /// Fails if the file cannot be read, a line is not valid JSON, or the header
137    /// names a version this build does not understand.
138    pub fn all_entries(&self) -> Result<Vec<Entry>> {
139        Ok(self.load()?.1)
140    }
141
142    /// The model this conversation ended up on.
143    ///
144    /// The last [`Entry::Model`] on the active branch, which is the one in force
145    /// at the head. `None` for a session that never switched, meaning the
146    /// caller's configured default is still the answer.
147    ///
148    /// # Errors
149    ///
150    /// As [`SessionLog::active_entries`].
151    pub fn active_model(&self) -> Result<Option<String>> {
152        Ok(self.active_entries()?.iter().rev().find_map(|entry| {
153            if let Entry::Model { model, .. } = entry {
154                Some(model.clone())
155            } else {
156                None
157            }
158        }))
159    }
160
161    /// Copy the whole file to `destination`.
162    ///
163    /// This is a fork. Both files share a past and diverge from it, and because
164    /// nothing is ever rewritten neither can damage the other.
165    ///
166    /// # Errors
167    ///
168    /// [`yk_core::Error::Read`] when the destination cannot be written, and
169    /// [`yk_core::Error::Malformed`] when the source cannot be read.
170    pub fn fork(&self, destination: &std::path::Path) -> Result<()> {
171        let (header, entries) = self.load()?;
172
173        if let Some(parent) = destination.parent() {
174            std::fs::create_dir_all(parent).map_err(|source| yk_core::Error::Write {
175                path: parent.display().to_string(),
176                source,
177            })?;
178        }
179
180        let mut rendered = String::new();
181        if let Some(header) = &header {
182            let line = serde_json::to_string(header)
183                .map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
184            rendered.push_str(&line);
185            rendered.push('\n');
186        }
187        for entry in &entries {
188            let line = serde_json::to_string(entry)
189                .map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
190            rendered.push_str(&line);
191            rendered.push('\n');
192        }
193
194        std::fs::write(destination, rendered).map_err(|source| yk_core::Error::Write {
195            path: destination.display().to_string(),
196            source,
197        })
198    }
199
200    /// Append a rewind, so the branch walk stops at `to`.
201    ///
202    /// # Errors
203    ///
204    /// [`yk_core::Error::Malformed`] when `to` names no entry in the file.
205    pub fn rewind(&mut self, to: &Id) -> Result<()> {
206        let entries = self.all_entries()?;
207
208        if !entries.iter().any(|entry| entry.id() == to) {
209            return Err(yk_core::Error::Malformed(format!(
210                "cannot rewind to `{to}`; no such entry"
211            )));
212        }
213
214        let id = next_id(entries.len());
215        let entry = Entry::Rewind {
216            id,
217            parent: None,
218            to: to.clone(),
219        };
220
221        self.append(&entry)
222    }
223
224    /// Move the head back by `messages` entries on the active branch.
225    ///
226    /// Counting entries rather than messages is deliberate: a turn is one
227    /// assistant entry plus one entry per tool result, so "go back three" means
228    /// something different from "go back three turns". Counting entries is the
229    /// literal thing a user watching the transcript expects.
230    ///
231    /// # Errors
232    ///
233    /// [`yk_core::Error::Malformed`] when the branch is shorter than `messages`,
234    /// which would mean rewinding past the start.
235    pub fn rewind_by(&mut self, messages: usize) -> Result<Id> {
236        let entries = self.active_entries()?;
237        let count = entries.len();
238
239        if messages == 0 || messages >= count {
240            return Err(yk_core::Error::InvalidInput(format!(
241                "cannot rewind by {messages}; the branch has {count} entries"
242            )));
243        }
244
245        let target = entries
246            .get(count.saturating_sub(messages).saturating_sub(1))
247            .ok_or_else(|| yk_core::Error::Malformed(format!("branch has only {count} entries")))?
248            .id()
249            .clone();
250
251        self.rewind(&target)?;
252        Ok(target)
253    }
254
255    /// Append a compaction, shadowing everything before it.
256    ///
257    /// # Errors
258    ///
259    /// [`yk_core::Error::Read`] when the entry cannot be written.
260    pub fn compact(&mut self, summary: &str, parent: Option<&Id>) -> Result<Id> {
261        let entries = self.all_entries()?;
262        let id = next_id(entries.len());
263
264        let entry = Entry::Compaction {
265            id: id.clone(),
266            parent: parent.map(ToOwned::to_owned),
267            summary: summary.to_owned(),
268        };
269
270        self.append(&entry)?;
271        Ok(id)
272    }
273}
274
275/// The id the active branch ends at: the last entry's id, or a rewind's target.
276fn head_id(entries: &[Entry]) -> Option<Id> {
277    entries.last().map(|last| match last {
278        Entry::Rewind { to, .. } => to.clone(),
279        other => other.id().clone(),
280    })
281}
282
283/// The message an entry contributes to the conversation, if any.
284///
285/// A [`Entry::Rewind`] contributes nothing: it is a direction, not a message.
286#[must_use]
287pub fn entry_to_message(entry: &Entry) -> Option<yk_core::Message> {
288    match entry {
289        Entry::Message { message, .. } => Some(message.clone()),
290        Entry::Assistant { turn, .. } => Some(yk_core::Message::assistant_with_calls(
291            turn.text.clone(),
292            turn.tool_calls.clone(),
293        )),
294        Entry::Result { result, .. } => Some(yk_core::Message::tool_result(
295            result.call_id.clone(),
296            result.output.clone(),
297            result.is_error,
298        )),
299        Entry::Compaction { summary, .. } => Some(summary_message(summary)),
300        Entry::Model { .. } | Entry::Rewind { .. } => None,
301    }
302}
303
304/// The message a compaction contributes to the conversation.
305///
306/// A user turn rather than an assistant one, because it is context handed to the
307/// model about the past, not something the model said. Labelled so the model can
308/// tell it from a person's message, and so a session that was compacted reads as
309/// compacted rather than as a strange opening turn.
310#[must_use]
311pub fn summary_message(summary: &str) -> yk_core::Message {
312    yk_core::Message::user(format!("Summary of the conversation so far:\n\n{summary}"))
313}