neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Pi's stream as the record reads it (X5a). The lines follow Pi 1.7.0's
//! installed `json.md` and the order its agent loop emits them in
//! (`pi-agent-core/dist/agent-loop.js`, `agent-session.js`): doc- and
//! source-derived, since no successful Pi turn has run here.

use serde_json::{Value, json};

use super::super::Said;
use super::Reader;

const SESSION: &str = "5eab6b3f-d0af-49c3-9c0c-a9b47c2c8ebe";

fn header() -> Value {
    json!({"type": "session", "version": 3, "id": SESSION,
        "timestamp": "2026-11-28T21:09:13.378Z", "cwd": "/h/work"})
}

fn assistant(text: &str, stop: &str) -> Value {
    json!({"type": "message_end", "message": {"role": "assistant",
        "content": [{"type": "text", "text": text}], "stopReason": stop}})
}

fn tool(id: &str, error: bool) -> Vec<Value> {
    vec![
        json!({"type": "tool_execution_start", "toolCallId": id, "toolName": "read",
            "args": {"path": "note.txt"}}),
        json!({"type": "tool_execution_end", "toolCallId": id, "toolName": "read",
            "result": {"content": [{"type": "text", "text": "banana"}], "details": {}},
            "isError": error}),
        json!({"type": "message_end", "message": {"role": "toolResult", "toolCallId": id,
            "toolName": "read", "content": [{"type": "text", "text": "banana"}],
            "isError": error}}),
    ]
}

fn settled(aborted: bool) -> Value {
    json!({"type": "agent_settled", "aborted": aborted})
}

fn end(retry: bool) -> Value {
    json!({"type": "agent_end", "messages": [], "willRetry": retry})
}

fn read(lines: &[Value]) -> Vec<Said> {
    let mut reader = Reader::default();
    lines
        .iter()
        .flat_map(|line| reader.line(line.as_object().unwrap()))
        .collect()
}

fn turn(middle: Vec<Value>, last: Vec<Value>) -> Vec<Value> {
    let mut lines = vec![header(), assistant("Reading.", "toolUse")];
    lines.extend(middle);
    lines.extend(last);
    lines
}

#[test]
fn a_settled_turn_pairs_its_tool_and_keeps_an_error_result() {
    for error in [false, true] {
        let lines = turn(
            tool("c1", error),
            vec![assistant("banana", "stop"), end(false), settled(false)],
        );
        let said = read(&lines);
        assert_eq!(
            said,
            vec![
                Said::Session(SESSION.into()),
                Said::Answer("Reading.".into()),
                Said::Call {
                    id: "c1".into(),
                    name: "read".into(),
                    input: json!({"path": "note.txt"}),
                },
                Said::Result {
                    id: "c1".into(),
                    response: json!({"content": [{"type": "text", "text": "banana"}],
                        "isError": error}),
                    ok: true,
                },
                Said::Answer("banana".into()),
                Said::Completed,
            ],
            "error {error}"
        );
    }
}

#[test]
fn only_settlement_completes_and_a_retry_is_balanced_first() {
    // No settlement: no completion, whatever agent_end says.
    let unsettled = turn(tool("c1", false), vec![assistant("x", "stop"), end(false)]);
    assert!(!read(&unsettled).contains(&Said::Completed));
    // A failed attempt, a retry that succeeds, then settlement.
    let retried = vec![
        header(),
        json!({"type": "message_end", "message": {"role": "assistant", "content": [],
            "stopReason": "error", "errorMessage": "529 overloaded"}}),
        end(true),
        json!({"type": "auto_retry_start", "attempt": 1, "maxAttempts": 3,
            "delayMs": 2000, "errorMessage": "529 overloaded"}),
        json!({"type": "auto_retry_start", "attempt": 2, "maxAttempts": 3,
            "delayMs": 4000, "errorMessage": "529 overloaded"}),
        assistant("ok", "stop"),
        json!({"type": "auto_retry_end", "success": true, "attempt": 2}),
        end(false),
        settled(false),
    ];
    assert_eq!(read(&retried).last(), Some(&Said::Completed));
    let mut open = retried.clone();
    open.remove(6);
    assert_eq!(read(&open).last(), Some(&Said::Failed), "a retry left open");
    let mut failed = retried;
    failed[6] = json!({"type": "auto_retry_end", "success": false, "finalError": "x"});
    assert_eq!(read(&failed).last(), Some(&Said::Failed));
}

#[test]
fn an_unsuccessful_or_contradicted_turn_does_not_complete() {
    let ending = |stop: &str, aborted: bool| {
        turn(
            vec![],
            vec![assistant("x", stop), end(false), settled(aborted)],
        )
    };
    for stop in ["length", "error", "aborted", "toolUse"] {
        assert_eq!(
            read(&ending(stop, false)).last(),
            Some(&Said::Failed),
            "{stop}"
        );
    }
    assert_eq!(read(&ending("stop", true)).last(), Some(&Said::Failed));
    let mut other = ending("stop", false);
    other.insert(1, json!({"type": "session", "id": "another"}));
    assert_eq!(read(&other).last(), Some(&Said::Failed), "two sessions");
    let mut started = tool("c1", false);
    started.truncate(1);
    let open = turn(started, vec![assistant("x", "stop"), settled(false)]);
    assert_eq!(
        read(&open).last(),
        Some(&Said::Failed),
        "a call never ended"
    );
    let mut orphan = tool("c1", false);
    orphan.remove(0);
    let orphan = turn(orphan, vec![assistant("x", "stop"), settled(false)]);
    assert_eq!(
        read(&orphan).last(),
        Some(&Said::Failed),
        "an end never started"
    );
    let mut differs = tool("c1", false);
    differs[2]["message"]["isError"] = json!(true);
    let differs = turn(differs, vec![assistant("x", "stop"), settled(false)]);
    assert_eq!(
        read(&differs).last(),
        Some(&Said::Failed),
        "a result contradicted"
    );
    // What follows settlement is not this run's.
    let mut after = ending("stop", false);
    after.push(assistant("later", "stop"));
    assert_eq!(read(&after).last(), Some(&Said::Completed));
}

#[test]
fn a_live_turn_against_a_local_model_completes_with_its_tool_round() {
    // X7a: Pi 1.7.0 with a 2B Qwen behind llama.cpp's OpenAI-compatible
    // server (scrubbed): a system message first, thinking, one read.
    let mut reader = Reader::default();
    let said: Vec<Said> =
        include_str!("../../../../../../tests/contract/fixtures/harness/pi-read-turn.jsonl")
            .lines()
            .flat_map(|line| {
                reader.line(
                    serde_json::from_str::<Value>(line)
                        .unwrap()
                        .as_object()
                        .unwrap(),
                )
            })
            .collect();
    assert!(
        said.iter()
            .any(|s| matches!(s, Said::Call { name, .. } if name == "read"))
    );
    assert!(
        said.iter()
            .any(|s| matches!(s, Said::Result { ok: true, .. }))
    );
    assert_eq!(said.last(), Some(&Said::Completed), "{said:?}");
}