Skip to main content

agentmux_srv_core/backend/
history_registry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agents the History pane lists (`history.agents`): every agent
5//! whose history the global transcript store holds, with how much of it is
6//! current and how much archived. Read from the store's file records only,
7//! never the transcripts, so it stays fast however large they are. An agent
8//! that was deleted keeps its history and is listed too.
9
10use 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/// What the agent registry says about a definition id.
17#[derive(Debug, Clone, Default)]
18pub struct AgentInfo {
19    pub name: String,
20    pub provider: String,
21    /// The definition it was forked from; empty for an agent that isn't a fork.
22    pub fork_of: String,
23}
24
25/// Which agent a zone belongs to, and whether it's an archive.
26fn 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
36/// Every agent with history in `store`, most recently active first. `info`
37/// looks a definition id up in the agent registry; `None` is a deleted agent.
38pub 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        // A zone found corrupt is left out of the list, not the whole list failed for it
45        // (`transcript::damage`): the rest of the agents are still there.
46        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;