neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Antigravity's stream-json read for the record (X6a), from 1.5.20's live
//! runs (record/investigation-2026-11-29, section 2):
//!
//! - `init` names the conversation; every `step_update` and the `result`
//!   carry the same `conversation_id`, and one naming another contradicts
//!   the turn.
//! - A tool step is `ACTIVE`, then `DONE` or `ERROR` under the same
//!   `step_index`; the settled step is recorded with `tool_info.parameters`
//!   as its input and its `output` (a summary for `read_file`) or `error` as
//!   its result. A settled step never started, or one started and never
//!   settled, contradicts the turn.
//! - The turn completed on a `result` whose status is `SUCCESS`, nothing
//!   contradicted: its `response` is the answer. A stream without one is
//!   not complete. The watcher also needs exit 0.

use std::collections::HashSet;

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

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

/// What the record holds of an Antigravity turn while it runs.
#[derive(Default)]
pub struct Reader {
    session: Option<String>,
    open: HashSet<u64>,
    broken: bool,
    done: bool,
}

impl Reader {
    /// What the reader holds of the turn, in bytes.
    pub fn held(&self) -> u64 {
        (self.session.as_ref().map_or(0, String::len) + 8 * self.open.len()) as u64
    }

    pub fn line(&mut self, event: &Map<String, Value>) -> Vec<Said> {
        if self.done {
            return Vec::new();
        }
        let kind = text(event.get("event")).unwrap_or_default();
        let body = event.get(kind).filter(|_| kind != "init");
        let named = text(body.unwrap_or(&Value::Null).get("conversation_id"))
            .or_else(|| text(event.get("conversation_id")));
        let mut said = Vec::new();
        match (&self.session, named) {
            (None, Some(session)) if kind == "init" => {
                self.session = Some(session.to_string());
                said.push(Said::Session(session.to_string()));
            }
            (Some(known), Some(session)) if known == session => {}
            _ => self.broken = true,
        }
        match kind {
            "step_update" => said.extend(body.and_then(|step| self.step(step))),
            "result" => {
                self.done = true;
                let result = body.unwrap_or(&Value::Null);
                let success = text(result.get("status")) == Some("SUCCESS")
                    && self.open.is_empty()
                    && !self.broken;
                match text(result.get("response")).filter(|_| success) {
                    Some(answer) => {
                        said.extend([Said::Answer(answer.to_string()), Said::Completed])
                    }
                    None => said.push(Said::Failed),
                }
            }
            _ => {}
        }
        said
    }

    fn step(&mut self, step: &Value) -> Option<Said> {
        if text(step.get("step_type")) != Some("tool") {
            return None;
        }
        let Some(index) = step.get("step_index").and_then(Value::as_u64) else {
            self.broken = true;
            return None;
        };
        match text(step.get("state")) {
            Some("ACTIVE") => {
                self.open.insert(index);
                None
            }
            Some("DONE" | "ERROR") if self.open.remove(&index) => {
                let info = step.get("tool_info");
                let name = text(info.and_then(|i| i.get("name")))
                    .or_else(|| text(step.get("tool_name")))
                    .unwrap_or("tool");
                let field = |key: &str| info.and_then(|i| i.get(key)).cloned();
                let response = match field("error") {
                    Some(error) => json!({"error": error}),
                    None => json!({"output": field("output")}),
                };
                Some(Said::Tool {
                    id: Some(format!("step-{index}")),
                    name: name.to_string(),
                    input: field("parameters").unwrap_or(Value::Null),
                    response,
                })
            }
            _ => {
                self.broken = true;
                None
            }
        }
    }
}

#[cfg(test)]
mod tests;