neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A child's own neosian memory, where neosian writes the child's whole
//! configuration (X7b, ruling W3): a Vibe child's private home, made fresh
//! before every launch, registers exactly one MCP server,
//! neosian's own stdio server. It is this running executable, with the
//! store selection the watcher's checked plan holds, each mount read-only in
//! `read-only` mode, the actor `mcp:<kind>`, and the child marker in its
//! environment, so it never offers the `harness` tool. A store reached with
//! a credential (a hosted store, PostgreSQL, a managed login) gets nothing:
//! no child holds the credential (X4). On macOS the child's server runs
//! inside the child's policy, where every store is write-protected, so the
//! child reads memory and cannot change it in either mode.
//!
//! In `read-only` mode only the tools that cannot change state are allowed
//! (and `memory`, when every mount is read-only); in `write` mode the
//! client's own approval covers every tool. Muse Code 1.4.25 withholds every
//! MCP server, the user's included, in a workspace it does not trust (seen
//! with its echo provider and in a live turn, record/x7b-2026-11-29), and a
//! child's workspace is never trusted, since trust would load the project's
//! own hooks, servers and rules; Pi reads MCP servers only from its agent
//! directory's `mcp.json` (the person's, with their other servers) and a
//! trusted project's; Cursor only from files every child is denied. None of
//! the three gets one (`assets/docs/harness.md`).

use std::path::Path;

use super::adapter::{Agent, Mode, READ_ONLY_TOOLS, SERVER_KEY};
use super::plan::{Checked, read_only};
pub use super::server::{ChildServer, vibe_tool};
use super::text::say;

/// The one server a Vibe child registers, or None: another agent, or a
/// store reached with a credential.
pub fn server(plan: &Checked, private: &Path) -> std::io::Result<Option<ChildServer>> {
    if plan.agent != Agent::Vibe || !super::sandbox::local_store(&plan.selection, &plan.directory) {
        return Ok(None);
    }
    let exe = std::env::current_exe()?;
    let exe = exe.canonicalize().unwrap_or(exe);
    let args = args(plan, plan.mode);
    let mut env = vec![(super::CHILD_ENV.to_string(), "1".to_string())];
    if let Some(home) = super::selection::home() {
        env.push((
            crate::home::HOME_ENV.to_string(),
            home.display().to_string(),
        ));
    }
    env.push(("TMPDIR".to_string(), private.display().to_string()));
    let tools = (plan.mode == Mode::ReadOnly).then(|| {
        let mut tools = READ_ONLY_TOOLS.to_vec();
        if !plan.mounts.is_empty() {
            tools.push("memory");
        }
        tools
    });
    Ok(Some(ChildServer {
        command: exe.display().to_string(),
        args,
        env,
        tools,
    }))
}

/// A child's own neosian server's arguments (#431, X7c): the parent's
/// pinned selection, never a profile found again from the child's
/// directory; with a profile, the digest of its identity, which the server
/// checks against what it resolves; each mount read-only in `read-only`
/// mode, where the server itself also opens every mount read-only and
/// refuses every tool that changes state, whatever the client allows.
pub fn args(plan: &Checked, mode: Mode) -> Vec<String> {
    let mut args = vec!["mcp".to_string()];
    args.extend(plan.selection.iter().cloned());
    for mount in &plan.mounts {
        let token = match mode {
            Mode::ReadOnly => read_only(mount),
            Mode::Write => mount.clone(),
        };
        args.extend(["--mount".to_string(), token]);
    }
    args.push("--pinned".to_string());
    if let Some(identity) = &plan.identity {
        args.extend(["--identity".to_string(), super::selection::digest(identity)]);
    }
    if mode == Mode::ReadOnly {
        args.push("--read-only".to_string());
    }
    args.extend(["--actor".to_string(), format!("mcp:{}", plan.agent.kind())]);
    args
}

/// The server written into the child's private home, made fresh just
/// before (`home.rs`): Vibe's `config.toml`, with each allowed tool's
/// permission `always` in `read-only` mode. Nothing is written without a
/// server.
pub fn register(agent: Agent, home: &Path, server: Option<&ChildServer>) -> Result<(), String> {
    let Some(server) = server else {
        return Ok(());
    };
    let failed = |e: String| say("spawn_failed", &[("agent", agent.name()), ("error", &e)]);
    match agent {
        Agent::Vibe => {
            let text = vibe_config(server).map_err(failed)?;
            std::fs::write(home.join("config.toml"), text).map_err(|e| failed(e.to_string()))
        }
        _ => Ok(()),
    }
}

fn vibe_config(server: &ChildServer) -> Result<String, String> {
    let mut entry = toml::Table::new();
    entry.insert("name".into(), SERVER_KEY.into());
    entry.insert("transport".into(), "stdio".into());
    // Vibe splits a string command as a POSIX shell would (X7c Y3).
    let command = crate::clients::context::shell_join(std::slice::from_ref(&server.command));
    entry.insert("command".into(), command.into());
    let args: Vec<toml::Value> = server.args.iter().map(|a| a.clone().into()).collect();
    entry.insert("args".into(), args.into());
    let env: toml::Table = server
        .env
        .iter()
        .map(|(k, v)| (k.clone(), toml::Value::from(v.clone())))
        .collect();
    entry.insert("env".into(), env.into());
    let mut config = toml::Table::new();
    config.insert("mcp_servers".into(), vec![toml::Value::from(entry)].into());
    if let Some(tools) = &server.tools {
        let mut permissions = toml::Table::new();
        for tool in tools {
            let mut allowed = toml::Table::new();
            allowed.insert("permission".into(), "always".into());
            permissions.insert(vibe_tool(tool), allowed.into());
        }
        config.insert("tools".into(), permissions.into());
    }
    toml::to_string(&config).map_err(|e| e.to_string())
}

#[cfg(test)]
mod tests;