neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Whether a Mistral Vibe turn is committed, and its committed answer (A1c,
//! measured on Vibe 3.1.5's session store `mistral.vibe.unified-session-store/v1`).
//! `post_agent` gives only a candidate a later hook may reject, so the answer
//! comes from the session's own directory,
//! `$VIBE_HOME/logs/session/unified/<id>/`, which the hook's `transcript_path`
//! must name. `CURRENT` names the generation. Its `checkpoint.json` names the
//! last finished turn with its output once the session has written a
//! generation; before that, the generation's journal segment (from its
//! `manifest.json`) holds, for the turn's own `turn/start` command, a
//! `projection_delta` appending the turn's assistant message with
//! `outcome: committed` and `generationStatus: completed`, then a
//! `receipt_succeeded`. The journal is read back from its end to the turn's
//! `command_reserved` record, at most 16 MiB; every other file is small and
//! read whole within 1 MiB. No component below `VIBE_HOME` may be a link.
//! `meta.json`, chunks and older turns are never read.

use super::bounded;
use serde_json::Value;
use std::path::{Path, PathBuf};

/// The most journal one turn's window may hold.
pub const CAP: u64 = 16 << 20;
const SMALL: u64 = 1 << 20;

/// The one session directory this session's hooks may name.
pub fn canonical(vibe_home: &Path, native: &str) -> PathBuf {
    vibe_home.join("logs/session/unified").join(native)
}

fn whole(vibe_home: &Path, path: &Path) -> Result<Value, String> {
    let checked = bounded::plain(vibe_home, path)?;
    let bytes = bounded::tail(path, &checked, SMALL, |_| false)?;
    serde_json::from_slice(&bytes).map_err(|_| format!("{} is not JSON", path.display()))
}

fn digits(text: &str) -> bool {
    !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
}

/// The text parts of a message's content or a turn's output.
fn texts(parts: &Value) -> String {
    let parts = parts.as_array().into_iter().flatten();
    let texts: Vec<&str> = parts
        .filter(|p| p["type"] == "text")
        .filter_map(|p| p["text"].as_str())
        .collect();
    texts.join("\n")
}

/// `Ok(Some(answer))` once `turn` is shown committed, `Ok(None)` while it is
/// not yet, `Err` when the session's files may not be read for it.
pub fn committed(
    vibe_home: &Path,
    native: &str,
    given: &str,
    turn: &str,
) -> Result<Option<String>, String> {
    let directory = canonical(vibe_home, native);
    if Path::new(given) != directory {
        return Err("the hook named a session directory other than this session's own".into());
    }
    let current = whole(vibe_home, &directory.join("CURRENT"))?;
    if current["session_id"] != native {
        return Err("the session directory's CURRENT names another session".into());
    }
    let generation = current["generation"]
        .as_str()
        .filter(|g| digits(g))
        .ok_or("the session directory's CURRENT names no generation")?;
    let at = directory.join("generations").join(generation);
    let finished = &whole(vibe_home, &at.join("checkpoint.json"))?["turn"];
    let own = finished["turn_id"] == turn && finished["type"] == "terminal";
    // Terminal evidence for this turn that is not a completion drops it.
    if own && finished["outcome"]["type"] != "completed" {
        return Err("the turn ended without completing".into());
    }
    if own {
        let answer = texts(&finished["outcome"]["output"]);
        return match answer.is_empty() {
            true => Err("the turn finished without an answer".into()),
            false => Ok(Some(answer)),
        };
    }
    let manifest = whole(vibe_home, &at.join("manifest.json"))?;
    let segment = manifest["recovery_journal_segment"]["path"]
        .as_str()
        .filter(|p| {
            p.strip_prefix("journal/")
                .and_then(|name| name.strip_suffix(".jsonl"))
                .is_some_and(digits)
        })
        .ok_or("the generation names no journal segment")?;
    let path = directory.join(segment);
    if !path.exists() {
        return Ok(None);
    }
    let checked = bounded::plain(vibe_home, &path)?;
    let window = bounded::tail(&path, &checked, CAP, |lines| {
        lines
            .split(|b| *b == b'\n')
            .any(|line| reserves(line, turn))
    })?;
    journal(&window, turn)
}

/// Whether this line is the turn's own `turn/start` reservation; only a
/// line naming the turn is parsed.
fn reserves(line: &[u8], turn: &str) -> bool {
    let named = std::str::from_utf8(line).is_ok_and(|l| l.contains(turn));
    named
        && serde_json::from_slice::<Value>(line).is_ok_and(|record| {
            record["type"] == "command_reserved" && record["payload"]["client_command_id"] == turn
        })
}

/// The turn's committed assistant message, if a delta appended one.
fn appended<'a>(record: &'a Value, turn: &str) -> Option<&'a Value> {
    let ops = record["payload"]["delta"].as_array()?;
    ops.iter()
        .rev()
        .filter(|op| op["op"] == "append_entry")
        .map(|op| &op["entry"])
        .find(|entry| {
            entry["type"] == "message"
                && entry["role"] == "assistant"
                && entry["turnId"] == turn
                && entry["outcome"]["type"] == "committed"
                && entry["generationStatus"] == "completed"
        })
}

fn journal(window: &[u8], turn: &str) -> Result<Option<String>, String> {
    let text = std::str::from_utf8(window).map_err(|_| "the journal is not UTF-8")?;
    let lines: Vec<&str> = text.split('\n').filter(|l| !l.trim().is_empty()).collect();
    let (mut answer, mut done) = (None, false);
    for (index, line) in lines.iter().enumerate() {
        let Ok(record) = serde_json::from_str::<Value>(line) else {
            // A last line Vibe is still writing holds nothing committed yet.
            if index + 1 == lines.len() && !text.ends_with('\n') {
                break;
            }
            return Err("a journal record is not whole JSON".into());
        };
        match record["type"].as_str() {
            Some("receipt_succeeded") if record["payload"]["client_command_id"] == turn => {
                done = true;
            }
            Some("projection_delta") => {
                if let Some(entry) = appended(&record, turn) {
                    answer = Some(texts(&entry["content"]));
                }
            }
            _ => {}
        }
    }
    match (done, answer) {
        (true, Some(answer)) if !answer.is_empty() => Ok(Some(answer)),
        (true, _) => Err("the turn completed without a committed answer".into()),
        (false, _) => Ok(None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn record(kind: &str, payload: Value) -> String {
        format!(
            "{}\n",
            serde_json::json!({"type": kind, "payload": payload})
        )
    }

    fn message(turn: &str, outcome: &str, text: &str) -> String {
        let entry = serde_json::json!({"type": "message", "role": "assistant", "turnId": turn,
            "outcome": {"type": outcome}, "generationStatus": "completed",
            "content": [{"type": "text", "text": text}]});
        record(
            "projection_delta",
            serde_json::json!({"delta": [{"op": "append_entry", "entry": entry}]}),
        )
    }

    #[test]
    fn only_this_turns_committed_message_and_receipt_close_it() {
        let reserved = record(
            "command_reserved",
            serde_json::json!({"client_command_id": "t2"}),
        );
        let receipt = record(
            "receipt_succeeded",
            serde_json::json!({"client_command_id": "t2"}),
        );
        let window = [
            reserved.clone(),
            message("t2", "committed", "banana"),
            receipt.clone(),
        ]
        .concat();
        assert_eq!(journal(window.as_bytes(), "t2").unwrap().unwrap(), "banana");
        assert!(reserves(reserved.trim().as_bytes(), "t2") && !reserves(reserved.as_bytes(), "t1"));
        let early = [reserved.clone(), message("t2", "committed", "banana")].concat();
        assert_eq!(journal(early.as_bytes(), "t2").unwrap(), None);
        let other = [message("t1", "committed", "OLD"), receipt.clone()].concat();
        assert!(journal(other.as_bytes(), "t2").is_err());
        let candidate = [message("t2", "candidate", "maybe"), receipt.clone()].concat();
        assert!(journal(candidate.as_bytes(), "t2").is_err());
        let writing = format!("{}{{\"type\": \"proj", early);
        assert_eq!(journal(writing.as_bytes(), "t2").unwrap(), None);
    }
}