neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A child's private home (X6a, X6b, X6c):
//! `neosian-harness-<server>-<kind>-<random>` in the temporary directory,
//! mode 0700, holding the child marker so that a later server sweeps it if
//! this one is killed; made at the child's first turn, removed when the
//! child is forgotten. Vibe's is its `VIBE_HOME`; Muse Code's is its
//! `XDG_CONFIG_HOME`, holding a `muse` directory with the person's settings
//! less their hooks and MCP servers, and their sign-in metadata.
//!
//! The home is made fresh before every launch and every sign-in probe
//! (X6c U2, U3): everything in it is removed but the marker and, for a Vibe
//! child continuing a session, that session's own state (`kept`); Muse's
//! configuration is then built again from the person's. When anything else survives, the turn is refused. On
//! macOS no child may write any private home but its own Vibe logs
//! (`sandbox/policy.rs`). It is not in neosian's home, which no child may
//! write.

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

use super::adapter::Agent;
use super::text::say;

/// The name every private home starts with, before the server's ID.
pub const PREFIX: &str = "neosian-harness-";

/// The kind of private home an agent's child gets, if any.
pub fn kind(agent: Agent) -> Option<&'static str> {
    match agent {
        Agent::Vibe => Some("vibe"),
        Agent::Muse => Some("muse"),
        _ => None,
    }
}

fn failed(agent: Agent) -> impl Fn(std::io::Error) -> String {
    move |e| {
        say(
            "spawn_failed",
            &[("agent", agent.name()), ("error", &e.to_string())],
        )
    }
}

/// A directory being made, removed unless it is handed on (X6c U10).
struct Made(Option<PathBuf>);

impl Drop for Made {
    fn drop(&mut self) {
        if let Some(dir) = self.0.take() {
            remove(&dir);
        }
    }
}

/// The child's private home made new under a random name, its canonical
/// path returned; a Muse home is then filled (`muse.rs`), or refused with a
/// sentence. From the moment it exists it is removed again on any failure.
pub fn make(agent: Agent) -> Result<Option<PathBuf>, String> {
    use std::os::unix::fs::DirBuilderExt;
    let Some(kind) = kind(agent) else {
        return Ok(None);
    };
    let random = uuid::Uuid::new_v4().simple();
    let name = format!("{PREFIX}{}-{kind}-{random}", std::process::id());
    let dir = std::env::temp_dir().join(name);
    std::fs::DirBuilder::new()
        .mode(0o700)
        .create(&dir)
        .map_err(failed(agent))?;
    let mut made = Made(Some(dir.clone()));
    std::fs::write(dir.join(super::MARKER), "").map_err(failed(agent))?;
    let canonical = dir.canonicalize().map_err(failed(agent))?;
    made.0 = Some(canonical.clone());
    if agent == Agent::Muse {
        super::muse::fill(&canonical)?;
    }
    made.0 = None;
    Ok(Some(canonical))
}

/// The home made fresh for a launch or a probe: everything but the marker
/// removed, and for a Vibe child continuing `session` all but that
/// session's own state (`kept`); Muse's configuration built again. Refused
/// when the home is not one neosian made or anything else survives.
pub fn renew(agent: Agent, home: &Path, session: Option<&str>) -> Result<(), String> {
    let refused = || {
        say(
            "home_refused",
            &[("directory", &home.display().to_string())],
        )
    };
    if !ours(home) {
        return Err(refused());
    }
    let kept = kept(agent, session);
    prune(home, &kept, true);
    if !bare(home, &kept, true) {
        return Err(refused());
    }
    if agent == Agent::Muse {
        super::muse::fill(home)?;
    }
    Ok(())
}

/// What a Vibe child continuing `session` keeps (X6c U3): the session's
/// own directory, and the content-addressed plugin store the session pins
/// (its manifests and blobs, and the session's own plugin data), without
/// which Vibe cannot restore the session (seen live: "the session's pinned
/// plugin environment could not be rebuilt"). The unpacked packages go:
/// Vibe uses one unchecked when it is there, and otherwise rebuilds it from
/// the blobs and checks it against its digest.
fn kept(agent: Agent, session: Option<&str>) -> Vec<Vec<&str>> {
    let (Agent::Vibe, Some(session)) = (agent, session) else {
        return Vec::new();
    };
    let plugins = ["logs", "session", "plugins"];
    vec![
        vec!["logs", "session", "unified", session],
        [&plugins[..], &["manifests"]].concat(),
        [&plugins[..], &["blobs"]].concat(),
        [&plugins[..], &["data", session]].concat(),
    ]
}

/// The paths of `kept` below an entry named `name`: None when nothing
/// there is kept, an empty list when the entry is kept whole.
fn below<'a>(kept: &[Vec<&'a str>], name: &std::ffi::OsStr) -> Option<Vec<Vec<&'a str>>> {
    let mut tails = Vec::new();
    for path in kept {
        match path.split_first() {
            Some((first, [])) if name == *first => return Some(Vec::new()),
            Some((first, rest)) if name == *first => tails.push(rest.to_vec()),
            _ => {}
        }
    }
    (!tails.is_empty()).then_some(tails)
}

/// A real directory, no link, closed to others, holding the marker.
fn ours(dir: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    let found = dir.symlink_metadata().ok().filter(|m| m.is_dir());
    found.is_some_and(|m| m.mode() & 0o077 == 0) && dir.join(super::MARKER).is_file()
}

fn real_dir(entry: &std::fs::DirEntry) -> bool {
    entry.file_type().is_ok_and(|kind| kind.is_dir())
}

fn marker(entry: &std::fs::DirEntry, top: bool) -> bool {
    top && entry.file_name() == super::MARKER && entry.file_type().is_ok_and(|k| k.is_file())
}

/// Everything in `dir` removed but the marker (at the top) and the paths
/// of directories `kept` names, whose last ones are kept whole.
fn prune(dir: &Path, kept: &[Vec<&str>], top: bool) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
    for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
        let path = entry.path();
        match below(kept, &entry.file_name()) {
            _ if marker(&entry, top) => {}
            Some(tails) if real_dir(&entry) => {
                if !tails.is_empty() {
                    prune(&path, &tails, false);
                }
            }
            _ if real_dir(&entry) => remove(&path),
            _ => drop(std::fs::remove_file(&path)),
        }
    }
}

/// Whether `dir` holds nothing but what `prune` keeps.
fn bare(dir: &Path, kept: &[Vec<&str>], top: bool) -> bool {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return false;
    };
    entries.into_iter().all(|entry| {
        let Ok(entry) = entry else {
            return false;
        };
        match below(kept, &entry.file_name()) {
            _ if marker(&entry, top) => true,
            Some(tails) if real_dir(&entry) => {
                tails.is_empty() || bare(&entry.path(), &tails, false)
            }
            _ => false,
        }
    })
}

/// The child's private home removed, when it is one neosian made.
pub fn forget(home: &Path) {
    if ours(home) {
        remove(home);
    }
}

/// Turn directories and private homes a killed server or watcher left
/// behind: `neosian-harness-PID-*` holding the marker, whose PID no longer
/// runs, removed as a forgotten child's home is (X6c U10).
pub fn sweep() {
    sweep_in(&std::env::temp_dir());
    // A Cursor child's short private directory (X7c Y1), the user's own.
    let short = Path::new(super::sandbox::SHORT_PARENT);
    if short.canonicalize().ok() != std::env::temp_dir().canonicalize().ok() {
        sweep_in(short);
    }
}

fn sweep_in(parent: &Path) {
    use std::os::unix::fs::MetadataExt;
    let Ok(entries) = std::fs::read_dir(parent) else {
        return;
    };
    for entry in entries.flatten() {
        let own = entry
            .metadata()
            .is_ok_and(|m| m.uid() == super::sandbox::uid());
        if !own {
            continue;
        }
        let name = entry.file_name();
        let pid = name
            .to_str()
            .and_then(|name| name.strip_prefix(PREFIX))
            .and_then(|rest| rest.split('-').next())
            .and_then(|pid| pid.parse::<i32>().ok());
        let path = entry.path();
        let marked = real_dir(&entry) && path.join(super::MARKER).is_file();
        if let Some(pid) = pid
            && marked
            && !super::tree::exists(pid)
        {
            remove(&path);
        }
    }
}

/// A directory removed with everything in it. Vibe unpacks its plugins
/// into read-only directories (seen live), so each directory is made
/// writable before it is emptied; a link is removed, never followed.
fn remove(dir: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
    for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
        let path = entry.path();
        match entry.file_type() {
            Ok(kind) if kind.is_dir() => remove(&path),
            _ => drop(std::fs::remove_file(&path)),
        }
    }
    let _ = std::fs::remove_dir(dir);
}

#[cfg(test)]
mod tests;