neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! What the parent receives about a child (ยง40.50 items 6, 8, 9, amended
//! by #430): its state; the child's own words (`text`, `answer`) apart from
//! what neosian observed (`events`) and from neosian's own sentences
//! (`notes`); every text bounded with the cut stated; where its turns are
//! recorded in this store; and the link, said only once read back.

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

use super::events::{ERROR_BYTES, EVENTS_PER_ANSWER, OUTPUT_BYTES, head};
use super::link::{self, Linked, Naming};
use super::text::say;
use super::turn::{End, lock};

pub use super::child::Child;
use super::child::filed_as;
use crate::memory::dispatch::Memory;

/// How much of an error `list` shows per child.
const LIST_ERROR_BYTES: usize = 512;

/// How much one answer says about a child.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum View {
    /// `wait` and `stop`: new text and events, consumed.
    Read,
    /// `start` and `send`: the state.
    Brief,
    /// `list`: the state, no text, a short error.
    Listed,
}

/// Why the store shows no new turn, from what the watcher's filing said
/// (X4a). Only the store says recorded; the filing only explains.
fn unrecorded(filed: Option<&Value>, ended: bool) -> String {
    let Some(filed) = filed else {
        return say(if ended { "record_gap" } else { "not_recorded" }, &[]);
    };
    let key = match filed["disposition"].as_str().unwrap_or_default() {
        "pending" => "record_pending",
        "capture_off" | "capture_off_pending" => "record_off",
        "capture_paused" => "record_paused",
        "excluded" | "empty" => "record_excluded",
        "gap" => "record_gap",
        "stopped" => "record_stopped",
        "bound" => "record_bound",
        "session" | "existing" => "record_session",
        "recorded" => "record_elsewhere",
        "error" => {
            let error = filed["error"].as_str().unwrap_or_default();
            return say("record_error", &[("error", head(error, ERROR_BYTES))]);
        }
        _ => "not_recorded",
    };
    say(key, &[])
}

/// How the parent may read a turn: the conversation and the turns that
/// landed, or why there are none; and the link once the turn has ended.
fn record(
    memory: &Memory,
    naming: &Naming,
    child: &Child,
    ended: bool,
    notes: &mut Vec<String>,
) -> Value {
    let Some(native) = child.session.as_deref() else {
        notes.push(say("record_unknown", &[]));
        return Value::Null;
    };
    if child.existed {
        notes.push(say("announced_existing", &[("session", native)]));
        return Value::Null;
    }
    let conversation = naming.conversation(child.agent.kind(), native);
    let before = child
        .current
        .as_ref()
        .map_or(Ok(0), |turn| turn.before.clone());
    let read = before.and_then(|before| {
        link::last_turn_bounded(&memory.store, &conversation).map(|after| (before, after))
    });
    let (before, after) = match read {
        Ok(pair) => pair,
        Err(error) => {
            notes.push(say(
                "record_failed",
                &[("error", head(&error, ERROR_BYTES))],
            ));
            return Value::Null;
        }
    };
    let parent = if ended { child.parent.as_deref() } else { None };
    let linked = parent.map(|parent| link::link(memory, child.agent.kind(), &conversation, parent));
    // A lander writes the turn and then the parent line. When it lands between
    // the two reads, the turn is read again, so an answer never says linked
    // while it says the first turn is not yet readable.
    let after = match &linked {
        Some(Linked::Yes | Linked::Written) if after <= before => {
            link::last_turn_bounded(&memory.store, &conversation).unwrap_or(after)
        }
        _ => after,
    };
    let value = if after > before {
        let turns = if after == before + 1 {
            after.to_string()
        } else {
            format!("{}-{after}", before + 1)
        };
        notes.push(say(
            "recorded",
            &[("conversation", &conversation), ("turns", &turns)],
        ));
        json!({"conversation": conversation, "turns": turns})
    } else {
        let filed = child
            .current
            .as_ref()
            .and_then(|turn| lock(&turn.shared).filed.clone());
        notes.push(unrecorded(filed.as_ref(), ended));
        Value::Null
    };
    if !ended {
        return value;
    }
    let (Some(parent), Some(linked)) = (parent, linked) else {
        notes.push(say("not_linked_session", &[]));
        return value;
    };
    notes.push(match linked {
        Linked::Yes => say("linked", &[("session", parent)]),
        Linked::Written => say("link_written", &[("session", parent)]),
        Linked::Absent if after > 0 => say("not_linked_mount", &[]),
        Linked::Absent => say("not_linked_absent", &[]),
        Linked::NoMount => say("not_linked_mount", &[]),
        Linked::OtherAgent => say("not_linked_agent", &[]),
        Linked::Retry => say("not_linked_retry", &[]),
        Linked::Failed(error) => say("link_failed", &[("error", head(&error, ERROR_BYTES))]),
    });
    value
}

/// The child as one JSON object.
pub fn child(memory: &Memory, naming: &Naming, child: &mut Child, view: View) -> Value {
    child.learn();
    let state = child.state();
    // A stopped child still says why its last turn failed.
    let failed = child.outcome() == "failed";
    let mut out = Map::new();
    out.insert("child".into(), json!(child.id));
    out.insert("agent".into(), json!(child.agent.name()));
    out.insert("mode".into(), json!(child.mode.name()));
    out.insert("model".into(), json!(child.model));
    out.insert(
        "directory".into(),
        json!(child.directory.display().to_string()),
    );
    out.insert("state".into(), json!(state));
    out.insert("turn".into(), json!(child.turns));
    out.insert("session".into(), json!(child.session));
    let conversation = child
        .session
        .as_deref()
        .filter(|_| !child.existed)
        .map(|native| naming.conversation(child.agent.kind(), native));
    out.insert("conversation".into(), json!(conversation));
    let mut notes = Vec::new();
    let ended = state != "running" && state != "starting";
    if let Some(turn) = child.current.as_mut() {
        if view != View::Listed {
            notes.extend(turn.notes.iter().cloned());
        }
        let shared = lock(&turn.shared);
        if view == View::Read {
            let (text, skipped) = shared.text.since(turn.read_text, OUTPUT_BYTES);
            // Two places are kept for the truncation entries, so the cap holds.
            let (mut events, left_out) = shared.log.since(turn.read_events, EVENTS_PER_ANSWER - 2);
            if left_out > 0 {
                events.insert(
                    0,
                    json!({"kind": "truncated", "field": "events", "count": left_out}),
                );
            }
            if skipped > 0 {
                events.insert(
                    0,
                    json!({"kind": "truncated", "field": "text", "bytes": skipped}),
                );
                notes.push(say("output_cut", &[("bytes", &skipped.to_string())]));
            }
            out.insert("text".into(), json!(text));
            out.insert("events".into(), json!(events));
            turn.read_text = shared.text.total();
            turn.read_events = shared.log.total();
        }
        if ended
            && view != View::Listed
            && let Some(answer) = shared.final_answer()
        {
            let shown = head(answer, OUTPUT_BYTES);
            out.insert("answer".into(), json!(shown));
            if shown.len() < answer.len() {
                out.insert("answer_bytes".into(), json!(answer.len()));
                let (shown, bytes) = (shown.len().to_string(), answer.len().to_string());
                notes.push(say("answer_cut", &[("shown", &shown), ("bytes", &bytes)]));
            }
        }
        if failed {
            let limit = if view == View::Listed {
                LIST_ERROR_BYTES
            } else {
                ERROR_BYTES
            };
            let error = match (&shared.failure, shared.end) {
                (Some(failure), _) => failure.clone(),
                (None, Some(End::Lost)) => say("watcher_lost", &[]),
                (None, _) => shared.stderr.text().to_string(),
            };
            out.insert("error".into(), json!(head(&error, limit)));
            if let Some(End::Exited(code)) = shared.end {
                out.insert("exit".into(), json!(code));
            }
        }
        // From the watcher's receipt, never from filing having begun (X4f Q4).
        if child.stopped && filed_as(shared.filed.as_ref(), &["recorded", "pending"]) {
            notes.push(say("stopped_recorded", &[]));
        }
        if state == "timed_out" {
            notes.push(say(
                "timed_out",
                &[("seconds", &child.limit_seconds.to_string())],
            ));
        }
    }
    let recorded = record(memory, naming, child, ended, &mut notes);
    out.insert("record".into(), recorded);
    notes.extend(super::sandbox::note(
        super::sandbox::platform(),
        child.agent,
        child.mode,
    ));
    // `send` is offered only for a session something of which was filed:
    // a turn that failed before that leaves nothing to continue (X7d).
    let filed = child.claim();
    notes.push(match state {
        "running" | "starting" => say("running", &[("child", &child.id)]),
        "stopped" => say("stopped_note", &[]),
        "failed" | "timed_out" if !filed => say("ended_unfiled", &[("child", &child.id)]),
        _ => say("ended", &[("child", &child.id)]),
    });
    out.insert("notes".into(), json!(notes));
    Value::Object(out)
}