neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The clients whose native registration file neosian edits directly and for
//! which this release installs memory alone (A1a): Antigravity CLI and
//! Mistral Vibe. The entry under `neosian` is ours by the receipt or by
//! adoption, never by its name; everything is checked before anything is
//! written, and a write that fails puts back what this run wrote.

use super::{
    agy,
    context::Context,
    edit::{Edit, same},
    files::{self, Failure},
    hooks, mcp,
    naming::NEW,
    receipt,
    settings::Settings,
    targets::{self, Target},
    vibe, write_key,
};
use serde_json::{Value, json};

pub const CLIENTS: [&str; 2] = ["agy", "vibe"];

/// Whether neosian edits this client's registration file directly.
pub fn direct(client: &str) -> bool {
    CLIENTS.contains(&client)
}

/// Run one install's writes; when one fails, put back what they wrote,
/// unless a caller records them and puts them back itself (setup's halves).
pub fn atomically(work: impl FnOnce() -> Result<(), Failure>) -> Result<(), Failure> {
    if files::recording() {
        return work();
    }
    let (result, record) = files::recorded(work);
    if let Err(mut failure) = result {
        let notes = super::refresh_write::restore(&record, &[]);
        failure.message = if notes.is_empty() {
            format!("{}; nothing this run wrote was kept", failure.message)
        } else {
            format!("{}; {}", failure.message, notes.join("; "))
        };
        return Err(failure);
    }
    Ok(())
}

pub fn label(client: &str) -> &'static str {
    if client == "vibe" {
        "Mistral Vibe"
    } else {
        "Antigravity CLI"
    }
}

/// The file as the client reads it, for the reader every registration path
/// uses: Vibe's servers keyed by name, and Antigravity's empty file as an
/// empty document. `None` for any other client.
pub fn document(client: &str, path: &std::path::Path) -> Option<targets::Document> {
    match client {
        "vibe" => Some(vibe::document(path)),
        "agy" if agy::blank(path) => Some(targets::Document::Read(json!({}))),
        _ => None,
    }
}

/// The servers member of the registration file (`mcpServers` for every
/// client whose own branch does not name another).
pub fn key(client: &str) -> &'static str {
    if client == "vibe" {
        vibe::ARRAY
    } else {
        "mcpServers"
    }
}

/// The registration file (`hooks` false), or the hooks file the next slices
/// install, relative to the client directory or (`project`) a project.
pub fn relative(client: &str, project: bool, hooks: bool) -> &'static str {
    match (client, project, hooks) {
        ("vibe", false, false) => "config.toml",
        ("vibe", false, true) => "hooks.toml",
        ("vibe", true, false) => ".vibe/config.toml",
        ("vibe", true, true) => ".vibe/hooks.toml",
        (_, false, false) => "mcp_config.json",
        (_, false, true) => "hooks.json",
        (_, true, false) => ".agents/mcp_config.json",
        (_, true, true) => ".agents/hooks.json",
    }
}

/// The entry this release writes, from a full command line.
pub fn entry(client: &str, argv: &[String]) -> Value {
    if client == "vibe" {
        json!({"name": NEW, "transport": "stdio", "command": argv[0], "args": argv[1..]})
    } else {
        json!({"command": argv[0], "args": argv[1..], "disabled": false})
    }
}

/// A credential reaches neosian only through the environment, and neither
/// client is shown to pass one to an MCP server: Vibe 3.1.5 passes only
/// HOME, LOGNAME, PATH, SHELL, TERM and USER (and its own `env` table, which
/// would hold the value); Antigravity's documentation does not say.
fn credentials(target: &Target, settings: &Settings) -> Result<(), Failure> {
    if settings.credentials.is_empty() {
        return Ok(());
    }
    let names = settings.credentials.join(", ");
    let why = if target.client == "vibe" {
        "Mistral Vibe 3.1.5 passes only HOME, LOGNAME, PATH, SHELL, TERM and USER to an MCP server"
    } else {
        "Antigravity CLI is not shown to pass its environment to an MCP server"
    };
    Err(Failure::new(
        format!(
            "{why}, so {names} would not reach neosian; a credential is never written into its configuration"
        ),
        format!(
            "register {} with the local file store (no --url, Postgres or credential-backed profile)",
            target.label
        ),
    ))
}

fn with_entry(target: &Target, entry: &Value) -> Result<(Edit, Value), Failure> {
    if target.client == "vibe" {
        vibe::with_entry(target, entry)
    } else {
        agy::with_entry(target, entry)
    }
}

fn without(target: &Target) -> Result<Option<Edit>, Failure> {
    if target.client == "vibe" {
        vibe::without(target)
    } else {
        agy::without(target)
    }
}

/// The edit of the project file without our entry, when a user install moves
/// it; and the other level's file, when it is only reported.
type Levels = (Option<Edit>, Option<String>);

/// What the other level's registration means for this one: at the user level
/// our entry in this directory's project file is moved here; ours at the user
/// level beside a project install is reported, since the two may shadow one
/// another. Another server's `neosian` was refused before (`write_key`).
fn levels(target: &Target, context: &Context) -> Result<Levels, Failure> {
    let other = targets::mcp(
        &target.client,
        context,
        if target.level == "user" {
            "project"
        } else {
            "user"
        },
    );
    // A project file that links to the user file is the same target.
    if same(context, &other.path, &target.path) || targets::registered(&other).is_none() {
        return Ok((None, None));
    }
    if target.level == "user" && write_key::ours_at(&other, NEW) {
        return Ok((without(&other)?, None));
    }
    Ok((None, Some(other.path.display().to_string())))
}

fn note(target: &Target, shadowed: Option<&String>) -> Option<String> {
    let mut notes = vec![];
    if let Some(path) = shadowed {
        notes.push(if target.client == "vibe" {
            format!("{path} also registers neosian; in a project with both, Vibe uses the project's entry")
        } else {
            format!("{path} also registers neosian; Antigravity keeps whichever of the two starts first")
        });
    }
    if target.client == "vibe" && target.level == "project" {
        notes.push(vibe::TRUST.into());
    }
    (!notes.is_empty()).then(|| notes.join("; "))
}

pub fn install(
    target: &Target,
    context: &Context,
    settings: &Settings,
    entry: &Value,
    write: bool,
) -> Result<Value, Failure> {
    credentials(target, settings)?;
    let (change, written) = with_entry(target, entry)?;
    write_key::write_key(target, context)?;
    let (displaced, shadowed) = levels(target, context)?;
    let created = write && !target.path.exists();
    if write {
        let pointer = targets::pointer(target, NEW);
        atomically(|| {
            change.write()?;
            if let Some(displaced) = &displaced {
                displaced.write()?;
            }
            receipt::record(&target.client, context, &target.path, &pointer, &written)
        })?;
    }
    Ok(
        json!({"success": true, "client": target.client, "label": target.label, "level": target.level,
        "config_path": target.path, "servers_key": target.key, "server_name": NEW, "entry": written,
        "displaced": displaced.map(|edit| edit.path), "mcp_shadowed_by": shadowed,
        "written": write, "created": created, "apply": null, "note": note(target, shadowed.as_ref())}),
    )
}

/// Setup's halves for a client whose files neosian edits itself: both are
/// checked before either is written, and when the second fails the first is
/// put back too. `None` for hooks not tried because the registration failed.
pub fn pair(
    target: &Target,
    hook: &Target,
    context: &Context,
    settings: &Settings,
    write: bool,
) -> (Value, Option<Value>) {
    let check = |write: bool| {
        let mcp = mcp::install(target, context, settings, write);
        let go = !write || mcp["success"] == true;
        (
            mcp,
            go.then(|| hooks::install(hook, context, settings, write)),
        )
    };
    let (mcp, hooks) = check(false);
    let ready = mcp["success"] == true && hooks.as_ref().is_none_or(|h| h["success"] == true);
    if !write || !ready {
        return (mcp, hooks);
    }
    let ((mcp, hooks), record) = files::recorded(|| check(true));
    let failed = [Some(&mcp), hooks.as_ref()]
        .into_iter()
        .flatten()
        .find(|half| half["success"] != true)
        .map(|half| {
            half["error"]
                .as_str()
                .unwrap_or("a write failed")
                .to_owned()
        });
    let Some(error) = failed else {
        return (mcp, hooks);
    };
    let notes = super::refresh_write::restore(&record, &[]);
    let kept = if notes.is_empty() {
        "nothing this run wrote was kept".into()
    } else {
        notes.join("; ")
    };
    let undone = |mut half: Value| {
        let own = half["error"].as_str().map(str::to_owned);
        half["error"] = json!(match own {
            Some(own) => format!("{own}; {kept}"),
            None => format!("put back because the other half failed ({error}); {kept}"),
        });
        half["success"] = json!(false);
        half["written"] = json!(false);
        half
    };
    (undone(mcp), hooks.map(undone))
}