neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Mistral Vibe (`vibe`, measured 3.1.5): its registrations are
//! `[[mcp_servers]]` elements named by `name` in `$VIBE_HOME/config.toml`
//! (`~/.vibe` by default) or a trusted folder's `.vibe/config.toml` (A1a).
//! Vibe splits a string `command` into words as a shell does, so the
//! executable is quoted for that split before it is quoted for TOML.

use super::{
    context::{Context, absolute, expand, shell_join},
    edit::Edit,
    files::{FIX, Failure},
    naming::{NEW, OLD},
    refresh_parts::Part,
    rename::named,
    targets::{Document, Target},
};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

pub const ARRAY: &str = "mcp_servers";
pub const TRUST: &str = "Mistral Vibe reads a project's .vibe/config.toml only in a folder you have trusted in Vibe; setup does not grant that trust";

/// `$VIBE_HOME`, resolved as Vibe resolves it, else `~/.vibe`.
pub fn directory(context: &Context) -> PathBuf {
    match context.env.get("VIBE_HOME").filter(|v| !v.is_empty()) {
        Some(value) => absolute(&context.cwd, &expand(value, &context.home)),
        None => context.home.join(".vibe"),
    }
}

/// An entry as Vibe runs it: a string command split into words, an array
/// command taken word for word, and the words after the first put before
/// `args`. Ownership and the refresh read this form.
fn view(mut entry: Value) -> Value {
    let words = match entry.get("command") {
        Some(Value::String(command)) => shlex::split(command),
        Some(Value::Array(parts)) => parts
            .iter()
            .map(|p| p.as_str().map(str::to_owned))
            .collect(),
        _ => None,
    };
    let Some((first, rest)) = words.as_deref().and_then(<[String]>::split_first) else {
        return entry;
    };
    let mut args: Vec<Value> = rest.iter().map(|w| json!(w)).collect();
    if let Some(Value::Array(more)) = entry.get("args") {
        args.extend(more.iter().cloned());
    }
    let had = entry.get("args").is_some();
    entry["command"] = json!(first);
    if had || !args.is_empty() {
        entry["args"] = json!(args);
    }
    entry
}

/// The file as Vibe reads it, with `mcp_servers` keyed by each element's
/// name. A file Vibe refuses (not TOML, `mcp_servers` not an array of named
/// tables) or that names `neosian` or `neosian-memory` twice is `Unreadable`.
pub fn document(path: &Path) -> Document {
    if !path.exists() {
        return Document::Absent;
    }
    let Some(mut value) = std::fs::read_to_string(path)
        .ok()
        .and_then(|text| text.parse::<toml::Table>().ok())
        .and_then(|table| serde_json::to_value(table).ok())
    else {
        return Document::Unreadable;
    };
    let Some(servers) = value.get(ARRAY).cloned() else {
        return Document::Read(value);
    };
    let mut named = serde_json::Map::new();
    for element in servers.as_array().into_iter().flatten() {
        let Some(name) = element.get("name").and_then(Value::as_str) else {
            return Document::Unreadable;
        };
        if named.contains_key(name) && [NEW, OLD].contains(&name) {
            return Document::Unreadable;
        }
        named.insert(name.to_owned(), view(element.clone()));
    }
    if !servers.is_array() {
        return Document::Unreadable;
    }
    value[ARRAY] = Value::Object(named);
    Document::Read(value)
}

pub(super) fn quoted(text: &str) -> String {
    toml::Value::String(text.to_owned()).to_string()
}

/// The `[[mcp_servers]]` element for an entry in the read form.
pub fn element(entry: &Value) -> String {
    let word = |v: &Value| v.as_str().unwrap_or_default().to_owned();
    let args: Vec<String> = entry["args"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|a| quoted(&word(a)))
        .collect();
    format!(
        "[[{ARRAY}]]\nname = {}\ntransport = {}\ncommand = {}\nargs = [{}]\n",
        quoted(&word(&entry["name"])),
        quoted(&word(&entry["transport"])),
        quoted(&shell_join(&[word(&entry["command"])])),
        args.join(", ")
    )
}

pub(super) fn refused(path: &Path, reason: String) -> Failure {
    Failure::new(
        format!("{}: {reason}; refusing to rewrite it", path.display()),
        FIX,
    )
}

pub(super) fn text(path: &Path) -> Result<Option<String>, Failure> {
    match std::fs::read_to_string(path) {
        Ok(text) => Ok(Some(text)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(refused(path, e.to_string())),
    }
}

/// The members of the element named `name` beyond `ours`, as TOML lines and
/// as JSON: what a person added to an element of ours stays on a reinstall
/// (review finding 10); comments inside the element do not.
pub(super) fn added(source: &str, array: &str, name: &str, ours: &[&str]) -> (String, Value) {
    let table = source.parse::<toml::Table>().unwrap_or_default();
    let items = table.get(array).and_then(toml::Value::as_array);
    let found = items
        .into_iter()
        .flatten()
        .filter_map(toml::Value::as_table)
        .find(|t| t.get("name").and_then(toml::Value::as_str) == Some(name));
    let (mut lines, mut value) = (String::new(), json!({}));
    for (key, item) in found.into_iter().flatten() {
        if !ours.contains(&key.as_str()) {
            lines.push_str(&format!("{key} = {item}\n"));
            value[key] = serde_json::to_value(item).unwrap_or_default();
        }
    }
    (lines, value)
}

/// The edit setting our element to `entry`, and the element as written (in
/// the read form) with the members a person added to it.
pub fn with_entry(target: &Target, entry: &Value) -> Result<(Edit, Value), Failure> {
    let prior = text(&target.path)?;
    let source = prior.as_deref().unwrap_or("");
    let ours = ["name", "transport", "command", "args"];
    let (lines, extra) = added(source, ARRAY, NEW, &ours);
    let body = element(entry) + &lines;
    let edited =
        named::put(source, ARRAY, NEW, &body).map_err(|reason| refused(&target.path, reason))?;
    let mut written = entry.clone();
    for (key, value) in extra.as_object().into_iter().flatten() {
        written[key] = value.clone();
    }
    let path = target.path.clone();
    Ok((
        Edit {
            path,
            read: prior,
            text: edited,
        },
        written,
    ))
}

/// The edit removing our element; `None` when the file holds none.
pub fn without(target: &Target) -> Result<Option<Edit>, Failure> {
    let prior = text(&target.path)?;
    let source = prior.clone().unwrap_or_default();
    let removed =
        named::remove(&source, ARRAY, NEW).map_err(|reason| refused(&target.path, reason))?;
    let path = target.path.clone();
    Ok(removed.map(|text| Edit {
        path,
        read: prior,
        text,
    }))
}

/// The refresh of an entry that lacks members this release writes: only those
/// members are added, as lines under the element's header.
pub fn refresh(part: Part, target: &Target, missing: &[(&String, &Value)]) -> Part {
    let read = match text(&target.path) {
        Ok(Some(read)) => read,
        Ok(None) => return part,
        Err(failure) => return part.refused(&failure),
    };
    let lines: String = missing
        .iter()
        .map(|(key, value)| format!("{key} = {}\n", quoted(value.as_str().unwrap_or_default())))
        .collect();
    match named::add(&read, ARRAY, NEW, &lines) {
        Ok(text) => part
            .update(super::refresh_parts::Change::Text(text), Some(read))
            .guarded(std::slice::from_ref(&target.path)),
        Err(reason) => part.refused(&refused(&target.path, reason)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_executable_is_quoted_for_vibes_split_then_for_toml_and_read_back() {
        let entry = json!({"name": "neosian", "transport": "stdio",
            "command": "/opt/my tools/it's/neosian", "args": ["mcp", "--root", "/a b"]});
        let text = element(&entry);
        let table: toml::Table = text.parse().unwrap();
        let written = serde_json::to_value(&table[ARRAY][0]).unwrap();
        assert_eq!(
            shlex::split(written["command"].as_str().unwrap()).unwrap(),
            ["/opt/my tools/it's/neosian"]
        );
        assert_eq!(view(written), entry);
        let words = json!({"name": "x", "command": "neosian mcp", "args": ["--root", "/r"]});
        assert_eq!(view(words)["args"], json!(["mcp", "--root", "/r"]));
        let list = json!({"name": "x", "command": ["neosian", "mcp"]});
        assert_eq!(
            view(list),
            json!({"name": "x", "command": "neosian", "args": ["mcp"]})
        );
    }
}