neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Mistral Vibe's recording hooks (A1c): six `[[hooks]]` elements in
//! `$VIBE_HOME/hooks.toml` or a trusted folder's `.vibe/hooks.toml`, from
//! `assets/clients/vibe-hooks.toml`, each named `neosian-<type>` and found by
//! that name (`rename::named`), never by position: `session_start`,
//! `pre_agent` and `post_agent` (`match = "main"`), `post_tool`,
//! `notification` (`turn_completed` and `turn_failed`) and `session_end`.
//! `strict` is left at its default, off, so a recorder that fails never blocks
//! Vibe. An element is neosian's by the receipt or because its command is a
//! `neosian record` line; another program's element under one of these names,
//! another element already running `neosian record`, and a file that is not
//! TOML are refused before anything is written. Every other line keeps its
//! bytes. One level per client, as for the other clients.

use super::{
    context::{Context, shell_join},
    edit::{Edit, same},
    files::{self, Failure},
    hooks, owned, receipt,
    refresh_parts::{Change, Part},
    rename::named,
    targets::{self, Target},
    vibe::{added, quoted, refused, text},
};
use serde_json::{Value, json};

const ARRAY: &str = "hooks";
const TEMPLATE: &str = include_str!(concat!(env!("NEOSIAN_ASSETS"), "/clients/vibe-hooks.toml"));
const PLACEHOLDER: &str = "__NEOSIAN_RECORD_COMMAND__";
const TRUST: &str = "Mistral Vibe reads a project's .vibe/hooks.toml only in a folder you have trusted in Vibe; setup does not grant that trust";

/// One element this release writes: its name, its TOML text and its value.
struct Element {
    name: String,
    body: String,
    value: Value,
}

fn elements(command: &str) -> Vec<Element> {
    let template: toml::Table = TEMPLATE.parse().expect("vibe-hooks.toml is TOML");
    let items = template[ARRAY].as_array().expect("an array of hooks");
    items
        .iter()
        .filter_map(toml::Value::as_table)
        .map(|table| {
            let mut value = json!({});
            let mut body = format!("[[{ARRAY}]]\n");
            for (key, item) in table {
                let item = match item.as_str() {
                    Some(PLACEHOLDER) => toml::Value::String(command.into()),
                    _ => item.clone(),
                };
                let shown = item.as_str().map_or_else(|| item.to_string(), quoted);
                body.push_str(&format!("{key} = {shown}\n"));
                value[key] = serde_json::to_value(&item).expect("TOML is JSON");
            }
            let name = value["name"].as_str().unwrap_or_default().to_owned();
            Element { name, body, value }
        })
        .collect()
}

fn names() -> Vec<String> {
    elements("").into_iter().map(|e| e.name).collect()
}

/// The file's `[[hooks]]` elements as JSON; `Err` when it is not TOML or
/// `hooks` is not an array of tables.
fn present(target: &Target) -> Result<(Option<String>, Vec<Value>), Failure> {
    let prior = text(&target.path)?;
    let Some(source) = &prior else {
        return Ok((None, vec![]));
    };
    let table: toml::Table = source
        .parse()
        .map_err(|_| refused(&target.path, "the file does not parse as TOML".into()))?;
    let value = serde_json::to_value(table).expect("TOML is JSON");
    match &value[ARRAY] {
        Value::Null => Ok((prior, vec![])),
        Value::Array(items) if items.iter().all(Value::is_object) => Ok((prior, items.clone())),
        _ => Err(refused(
            &target.path,
            "hooks is not written as [[hooks]] tables".into(),
        )),
    }
}

fn carries(element: &Value) -> bool {
    element["command"].as_str().is_some_and(hooks::carries)
}

fn pointer(name: &str) -> String {
    super::rename::jsonedit::join(&[ARRAY, name])
}

/// The record command line our elements run, when the file holds them.
pub fn installed(target: &Target) -> Option<Vec<String>> {
    let (_, items) = present(target).ok()?;
    let ours = names();
    let element = items.iter().find(|e| {
        e["name"]
            .as_str()
            .is_some_and(|n| ours.iter().any(|o| o == n))
            && carries(e)
    })?;
    shlex::split(element["command"].as_str()?)
}

/// The edit setting our elements, refused where a name is another program's
/// or another element runs our command. An element already there keeps the
/// members a person added (`timeout`, `description`, ...); `wanted` gains
/// them for the receipt (review finding 10).
fn with_hooks(target: &Target, wanted: &mut [Element]) -> Result<Edit, Failure> {
    let (prior, items) = present(target)?;
    let shown = target.path.display();
    let book = targets::book(target);
    for item in &items {
        let name = item["name"].as_str().unwrap_or_default();
        let owned = wanted.iter().any(|w| w.name == name);
        let recorded = receipt::owns_in(&book, &target.path, &pointer(name), item);
        if owned && !(recorded || carries(item)) {
            let message =
                format!("the hook name {name} in {shown} is taken by another program's hook");
            return Err(Failure::new(
                message,
                "rename that hook, then run setup again",
            ));
        }
        if !owned && carries(item) {
            let message = format!(
                "{shown} already runs neosian record in the hook {name}; both would record"
            );
            return Err(Failure::new(
                message,
                "remove that hook, then run setup again",
            ));
        }
    }
    let source = prior.clone().unwrap_or_default();
    let mut edited = source.clone();
    for element in wanted.iter_mut() {
        let ours: Vec<&str> = element
            .value
            .as_object()
            .into_iter()
            .flatten()
            .map(|(k, _)| k.as_str())
            .collect();
        let (lines, extra) = added(&source, ARRAY, &element.name, &ours);
        for (key, value) in extra.as_object().into_iter().flatten() {
            element.value[key] = value.clone();
        }
        let body = format!("{}{lines}", element.body);
        edited = named::put(&edited, ARRAY, &element.name, &body)
            .map_err(|reason| refused(&target.path, reason))?;
    }
    let path = target.path.clone();
    Ok(Edit {
        path,
        read: prior,
        text: edited,
    })
}

/// The edit removing our elements; `None` when the file holds none. Every
/// element under one of our names must be ours: one now running another
/// program's command refuses the move, and nothing changes (finding 4).
fn without(target: &Target) -> Result<Option<Edit>, Failure> {
    let (prior, items) = present(target)?;
    let reserved = names();
    let book = targets::book(target);
    for item in &items {
        let name = item["name"].as_str().unwrap_or_default();
        let recorded = receipt::owns_in(&book, &target.path, &pointer(name), item);
        if reserved.iter().any(|r| r == name) && !(recorded || carries(item)) {
            let message = format!(
                "the hook {name} in {} is no longer neosian's, so the neosian hooks there are not moved",
                target.path.display()
            );
            return Err(Failure::new(
                message,
                "remove the neosian hooks there by hand, then run setup again",
            ));
        }
    }
    let mut edited = prior.clone().unwrap_or_default();
    let mut removed = false;
    for name in names() {
        if let Some(shorter) =
            named::remove(&edited, ARRAY, &name).map_err(|reason| refused(&target.path, reason))?
        {
            edited = shorter;
            removed = true;
        }
    }
    let path = target.path.clone();
    Ok(removed.then_some(Edit {
        path,
        read: prior,
        text: edited,
    }))
}

pub fn install(
    target: &Target,
    context: &Context,
    command: &str,
    write: bool,
) -> Result<Value, Failure> {
    files::evidence(target)?;
    let mut wanted = elements(command);
    let change = with_hooks(target, &mut wanted)?;
    let level = if target.level == "user" {
        "project"
    } else {
        "user"
    };
    let other = targets::hooks(&target.client, context, level);
    let mut displaced = None;
    if !same(context, &other.path, &target.path) && installed(&other).is_some() {
        if target.level == "project" {
            let message = format!(
                "Mistral Vibe already carries the neosian hooks at the user level ({}); both would record",
                other.path.display()
            );
            return Err(Failure::new(
                message,
                "keep the user hooks, or remove the neosian hooks there by hand",
            ));
        }
        displaced = without(&other)?;
    }
    let created = write && !target.path.exists();
    if write {
        owned::atomically(|| {
            change.write()?;
            if let Some(displaced) = &displaced {
                displaced.write()?;
            }
            for element in &wanted {
                let at = pointer(&element.name);
                receipt::record(&target.client, context, &target.path, &at, &element.value)?;
            }
            Ok(())
        })?;
    }
    let hooks: Vec<Value> = wanted.into_iter().map(|e| e.value).collect();
    Ok(
        json!({"success": true, "client": target.client, "label": target.label, "level": target.level,
        "config_path": target.path, "hooks": hooks, "plugin": null, "command": command,
        "displaced": displaced.map(|edit| edit.path), "written": write, "created": created,
        "trust_hint": (target.level == "project").then_some(TRUST)}),
    )
}

/// The elements as `record install` prints them.
pub fn shown(command: &str) -> String {
    let bodies: Vec<String> = elements(command).into_iter().map(|e| e.body).collect();
    bodies.join("\n")
}

/// The refresh: an element the release writes and the file lacks is added
/// with the registered command, word for word; present elements stay.
pub fn refresh(part: Part, target: &Target, argv: &[String]) -> Part {
    let (read, items) = match present(target) {
        Ok(found) => found,
        Err(failure) => return part.refused(&failure),
    };
    let command = items
        .iter()
        .filter(|e| carries(e))
        .find_map(|e| e["command"].as_str().map(str::to_owned))
        .unwrap_or_else(|| shell_join(argv));
    let mut edited = read.clone().unwrap_or_default();
    let mut changed = false;
    for element in elements(&command) {
        if items.iter().any(|i| i["name"] == element.name.as_str()) {
            continue;
        }
        match named::put(&edited, ARRAY, &element.name, &element.body) {
            Ok(text) => edited = text,
            Err(reason) => return part.refused(&refused(&target.path, reason)),
        }
        changed = true;
    }
    if !changed {
        return part;
    }
    part.update(Change::Text(edited), read)
        .guarded(std::slice::from_ref(&target.path))
}