neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Antigravity CLI (`agy`, measured 1.5.15): its registrations are the
//! `mcpServers` map of `~/.gemini/config/mcp_config.json` or a workspace's
//! `.agents/mcp_config.json` (A1a). No variable relocates that directory;
//! `--at agy=DIR` names it for setup. Antigravity leaves an empty
//! `mcp_config.json` behind, which reads as no servers.

use super::{
    edit::Edit,
    files::{self, FIX, Failure},
    naming::NEW,
    targets::Target,
};
use serde_json::{Value, json};
use std::path::Path;

/// Whether the file exists and holds nothing but whitespace.
pub fn blank(path: &Path) -> bool {
    std::fs::read_to_string(path).is_ok_and(|text| text.trim().is_empty())
}

/// The document and its exact text; an empty file is an empty document.
pub fn load(path: &Path) -> Result<(Option<String>, Value), Failure> {
    if blank(path) {
        return Ok((std::fs::read_to_string(path).ok(), json!({})));
    }
    files::load_text(path)
}

/// The edit setting our entry to `entry`, and the entry as written. An entry
/// already there keeps every member but its `command` and `args`: a person's
/// `disabled`, `enabledTools`, `disabledTools`, `tools` or timeout stays, and
/// `disabled: false` is written only with a new entry (review finding 10).
pub fn with_entry(target: &Target, entry: &Value) -> Result<(Edit, Value), Failure> {
    let (prior, mut document) = load(&target.path)?;
    if document.get(target.key).is_none() {
        document[target.key] = json!({});
    }
    let Some(servers) = document[target.key].as_object_mut() else {
        return Err(Failure::new(
            format!(
                "{} in {} is not a JSON object; refusing to rewrite it",
                target.key,
                target.path.display()
            ),
            FIX,
        ));
    };
    let written = match servers.get(NEW).and_then(Value::as_object) {
        Some(present) => {
            let mut kept = present.clone();
            for key in ["command", "args"] {
                kept.insert(key.into(), entry[key].clone());
            }
            Value::Object(kept)
        }
        None => entry.clone(),
    };
    servers.insert(NEW.into(), written.clone());
    let text = files::pretty(&document);
    let path = target.path.clone();
    Ok((
        Edit {
            path,
            read: prior,
            text,
        },
        written,
    ))
}

/// The edit removing our entry; `None` when the file holds none.
pub fn without(target: &Target) -> Result<Option<Edit>, Failure> {
    let (prior, mut document) = load(&target.path)?;
    let removed = document
        .get_mut(target.key)
        .and_then(Value::as_object_mut)
        .and_then(|servers| servers.shift_remove(NEW));
    let path = target.path.clone();
    Ok(removed.map(|_| Edit {
        path,
        read: prior,
        text: files::pretty(&document),
    }))
}