use std::collections::HashMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
pub type Result<T> = std::result::Result<T, ManifestError>;
#[derive(Debug, Error)]
pub enum ManifestError {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
}
pub const MANIFEST_FILE: &str = ".trusty-mpm-manifest.json";
#[derive(Debug)]
pub enum ManifestLoad {
Ok(AgentManifest),
Corrupt(String),
}
pub fn temp_path(path: &std::path::Path) -> std::path::PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default();
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{}.{nanos}.tmp", std::process::id()));
path.with_file_name(name)
}
pub fn atomic_write(path: &std::path::Path, content: &str) -> Result<()> {
let tmp = temp_path(path);
if let Err(e) = std::fs::write(&tmp, content) {
let _ = std::fs::remove_file(&tmp);
return Err(ManifestError::Io(e));
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(ManifestError::Io(e));
}
Ok(())
}
pub fn manifest_lock_path(target_dir: &Path) -> std::path::PathBuf {
target_dir.join(format!("{MANIFEST_FILE}.lock"))
}
pub fn with_agent_manifest_lock<T, E, F>(target_dir: &Path, f: F) -> std::result::Result<T, E>
where
E: From<ManifestError>,
F: FnOnce() -> std::result::Result<T, E>,
{
std::fs::create_dir_all(target_dir).map_err(|e| E::from(ManifestError::Io(e)))?;
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(manifest_lock_path(target_dir))
.map_err(|e| E::from(ManifestError::Io(e)))?;
let mut lock = fd_lock::RwLock::new(file);
let _guard = lock.write().map_err(|e| E::from(ManifestError::Io(e)))?;
f()
}
const MANIFEST_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Origin {
Bundled,
Registry,
User,
}
impl Origin {
pub fn is_framework_owned(self) -> bool {
matches!(self, Origin::Bundled)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManifestEntry {
pub source_chain: Vec<String>,
pub checksum: String,
pub deployed_at: String,
pub origin: Origin,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentManifest {
pub version: u32,
pub managed: HashMap<String, ManifestEntry>,
}
impl Default for AgentManifest {
fn default() -> Self {
Self {
version: MANIFEST_VERSION,
managed: HashMap::new(),
}
}
}
pub fn checksum(content: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(content.as_bytes());
let digest = hasher.finalize();
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
hex.push_str(&format!("{byte:02x}"));
}
hex
}
impl AgentManifest {
pub fn load_checked(target_dir: &Path) -> ManifestLoad {
let path = target_dir.join(MANIFEST_FILE);
match std::fs::read_to_string(&path) {
Ok(raw) => match serde_json::from_str::<AgentManifest>(&raw) {
Ok(m) => ManifestLoad::Ok(m),
Err(e) => ManifestLoad::Corrupt(format!("{path}: {e}", path = path.display())),
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => ManifestLoad::Ok(Self::default()),
Err(_) => ManifestLoad::Ok(Self::default()),
}
}
pub fn load(target_dir: &Path) -> Self {
match Self::load_checked(target_dir) {
ManifestLoad::Ok(m) => m,
ManifestLoad::Corrupt(_) => Self::default(),
}
}
pub fn save(&self, target_dir: &Path) -> Result<()> {
std::fs::create_dir_all(target_dir)?;
let path = target_dir.join(MANIFEST_FILE);
let json = serde_json::to_string_pretty(self)?;
atomic_write(&path, &json)?;
Ok(())
}
pub fn is_managed(&self, filename: &str) -> bool {
self.managed.contains_key(filename)
}
pub fn checksum_matches(&self, filename: &str, content: &str) -> bool {
self.managed
.get(filename)
.is_some_and(|entry| entry.checksum == checksum(content))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
fn sample_entry() -> ManifestEntry {
ManifestEntry {
source_chain: vec!["base-agent".into(), "engineer".into()],
checksum: checksum("hello world"),
deployed_at: "2026-05-16T00:00:00Z".into(),
origin: Origin::Bundled,
}
}
#[test]
fn manifest_load_missing_returns_empty() {
let tmp = TempDir::new().unwrap();
let manifest = AgentManifest::load(tmp.path());
assert_eq!(manifest.version, MANIFEST_VERSION);
assert!(manifest.managed.is_empty());
}
#[test]
fn manifest_load_checked_missing_returns_ok() {
let tmp = TempDir::new().unwrap();
let result = AgentManifest::load_checked(tmp.path());
assert!(
matches!(result, ManifestLoad::Ok(m) if m.managed.is_empty()),
"expected Ok(empty) for missing manifest"
);
}
#[test]
fn manifest_load_corrupt_returns_corrupt() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join(MANIFEST_FILE), b"not valid json{{{").unwrap();
let result = AgentManifest::load_checked(tmp.path());
assert!(
matches!(result, ManifestLoad::Corrupt(_)),
"expected Corrupt for malformed manifest"
);
}
#[test]
fn manifest_load_truncated_returns_corrupt() {
let tmp = TempDir::new().unwrap();
fs::write(
tmp.path().join(MANIFEST_FILE),
b"{\"version\":1,\"managed\":{",
)
.unwrap();
let result = AgentManifest::load_checked(tmp.path());
assert!(
matches!(result, ManifestLoad::Corrupt(_)),
"expected Corrupt for truncated manifest"
);
}
#[test]
fn manifest_round_trip() {
let tmp = TempDir::new().unwrap();
let mut manifest = AgentManifest::default();
manifest
.managed
.insert("engineer.md".into(), sample_entry());
manifest.save(tmp.path()).unwrap();
let loaded = AgentManifest::load(tmp.path());
assert_eq!(loaded, manifest);
assert!(tmp.path().join(MANIFEST_FILE).exists());
}
#[test]
fn manifest_save_is_atomic() {
let tmp = TempDir::new().unwrap();
let mut manifest = AgentManifest::default();
manifest
.managed
.insert("engineer.md".into(), sample_entry());
manifest.save(tmp.path()).unwrap();
let tmp_path = tmp.path().join(MANIFEST_FILE).with_extension("tmp");
assert!(
!tmp_path.exists(),
".tmp staging file must be removed after successful save"
);
}
#[test]
fn atomic_write_leaves_old_intact_on_interrupted_write() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("manifest.json");
fs::write(&path, "original content").unwrap();
let orphan = temp_path(&path);
fs::write(&orphan, "incomplete new content").unwrap();
assert!(
orphan
.file_name()
.unwrap()
.to_string_lossy()
.ends_with(".tmp"),
"the orphan cleaner matches on the `.tmp` suffix: {}",
orphan.display()
);
assert_eq!(fs::read_to_string(&path).unwrap(), "original content");
atomic_write(&path, "new content").unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "new content");
}
#[test]
fn manifest_checksum_matches() {
let mut manifest = AgentManifest::default();
manifest
.managed
.insert("engineer.md".into(), sample_entry());
assert!(manifest.checksum_matches("engineer.md", "hello world"));
assert!(!manifest.checksum_matches("engineer.md", "hello world!"));
assert!(!manifest.checksum_matches("other.md", "hello world"));
}
#[test]
fn manifest_is_managed() {
let mut manifest = AgentManifest::default();
manifest
.managed
.insert("engineer.md".into(), sample_entry());
assert!(manifest.is_managed("engineer.md"));
assert!(!manifest.is_managed("user-agent.md"));
}
#[test]
fn origin_framework_ownership_tiers() {
assert!(Origin::Bundled.is_framework_owned());
assert!(!Origin::User.is_framework_owned());
assert!(!Origin::Registry.is_framework_owned());
}
#[test]
fn manifest_lock_path_is_a_sidecar() {
let dir = Path::new("/some/agents");
assert_eq!(
manifest_lock_path(dir),
dir.join(".trusty-mpm-manifest.json.lock")
);
}
#[test]
fn atomic_write_temp_names_are_unique_per_attempt() {
let tmp = TempDir::new().unwrap();
let target = tmp.path().join(MANIFEST_FILE);
let a = temp_path(&target);
let b = temp_path(&target);
assert_ne!(a, b, "two attempts must not share a scratch path");
assert!(
a.file_name()
.unwrap()
.to_string_lossy()
.contains(&std::process::id().to_string()),
"the scratch name must carry the writer's pid: {}",
a.display()
);
assert_eq!(
a.parent(),
target.parent(),
"publish must stay a same-fs rename"
);
}
#[test]
fn atomic_write_leaves_no_scratch_behind() {
let tmp = TempDir::new().unwrap();
let target = tmp.path().join(MANIFEST_FILE);
atomic_write(&target, "{}").unwrap();
assert_eq!(fs::read_to_string(&target).unwrap(), "{}");
let leftovers: Vec<String> = fs::read_dir(tmp.path())
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.collect();
assert!(leftovers.is_empty(), "stale scratch files: {leftovers:?}");
}
#[test]
fn manifest_lock_serialises_concurrent_writers() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_path_buf();
AgentManifest::default().save(&dir).unwrap();
let handles: Vec<_> = (0..8)
.map(|i| {
let dir = dir.clone();
std::thread::spawn(move || {
with_agent_manifest_lock::<(), ManifestError, _>(&dir, || {
let mut m = AgentManifest::load(&dir);
m.managed.insert(format!("agent-{i}.md"), sample_entry());
std::thread::sleep(std::time::Duration::from_millis(5));
m.save(&dir)
})
.unwrap();
})
})
.collect();
for h in handles {
h.join().unwrap();
}
let final_manifest = AgentManifest::load(&dir);
assert_eq!(
final_manifest.managed.len(),
8,
"every writer's entry must survive: {:?}",
final_manifest.managed.keys().collect::<Vec<_>>()
);
}
#[test]
fn manifest_lock_releases_so_a_second_acquisition_succeeds() {
let tmp = TempDir::new().unwrap();
for _ in 0..3 {
with_agent_manifest_lock::<(), ManifestError, _>(tmp.path(), || Ok(())).unwrap();
}
}
#[test]
fn checksum_is_stable_and_distinct() {
assert_eq!(checksum("abc"), checksum("abc"));
assert_ne!(checksum("abc"), checksum("abd"));
assert_eq!(checksum("anything").len(), 64);
}
}