neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! `neosian mcp` (`neosian/mcp/serve.py`, `mcp/settings.py`, DESIGN §14.5,
//! §22.6): the store flags are the memory grammar's own with `mcp:stdio`
//! as the actor; a client spawns the server wherever its session runs, so
//! a directory with no name serves the user mount, never a refusal. The
//! start door is read from the actor the installer rendered (§33): a
//! hooked client's instructions carry the write discipline alone, any
//! other client gets the whole block. stdout is the wire.

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

use clap::Args;

use super::rpc::serve;
use super::server::Server;
use crate::assets::{CONTEXT, literal};
use crate::cli::usage;
use crate::home::{project_mounts, user_mount};
use crate::memory::dispatch::Memory;
use crate::memory::grammar::{SCOPE_ENV, SUGAR_MOUNT_PATH};
use crate::memory::mounts::{Mount, Refusal};
use crate::record::context::{History, render_instructions_with};
use crate::remote::selection::Selection;
use crate::repr::repr;
use crate::state::records::HistoryReader;
use crate::store::grammar::Actor;
use crate::store::time::Stamp;

pub const DEFAULT_ACTOR: &str = "mcp:stdio";
/// The clients whose SessionStart hook prints the index, the note and
/// "where we left off" (§33): their instructions carry the discipline alone.
/// Mistral Vibe joined once a live 3.1.5 canary showed its `session_start`
/// context reaching the model; Antigravity's delivery waits for its own check.
const HOOKED_CLIENTS: [&str; 6] = ["claude-code", "codex", "cursor", "muse-code", "pi", "vibe"];

/// Serve neosian memory to MCP clients on stdio.
#[derive(Args)]
pub struct Mcp {
    /// Select a portable workspace profile and its local bindings.
    #[arg(long)]
    profile: Option<String>,
    /// FileStore root directory (created on start; default: the home,
    /// ~/.neosian or $NEOSIAN_HOME)
    #[arg(long)]
    root: Option<PathBuf>,
    /// State process URL; bearer token comes from NEOSIAN_CLIENT_TOKEN.
    #[arg(long)]
    url: Option<String>,
    /// Postgres schema (Postgres only).
    #[arg(long)]
    schema: Option<String>,
    /// single read-write mount of SCOPE at /memories
    #[arg(long)]
    scope: Option<String>,
    /// explicit mount; repeatable (ro = read-only, eo = edit-only:
    /// existing documents only)
    #[arg(long, value_name = "scope=...,path=...[,ro|,eo]")]
    mount: Vec<String>,
    /// who writes: <kind>:<id>[/...], recorded on every row
    #[arg(long, default_value = DEFAULT_ACTOR)]
    actor: String,
    /// A harness child's server (X7c Y4): the selection named, never a
    /// profile found from the working directory or `NEOSIAN_PROFILE`.
    #[arg(long, hide = true)]
    pinned: bool,
    /// With `--profile`: the digest of the profile's identity as the
    /// parent's server resolved it; any other selection refuses to start.
    #[arg(long, hide = true, value_name = "SHA256", requires = "pinned")]
    identity: Option<String>,
    /// Every mount read-only, and only the tools that change nothing, with
    /// `memory` over those mounts (X7c Y2).
    #[arg(long, hide = true)]
    read_only: bool,
    #[command(subcommand)]
    command: Option<crate::clients::install::McpCommand>,
}

/// The mount half of the shared grammar (`resolve_mounts`): the flags,
/// else `NEOSIAN_SCOPE`, else the working directory's layout; `nameless`
/// is what a directory with no project name yields (§22.6: the user mount
/// for a door a client spawns, nothing for the state process).
pub fn resolve_mounts(
    scope: Option<&str>,
    mount: &[String],
    nameless: impl FnOnce() -> Result<Vec<Mount>, Refusal>,
) -> Result<Vec<Mount>, Refusal> {
    if scope.is_some() && !mount.is_empty() {
        let sugar = "--scope is the single-mount sugar; use --mount for multi-mount";
        return Err(Refusal::Usage(sugar.to_string()));
    }
    if !mount.is_empty() {
        let mounts: Vec<Mount> = mount
            .iter()
            .map(|token| Mount::parse(token))
            .collect::<Result<_, _>>()?;
        let twice = |mount: &Mount| {
            mounts
                .iter()
                .filter(|other| other.path == mount.path)
                .count()
                > 1
        };
        if mounts.iter().any(twice) {
            return Err(Refusal::Usage("mount paths must be unique".to_string()));
        }
        return Ok(mounts);
    }
    let named = env::var(SCOPE_ENV).ok().filter(|scope| !scope.is_empty());
    if let Some(scope) = scope.or(named.as_deref()) {
        return Ok(vec![Mount::new(
            scope,
            SUGAR_MOUNT_PATH,
            (false, false),
            "",
        )?]);
    }
    let cwd = env::current_dir().map_err(|error| Refusal::Usage(error.to_string()))?;
    match project_mounts(&cwd) {
        Ok(mounts) => Ok(mounts),
        Err(_) => nameless(),
    }
}

/// Which start door the client has (§33), from the actor the installer
/// rendered (`mcp:<client>`).
fn hooked(actor: &str) -> bool {
    let client = actor.strip_prefix("mcp:").unwrap_or("");
    HOOKED_CLIENTS.contains(&client)
}

pub fn run(args: &Mcp, out: &mut impl Write, err: &mut impl Write) -> io::Result<u8> {
    if let Some(crate::clients::install::McpCommand::Install(install)) = &args.command {
        if args.profile.is_some() {
            return usage(false, "place --profile after install", out, err);
        }
        return crate::clients::install::mcp(install, out, err);
    }
    let cwd = env::current_dir()?;
    let resolve = || {
        if args.pinned && args.profile.is_none() {
            let (root, url) = (args.root.as_deref(), args.url.as_deref());
            return Selection::resolve_schema(root, url, args.schema.as_deref());
        }
        Selection::resolve_profile(
            args.root.as_deref(),
            args.url.as_deref(),
            args.schema.as_deref(),
            args.profile.as_deref(),
            &cwd,
            args.scope.is_some() || !args.mount.is_empty(),
        )
    };
    let selected = match resolve().and_then(|selection| {
        if let Selection::Profile(profile) = &selection
            && profile.login.is_some()
            && crate::login::refresh_if_due(&profile.home)
        {
            return resolve();
        }
        Ok(selection)
    }) {
        Ok(selected) => selected,
        Err(message) => return usage(false, &message, out, err),
    };
    #[cfg(unix)]
    let expected = crate::harness::selection::expected(&selected, args.identity.as_deref());
    #[cfg(not(unix))]
    let expected = match args.identity {
        Some(_) => Err("--identity names a harness child's selection, served on Unix only"),
        None => Ok(()),
    };
    if let Err(message) = expected {
        writeln!(err, "error: {message}")?;
        return Ok(2);
    }
    let resolved_mounts = selected
        .mounts()
        .map(|m| m.map_err(Refusal::Usage))
        .unwrap_or_else(|| {
            resolve_mounts(args.scope.as_deref(), &args.mount, || {
                Ok(vec![user_mount()?])
            })
        });
    let mut mounts = match resolved_mounts {
        Ok(mounts) => mounts,
        Err(Refusal::Usage(message)) => return usage(false, &message, out, err),
        Err(Refusal::Memory(error)) => {
            writeln!(err, "error: [{}] {}", error.code, error.message)?;
            return Ok(2);
        }
    };
    if args.read_only {
        for mount in &mut mounts {
            (mount.read_only, mount.edit_only) = (true, false);
        }
    }
    let actor = match Actor::parse(&args.actor) {
        Ok(actor) => actor,
        Err(reason) => {
            let message = format!(
                "--actor {}: {reason} (e.g. cli:claude-code)",
                repr(&args.actor)
            );
            return usage(false, &message, out, err);
        }
    };
    // The selection as this server resolved it, pinned for its harness
    // children's watchers (X4f Q1).
    #[cfg(unix)]
    let selection = crate::harness::selection::pin(&selected);
    let history = match HistoryReader::open(&selected) {
        Ok(history) => history,
        Err(error) => {
            writeln!(
                err,
                "error: {}",
                crate::conversation::Error::from(error).text()
            )?;
            return Ok(1);
        }
    };
    let store = history.state();
    let instructions = if hooked(actor.as_str()) {
        literal(
            CONTEXT,
            if store.profile().is_some() {
                "profile_instructions"
            } else {
                "start_instructions"
            },
        )
        .expect("context.yaml carries the discipline")
    } else {
        let rendered = history.records().and_then(|records| {
            let records = records.as_deref();
            match store.profile() {
                Some(profile) if actor.as_str() == "mcp:opencode" => {
                    let limit = profile.context.max_chars
                        - crate::profile::context::opencode_hook_limit(profile);
                    let render = crate::profile::context::render_context;
                    render(store.as_ref(), records, &mounts, limit, None)
                }
                _ => {
                    let history = History::new(store.as_ref(), records);
                    render_instructions_with(history, &mounts, Stamp::now())
                }
            }
        });
        match rendered {
            Ok(instructions) => instructions,
            Err(error) => {
                writeln!(err, "error: {}", error.text())?;
                return Ok(1);
            }
        }
    };
    let memory = Memory {
        store,
        mounts,
        actor,
    };
    let mut server = Server::new(memory, history, instructions);
    #[cfg(unix)]
    {
        let mut warned = Vec::new();
        let served = crate::harness::served(&mut |line: &str| warned.push(line.to_string()));
        for line in warned {
            writeln!(err, "{line}")?;
        }
        if let Some(settings) = served {
            let registry = crate::harness::registry::Registry::new(settings, selection);
            server = server.with_harness(registry);
        }
    }
    if args.read_only {
        server = server.read_only();
    }
    serve(&mut server, io::stdin().lock(), out)?;
    Ok(0)
}