yk-session 0.1.0

Append-only JSONL sessions as a tree of entries
Documentation
//! The tree: which entries are actually in play.
//!
//! The file is append-only and every entry names its parent, so a session is a
//! tree rather than a list. This module answers the only question that matters
//! when reading one back: *given the last entry, which entries form the
//! conversation?*
//!
//! Three operations make that non-obvious, and all three are append-only. None
//! of them rewrites or deletes a line.
//!
//! - **A fork** appends nothing. It copies the file, and the two copies grow
//!   apart from a common past.
//! - **A rewind** appends a [`Entry::Rewind`] naming an earlier id. The next
//!   append parents to that id, so the branch walk from the head never reaches
//!   what was dropped. The dropped entries are still on disk.
//! - **A compaction** appends a [`Entry::Compaction`]. The walk stops when it
//!   meets one, because a summary shadows everything before it.
//!
//! Rewinding by deletion would be simpler and would also throw away the only
//! record of what the model was told, which is the thing worth keeping.

use std::collections::BTreeMap;

use yk_core::{Id, Result};

use crate::{Entry, SessionLog, next_id};

impl SessionLog {
    /// The entry the active branch ends at.
    ///
    /// That is the last line in the file, except when it is a rewind, in which
    /// case it is the entry that rewind names. `None` is a file with nothing in
    /// it, and only that: a file that cannot be read is an error, not an empty
    /// session.
    ///
    /// A rewind whose target names nothing is returned as written, because this
    /// reads the last line rather than walking the branch. [`SessionLog::active_entries`] is
    /// the method that reports a target that names nothing.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] naming the file when it cannot be read, and
    /// [`yk_core::Error::Malformed`] when a line cannot be parsed. Reporting the
    /// read failure rather than turning it into `None` is the point: a caller
    /// that got `None` back could not tell a file it could not read from one
    /// nobody had written to.
    pub fn head_id(&self) -> Result<Option<Id>> {
        Ok(head_id(&self.all_entries()?))
    }

    /// The entries that make up the conversation, oldest first.
    ///
    /// Returns borrowed slices of the file read, which is why it is on `&self`
    /// and why the ids inside are borrowed too. A caller that needs to mutate
    /// the history wants [`SessionLog::active_messages`] instead.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] naming the file when it cannot be read, and
    /// [`yk_core::Error::Malformed`] when a line cannot be parsed or a parent id
    /// names no entry. A dangling parent is a corrupted file, and silently
    /// stopping the walk there would truncate a conversation in a way that looks
    /// like nothing happened.
    pub fn active_entries(&self) -> Result<Vec<Entry>> {
        let entries = self.all_entries()?;
        if entries.is_empty() {
            return Ok(Vec::new());
        }

        let by_id: BTreeMap<&Id, &Entry> =
            entries.iter().map(|entry| (entry.id(), entry)).collect();

        let head = head_id(&entries);
        let mut current = head.as_ref();

        let mut chain: Vec<&Entry> = Vec::new();
        let mut seen: Vec<&Id> = Vec::new();

        while let Some(id) = current {
            let entry = by_id
                .get(id)
                .copied()
                .ok_or_else(|| yk_core::Error::Malformed(format!("entry `{id}` is missing")))?;

            // A cycle would otherwise hang the walk. Nothing writes one, and a
            // file that contains one is not a tree.
            if seen.contains(&id) {
                return Err(yk_core::Error::Malformed(format!(
                    "entry `{id}` is its own ancestor"
                )));
            }
            seen.push(id);

            match entry {
                // Everything before a summary is shadowed by it.
                Entry::Compaction { .. } => {
                    chain.push(entry);
                    break;
                }
                Entry::Rewind { .. } => {
                    return Err(yk_core::Error::Malformed(format!(
                        "entry `{id}` is a rewind and cannot be part of a branch"
                    )));
                }
                _ => chain.push(entry),
            }

            current = entry.parent();
        }

        chain.reverse();
        Ok(chain.into_iter().cloned().collect())
    }

    /// The conversation as messages, oldest first.
    ///
    /// # Errors
    ///
    /// As [`SessionLog::active_entries`].
    pub fn active_messages(&self) -> Result<Vec<yk_core::Message>> {
        Ok(self
            .active_entries()?
            .iter()
            .filter_map(entry_to_message)
            .collect())
    }

    /// Every entry in the file, in the order written.
    ///
    /// The header is not an entry and is not returned. A corrupt line is
    /// reported rather than skipped, because a session that silently loses turns
    /// is worse than one that refuses to load.
    ///
    /// # Errors
    ///
    /// Fails if the file cannot be read, a line is not valid JSON, or the header
    /// names a version this build does not understand.
    pub fn all_entries(&self) -> Result<Vec<Entry>> {
        Ok(self.load()?.1)
    }

    /// The model this conversation ended up on.
    ///
    /// The last [`Entry::Model`] on the active branch, which is the one in force
    /// at the head. `None` for a session that never switched, meaning the
    /// caller's configured default is still the answer.
    ///
    /// # Errors
    ///
    /// As [`SessionLog::active_entries`].
    pub fn active_model(&self) -> Result<Option<String>> {
        Ok(self.active_entries()?.iter().rev().find_map(|entry| {
            if let Entry::Model { model, .. } = entry {
                Some(model.clone())
            } else {
                None
            }
        }))
    }

    /// Copy the whole file to `destination`.
    ///
    /// This is a fork. Both files share a past and diverge from it, and because
    /// nothing is ever rewritten neither can damage the other.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] when the destination cannot be written, and
    /// [`yk_core::Error::Malformed`] when the source cannot be read.
    pub fn fork(&self, destination: &std::path::Path) -> Result<()> {
        let (header, entries) = self.load()?;

        if let Some(parent) = destination.parent() {
            std::fs::create_dir_all(parent).map_err(|source| yk_core::Error::Write {
                path: parent.display().to_string(),
                source,
            })?;
        }

        let mut rendered = String::new();
        if let Some(header) = &header {
            let line = serde_json::to_string(header)
                .map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
            rendered.push_str(&line);
            rendered.push('\n');
        }
        for entry in &entries {
            let line = serde_json::to_string(entry)
                .map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
            rendered.push_str(&line);
            rendered.push('\n');
        }

        std::fs::write(destination, rendered).map_err(|source| yk_core::Error::Write {
            path: destination.display().to_string(),
            source,
        })
    }

    /// Append a rewind, so the branch walk stops at `to`.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Malformed`] when `to` names no entry in the file.
    pub fn rewind(&mut self, to: &Id) -> Result<()> {
        let entries = self.all_entries()?;

        if !entries.iter().any(|entry| entry.id() == to) {
            return Err(yk_core::Error::Malformed(format!(
                "cannot rewind to `{to}`; no such entry"
            )));
        }

        let id = next_id(entries.len());
        let entry = Entry::Rewind {
            id,
            parent: None,
            to: to.clone(),
        };

        self.append(&entry)
    }

    /// Move the head back by `messages` entries on the active branch.
    ///
    /// Counting entries rather than messages is deliberate: a turn is one
    /// assistant entry plus one entry per tool result, so "go back three" means
    /// something different from "go back three turns". Counting entries is the
    /// literal thing a user watching the transcript expects.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Malformed`] when the branch is shorter than `messages`,
    /// which would mean rewinding past the start.
    pub fn rewind_by(&mut self, messages: usize) -> Result<Id> {
        let entries = self.active_entries()?;
        let count = entries.len();

        if messages == 0 || messages >= count {
            return Err(yk_core::Error::InvalidInput(format!(
                "cannot rewind by {messages}; the branch has {count} entries"
            )));
        }

        let target = entries
            .get(count.saturating_sub(messages).saturating_sub(1))
            .ok_or_else(|| yk_core::Error::Malformed(format!("branch has only {count} entries")))?
            .id()
            .clone();

        self.rewind(&target)?;
        Ok(target)
    }

    /// Append a compaction, shadowing everything before it.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] when the entry cannot be written.
    pub fn compact(&mut self, summary: &str, parent: Option<&Id>) -> Result<Id> {
        let entries = self.all_entries()?;
        let id = next_id(entries.len());

        let entry = Entry::Compaction {
            id: id.clone(),
            parent: parent.map(ToOwned::to_owned),
            summary: summary.to_owned(),
        };

        self.append(&entry)?;
        Ok(id)
    }
}

/// The id the active branch ends at: the last entry's id, or a rewind's target.
fn head_id(entries: &[Entry]) -> Option<Id> {
    entries.last().map(|last| match last {
        Entry::Rewind { to, .. } => to.clone(),
        other => other.id().clone(),
    })
}

/// The message an entry contributes to the conversation, if any.
///
/// A [`Entry::Rewind`] contributes nothing: it is a direction, not a message.
#[must_use]
pub fn entry_to_message(entry: &Entry) -> Option<yk_core::Message> {
    match entry {
        Entry::Message { message, .. } => Some(message.clone()),
        Entry::Assistant { turn, .. } => Some(yk_core::Message::assistant_with_calls(
            turn.text.clone(),
            turn.tool_calls.clone(),
        )),
        Entry::Result { result, .. } => Some(yk_core::Message::tool_result(
            result.call_id.clone(),
            result.output.clone(),
            result.is_error,
        )),
        Entry::Compaction { summary, .. } => Some(summary_message(summary)),
        Entry::Model { .. } | Entry::Rewind { .. } => None,
    }
}

/// The message a compaction contributes to the conversation.
///
/// A user turn rather than an assistant one, because it is context handed to the
/// model about the past, not something the model said. Labelled so the model can
/// tell it from a person's message, and so a session that was compacted reads as
/// compacted rather than as a strange opening turn.
#[must_use]
pub fn summary_message(summary: &str) -> yk_core::Message {
    yk_core::Message::user(format!("Summary of the conversation so far:\n\n{summary}"))
}