neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Antigravity CLI's recording hooks (A1b): one named hook, `neosian`, in
//! `~/.gemini/config/hooks.json` or a workspace's `.agents/hooks.json`, from
//! `assets/clients/agy-hooks.json` (`SessionStart`, `PreInvocation`,
//! `PostToolUse` for every tool, `Stop`). The group is neosian's by the
//! receipt or because every command in it is a `neosian record` line;
//! another program's hook named `neosian` and a file that is not a JSON
//! object are refused before anything is written, and every other named hook
//! keeps its place and its members. One level per client: a user install
//! moves the group out of this directory's project file, and a project
//! install beside the user group is refused, since both would record.

use super::{
    agy,
    context::Context,
    edit::{Edit, same},
    files::{self, Failure},
    hooks, owned, receipt,
    refresh_parts::{Change, Part},
    targets::{self, Target},
};
use serde_json::{Value, json};

pub const NAME: &str = "neosian";
const TEMPLATE: &str = include_str!(concat!(env!("NEOSIAN_ASSETS"), "/clients/agy-hooks.json"));
const PLACEHOLDER: &str = "__NEOSIAN_RECORD_COMMAND__";

fn filled(value: &Value, command: &str) -> Value {
    match value {
        Value::String(text) if text == PLACEHOLDER => json!(command),
        Value::Array(items) => Value::Array(items.iter().map(|v| filled(v, command)).collect()),
        Value::Object(members) => Value::Object(
            members
                .iter()
                .map(|(k, v)| (k.clone(), filled(v, command)))
                .collect(),
        ),
        other => other.clone(),
    }
}

/// The group this release writes for a record command line.
pub fn group(command: &str) -> Value {
    filled(
        &serde_json::from_str(TEMPLATE).expect("agy-hooks.json is JSON"),
        command,
    )
}

/// Every command of a named hook, flat handlers and matcher groups alike.
fn commands(hook: &Value) -> Vec<&str> {
    hook.as_object()
        .into_iter()
        .flatten()
        .filter_map(|(_, handlers)| handlers.as_array())
        .flatten()
        .flat_map(hooks::commands)
        .collect()
}

/// The record command line our group runs, when the file holds our group.
pub fn installed(target: &Target) -> Option<Vec<String>> {
    let (_, document) = agy::load(&target.path).ok()?;
    let command = commands(document.get(NAME)?)
        .into_iter()
        .find(|c| hooks::carries(c))?;
    shlex::split(command)
}

/// Whether the `neosian` hook in the file is ours: recorded in the
/// receipt as written, or made only of `neosian record` lines.
fn ours(target: &Target, hook: &Value) -> bool {
    let pointer = super::rename::jsonedit::join(&[NAME]);
    let lines = commands(hook);
    receipt::owns_in(&targets::book(target), &target.path, &pointer, hook)
        || (!lines.is_empty() && lines.iter().all(|c| hooks::carries(c)))
}

/// The edit setting our group to `hook`, and the group as written, refused
/// where the name is another program's or another hook runs our command. A
/// group already there keeps every member but the four events this release
/// writes, `"enabled": false` included (review finding 10).
fn with_group(target: &Target, hook: &Value) -> Result<(Edit, Value), Failure> {
    let (prior, mut document) = agy::load(&target.path)?;
    let shown = target.path.display();
    if let Some(found) = document.get(NAME)
        && !ours(target, found)
    {
        let message =
            format!("the hook name neosian in {shown} is taken by another program's hook");
        return Err(Failure::new(
            message,
            "rename that hook, then run setup again",
        ));
    }
    let members = document.as_object().expect("a JSON object");
    if let Some((name, _)) = members
        .iter()
        .find(|(name, hook)| *name != NAME && commands(hook).iter().any(|c| hooks::carries(c)))
    {
        let message = format!(
            "{shown} already runs neosian record under the hook name {name}; both would record"
        );
        return Err(Failure::new(
            message,
            "remove that hook's neosian record line, then run setup again",
        ));
    }
    let mut written = document
        .get(NAME)
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    for (event, handlers) in hook.as_object().expect("the template is an object") {
        written.insert(event.clone(), handlers.clone());
    }
    document[NAME] = Value::Object(written.clone());
    let text = files::pretty(&document);
    let path = target.path.clone();
    Ok((
        Edit {
            path,
            read: prior,
            text,
        },
        Value::Object(written),
    ))
}

/// The edit removing our group; `None` when the file holds none. A group
/// that is not wholly ours (a foreign handler beside the recorder, not the
/// group the receipt records) is refused, and nothing changes (finding 4).
fn without(target: &Target) -> Result<Option<Edit>, Failure> {
    let (prior, mut document) = agy::load(&target.path)?;
    if let Some(found) = document.get(NAME)
        && !ours(target, found)
    {
        let message = format!(
            "the neosian hook in {} also holds hooks that are not neosian's, so it is not moved",
            target.path.display()
        );
        return Err(Failure::new(
            message,
            "remove the neosian hook there by hand, then run setup again",
        ));
    }
    let removed = document
        .as_object_mut()
        .and_then(|members| members.shift_remove(NAME));
    let path = target.path.clone();
    Ok(removed.map(|_| Edit {
        path,
        read: prior,
        text: files::pretty(&document),
    }))
}

pub fn install(
    target: &Target,
    context: &Context,
    command: &str,
    write: bool,
) -> Result<Value, Failure> {
    files::evidence(target)?;
    let (change, hook) = with_group(target, &group(command))?;
    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!(
                "Antigravity CLI 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 hook 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()?;
            }
            let pointer = super::rename::jsonedit::join(&[NAME]);
            receipt::record(&target.client, context, &target.path, &pointer, &hook)
        })?;
    }
    Ok(
        json!({"success": true, "client": target.client, "label": target.label, "level": target.level,
        "config_path": target.path, "hooks": hook, "plugin": null, "command": command,
        "displaced": displaced.map(|edit| edit.path), "written": write, "created": created,
        "trust_hint": null}),
    )
}

/// The refresh of our group: an event the release registers and the group
/// lacks gains its handler with the registered command, word for word;
/// every other member, `enabled: false` included, stays.
pub fn refresh(part: Part, target: &Target, argv: &[String]) -> Part {
    let (read, mut document) = match agy::load(&target.path) {
        Ok(loaded) => loaded,
        Err(failure) => return part.refused(&failure),
    };
    let Some(present) = document.get_mut(NAME).and_then(Value::as_object_mut) else {
        return part.left_alone("the neosian hook is not a JSON object; fix it by hand");
    };
    let command = commands(&Value::Object(present.clone()))
        .into_iter()
        .find(|c| hooks::carries(c))
        .map(str::to_owned)
        .unwrap_or_else(|| super::context::shell_join(argv));
    let wanted = group(&command);
    let mut changed = false;
    for (event, handlers) in wanted.as_object().expect("the template is an object") {
        if !present.contains_key(event) {
            present.insert(event.clone(), handlers.clone());
            changed = true;
        }
    }
    if !changed {
        return part;
    }
    part.update(Change::Json(document, false), read)
        .guarded(std::slice::from_ref(&target.path))
}