neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Cursor's places outside its configuration that a child needs (X7a):
//! its local worker's socket (`worker_dir`), and the persistent-session
//! state for a resumed chat (seen live on
//! 2026.11.22-e9042b2: `--resume` refused with "could not verify its
//! persistent session: EPERM: ... mkdir '/tmp/cursor-agent-persist-<uid>'").
//! Before resuming, Cursor takes a claim lock for the chat, a directory
//! `claim-locks/<chat>.lock` holding `owner.json` below
//! `/tmp/cursor-agent-persist-<uid>`, looks for a tmux session of the chat,
//! reads `bindings/<chat>.json` if there is one, and removes its lock. It
//! makes the state directories itself, mode 0700, and refuses ones that are
//! links, another user's or open to others.
//!
//! The watcher makes those directories outside the child, as Cursor would,
//! and checks them the same way; the child may write only its chat's own
//! lock (and the name Cursor moves an abandoned one to), nothing else there.

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

use super::super::text::say;
use super::cursor::slug;
use super::policy::{Rule, escape, resolve, text};

unsafe extern "C" {
    fn getuid() -> u32;
}

pub fn uid() -> u32 {
    // SAFETY: getuid takes nothing and cannot fail.
    unsafe { getuid() }
}

/// Cursor's state root: `/tmp`, never `TMPDIR`, and the user's ID.
pub fn root() -> PathBuf {
    PathBuf::from(format!("/tmp/cursor-agent-persist-{}", uid()))
}

fn refused(dir: &Path) -> String {
    say(
        "sandbox_state",
        &[("agent", "cursor"), ("path", &dir.display().to_string())],
    )
}

/// The state directories made where missing, mode 0700, and each checked as
/// Cursor checks it: a real directory, the user's own, closed to others.
pub fn ready(root: &Path) -> Result<(), String> {
    use std::os::unix::fs::{DirBuilderExt, MetadataExt};
    for dir in [
        root.to_path_buf(),
        root.join("claim-locks"),
        root.join("bindings"),
    ] {
        let made = std::fs::DirBuilder::new().mode(0o700).create(&dir);
        if made.is_err() && !dir.exists() {
            return Err(refused(&dir));
        }
        let found = dir.symlink_metadata().map_err(|_| refused(&dir))?;
        if !found.is_dir() || found.uid() != uid() || found.mode() & 0o077 != 0 {
            return Err(refused(&dir));
        }
    }
    Ok(())
}

/// The child's allowance: its chat's claim lock, and the name an abandoned
/// lock of that chat is moved to before Cursor removes it.
pub fn rules(root: &Path, chat: &str) -> Result<Vec<Rule>, String> {
    // Cursor takes no lock for a chat ID that is not a UUID.
    if uuid::Uuid::parse_str(chat).is_err() {
        return Ok(Vec::new());
    }
    let locks = resolve(&root.join("claim-locks")).ok_or_else(|| refused(root))?;
    let chat = chat.to_lowercase();
    let lock = locks.join(format!("{chat}.lock"));
    let abandoned = format!("^{}\\.abandoned-[0-9a-f]+(/.*)?$", escape(&text(&lock)?));
    Ok(vec![Rule::Subpath(text(&lock)?), Rule::Pattern(abandoned)])
}

/// Where Cursor's local worker keeps its socket for a workspace (X7a, seen
/// live on 2026.11.22-e9042b2: a print run refuses to start when it cannot
/// make it), as its `paths.js` names it: below `<data>/projects`, or the
/// first of `<data>`, `<tmp>/.cursor` (the child's own `TMPDIR`) and
/// `/tmp/.cursor` that is at most 83 characters long, `<slug>`; past 91
/// characters, its first 83 and a dash with the first 7 hex digits of the
/// whole path's SHA-256.
pub fn worker_dir(data: &Path, tmp: &Path, directory: &Path) -> PathBuf {
    use sha2::{Digest as _, Sha256};
    let short = |path: &PathBuf| path.as_os_str().len() <= 83;
    let base = [
        data.join("projects"),
        data.to_path_buf(),
        tmp.join(".cursor"),
    ]
    .into_iter()
    .find(short)
    .unwrap_or_else(|| PathBuf::from("/tmp/.cursor"));
    let whole = base.join(slug(directory)).to_string_lossy().into_owned();
    if whole.chars().count() <= 91 {
        return PathBuf::from(whole);
    }
    let digest = Sha256::digest(whole.as_bytes());
    let hex: String = digest.iter().take(4).map(|b| format!("{b:02x}")).collect();
    let kept: String = whole.chars().take(83).collect();
    PathBuf::from(format!("{kept}-{}", &hex[..7]))
}

/// The worker directory a Cursor child may make, checked without following
/// a link (X7c Y1): None when it falls in the child's own private
/// directory, which is short so that it always does once the data
/// directory's names are too long, and never the shared `/tmp/.cursor`.
/// Below the data directory, every component that exists, from the data
/// directory down, is a real directory of this user's, and `worker.sock`, if
/// there, is a socket of this user's; one that answers is a worker of the
/// person's own, which a child would use outside the policy, so the child
/// is refused.
pub fn worker(data: &Path, private: &Path, directory: &Path) -> Result<Option<PathBuf>, String> {
    use std::os::unix::fs::{FileTypeExt, MetadataExt};
    let worker = worker_dir(data, private, directory);
    let shown = worker.display().to_string();
    let state = || say("cursor_worker_state", &[("path", &shown)]);
    if worker.starts_with(private) {
        return Ok(None);
    }
    if !worker.starts_with(data) {
        return Err(state());
    }
    let chain = worker.ancestors().take_while(|dir| dir.starts_with(data));
    for dir in chain {
        if let Ok(found) = dir.symlink_metadata()
            && (!found.is_dir() || found.uid() != uid())
        {
            return Err(state());
        }
    }
    let socket = worker.join("worker.sock");
    if let Ok(found) = socket.symlink_metadata() {
        if !found.file_type().is_socket() || found.uid() != uid() {
            return Err(state());
        }
        if std::os::unix::net::UnixStream::connect(&socket).is_ok() {
            let socket = socket.display().to_string();
            let directory = directory.display().to_string();
            let busy = [
                ("socket", socket.as_str()),
                ("directory", directory.as_str()),
            ];
            return Err(say("cursor_worker_busy", &busy));
        }
    }
    Ok(Some(worker))
}