use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Duration, Utc};
use rusty_agent_runtime::agents::{CapabilityManifest, SupervisionAttempt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::tasks::TaskRecord;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct AgentRecord {
pub agent_id: String,
pub manifest: CapabilityManifest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub team_id: Option<String>,
#[serde(default)]
pub metadata: Value,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "AgentSupervision::is_empty")]
pub supervision: AgentSupervision,
}
impl AgentRecord {
pub(crate) fn wire(&self) -> Value {
let mut value =
serde_json::to_value(self).expect("AgentRecord serialization is infallible");
if let Value::Object(ref mut map) = value {
map.remove("supervision");
}
value
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub(crate) struct AgentSupervision {
#[serde(default)]
pub attempts: Vec<SupervisionAttempt>,
#[serde(default)]
pub escalated: bool,
#[serde(default)]
pub deadline_breached: bool,
#[serde(default)]
pub suppressed_failures: u64,
}
impl AgentSupervision {
pub(crate) fn is_empty(&self) -> bool {
self == &Self::default()
}
pub(crate) fn next_ordinal(&self) -> u32 {
self.attempts.len() as u32 + 1
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ActivationLease {
pub agent_id: String,
pub owner: String,
pub fencing: u64,
pub expires_at: DateTime<Utc>,
pub acquired_at: DateTime<Utc>,
}
impl ActivationLease {
pub(crate) fn held_by(&self, owner: &str, fencing: u64, now: DateTime<Utc>) -> bool {
self.owner == owner && self.fencing == fencing && self.expires_at > now
}
}
#[derive(Debug, Clone)]
pub(crate) enum ActivationOutcome {
Claimed(Box<ActivationLease>),
Held(Box<ActivationLease>),
}
#[derive(Debug, Clone)]
pub(crate) enum ActivationMutation {
Applied(Box<ActivationLease>),
FencingLost,
Unknown,
}
#[derive(Debug, Clone)]
pub(crate) enum MailboxClaim {
Claimed(Box<TaskRecord>),
Empty,
ActivationLost,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct MailboxClaimScope<'a> {
pub agent_id: &'a str,
pub recipient: &'a str,
pub owner: &'a str,
pub fencing: u64,
}
pub(crate) fn validate_recipient(recipient: &str) -> Result<(), String> {
let Some(agent_id) = rusty_agent_runtime::agents::agent_id_from_recipient(recipient) else {
return Err(
"`recipient` must be a mailbox address of the form `agent:{agent_id}`".to_string(),
);
};
let ok = !agent_id.is_empty()
&& agent_id.len() <= 256
&& agent_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
if ok {
Ok(())
} else {
Err("`recipient` agent id must match [A-Za-z0-9._-] and be 1..=256 chars".to_string())
}
}
pub(crate) fn dir(root: &Path) -> PathBuf {
root.join("agents")
}
pub(crate) fn lease_dir(root: &Path) -> PathBuf {
root.join("agent_leases")
}
async fn persist_record<T: Serialize>(dir: &Path, id: &str, record: &T) -> io::Result<()> {
tokio::fs::create_dir_all(dir).await?;
let bytes = serde_json::to_vec_pretty(record)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let path = dir.join(format!("{id}.json"));
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let tmp = dir.join(format!("{id}.tmp"));
tokio::fs::write(&tmp, bytes).await?;
tokio::fs::rename(&tmp, path).await
}
fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_json_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
}
fn load_records<T: serde::de::DeserializeOwned>(
dir: &Path,
what: &str,
id_of: impl Fn(&T) -> String,
) -> HashMap<String, T> {
let mut out = HashMap::new();
let mut files = Vec::new();
collect_json_files(dir, &mut files);
for path in files {
let parsed = std::fs::read_to_string(&path)
.ok()
.and_then(|raw| serde_json::from_str::<T>(&raw).ok());
match parsed {
Some(record) => {
out.insert(id_of(&record), record);
}
None => {
tracing::warn!(path = %path.display(), "skipping unreadable {what} file")
}
}
}
out
}
pub(crate) async fn persist(root: &Path, record: &AgentRecord) -> io::Result<()> {
persist_record(&dir(root), &record.agent_id, record).await
}
pub(crate) fn load(root: &Path) -> HashMap<String, AgentRecord> {
load_records(&dir(root), "agent", |record: &AgentRecord| {
record.agent_id.clone()
})
}
pub(crate) async fn persist_lease(root: &Path, lease: &ActivationLease) -> io::Result<()> {
persist_record(&lease_dir(root), &lease.agent_id, lease).await
}
pub(crate) async fn remove_lease(root: &Path, agent_id: &str) -> io::Result<()> {
let path = lease_dir(root).join(format!("{agent_id}.json"));
match tokio::fs::remove_file(&path).await {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
pub(crate) fn load_leases(root: &Path) -> HashMap<String, ActivationLease> {
load_records(
&lease_dir(root),
"agent lease",
|lease: &ActivationLease| lease.agent_id.clone(),
)
}
pub(crate) fn lease_duration(lease_ms: u64) -> Duration {
Duration::milliseconds(lease_ms.min(i64::MAX as u64) as i64)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn record() -> AgentRecord {
let manifest = CapabilityManifest::new("researcher", "researcher/1.4.0");
AgentRecord {
agent_id: "acme/researcher-7".to_string(),
manifest,
team_id: None,
metadata: json!({"team": "qa"}),
created_at: Utc::now(),
supervision: AgentSupervision::default(),
}
}
fn lease() -> ActivationLease {
ActivationLease {
agent_id: "acme/researcher-7".to_string(),
owner: "host-1".to_string(),
fencing: 3,
expires_at: Utc::now() + Duration::seconds(30),
acquired_at: Utc::now(),
}
}
#[test]
fn held_by_checks_owner_fencing_and_liveness() {
let lease = lease();
let now = Utc::now();
assert!(lease.held_by("host-1", 3, now));
assert!(!lease.held_by("host-2", 3, now), "wrong owner");
assert!(!lease.held_by("host-1", 2, now), "stale fencing ordinal");
assert!(
!lease.held_by("host-1", 3, now + Duration::seconds(31)),
"expired lease"
);
}
#[test]
fn recipient_validation_accepts_only_mailbox_addresses() {
assert!(validate_recipient("agent:researcher-7").is_ok());
assert!(validate_recipient("agent:team.eu-west_2").is_ok());
assert!(validate_recipient("pool-default").is_err());
assert!(validate_recipient("agent:").is_err());
assert!(validate_recipient("agent:bad/id").is_err());
assert!(validate_recipient("agent:bad id").is_err());
assert!(validate_recipient(&format!("agent:{}", "x".repeat(257))).is_err());
}
#[tokio::test]
async fn registry_and_lease_files_round_trip_with_corrupt_tolerance() {
let root = std::env::temp_dir().join(format!("rusty-agents-test-{}", uuid::Uuid::new_v4()));
persist(&root, &record()).await.unwrap();
persist_lease(&root, &lease()).await.unwrap();
std::fs::create_dir_all(dir(&root)).unwrap();
std::fs::write(dir(&root).join("broken.json"), b"{nope").unwrap();
let agents = load(&root);
assert_eq!(agents.len(), 1);
assert_eq!(
agents["acme/researcher-7"].manifest.agent_kind,
"researcher"
);
let leases = load_leases(&root);
assert_eq!(leases.len(), 1);
assert_eq!(leases["acme/researcher-7"].fencing, 3);
remove_lease(&root, "acme/researcher-7").await.unwrap();
assert!(load_leases(&root).is_empty());
remove_lease(&root, "acme/researcher-7").await.unwrap();
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn agent_record_wave2_fields_are_additive_and_wire_strips_supervision() {
let wave1_shape = json!({
"agent_id": "acme/researcher-7",
"manifest": {"agent_kind": "researcher", "manifest_version": "researcher/1.4.0"},
"metadata": null,
"created_at": Utc::now(),
});
let pristine: AgentRecord = serde_json::from_value(wave1_shape).unwrap();
assert_eq!(pristine.team_id, None);
assert!(pristine.supervision.is_empty());
let stored = serde_json::to_value(&pristine).unwrap();
assert!(stored.get("team_id").is_none());
assert!(stored.get("supervision").is_none());
let mut supervised = record();
supervised.team_id = Some("squad-1".into());
supervised.supervision.escalated = true;
supervised.supervision.suppressed_failures = 2;
let stored = serde_json::to_value(&supervised).unwrap();
assert_eq!(stored["team_id"], json!("squad-1"));
assert_eq!(stored["supervision"]["escalated"], json!(true));
let wire = supervised.wire();
assert!(wire.get("supervision").is_none());
assert_eq!(wire["team_id"], json!("squad-1"));
assert_eq!(wire["manifest"]["agent_kind"], json!("researcher"));
let back: AgentRecord = serde_json::from_value(stored).unwrap();
assert!(back.supervision.escalated);
assert_eq!(back.supervision.suppressed_failures, 2);
assert_eq!(back.supervision.next_ordinal(), 1);
}
}