neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
use super::*;
use serde_json::json;

const PROMPT: &str = "Read the file note.txt and reply with its first word.";

fn step(index: u64, body: Value) -> String {
    let mut step =
        json!({"step_index": index, "status": "DONE", "created_at": "2026-11-28T21:14:15Z"});
    for (key, value) in body.as_object().unwrap() {
        step[key] = value.clone();
    }
    format!("{step}\n")
}

/// Turn one (steps 0 to 2), then the turn under test from step `user`.
fn transcript(user: u64, last: Value) -> String {
    let wrapped = |text: &str| {
        format!(
            "<USER_REQUEST>\n{text}\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nnow\n</ADDITIONAL_METADATA>"
        )
    };
    [
        step(
            0,
            json!({"source": "USER_EXPLICIT", "type": "USER_INPUT", "content": wrapped("earlier")}),
        ),
        step(
            1,
            json!({"source": "MODEL", "type": "PLANNER_RESPONSE", "content": "OLD ANSWER"}),
        ),
        step(
            2,
            json!({"source": "SYSTEM_SDK", "type": "SYSTEM_MESSAGE", "content": "injected"}),
        ),
        step(
            user,
            json!({"source": "USER_EXPLICIT", "type": "USER_INPUT", "content": wrapped(PROMPT)}),
        ),
        step(
            user + 1,
            json!({"source": "SYSTEM_SDK", "type": "SYSTEM_MESSAGE", "content": "x"}),
        ),
        step(
            user + 2,
            json!({"source": "MODEL", "type": "PLANNER_RESPONSE",
            "tool_calls": [{"name": "read_file", "args": {"Path": "note.txt"}}]}),
        ),
        step(
            user + 3,
            json!({"source": "MODEL", "type": "GENERIC", "content": "1: banana split"}),
        ),
        step(user + 4, last),
    ]
    .concat()
}

fn call(step: u64) -> Call {
    Call {
        id: "call_1".into(),
        name: "read_file".into(),
        args: json!({"Path": "note.txt"}),
        step,
        error: String::new(),
        kept: true,
    }
}

/// The window read against a prompt's text, as the reader's digest check does.
fn turn_for(window: &[u8], user: u64, prompt: &str, calls: &[Call]) -> Result<Turn, String> {
    turn(window, user, &|request| request == prompt.trim(), calls)
}

fn read_for(
    home: &std::path::Path,
    native: &str,
    given: &str,
    user: u64,
    prompt: &str,
    calls: &[Call],
) -> Result<Turn, String> {
    read(
        home,
        native,
        given,
        user,
        &|request| request == prompt.trim(),
        calls,
    )
}

fn answer() -> Value {
    json!({"source": "MODEL", "type": "PLANNER_RESPONSE", "content": "banana"})
}

#[test]
fn the_window_from_the_user_step_gives_each_output_and_the_answer() {
    let text = transcript(3, answer());
    let read = turn_for(text.as_bytes(), 3, PROMPT, &[call(6)]).unwrap();
    assert_eq!(read.outputs, ["1: banana split"]);
    assert_eq!(read.answer, "banana");
    let failed = Call {
        error: "exit status 1".into(),
        ..call(6)
    };
    let read = turn_for(text.as_bytes(), 3, PROMPT, &[failed]).unwrap();
    assert_eq!(read.outputs, ["error: exit status 1\n1: banana split"]);
}

#[test]
fn an_ambiguous_incomplete_or_mismatched_window_is_a_gap() {
    let text = transcript(3, answer());
    let gap = |text: &str, user, prompt, calls: &[Call]| {
        turn_for(text.as_bytes(), user, prompt, calls).unwrap_err()
    };
    assert!(gap(&text, 3, "another prompt", &[call(6)]).contains("prompt"));
    assert!(gap(&text, 4, PROMPT, &[call(6)]).contains("prompt"));
    assert!(gap(&text, 3, PROMPT, &[]).contains("no staged tool call"));
    assert!(gap(&text, 3, PROMPT, &[call(5)]).contains("no result step"));
    // The turn's own answer is missing: the earlier turn's is never taken.
    let silent = transcript(
        3,
        json!({"source": "MODEL", "type": "PLANNER_RESPONSE", "content": ""}),
    );
    assert!(gap(&silent, 3, PROMPT, &[call(6)]).contains("completed answer"));
    let running = transcript(
        3,
        json!({"source": "MODEL", "type": "PLANNER_RESPONSE", "status": "ACTIVE", "content": "ba"}),
    );
    assert!(gap(&running, 3, PROMPT, &[call(6)]).contains("not complete"));
    let next = format!(
        "{text}{}",
        step(8, json!({"type": "USER_INPUT", "content": "again"}))
    );
    assert!(gap(&next, 3, PROMPT, &[call(6)]).contains("another user step"));
    let unknown = format!(
        "{text}{}",
        step(8, json!({"source": "MODEL", "type": "CHECKPOINT"}))
    );
    assert!(gap(&unknown, 3, PROMPT, &[call(6)]).contains("not verified"));
    assert!(gap(&format!("{text}{{\"step_"), 3, PROMPT, &[call(6)]).contains("whole JSON"));
}

#[test]
fn only_the_canonical_file_is_read() {
    let scratch = crate::testing::Scratch::new("agy-window");
    let home = scratch.path();
    let native = "368faa30-7727-4639-bd54-8d3342848ba8";
    let path = canonical(home, native);
    let text = transcript(3, answer());
    scratch.plant(path.strip_prefix(home).unwrap().to_str().unwrap(), &text);
    let given = format!("~/{}", path.strip_prefix(home).unwrap().display());
    assert_eq!(
        read_for(home, native, &given, 3, PROMPT, &[call(6)])
            .unwrap()
            .answer,
        "banana"
    );
    let given = path.display().to_string();
    assert!(read_for(home, native, &given, 3, PROMPT, &[call(6)]).is_ok());
    scratch.plant("elsewhere.jsonl", &text);
    let foreign = home.join("elsewhere.jsonl").display().to_string();
    assert!(
        read_for(home, native, &foreign, 3, PROMPT, &[call(6)])
            .unwrap_err()
            .contains("other than")
    );
    assert!(read_for(home, "another-id", &given, 3, PROMPT, &[call(6)]).is_err());
}