neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! A child's private home made fresh before each launch, with a random
//! name, removed from the moment it exists, and swept as it is forgotten
//! (X6c U3, U10).

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use super::super::MARKER;
use super::super::adapter::Agent;

fn home(name: &str) -> PathBuf {
    use std::os::unix::fs::DirBuilderExt;
    let dir = std::env::temp_dir().join(name);
    fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
    fs::write(dir.join(MARKER), "").unwrap();
    dir.canonicalize().unwrap()
}

fn read_only(dir: &Path) {
    fs::create_dir_all(dir).unwrap();
    fs::write(dir.join("hooks.toml"), "x").unwrap();
    fs::set_permissions(dir, fs::Permissions::from_mode(0o555)).unwrap();
}

fn listing(dir: &Path) -> Vec<String> {
    let mut found = Vec::new();
    for entry in fs::read_dir(dir).unwrap().flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        if entry.file_type().unwrap().is_dir() {
            for below in listing(&entry.path()) {
                found.push(format!("{name}/{below}"));
            }
        } else {
            found.push(name);
        }
    }
    found.sort();
    found
}

#[test]
fn a_launch_starts_from_a_fresh_home_keeping_only_the_continued_session() {
    let unique = uuid::Uuid::new_v4().simple().to_string();
    let dir = home(&format!("neosian-x6c-renew-{unique}"));
    let session = "9605c47d-56d9-97e5-7c3b-7cf83f7853bf";
    let store = "logs/session/plugins";
    let kept = [
        format!("logs/session/unified/{session}/meta.json"),
        format!("{store}/blobs/ab/abcd"),
        format!("{store}/data/{session}/vibe/state.json"),
        format!("{store}/manifests/ab/abcd.json"),
    ];
    let planted = [
        "hooks.toml",
        "config.toml",
        "logs/vibe.log",
        "logs/session/unified/.session-index.json",
        "logs/session/unified/other-session/meta.json",
        "logs/session/plugins/data/other-session/vibe/state.json",
        "logs/session/plugins/tmp/package-1/hooks.toml",
    ];
    for name in kept.iter().map(String::as_str).chain(planted) {
        let path = dir.join(name);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, "planted").unwrap();
    }
    read_only(&dir.join("plugins/p"));
    read_only(&dir.join("logs/session/plugins/packages/ab/abcd"));
    super::renew(Agent::Vibe, &dir, Some(session)).unwrap();
    let mut expected = vec![MARKER.to_string()];
    expected.extend(kept);
    expected.sort();
    assert_eq!(listing(&dir), expected);
    super::renew(Agent::Vibe, &dir, None).unwrap();
    assert_eq!(listing(&dir), vec![MARKER.to_string()]);
    super::forget(&dir);
    assert!(!dir.exists());
}

#[test]
fn a_home_neosian_did_not_make_is_refused() {
    let unique = uuid::Uuid::new_v4().simple().to_string();
    let dir = std::env::temp_dir().join(format!("neosian-x6c-foreign-{unique}"));
    fs::create_dir(&dir).unwrap();
    fs::write(dir.join("kept"), "x").unwrap();
    assert!(super::renew(Agent::Vibe, &dir, None).is_err(), "no marker");
    fs::write(dir.join(MARKER), "").unwrap();
    fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
    assert!(
        super::renew(Agent::Vibe, &dir, None).is_err(),
        "open to others"
    );
    assert!(dir.join("kept").exists());
    let link = std::env::temp_dir().join(format!("neosian-x6c-link-{unique}"));
    std::os::unix::fs::symlink(&dir, &link).unwrap();
    super::forget(&link);
    assert!(dir.join("kept").exists(), "a link is never followed");
    fs::remove_file(&link).unwrap();
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_home_is_named_at_random_and_removed_from_the_moment_it_exists() {
    let first = super::make(Agent::Vibe).unwrap().unwrap();
    let second = super::make(Agent::Vibe).unwrap().unwrap();
    let named = format!("neosian-harness-{}-vibe-", std::process::id());
    for made in [&first, &second] {
        let name = made.file_name().unwrap().to_str().unwrap();
        let random = name.strip_prefix(&named).unwrap();
        assert!(random.len() == 32 && random.bytes().all(|b| b.is_ascii_hexdigit()));
    }
    assert_ne!(first, second);
    super::forget(&first);
    super::forget(&second);
    // A directory being made goes on any failure, a read-only one inside too.
    let unique = uuid::Uuid::new_v4().simple().to_string();
    let dir = std::env::temp_dir().join(format!("neosian-x6c-made-{unique}"));
    fs::create_dir(&dir).unwrap();
    read_only(&dir.join("plugins/p"));
    drop(super::Made(Some(dir.clone())));
    assert!(!dir.exists());
}

#[test]
fn the_sweep_removes_a_dead_servers_home_with_its_read_only_folders() {
    let mut ended = std::process::Command::new("/usr/bin/true").spawn().unwrap();
    let dead = ended.id();
    ended.wait().unwrap();
    let unique = uuid::Uuid::new_v4().simple().to_string();
    let stale = home(&format!("neosian-harness-{dead}-vibe-{unique}"));
    read_only(&stale.join("logs/session/plugins/packages/p"));
    let live = home(&format!(
        "neosian-harness-{}-vibe-{unique}",
        std::process::id()
    ));
    super::sweep();
    assert!(!stale.exists(), "swept, read-only folders and all");
    assert!(live.exists(), "a running server's home is kept");
    super::forget(&live);
}