neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Cursor's state and integrations for one child (X5b), from the installed
//! 2026.09.10-fd3934a's code (`paths.js`, `src/state/index.ts`, the loaders,
//! the trust module), observed in live child turns on 2026.11.22-e9042b2
//! (X7a): with every file below unreadable the turns completed.
//!
//! - The config root is `CURSOR_CONFIG_DIR`, else `$XDG_CONFIG_HOME/cursor`,
//!   else `~/.cursor`; the data root is `CURSOR_DATA_DIR`, else `~/.cursor`.
//!   Both, and `~/.cursor`, are every child's denied roots.
//! - A chat lives in `<config>/chats/<md5 of the workspace path>/<chat>/`,
//!   with `store.db` in SQLite, which writes a rollback journal,
//!   `store.db-journal`, beside it (seen live on 2026.11.22-e9042b2, X7d:
//!   with the journal refused the store stayed empty and `--resume` started
//!   without the first turn), or `-wal` and `-shm` in WAL mode, and
//!   `meta.json`. A first turn's chat ID is Cursor's, so it may create a
//!   chat directory of this workspace at that depth, but write none of the
//!   chats there at launch, each denied by name (X5d); `send` names its
//!   chat, after checking it is still Cursor's own.
//! - The workspace's project directory, `<data>/projects/<slug>`, may be
//!   created, nothing in it: its trust marker, MCP approvals, worker log and
//!   transcripts stay unwritable.
//! - Cursor reads MCP servers from `~/.cursor/mcp.json` (the home directory's,
//!   whatever the config root) and each workspace root's `.cursor/mcp.json`;
//!   hooks from `/Library/Application Support/Cursor/hooks.json`,
//!   `~/.cursor/hooks.json`, team hooks under `~/.cursor/managed`, the
//!   project's `.cursor/hooks.json` and Claude Code's `settings.json` files;
//!   plugins from `~/.cursor/plugins`, `~/.claude/plugins` and the project's
//!   `.cursor/settings.json`. A Cursor child may read none of them (nor the
//!   config root's equivalents), in the workspace and every ancestor, each
//!   also where a link leads: every loader catches a failed read and goes
//!   on without that integration, except the project plugin settings, whose
//!   read error is rethrown.

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

use md5::{Digest, Md5};

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

pub const CONFIG_VAR: &str = "CURSOR_CONFIG_DIR";
pub const DATA_VAR: &str = "CURSOR_DATA_DIR";
const TRUST: &str = ".workspace-trusted";
const CHAT_FILES: &str =
    "(meta\\.json|store\\.db|store\\.db-journal|store\\.db-wal|store\\.db-shm)";
/// Integration files below a config root, and directories.
const USER_FILES: [&str; 2] = ["mcp.json", "hooks.json"];
const USER_DIRS: [&str; 2] = ["plugins", "managed"];
/// Integration files below each workspace root and ancestor.
const PROJECT_FILES: [&str; 5] = [
    ".cursor/mcp.json",
    ".cursor/hooks.json",
    ".cursor/settings.json",
    ".claude/settings.json",
    ".claude/settings.local.json",
];
const ENTERPRISE_HOOKS: &str = "/Library/Application Support/Cursor/hooks.json";

fn outside(path: &Path) -> String {
    say(
        "sandbox_state",
        &[("agent", "cursor"), ("path", &path.display().to_string())],
    )
}

/// A variable's value when set and not blank, as Cursor reads it.
fn set(var: &dyn Fn(&str) -> Option<OsString>, name: &str) -> Option<PathBuf> {
    var(name)
        .filter(|value| !value.to_string_lossy().trim().is_empty())
        .map(PathBuf::from)
}

/// A root Cursor would use, canonical and strictly below the home
/// directory; a relative value refuses, since Cursor would take it from the
/// child's directory.
fn below(home: &Path, wanted: &Path) -> Result<PathBuf, String> {
    resolve(wanted)
        .filter(|root| root.starts_with(home) && root != home)
        .ok_or_else(|| outside(wanted))
}

pub fn config_root(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
    let wanted = match (set(var, CONFIG_VAR), set(var, "XDG_CONFIG_HOME")) {
        (Some(dir), _) => dir,
        (None, Some(xdg)) => xdg.join("cursor"),
        (None, None) => home.join(".cursor"),
    };
    below(home, &wanted)
}

pub fn data_root(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
    let wanted = set(var, DATA_VAR).unwrap_or_else(|| home.join(".cursor"));
    below(home, &wanted)
}

/// Every place Cursor keeps configuration or data, for every child's
/// denied roots.
pub fn roots(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
    let mut found = vec![home.join(".cursor")];
    found.extend(config_root(home, var).ok());
    found.extend(data_root(home, var).ok());
    found
}

/// The workspace's chats directory: the MD5 of its path, in hex.
pub fn chats(config: &Path, directory: &Path) -> PathBuf {
    let digest = Md5::digest(directory.to_string_lossy().as_bytes());
    let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
    config.join("chats").join(hex)
}

/// Cursor's name for a workspace below `projects`: every character but an
/// ASCII letter or digit a dash, runs of dashes one, none at either end.
pub fn slug(directory: &Path) -> String {
    let mut out = String::new();
    for c in directory.to_string_lossy().chars() {
        let c = if c.is_ascii_alphanumeric() { c } else { '-' };
        if !(c == '-' && out.ends_with('-')) {
            out.push(c);
        }
    }
    out.trim_matches('-').to_string()
}

/// The most chats of one workspace a first turn's policy names (X5d): each
/// is one denial in a profile the kernel receives as one argument.
pub const CHATS_NAMED: usize = 512;

/// The policy's allowances for a Cursor child, the chats 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>,
}

/// Every entry already in the workspace's chats directory, by name: a
/// first turn may create a chat but write none that existed at launch.
/// Past `CHATS_NAMED` the child is refused, never left with fewer denials.
fn existing(chats: &Path) -> Result<Vec<Rule>, String> {
    let Ok(entries) = std::fs::read_dir(chats) else {
        return Ok(Vec::new());
    };
    let mut rules = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|error| error.to_string())?;
        if rules.len() == CHATS_NAMED {
            let shown = chats.display().to_string();
            let most = CHATS_NAMED.to_string();
            return Err(say(
                "cursor_chats_many",
                &[("directory", &shown), ("most", &most)],
            ));
        }
        rules.push(Rule::Subpath(text(&entry.path())?));
    }
    Ok(rules)
}

/// A chat `send` continues: a real directory where Cursor keeps it, no
/// link on the way, holding its database as one regular file with one
/// link (X5d).
pub fn chat_ready(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    directory: &Path,
    chat: &str,
) -> Result<(), String> {
    use std::os::unix::fs::MetadataExt;
    let dir = chats(&config_root(home, var)?, directory).join(chat);
    let real = dir.symlink_metadata().is_ok_and(|m| m.is_dir())
        && resolve(&dir).as_deref() == Some(dir.as_path());
    let store = dir.join("store.db").symlink_metadata();
    if real && store.is_ok_and(|m| m.is_file() && m.nlink() == 1) {
        return Ok(());
    }
    let shown = dir.display().to_string();
    Err(say(
        "cursor_chat_state",
        &[("chat", chat), ("directory", &shown)],
    ))
}

pub fn rules(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    (directory, private, persist): (&Path, &Path, &Path),
    chat: Option<&str>,
) -> Result<Rules, String> {
    let config = config_root(home, var)?;
    let data = data_root(home, var)?;
    let chats = chats(&config, directory);
    let shown = text(&chats)?;
    let project = data.join("projects").join(slug(directory));
    let mut allow = vec![
        Rule::Literal(text(&config.join("chats"))?),
        Rule::Literal(shown.clone()),
        Rule::Literal(text(&project)?),
    ];
    // The local worker's socket and its directory, nothing else there; in
    // the child's own short private directory, nothing more (X7c Y1).
    if let Some(worker) = super::cursor_run::worker(&data, private, directory)? {
        if worker != project {
            allow.push(Rule::Literal(text(&worker)?));
        }
        allow.push(Rule::Literal(text(&worker.join("worker.sock"))?));
    }
    let prefix = escape(&shown);
    let mut protect = Vec::new();
    match chat {
        Some(chat) => {
            allow.extend(super::cursor_run::rules(persist, chat)?);
            allow.push(Rule::Literal(format!("{shown}/{chat}")));
            let chat = escape(chat);
            allow.push(Rule::Pattern(format!("^{prefix}/{chat}/{CHAT_FILES}$")));
        }
        None => {
            allow.push(Rule::Pattern(format!("^{prefix}/[^/]+$")));
            allow.push(Rule::Pattern(format!("^{prefix}/[^/]+/{CHAT_FILES}$")));
            protect = existing(&chats)?;
        }
    }
    Ok(Rules {
        allow,
        protect,
        hidden: hidden(home, &config, directory)?,
    })
}

/// Every integration load path, and where an existing one leads.
fn hidden(home: &Path, config: &Path, directory: &Path) -> Result<Vec<String>, String> {
    let user = home.join(".cursor");
    let mut places: Vec<PathBuf> = vec![PathBuf::from(ENTERPRISE_HOOKS)];
    for root in [&user, &config.to_path_buf()] {
        places.extend(
            USER_FILES
                .iter()
                .chain(&USER_DIRS)
                .map(|name| root.join(name)),
        );
    }
    places.push(home.join(".claude/settings.json"));
    places.push(home.join(".claude/plugins"));
    for ancestor in directory.ancestors() {
        places.extend(PROJECT_FILES.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)
}

/// Whether Cursor already trusts the workspace, as its trust check reads
/// it: the project directory's marker, or one of an ancestor's other than
/// the home directory, its ancestors and the shortest paths.
pub fn trusted(home: &Path, var: &dyn Fn(&str) -> Option<OsString>, directory: &Path) -> bool {
    let Ok(projects) = data_root(home, var).map(|data| data.join("projects")) else {
        return false;
    };
    let marked = |dir: &Path| projects.join(slug(dir)).join(TRUST).is_file();
    let excluded =
        |dir: &Path| dir == home || home.starts_with(dir) || dir.components().count() < 4;
    marked(directory)
        || directory
            .ancestors()
            .skip(1)
            .any(|dir| !excluded(dir) && marked(dir))
}