use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use objectiveai_sdk::lockfile::LockClaim;
pub struct AgentInstanceRegistry {
state_dir: PathBuf,
open: HashMap<String, LockClaim>,
attempted: HashSet<String>,
tag_claim: Option<LockClaim>,
}
impl AgentInstanceRegistry {
pub fn new(state_dir: PathBuf) -> Self {
Self {
state_dir,
open: HashMap::new(),
attempted: HashSet::new(),
tag_claim: None,
}
}
pub fn preseed(&mut self, hier: String, claim: LockClaim) {
self.attempted.insert(hier.clone());
self.open.insert(hier, claim);
}
pub fn hold_tag_claim(&mut self, claim: LockClaim) {
self.tag_claim = Some(claim);
}
pub async fn observe(&mut self, hier: &str) {
if !self.attempted.insert(hier.to_string()) {
return;
}
let (dir, key) = crate::command::agents::locks::agent_instance_lock(&self.state_dir, hier);
if let Some(claim) = objectiveai_sdk::lockfile::try_acquire(&dir, &key, "").await {
self.open.insert(hier.to_string(), claim);
if let Some(tag_claim) = self.tag_claim.take() {
let _ = tag_claim.release();
}
}
}
pub fn destroy(&mut self, hier: &str) {
if let Some(claim) = self.open.remove(hier) {
let _ = claim.release();
}
}
}
impl Drop for AgentInstanceRegistry {
fn drop(&mut self) {
for (_, claim) in self.open.drain() {
let _ = claim.release();
}
if let Some(claim) = self.tag_claim.take() {
let _ = claim.release();
}
}
}