neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The policy as data, and its macOS profile text. Every path in it is
//! canonical (symbolic links resolved, as the kernel compares them), comes
//! from the watcher's own validated inputs and never from the child, and
//! is refused when the profile language could not name it exactly.

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

use super::super::adapter::{Agent, Mode};
use super::super::text::say;
use super::state;
use super::store::Stores;

/// One path rule. A pattern is a whole anchored regular expression built
/// from an escaped canonical prefix.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Rule {
    Literal(String),
    Subpath(String),
    Pattern(String),
}

/// What the child may write, what it may never write even where an
/// allowance covers it, and the variables it is started with.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
    pub mode: Mode,
    pub allow: Vec<Rule>,
    /// Every client's own directory, denied after the allowances, and the
    /// harness's state entries allowed again after them (X4f Q5).
    pub roots: Vec<String>,
    /// Every private home in the temporary directory, Vibe's and Muse's,
    /// denied with the roots wherever that directory lies (X6c U2).
    pub homes: Vec<Rule>,
    pub state: Vec<Rule>,
    pub protect: Vec<Rule>,
    /// Existing lock files a store reader opens for writing: data writes
    /// only, after the protected places (`store.rs`).
    pub locks: Vec<String>,
    /// Places the child may not read: neosian's login state.
    pub hidden: Vec<String>,
    pub env: Vec<(String, String)>,
    /// Variables removed from the child's environment, in both modes.
    pub unset: Vec<String>,
}

/// What the policy is built from, all of it the watcher's own.
pub struct Inputs<'a> {
    pub agent: Agent,
    pub mode: Mode,
    pub directory: &'a Path,
    pub private: &'a Path,
    pub home: &'a Path,
    /// The parent's stores: what no child writes, reads or inherits.
    pub stores: &'a Stores,
    /// The watcher's environment, for a harness's state directory override.
    pub var: &'a dyn Fn(&str) -> Option<OsString>,
    /// The session the turn starts or continues, which names Pi's state.
    pub session: Option<&'a str>,
    /// A Vibe child's private home (X6a).
    pub child_home: Option<&'a Path>,
    /// A Muse child's session directory, made and checked outside it (X6c U5).
    pub session_dir: Option<&'a Path>,
    /// Cursor's persistent-session root (`cursor_run::root()` at a launch;
    /// a fixture's own in tests, X7c Y7).
    pub persist: &'a Path,
}

/// The devices every process writes in normal use (the investigation's
/// prototype, which all three harnesses ran under).
const DEVICES: [&str; 5] = [
    "/dev/null",
    "/dev/zero",
    "/dev/tty",
    "/dev/dtracehelper",
    "/dev/ptmx",
];
const DEVICE_PATTERNS: [&str; 2] = ["^/dev/fd/[0-9]+$", "^/dev/ttys[0-9]+$"];

/// Places in the child's directory that configure a harness or Git, so a
/// `write` child cannot plant code that a later session runs. Listed in
/// both modes; in `read-only` the directory is not writable anyway.
const PROJECT_DIRS: [&str; 9] = [
    ".git/hooks",
    ".claude",
    ".codex",
    ".opencode",
    ".agents",
    ".pi",
    ".cursor",
    ".vibe",
    ".muse",
];
const PROJECT_FILES: [&str; 4] = [
    ".git/config",
    ".mcp.json",
    "opencode.json",
    "opencode.jsonc",
];

/// The path as profile text: UTF-8 without a quote, a backslash or a
/// control character, which the profile language could not name exactly.
pub fn text(path: &Path) -> Result<String, String> {
    match path.to_str() {
        Some(text)
            if !text
                .chars()
                .any(|c| c == '"' || c == '\\' || c.is_control()) =>
        {
            Ok(text.to_string())
        }
        _ => Err(say(
            "sandbox_path",
            &[("path", &path.display().to_string())],
        )),
    }
}

/// The text with every regular expression operator escaped.
pub fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        if "^$.|?*+()[]{}".contains(c) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// An absolute path made canonical: its longest existing ancestor resolved
/// by the operating system, then the rest appended. None for a relative
/// path or a `..` in the part that does not exist yet.
pub fn resolve(path: &Path) -> Option<PathBuf> {
    if !path.is_absolute() {
        return None;
    }
    let mut tail = Vec::new();
    let mut existing = path;
    loop {
        if let Ok(found) = existing.canonicalize() {
            let mut out = found;
            for name in tail.iter().rev() {
                out.push(name);
            }
            return Some(out);
        }
        match existing.components().next_back() {
            Some(Component::Normal(name)) => tail.push(name.to_os_string()),
            _ => return None,
        }
        existing = existing.parent()?;
    }
}

fn canonical_dir(path: &Path, key: &str) -> Result<PathBuf, String> {
    path.canonicalize()
        .ok()
        .filter(|path| path.is_dir())
        .ok_or_else(|| say(key, &[("path", &path.display().to_string())]))
}

pub fn build(inputs: &Inputs) -> Result<Policy, String> {
    let home = canonical_dir(inputs.home, "sandbox_home")?;
    let private = canonical_dir(inputs.private, "sandbox_path")?;
    let directory = canonical_dir(inputs.directory, "sandbox_path")?;
    let mut allow: Vec<Rule> = DEVICES
        .iter()
        .map(|device| Rule::Literal(device.to_string()))
        .chain(DEVICE_PATTERNS.iter().map(|p| Rule::Pattern(p.to_string())))
        .collect();
    allow.push(Rule::Subpath(text(&private)?));
    let named = (inputs.session, inputs.child_home, inputs.session_dir);
    let places = (directory.as_path(), private.as_path(), inputs.persist);
    let own = state::rules(inputs.agent, &home, inputs.var, named, places)?;
    allow.extend(own.allow.iter().cloned());
    let mut roots = Vec::new();
    for root in state::roots(&home, inputs.var) {
        roots.push(text(&root)?);
    }
    let homes = homes()?;
    if inputs.mode == Mode::Write {
        allow.push(Rule::Subpath(text(&directory)?));
    }
    // The marker stays: removing it would hide the child from a server
    // that sees only TMPDIR.
    let mut protect = vec![Rule::Literal(text(&private.join(super::super::MARKER))?)];
    for (names, dir) in [(&PROJECT_DIRS[..], true), (&PROJECT_FILES[..], false)] {
        for name in names {
            protect.extend(guarded(&directory.join(name), dir)?);
        }
    }
    for root in &inputs.stores.protected {
        if let Some(root) = resolve(root) {
            protect.push(Rule::Subpath(text(&root)?));
        }
    }
    protect.extend(own.protect);
    let mut locks = Vec::new();
    for lock in &inputs.stores.locks {
        if let Some(lock) = lock_file(lock) {
            locks.push(text(&lock)?);
        }
    }
    let mut hidden = own.hidden;
    for place in &inputs.stores.hidden {
        if let Some(place) = resolve(place) {
            hidden.push(text(&place)?);
        }
    }
    let tmp = text(&private)?;
    let mut env = vec![("TMPDIR".to_string(), tmp.clone())];
    if let Some(name) = own.tmp_var {
        env.push((name.to_string(), tmp));
    }
    Ok(Policy {
        mode: inputs.mode,
        allow,
        roots,
        homes,
        state: own.allow,
        protect,
        locks,
        hidden,
        env,
        unset: inputs.stores.unset.clone(),
    })
}

/// Every private home a server makes in this temporary directory
/// (`home.rs`), as patterns: no child writes one, its own included, but
/// where its own state is allowed again after the roots (Vibe's logs).
fn homes() -> Result<Vec<Rule>, String> {
    let temp = std::env::temp_dir();
    let temp = canonical_dir(&temp, "sandbox_path")?;
    let prefix = escape(&text(&temp.join(super::super::home::PREFIX))?);
    Ok(["vibe", "muse"]
        .iter()
        .map(|kind| Rule::Pattern(format!("^{prefix}[0-9]+-{kind}-[0-9a-f]+(/.*)?$")))
        .collect())
}

/// A lock file named canonically, only when it exists as a regular file
/// with one link (X4e P7): a data write through a name that shares its
/// file with another, or through a link, would reach that other file.
fn lock_file(lock: &Path) -> Option<PathBuf> {
    use std::os::unix::fs::MetadataExt;
    let found = lock.symlink_metadata().ok()?;
    if !found.file_type().is_file() || found.nlink() != 1 {
        return None;
    }
    Some(lock.parent()?.canonicalize().ok()?.join(lock.file_name()?))
}

/// A protected place, and where it leads when it is already a link.
fn guarded(path: &Path, dir: bool) -> Result<Vec<Rule>, String> {
    let rule = |path: &Path| -> Result<Rule, String> {
        let path = text(path)?;
        Ok(if dir {
            Rule::Subpath(path)
        } else {
            Rule::Literal(path)
        })
    };
    let mut rules = vec![rule(path)?];
    if let Some(target) = resolve(path).filter(|target| target != path) {
        rules.push(rule(&target)?);
    }
    Ok(rules)
}