neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Muse Code's `exec --json` read for the record (X6b), from 1.4.25's live
//! runs (record/investigation-2026-11-29, section 1):
//!
//! - Every line names its stream: the session's (`kind` `session`, the ID
//!   neosian chose) and its usage stream under the same ID; a line of either
//!   kind under another ID contradicts the turn.
//! - A tool call's result is one `tool.result` with its `call_id`, the tool's
//!   name and outcome, and its text; the call's arguments are not on stdout
//!   (only in Muse's own session log), so the record keeps the name and the
//!   result, a failed one included.
//! - The session links the turn to one run (`session.run.linked`: its
//!   `command_id` and `run_stream`); a tool result or terminal event counts
//!   only on the session's own stream, for that run (X6c U6). Another run's
//!   events in the same session (a scheduled one) are not this turn's.
//! - The turn completed on its run's `run.terminal.completed`, nothing
//!   contradicted: its `text` is the answer. `run.terminal.failed` or a
//!   stream without its terminal event does not complete it. The watcher
//!   also needs exit 0.

use serde_json::{Map, Value, json};

use super::Said;
use crate::harness::muse::text;

/// What the record holds of a Muse Code turn while it runs.
#[derive(Default)]
pub struct Reader {
    session: Option<String>,
    /// The run the session linked: its command and its run stream's ID.
    run: Option<(String, String)>,
    broken: bool,
    done: bool,
}

impl Reader {
    /// What the reader holds of the turn, in bytes.
    pub fn held(&self) -> u64 {
        let run = self.run.as_ref().map_or(0, |(c, r)| c.len() + r.len());
        (self.session.as_ref().map_or(0, String::len) + run) as u64
    }

    pub fn line(&mut self, event: &Map<String, Value>) -> Vec<Said> {
        if self.done {
            return Vec::new();
        }
        let mut said = Vec::new();
        let stream = event.get("stream");
        let kind = text(stream.and_then(|s| s.get("kind"))).unwrap_or_default();
        let id = text(stream.and_then(|s| s.get("id")));
        if matches!(kind, "session" | "exec.usage") {
            match (&self.session, id) {
                (None, Some(session)) if kind == "session" => {
                    self.session = Some(session.to_string());
                    said.push(Said::Session(session.to_string()));
                }
                (Some(known), Some(session)) if known == session => {}
                _ => self.broken = true,
            }
        }
        let own_stream = kind == "session" && id.is_some() && self.session.as_deref() == id;
        let payload = event.get("payload");
        let field = |name: &str| payload.and_then(|p| p.get(name));
        let command = text(field("command_id"));
        let run_stream = field("run_stream");
        let run = text(run_stream.and_then(|r| r.get("id")))
            .filter(|_| text(run_stream.and_then(|r| r.get("kind"))) == Some("run"));
        let linked = matches!((&self.run, command, run), (Some((c, r)), Some(command), Some(run))
            if c == command && r == run);
        let ours = own_stream && linked;
        match text(event.get("payload_type")).unwrap_or_default() {
            "session.run.linked" if own_stream && self.run.is_none() => {
                if let (Some(command), Some(run)) = (command, run) {
                    self.run = Some((command.to_string(), run.to_string()));
                }
            }
            "tool.result" if ours => {
                let facts = field("correlation_facts");
                let name = text(facts.and_then(|f| f.get("tool_name"))).unwrap_or("tool");
                let outcome = facts.and_then(|f| f.get("outcome")).cloned();
                said.push(Said::Tool {
                    id: text(field("call_id")).map(str::to_string),
                    name: name.to_string(),
                    input: json!({}),
                    response: json!({"text": field("text"), "outcome": outcome}),
                });
            }
            "run.terminal.completed" if ours => {
                self.done = true;
                match text(field("text")).filter(|_| !self.broken) {
                    Some(answer) => {
                        said.extend([Said::Answer(answer.to_string()), Said::Completed])
                    }
                    None => said.push(Said::Failed),
                }
            }
            "run.terminal.failed" if ours => {
                self.done = true;
                said.push(Said::Failed);
            }
            _ => {}
        }
        said
    }
}

#[cfg(test)]
mod tests;