neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A Muse Code child's state (X6b, X6c U5), from 1.4.25's nested runs
//! (record/investigation-2026-11-29, section 1E, and record/x6c-2026-11-29/
//! probe): with only its session's directory of its data directory and a
//! writable `TMPDIR`, fresh and continued turns completed; every other write
//! (its tracing, runtime registry, session index, model catalog, the
//! configuration's auth lock) fails soft. Muse keeps a session at
//! `<data>/sessions/YYYY/MM/DD/<id>/`, the date its local one when the
//! session began, and uses that directory when it already exists. neosian
//! names the ID, so the server makes the directory at the child's first
//! turn, outside the child, and keeps its path for the later turns; the
//! child may write inside it and nowhere else of Muse's data, not
//! `sessions/` or the shared date directories. Its private configuration
//! home stays read-only to it.

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

use super::super::adapter::Agent;
use super::super::text::say;
use super::policy::{Rule, text};
use super::state;

/// The policy's allowance for a Muse child: its session's directory.
pub fn rules(dir: Option<&Path>) -> Result<Vec<Rule>, String> {
    let dir = dir.ok_or_else(|| refused(None))?;
    Ok(vec![Rule::Subpath(text(dir)?)])
}

fn refused(dir: Option<&Path>) -> String {
    let shown = dir.map_or_else(String::new, |dir| dir.display().to_string());
    say("muse_session_dir", &[("directory", &shown)])
}

/// Muse's `sessions` directory, canonical.
fn sessions(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
    let dir = state::root(Agent::Muse, home, var)?.join("sessions");
    dir.canonicalize().map_err(|_| refused(Some(&dir)))
}

/// The session's directory made for a first turn, at today's local date
/// as Muse names it: the date directories made where missing, the
/// session's own new (mode 0700), then checked as `validate` checks it.
pub fn make(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    session: &str,
) -> Result<PathBuf, String> {
    use std::os::unix::fs::DirBuilderExt;
    let root = state::root(Agent::Muse, home, var)?.join("sessions");
    let (year, month, day) = today();
    let date = format!("{year:04}/{month:02}/{day:02}");
    let wanted = root.join(&date).join(session);
    let made = std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(root.join(&date))
        .and_then(|()| std::fs::DirBuilder::new().mode(0o700).create(&wanted));
    made.map_err(|_| refused(Some(&wanted)))?;
    validate(
        home,
        var,
        &sessions(home, var)?.join(date).join(session),
        session,
    )
}

/// A session directory as the watcher and a later turn take it: exactly
/// `<sessions>/YYYY/MM/DD/<session>`, a real directory with no link on the
/// way, `session` a UUID.
pub fn validate(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    dir: &Path,
    session: &str,
) -> Result<PathBuf, String> {
    let sessions = sessions(home, var)?;
    let digits = |part: Option<&std::ffi::OsStr>, width: usize| {
        part.and_then(|p| p.to_str())
            .is_some_and(|p| p.len() == width && p.bytes().all(|b| b.is_ascii_digit()))
    };
    let parts: Vec<&Path> = dir.ancestors().take(5).collect();
    let placed = parts.len() == 5
        && parts[4] == sessions
        && digits(parts[3].file_name(), 4)
        && digits(parts[2].file_name(), 2)
        && digits(parts[1].file_name(), 2)
        && uuid::Uuid::parse_str(session).is_ok()
        && dir.file_name().is_some_and(|name| name == session);
    let real = dir.symlink_metadata().is_ok_and(|m| m.is_dir());
    if placed && real && dir.canonicalize().ok().as_deref() == Some(dir) {
        return Ok(dir.to_path_buf());
    }
    Err(refused(Some(dir)))
}

/// Today's local date (year, month, day), as Muse dates a new session.
fn today() -> (i32, i32, i32) {
    #[repr(C)]
    struct Tm {
        sec: i32,
        min: i32,
        hour: i32,
        mday: i32,
        mon: i32,
        year: i32,
        wday: i32,
        yday: i32,
        isdst: i32,
        gmtoff: i64,
        zone: *const std::ffi::c_char,
    }
    unsafe extern "C" {
        fn tzset();
        fn localtime_r(clock: *const i64, result: *mut Tm) -> *mut Tm;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64);
    let mut tm = Tm {
        sec: 0,
        min: 0,
        hour: 0,
        mday: 1,
        mon: 0,
        year: 70,
        wday: 0,
        yday: 0,
        isdst: 0,
        gmtoff: 0,
        zone: std::ptr::null(),
    };
    // SAFETY: tzset reads TZ; localtime_r writes only the struct given,
    // laid out as macOS and glibc define `struct tm` on 64-bit targets.
    unsafe {
        tzset();
        localtime_r(&now, &mut tm);
    }
    (tm.year + 1900, tm.mon + 1, tm.mday)
}

/// Muse's configuration directory and its application support folder,
/// for every child's denied roots.
pub fn roots(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
    let xdg = var("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute());
    let config = xdg.unwrap_or_else(|| home.join(".config")).join("muse");
    vec![config, home.join("Library/Application Support/Muse")]
}