neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Pi's plan and display reading (X5a). The stream lines are built from Pi
//! 1.7.0's installed `json.md` and `message-types.md` (doc-derived: no
//! successful Pi turn has run here), except the session header, whose shape
//! is the captured no-provider run's.

use std::path::{Path, PathBuf};

use serde_json::{Value, json};

use super::super::adapter::{Agent, Mode, Plan, Request, Unplanned, plan as adapter_plan};
use super::super::events::Event;
use super::*;

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

fn paths(file: Option<&str>) -> Paths {
    Paths {
        agent_dir: PathBuf::from("/h/.pi/agent"),
        session_dir: PathBuf::from(format!("/h/.pi/agent/sessions/neosian-harness/{SESSION}")),
        file: file.map(PathBuf::from),
    }
}

fn request<'a>(mode: Mode, resume: Option<&'a str>, pi: Option<&'a Paths>) -> Request<'a> {
    Request {
        agent: Agent::Pi,
        mode,
        model: None,
        directory: Path::new("/h/work"),
        resume,
        new_session: SESSION,
        private: Path::new("/tmp/neosian-harness-x"),
        codex_keys: &[],
        opencode_config: None,
        parent: Some("parent-1"),
        server: None,
        codex_off: &[],
        confined: false,
        pi,
        child_home: None,
        memory: None,
    }
}

fn argv(plan: &Plan) -> Vec<&str> {
    plan.argv.iter().map(String::as_str).collect()
}

#[test]
fn both_modes_run_the_planned_argv_with_no_prompt_and_no_mcp() {
    let state = paths(None);
    let dir = state.session_dir.display().to_string();
    for (mode, tools) in [
        (Mode::ReadOnly, "read,grep,find,ls"),
        (Mode::Write, "read,bash,edit,write"),
    ] {
        let mut asked = request(mode, None, Some(&state));
        asked.model = Some("anthropic/claude-sonnet-4-6:high");
        let built = adapter_plan(&asked).unwrap();
        let expected = [
            "pi",
            "-p",
            "--mode",
            "json",
            "--offline",
            "--agent-dir",
            "/h/.pi/agent",
            "--session-dir",
            &dir,
            "--no-approve",
            "--no-extensions",
            "--no-mcp",
            "--no-skills",
            "--no-prompt-templates",
            "--no-themes",
            "--no-context-files",
            "--tools",
            tools,
            "--model",
            "anthropic/claude-sonnet-4-6:high",
            "--session-id",
            SESSION,
        ];
        assert_eq!(argv(&built), expected, "{mode:?}");
        let env: Vec<(&str, &str)> = built
            .env
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        assert!(env.contains(&("NEOSIAN_HARNESS_CHILD", "1")));
        assert!(env.contains(&("NEOSIAN_HARNESS_SESSION", SESSION)));
        assert!(env.contains(&("NEOSIAN_HARNESS_PARENT", "parent-1")));
    }
}

#[test]
fn a_continued_session_is_opened_by_its_exact_file_or_not_at_all() {
    let file = format!("/h/.pi/agent/sessions/neosian-harness/{SESSION}/t_{SESSION}.jsonl");
    let state = paths(Some(&file));
    let built = adapter_plan(&request(Mode::ReadOnly, Some(SESSION), Some(&state))).unwrap();
    let said = argv(&built);
    assert_eq!(said[said.len() - 2..], ["--session", file.as_str()]);
    assert!(!said.contains(&"--session-id"));
    let none = paths(None);
    let unplanned = adapter_plan(&request(Mode::ReadOnly, Some(SESSION), Some(&none)));
    assert_eq!(unplanned, Err(Unplanned::PiState));
    let unplanned = adapter_plan(&request(Mode::Write, None, None));
    assert_eq!(unplanned, Err(Unplanned::PiState));
}

fn shown(line: Value) -> Vec<Event> {
    Agent::Pi.read(&line.to_string())
}

#[test]
fn the_display_shows_complete_text_tools_retries_and_unsuccessful_ends() {
    let header = json!({"type": "session", "version": 3, "id": SESSION,
        "timestamp": "2026-11-28T21:09:13.378Z", "cwd": "/h/work"});
    assert_eq!(shown(header), [Event::Session(SESSION.into())]);
    let delta = json!({"type": "message_update", "assistantMessageEvent":
        {"type": "text_delta", "contentIndex": 0, "delta": "Hel"}});
    assert!(shown(delta).is_empty(), "deltas are not the text");
    let said = json!({"type": "message_end", "message": {"role": "assistant",
        "content": [{"type": "text", "text": "Hello"},
            {"type": "toolCall", "id": "c1", "name": "read", "arguments": {}},
            {"type": "text", "text": "again"}], "stopReason": "toolUse"}});
    assert_eq!(shown(said), [Event::Text("Hello\nagain".into())]);
    let user = json!({"type": "message_end", "message": {"role": "user", "content": "q"}});
    assert!(shown(user).is_empty());
    let failed = json!({"type": "tool_execution_end", "toolCallId": "c1", "toolName": "read",
        "result": {"content": [{"type": "text", "text": "ENOENT"}], "details": {}},
        "isError": true});
    let Event::Observed(entry) = &shown(failed)[0] else {
        panic!("an entry")
    };
    assert_eq!(entry["kind"], "tool_error");
    assert_eq!(entry["text"], "ENOENT");
    let retrying = json!({"type": "agent_end", "willRetry": true, "messages": [
        {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "529"}]});
    assert!(shown(retrying).is_empty(), "a retry follows");
    let gave_up = json!({"type": "auto_retry_end", "success": false, "attempt": 3,
        "finalError": "529 overloaded"});
    assert_eq!(shown(gave_up), [Event::Failure("529 overloaded".into())]);
    let cut = json!({"type": "agent_end", "willRetry": false, "messages": [
        {"role": "assistant", "content": [], "stopReason": "length"}]});
    let [Event::Failure(said)] = &shown(cut)[..] else {
        panic!("a failure")
    };
    assert!(said.contains("stop reason length"), "{said}");
    let done = json!({"type": "agent_end", "willRetry": false, "messages": [
        {"role": "assistant", "content": [], "stopReason": "stop"}]});
    assert!(shown(done).is_empty());
}