agentmux_srv_core/backend/
history_registry.rs1use std::collections::BTreeMap;
11
12use crate::backend::agent_session::OUTPUT_FILE;
13use crate::backend::rpc_types::HistoryAgent;
14use crate::backend::storage::filestore::FileStore;
15
16#[derive(Debug, Clone, Default)]
18pub struct AgentInfo {
19 pub name: String,
20 pub provider: String,
21 pub fork_of: String,
23}
24
25fn agent_zone(zone: &str) -> Option<(&str, bool)> {
27 let rest = zone.strip_prefix("agent:")?;
28 if let Some(id) = rest.strip_suffix(":current") {
29 return (!id.is_empty() && !id.contains(':')).then_some((id, false));
30 }
31 let (id, ms) = rest.split_once(":archive:")?;
32 let valid = !id.is_empty() && !id.contains(':') && !ms.is_empty() && ms.bytes().all(|b| b.is_ascii_digit());
33 valid.then_some((id, true))
34}
35
36pub fn agents(store: &FileStore, info: impl Fn(&str) -> Option<AgentInfo>) -> Result<Vec<HistoryAgent>, String> {
39 use crate::backend::transcript::damage;
40 let zones = store.zone_ids_with_prefix("agent:").map_err(|e| format!("listing the transcript store: {e}"))?;
41 let mut by_id: BTreeMap<String, HistoryAgent> = BTreeMap::new();
42 for zone in &zones {
43 let Some((id, archived)) = agent_zone(zone) else { continue };
44 if damage::is_damaged(zone) {
47 continue;
48 }
49 let file = match store.stat(zone, OUTPUT_FILE) {
50 Ok(Some(file)) => file,
51 Ok(None) => continue,
52 Err(e) if damage::note_corrupt(zone, "history list", &e) => continue,
53 Err(e) => return Err(format!("reading {zone}: {e}")),
54 };
55 let row = by_id.entry(id.to_string()).or_insert_with(|| HistoryAgent { definition_id: id.to_string(), ..Default::default() });
56 let bytes = file.size.max(0) as u64;
57 if archived {
58 row.archives += 1;
59 row.archive_bytes += bytes;
60 } else {
61 row.current_bytes += bytes;
62 }
63 row.last_active_ms = row.last_active_ms.max(file.modts.max(0) as u64);
64 }
65 let mut rows: Vec<HistoryAgent> = by_id.into_values().collect();
66 for row in &mut rows {
67 match info(&row.definition_id) {
68 Some(agent) => {
69 row.name = agent.name;
70 row.provider = agent.provider;
71 if !agent.fork_of.is_empty() {
72 row.fork_of_name = info(&agent.fork_of).map(|p| p.name).unwrap_or_default();
73 row.fork_of = agent.fork_of;
74 }
75 }
76 None => row.deleted = true,
77 }
78 }
79 rows.sort_by(|a, b| b.last_active_ms.cmp(&a.last_active_ms).then_with(|| a.definition_id.cmp(&b.definition_id)));
80 Ok(rows)
81}
82
83#[cfg(test)]
84#[path = "history_registry_tests.rs"]
85mod tests;