use std::path::{Path, PathBuf};
use super::adapter::Agent;
use super::text::say;
pub const PREFIX: &str = "neosian-harness-";
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())],
)
}
}
struct Made(Option<PathBuf>);
impl Drop for Made {
fn drop(&mut self) {
if let Some(dir) = self.0.take() {
remove(&dir);
}
}
}
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))
}
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(())
}
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(),
]
}
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)
}
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())
}
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)),
}
}
}
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,
}
})
}
pub fn forget(home: &Path) {
if ours(home) {
remove(home);
}
}
pub fn sweep() {
sweep_in(&std::env::temp_dir());
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);
}
}
}
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;