neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A turn's private directory: mode 0700 under the system temporary
//! directory, holding the child marker; every child's TMPDIR on macOS and
//! Codex's elsewhere. It is removed when its guard goes, and also when the
//! marker cannot be written, since a directory without one is never swept
//! as stale (X4e P8). A Cursor child's is short and directly in `/tmp`, so
//! the worker directory Cursor names from its `TMPDIR` always fits and
//! Cursor never falls back to the shared `/tmp/.cursor` (X7c Y1).

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

pub struct Private(PathBuf);

/// Where a Cursor child's private directory is made.
pub const SHORT_PARENT: &str = "/tmp";

impl Private {
    pub fn make() -> io::Result<Self> {
        let name = uuid::Uuid::new_v4().simple().to_string();
        Self::make_at(&std::env::temp_dir(), &name)
    }

    /// The turn's private directory for `agent`: Cursor's short, in `/tmp`.
    pub fn make_for(agent: super::super::adapter::Agent) -> io::Result<Self> {
        if agent != super::super::adapter::Agent::Cursor {
            return Self::make();
        }
        let name = uuid::Uuid::new_v4().simple().to_string();
        Self::make_at(Path::new(SHORT_PARENT), &name[..12])
    }

    /// Made new (never an existing name), mode 0700, and checked as made:
    /// a real directory of this user's, closed to others.
    fn make_at(parent: &Path, name: &str) -> io::Result<Self> {
        use std::os::unix::fs::{DirBuilderExt, MetadataExt};
        let dir = parent.join(format!("neosian-harness-{}-{name}", std::process::id()));
        std::fs::DirBuilder::new().mode(0o700).create(&dir)?;
        let made = Self::marked(dir, |dir| {
            std::fs::write(dir.join(super::super::MARKER), "")
        })?;
        let found = made.0.symlink_metadata()?;
        let own = found.uid() == super::cursor_run::uid() && found.mode() & 0o077 == 0;
        if !found.is_dir() || !own {
            return Err(io::Error::other(
                "the private directory is not this user's own",
            ));
        }
        Ok(made)
    }

    /// The directory made, kept only once `mark` succeeded.
    pub fn marked(dir: PathBuf, mark: impl FnOnce(&Path) -> io::Result<()>) -> io::Result<Self> {
        let made = Self(dir);
        mark(&made.0)?;
        Ok(made)
    }

    pub fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for Private {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}