neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Mistral Vibe's `--output streaming` read for the record (X6a), from
//! 3.1.5's live runs (record/investigation-2026-11-29, section 3):
//!
//! - Every entry carries the session's `sessionId`; one naming another
//!   session contradicts the turn, and so does an entry of another turn.
//! - A tool call and its result are one `effect` entry; a `completed` or
//!   `failed` one is recorded with its input and output, the error kept.
//! - Vibe prints no result: an assistant message can be committed and
//!   completed mid-turn, before more tool calls. The turn completed only
//!   when the stream ended with a committed, completed assistant message
//!   (hook notices aside), nothing contradicted; that message is the answer.
//!   The stream must end cleanly (X6c U7): its output reached its end, not
//!   the watcher's drain deadline, and every nonblank line was a JSON
//!   object (all of Vibe's are, in every live capture). The watcher also
//!   needs exit 0.

use serde_json::{Map, Value};

use super::Said;
use crate::harness::vibe::{text, words};

/// What the record holds of a Vibe turn while it runs.
#[derive(Default)]
pub struct Reader {
    session: Option<String>,
    turn: Option<String>,
    /// The last entry but a notice, when it is a committed, completed
    /// assistant message: its text.
    last: Option<String>,
    broken: bool,
}

impl Reader {
    /// What the reader holds of the turn, in bytes.
    pub fn held(&self) -> u64 {
        [&self.session, &self.turn, &self.last]
            .iter()
            .map(|held| held.as_ref().map_or(0, String::len) as u64)
            .sum()
    }

    pub fn line(&mut self, event: &Map<String, Value>) -> Vec<Said> {
        let mut said = Vec::new();
        match (&self.session, text(event.get("sessionId"))) {
            (None, Some(session)) => {
                self.session = Some(session.to_string());
                said.push(Said::Session(session.to_string()));
            }
            (Some(known), Some(session)) if known == session => {}
            _ => self.broken = true,
        }
        match (&self.turn, text(event.get("turnId"))) {
            (None, Some(turn)) => self.turn = Some(turn.to_string()),
            (Some(known), Some(turn)) if known != turn => self.broken = true,
            _ => {}
        }
        let kind = text(event.get("type")).unwrap_or_default();
        if kind == "notice" {
            return said;
        }
        self.last = None;
        match kind {
            "message" if text(event.get("role")) == Some("assistant") => {
                let committed =
                    event.get("outcome").and_then(|o| text(o.get("type"))) == Some("committed");
                let completed = text(event.get("generationStatus")) == Some("completed");
                self.last = (committed && completed).then(|| words(event));
            }
            "effect" => said.extend(tool(event)),
            _ => {}
        }
        said
    }

    /// A line that is not a JSON object: the stream cannot be read whole.
    pub fn malformed(&mut self) {
        self.broken = true;
    }

    /// At the end of the stream: whether the turn completed, and its answer.
    /// `eof` says the output reached its end.
    pub fn finish(&mut self, eof: bool) -> Vec<Said> {
        match self
            .last
            .take()
            .filter(|_| eof && !self.broken && self.session.is_some())
        {
            Some(answer) => vec![Said::Answer(answer), Said::Completed],
            None => vec![Said::Failed],
        }
    }
}

/// A settled `effect` as the recorded call: its input and its output.
fn tool(event: &Map<String, Value>) -> Option<Said> {
    let state = event.get("state")?;
    if !matches!(text(state.get("status")), Some("completed" | "failed")) {
        return None;
    }
    let detail = event.get("detail");
    let response = state.get("output").or(state.get("error"));
    Some(Said::Tool {
        id: text(event.get("toolCallId")).map(str::to_string),
        name: text(detail.and_then(|d| d.get("toolName")))
            .unwrap_or("tool")
            .to_string(),
        input: detail
            .and_then(|d| d.get("input"))
            .cloned()
            .unwrap_or(Value::Null),
        response: response.cloned().unwrap_or(Value::Null),
    })
}

#[cfg(test)]
mod tests;