neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The verb's grammar and dispatch (`record/cli.py`, `record/settings.py`,
//! DESIGN §20.9): the store half and the mount half are the memory
//! grammar's own, new here are the foreign agent's kind and the spool, and
//! no `--actor`: the writer is `<agent>:<session_id>` by construction.
//! Exit tiers under a hook's semantics (Claude Code reads 2 as "block"):
//! 2 only for argv, nothing constructed, and 1 for everything after it (a
//! login the environment does not name, bad stdin, an unreachable store, a
//! corrupt spool), so a broken store never blocks the agent. Registered
//! once per machine (§22.6), the verb derives the layout per session from
//! `--project` (else the working directory), and a directory with no name
//! records to the user mount alone.

use std::env;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use super::event::record_payload;
use super::payload::parse_payload;
use super::settings::{Settings, cursor_project, environment, layout_of, resolve_mounts};
use crate::cli::usage;
use crate::conversation::failed;
use crate::conversation::sessions::sessions_mount;
use crate::home::home;
use crate::memory::grammar::SCOPE_ENV;
use crate::memory::mounts::{Mount, Refusal};
use crate::remote::selection::Selection;
use crate::repr::repr;
use crate::store::grammar::Actor;
use clap::Args;

pub(super) const DEFAULT_AGENT: &str = "claude-code";
const SPOOL_DIR_NAME: &str = "spool";
pub const HINT: &str = "the record never blocks the agent — fix the cause and the next Stop lands \
                        the whole span (the spool keeps it)";
const CURSOR_HINT: &str = "hint: Cursor has no unambiguous project; using /user. Set --project, \
                           --scope or --mount to select one.";
const AGY_HINT: &str = "hint: Antigravity named no absolute working directory; using /user. Set \
                        --project, --scope or --mount to select one.";
/// The clients whose hook runs outside the session's directory: the
/// project comes from the payload.
const PAYLOAD_PROJECT: [&str; 2] = ["cursor", "agy"];

/// Record a foreign agent's session from its hooks: one payload on stdin per call.
#[derive(Args)]
pub struct Record {
    /// Select a portable workspace profile and its local capture policy.
    #[arg(long)]
    pub(super) profile: Option<String>,
    #[command(subcommand)]
    pub(super) command: Option<crate::clients::install::RecordCommand>,
    /// FileStore root directory (created on start; default: the home,
    /// ~/.neosian or $NEOSIAN_HOME)
    #[arg(long)]
    pub(super) root: Option<PathBuf>,
    /// State process URL; bearer token comes from NEOSIAN_CLIENT_TOKEN.
    #[arg(long)]
    pub(super) url: Option<String>,
    /// Postgres schema (Postgres only).
    #[arg(long)]
    pub(super) schema: Option<String>,
    /// single read-write mount of SCOPE at /memories (the memory_scope= sugar)
    #[arg(long)]
    pub(super) scope: Option<String>,
    /// explicit mount; repeatable for multi-mount setups (ro = read-only,
    /// eo = edit-only: existing documents only)
    #[arg(long, value_name = "scope=...,path=...[,ro|,eo]")]
    pub(super) mount: Vec<String>,
    /// the foreign agent's actor kind: the writer is <agent>:<session_id>
    /// (default: claude-code)
    #[arg(long, default_value = DEFAULT_AGENT)]
    pub(super) agent: String,
    /// where an open span waits between the prompt and the stop; never the
    /// store (default: spool/ under the home)
    #[arg(long)]
    pub(super) spool: Option<PathBuf>,
    /// one diagnostic JSON envelope on stdout (otherwise the client's hook
    /// response, including startup context)
    #[arg(long)]
    pub(super) json: bool,
    /// the directory whose layout is the default mounts (default: the
    /// working directory, which a client's `cd` moves)
    #[arg(long)]
    pub(super) project: Option<PathBuf>,
    /// The harness watcher's own event (`watched.rs`, X6c U1): set only by
    /// `neosian harness-file`, never by a flag or a payload.
    #[arg(skip)]
    pub(super) watched: Option<super::watched::Watched>,
}

pub fn run(args: &Record, out: &mut impl Write, err: &mut impl Write) -> io::Result<u8> {
    use crate::clients::install::RecordCommand;
    match &args.command {
        Some(RecordCommand::Pause(control)) => {
            return super::pause::run(args, control, true, out, err);
        }
        Some(RecordCommand::Resume(control)) => {
            return super::pause::run(args, control, false, out, err);
        }
        Some(RecordCommand::Retry(retry)) => return super::retry::run(retry, out, err),
        Some(RecordCommand::Held(held)) => return super::held::run(held, out, err),
        Some(RecordCommand::Install(install)) => {
            if args.profile.is_some() {
                return usage(args.json, "place --profile after install", out, err);
            }
            return crate::clients::install::record(install, out, err);
        }
        None => {}
    }
    let json = args.json;
    let cwd = env::current_dir()?;
    let layout = layout_of(args.project.as_deref(), &cwd);
    if !PAYLOAD_PROJECT.contains(&args.agent.as_str())
        || args.project.is_some()
        || args.profile.is_some()
        || env::var_os("NEOSIAN_PROFILE").is_some_and(|v| !v.is_empty())
    {
        match crate::profile::resolve::selected(args.profile.as_deref(), &layout) {
            Ok(Some(selected)) => return super::profile::run(args, selected, None, out, err),
            Ok(None) => {}
            Err(message) => return failed(&message, None, json, out, err),
        }
    }
    let mut settled = |layout: &Path| -> io::Result<Result<Result<Vec<Mount>, String>, u8>> {
        Ok(match resolve_mounts(args, layout) {
            Ok(resolved) => Ok(resolved),
            Err(Refusal::Usage(message)) => Err(usage(json, &message, out, err)?),
            Err(Refusal::Memory(error)) => {
                writeln!(err, "error: [{}] {}", error.code, error.message)?;
                Err(2)
            }
        })
    };
    let mut mounts = match settled(&layout_of(args.project.as_deref(), &cwd))? {
        Ok(Ok(mounts)) => mounts,
        Ok(Err(message)) => return environment(&message, err),
        Err(code) => return Ok(code),
    };
    let Some(mut sessions) = sessions_mount(&mounts) else {
        let needs = "the sessions document needs a read-write mount (no ,ro or ,eo)";
        return usage(json, needs, out, err);
    };
    if let Err(reason) = Actor::parse(&format!("{}:session", args.agent)) {
        let message = format!(
            "--agent {}: {reason} (a kind, e.g. claude-code)",
            repr(&args.agent)
        );
        return usage(json, &message, out, err);
    }
    let store = match Selection::resolve_schema(
        args.root.as_deref(),
        args.url.as_deref(),
        args.schema.as_deref(),
    ) {
        Ok(store) => store,
        Err(message) => return usage(json, &message, out, err),
    };

    let spool = match &args.spool {
        Some(spool) => spool.clone(),
        None => home()?.join(SPOOL_DIR_NAME),
    };
    let mut text = String::new();
    if let Err(error) = io::stdin().read_to_string(&mut text) {
        return failed(&error.to_string(), Some(HINT), json, out, err);
    }
    if cfg!(windows) {
        text = text.replace("\r\n", "\n").replace('\r', "\n");
    }
    let payload =
        match super::watched::payload(args).map_or_else(|| parse_payload(&text, &args.agent), Ok) {
            Ok(payload) => payload,
            Err(message) => return failed(&message, Some(HINT), json, out, err),
        };
    let mut project_dir = layout.clone();
    if PAYLOAD_PROJECT.contains(&args.agent.as_str()) && args.project.is_none() {
        let project = if args.agent == "agy" {
            super::readers::agy::project(&payload)
        } else {
            cursor_project(&payload)
        };
        project_dir = project.clone();
        match crate::profile::resolve::selected(args.profile.as_deref(), &project) {
            Ok(Some(selected)) => {
                return super::profile::run(args, selected, Some(payload), out, err);
            }
            Ok(None) => {}
            Err(message) => return failed(&message, None, json, out, err),
        }
        mounts = match settled(&project)? {
            Ok(Ok(mounts)) => mounts,
            Ok(Err(message)) => return failed(&message, Some(HINT), json, out, err),
            Err(code) => return Ok(code),
        };
        let Some(found) = sessions_mount(&mounts) else {
            let needs = "the sessions document needs a read-write mount (no ,ro or ,eo)";
            return failed(needs, Some(HINT), json, out, err);
        };
        sessions = found;
        let named = env::var(SCOPE_ENV).ok().filter(|scope| !scope.is_empty());
        if project == Path::new("/")
            && args.scope.is_none()
            && args.mount.is_empty()
            && named.is_none()
        {
            let hint = if args.agent == "agy" {
                AGY_HINT
            } else {
                CURSOR_HINT
            };
            writeln!(err, "{hint}")?;
        }
    }
    let settings = Settings {
        provenance: None,
        store,
        mounts,
        sessions_mount: sessions,
        agent: args.agent.clone(),
        spool,
        parent: super::watched::parent(args, payload["session_id"].as_str().unwrap_or("")),
        project: project_dir,
        fingerprint: None,
        guard: None,
    };
    let native_context = crate::native_memory::hooks::run(
        &settings.store,
        &settings.mounts,
        &settings.agent,
        &layout,
        &payload,
        err,
    );
    let startup = super::landing::startup::direct(&payload, &settings);
    let reserve = startup.as_ref().map_or(0, |startup| startup.reserve());
    match record_payload(&settings, (&payload, args.watched.is_some()), reserve, err) {
        Ok(mut envelope) => {
            if let Some(native) = native_context {
                envelope.context = Some(match envelope.context {
                    Some(existing) => format!("{native}\n\n{existing}"),
                    None => native,
                });
            }
            super::landing::startup::answer(startup, &mut envelope, &settings.agent, json, out)
                .map(|()| 0)
        }
        Err(error) => {
            let hint = super::landing::held::hint(&error).unwrap_or_else(|| HINT.into());
            let (text, id) = (error.text(), payload["session_id"].as_str().unwrap_or("-"));
            let failure = (text.as_str(), Some(hint.as_str()));
            let alone = super::landing::startup::alone;
            match alone(startup, &settings.agent, (id, id), json, failure, out, err)? {
                Some(code) => Ok(code),
                None => failed(&text, Some(&hint), json, out, err),
            }
        }
    }
}