neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! An Antigravity child's state and integrations (X6a), from 1.5.20's live
//! runs (record/investigation-2026-11-29, section 2) and its documentation.
//! agy keeps everything below `~/.gemini` with no relocation; its CLI state
//! is `~/.gemini/antigravity-cli`, one of every child's denied roots.
//!
//! - A turn completes with nothing of that writable; continuing a
//!   conversation needs `conversations/`, where each conversation is one
//!   SQLite file, `<id>.db`, with its journal files beside it. A continued
//!   conversation's child may write that file and its journal names alone,
//!   the file checked to be a regular file with one link (X6c U4). agy
//!   chooses a new conversation's ID itself and cannot be given one
//!   (record/x6c-2026-11-29/probe), so a first turn's child may create a
//!   file named `<uuid>.db` (or a journal name) there, but none that existed
//!   at launch, each denied by name; a listing that fails refuses the turn.
//!   What stays open: a conversation another agy process creates while the
//!   child runs is writable to it.
//! - agy loads hooks from `~/.gemini/config/hooks.json` and the workspace's
//!   `.agents/hooks.json`, MCP servers from `~/.gemini/config/mcp_config.json`
//!   and `.agents/mcp_config.json`, and plugins (with their own hooks and
//!   servers) from `~/.gemini/config/plugins` and `.agents/plugins`, with no
//!   switch to skip them. A child may read none of them, in the workspace and
//!   every ancestor, each also where a link leads. Live: with the hook and
//!   MCP files unreadable no hook fired, no server started, and the turn
//!   completed.

use std::path::{Path, PathBuf};

use super::super::text::say;
use super::policy::{Rule, escape, resolve, text};

/// The most conversation files a child's policy names (X6a): agy keeps
/// every workspace's conversations in one directory.
pub const CONVERSATIONS_NAMED: usize = 2048;
const USER: [&str; 11] = [
    ".gemini/config/hooks.json",
    ".gemini/config/mcp_config.json",
    ".gemini/config/plugins",
    ".gemini/AGENTS.md",
    ".gemini/GEMINI.md",
    ".gemini/config/AGENTS.md",
    ".gemini/config/GEMINI.md",
    ".gemini/config/rules",
    ".gemini/config/skills",
    ".gemini/antigravity-cli/skills",
    ".gemini/skills",
];
const PROJECT: [&str; 3] = [
    ".agents/hooks.json",
    ".agents/mcp_config.json",
    ".agents/plugins",
];

/// agy's CLI state directory, below the canonical home.
pub fn root(home: &Path) -> PathBuf {
    home.join(".gemini/antigravity-cli")
}

/// The policy's allowances for an Antigravity child, the conversations it
/// may never write, and the places it may not read.
pub struct Rules {
    pub allow: Vec<Rule>,
    pub protect: Vec<Rule>,
    pub hidden: Vec<String>,
}

/// The journal names SQLite gives a database file, beside the file.
const JOURNALS: [&str; 3] = ["-journal", "-wal", "-shm"];

pub fn rules(home: &Path, directory: &Path, conversation: Option<&str>) -> Result<Rules, String> {
    let dir = root(home).join("conversations");
    let linked = dir
        .ancestors()
        .take_while(|path| *path != home)
        .any(|path| {
            path.symlink_metadata()
                .is_ok_and(|metadata| metadata.file_type().is_symlink())
        });
    if linked || resolve(&dir).as_deref() != Some(&dir) {
        return Err(say(
            "agy_conversations_path",
            &[("directory", text(&dir)?.as_str())],
        ));
    }
    let (allow, protect) = match conversation {
        Some(id) => (own(&dir, id)?, Vec::new()),
        None => first(&dir)?,
    };
    Ok(Rules {
        allow,
        protect,
        hidden: hidden(home, directory)?,
    })
}

/// A continued conversation's exact write set: its file, a regular file
/// with one link, and its journal names, each a regular file with one link
/// where it exists.
fn own(dir: &Path, id: &str) -> Result<Vec<Rule>, String> {
    use std::os::unix::fs::MetadataExt;
    let file = dir.join(format!("{id}.db"));
    let refused = |path: &Path| {
        say(
            "agy_conversation_file",
            &[("path", &path.display().to_string())],
        )
    };
    if uuid::Uuid::parse_str(id)
        .map(|u| u.to_string())
        .ok()
        .as_deref()
        != Some(id)
    {
        return Err(refused(&file));
    }
    let single = |path: &Path| {
        path.symlink_metadata()
            .is_ok_and(|m| m.file_type().is_file() && m.nlink() == 1)
    };
    if !single(&file) {
        return Err(refused(&file));
    }
    let mut rules = vec![Rule::Literal(text(&file)?)];
    for journal in JOURNALS {
        let path = dir.join(format!("{id}.db{journal}"));
        if path.symlink_metadata().is_ok() && !single(&path) {
            return Err(refused(&path));
        }
        rules.push(Rule::Literal(text(&path)?));
    }
    Ok(rules)
}

/// A first turn's allowance: a new `<uuid>.db` file or journal name in
/// `conversations/` (and the directory itself while it does not exist),
/// and every name there at launch denied.
fn first(dir: &Path) -> Result<(Vec<Rule>, Vec<Rule>), String> {
    let shown = text(dir)?;
    let hex = |n: usize| "[0-9a-f]".repeat(n);
    let uuid = [hex(8), hex(4), hex(4), hex(4), hex(12)].join("-");
    let mut allow: Vec<Rule> = [""]
        .iter()
        .chain(JOURNALS.iter())
        .map(|journal| Rule::Pattern(format!("^{}/{uuid}\\.db{journal}$", escape(&shown))))
        .collect();
    let protect = match std::fs::read_dir(dir) {
        Ok(entries) => existing(dir, entries)?,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            allow.push(Rule::Literal(shown));
            Vec::new()
        }
        Err(error) => {
            let shown = dir.display().to_string();
            let error = error.to_string();
            let said = [("directory", shown.as_str()), ("error", error.as_str())];
            return Err(say("agy_conversations_unlisted", &said));
        }
    };
    Ok((allow, protect))
}

/// Every name in `conversations/` at launch; past `CONVERSATIONS_NAMED`
/// the child is refused, and so it is when an entry cannot be read.
fn existing(dir: &Path, entries: std::fs::ReadDir) -> Result<Vec<Rule>, String> {
    let mut rules = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|error| {
            let (shown, error) = (dir.display().to_string(), error.to_string());
            say(
                "agy_conversations_unlisted",
                &[("directory", &shown), ("error", &error)],
            )
        })?;
        if rules.len() == CONVERSATIONS_NAMED {
            let most = CONVERSATIONS_NAMED.to_string();
            let shown = dir.display().to_string();
            return Err(say(
                "agy_conversations_many",
                &[("directory", &shown), ("most", &most)],
            ));
        }
        rules.push(Rule::Subpath(text(&entry.path())?));
    }
    Ok(rules)
}

/// Global customizations and the hook, MCP and plugin files in the
/// workspace, including the resolved targets of existing links.
fn hidden(home: &Path, directory: &Path) -> Result<Vec<String>, String> {
    let mut places: Vec<PathBuf> = USER.iter().map(|name| home.join(name)).collect();
    for ancestor in directory.ancestors() {
        places.extend(PROJECT.iter().map(|name| ancestor.join(name)));
    }
    let mut out = Vec::new();
    for place in places {
        for found in [Some(place.clone()), resolve(&place)].into_iter().flatten() {
            let found = text(&found)?;
            if !out.contains(&found) {
                out.push(found);
            }
        }
    }
    Ok(out)
}