Skip to main content

agentmux_srv_core/backend/
history_usage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How much conversation history is on this machine, and what it is made of.
5//! The running total in the status bar and its details panel read this. The total is the
6//! shared conversation-history store's pages in use; it is broken into kinds (messages,
7//! jekts, thinking, tool calls, tool results, other) by `transcript::kinds`, each kind's
8//! share of the history applied to that stored total.
9//!
10//! History is kept forever, so this only measures. It reads the store's page counts and the
11//! per-zone counts the owner srv keeps, never the conversations themselves, and callers get a
12//! cached result.
13
14use std::path::{Path, PathBuf};
15
16use crate::backend::rpc_types::{HistoryReclaim, HistoryUsage, HistoryUsageAgent, HistoryUsageKind, HistoryUsageProblem};
17use crate::backend::storage::filestore::FileStore;
18
19/// Where the store lives. Built from the machine's data roots, or from a temp folder in tests.
20#[derive(Debug, Clone)]
21pub struct Roots {
22    /// The shared conversation-history database (`filestore.db`, with its WAL).
23    pub transcripts_db: PathBuf,
24}
25
26impl Roots {
27    /// The roots on this machine, or `None` when they can't be resolved.
28    pub fn on_this_machine() -> Option<Roots> {
29        Some(Roots { transcripts_db: crate::registry::resolve_shared_transcripts_dir()?.join("filestore.db") })
30    }
31}
32
33fn file_size(path: &Path) -> u64 {
34    match std::fs::metadata(path) {
35        Ok(m) if m.is_file() => m.len(),
36        _ => 0,
37    }
38}
39
40/// Measure the history. `transcripts` is the shared conversation store; `name_of` turns a
41/// definition id into its name.
42pub fn compute(
43    roots: &Roots,
44    transcripts: Option<&FileStore>,
45    name_of: impl Fn(&str) -> Option<String>,
46    now_ms: u64,
47) -> HistoryUsage {
48    // The data the shared store holds, not the file around it: its free pages are space it
49    // reuses and hands back by itself.
50    let (total_bytes, unreadable) = stored_bytes(roots, transcripts);
51    let mut problem = unreadable.or_else(|| waiting_problem(roots.transcripts_db.parent()));
52    let kinds = match transcripts {
53        Some(t) => kinds_of(t, total_bytes).unwrap_or_else(|e| {
54            problem.get_or_insert_with(|| HistoryUsageProblem { key: "breakdown_unreadable".into(), detail: Some(e.to_string()) });
55            Vec::new()
56        }),
57        None => Vec::new(),
58    };
59    HistoryUsage { total_bytes, kinds, problem, agents: largest_agents(transcripts, name_of), computed_at_ms: now_ms }
60}
61
62/// The shared store's stored bytes, and what went wrong if they could not be read. With the
63/// store open that is its pages in use (compressed frames, parts not yet framed, indexes; the
64/// WAL's pages are in the page count). Without it, the files' lengths.
65fn stored_bytes(roots: &Roots, transcripts: Option<&FileStore>) -> (u64, Option<HistoryUsageProblem>) {
66    let mut problem = None;
67    let stats = transcripts.and_then(|t| match t.page_stats() {
68        Ok(s) => Some(s),
69        Err(e) => {
70            tracing::warn!(error = %e, "history.usage: couldn't read the transcript store's page counts");
71            problem = Some(HistoryUsageProblem { key: "store_unreadable".into(), detail: None });
72            None
73        }
74    });
75    if let Some((page_size, page_count, free_pages, _)) = stats {
76        let (size, count, free) = (page_size.max(0) as u64, page_count.max(0) as u64, free_pages.max(0) as u64);
77        return (count.saturating_sub(free) * size, None);
78    }
79    let mut bytes = file_size(&roots.transcripts_db);
80    for ext in ["-wal", "-shm"] {
81        let mut name = roots.transcripts_db.as_os_str().to_owned();
82        name.push(ext);
83        bytes += file_size(Path::new(&name));
84    }
85    (bytes, problem)
86}
87
88/// What `total` is made of: each kind's share of the history's logical bytes, applied to the stored
89/// total. A kind's share is exact in logical bytes (`transcript::kinds`); stored, it is proportional
90/// (kinds compress differently). What is not counted yet, the indexes and the rest of the store
91/// are `other`, and the six add up to `total`.
92fn kinds_of(store: &FileStore, total: u64) -> Result<Vec<HistoryUsageKind>, crate::backend::storage::error::StoreError> {
93    use crate::backend::transcript::kinds::{self, Kind, KINDS};
94    let counted = kinds::totals(store);
95    let logical = store.logical_bytes()?.max(0) as u64;
96    // Counts never exceed what the files hold; if they do (a file shrank since), the counts are the whole.
97    let whole = logical.max(counted.sum()).max(1) as u128;
98    let share = |k: Kind| (u128::from(total) * u128::from(counted.get(k)) / whole) as u64;
99    let named: u64 = KINDS.iter().filter(|(k, _)| *k != Kind::Other).map(|(k, _)| share(*k)).sum();
100    Ok(KINDS
101        .iter()
102        .map(|(k, key)| HistoryUsageKind {
103            key: (*key).to_string(),
104            bytes: if *k == Kind::Other { total.saturating_sub(named) } else { share(*k) },
105        })
106        .collect())
107}
108
109/// Compression held off by a running build that cannot read it: the one problem a person can act
110/// on (close that build). Only the srv that owns the store runs the framer and any srv may answer
111/// this, so it is checked here the way the framer checks it.
112fn waiting_problem(store_dir: Option<&Path>) -> Option<HistoryUsageProblem> {
113    use crate::backend::transcript::framer;
114    if !framer::enabled() {
115        return None;
116    }
117    store_dir
118        .and_then(framer::who_blocks)
119        .map(|who| HistoryUsageProblem { key: "compression_waiting".into(), detail: Some(who) })
120}
121
122/// [`waiting_problem`] for the shared store on this machine, for a cached answer: it can change
123/// any minute and costs little to read.
124pub fn waiting_now() -> Option<HistoryUsageProblem> {
125    let roots = Roots::on_this_machine()?;
126    waiting_problem(roots.transcripts_db.parent())
127}
128
129/// The reclaim's request and last result, from the files beside the store.
130pub fn reclaim_of(db: &Path) -> HistoryReclaim {
131    let (marker, last) = crate::backend::storage::filestore::reclaim::status(db);
132    let last = last.unwrap_or_default();
133    HistoryReclaim {
134        pending: marker.is_some(),
135        waiting_for: marker.as_ref().and_then(|m| m.waiting_for.clone()),
136        last_error: marker.as_ref().and_then(|m| m.last_error.clone()).or(last.error.clone()),
137        last_done_ms: if last.error.is_none() { last.at_ms } else { 0 },
138        last_before_bytes: last.before_bytes,
139        last_after_bytes: last.after_bytes,
140    }
141}
142
143/// The agents with the most pane history, largest first.
144fn largest_agents(transcripts: Option<&FileStore>, name_of: impl Fn(&str) -> Option<String>) -> Vec<HistoryUsageAgent> {
145    const TOP: usize = 12;
146    let Some(fs) = transcripts else { return Vec::new() };
147    let Ok(zones) = fs.zone_ids_with_prefix("agent:") else { return Vec::new() };
148    let mut agents: Vec<HistoryUsageAgent> = zones
149        .iter()
150        .filter_map(|zone| {
151            let id = zone.strip_prefix("agent:")?.strip_suffix(":current")?;
152            if crate::backend::transcript::damage::is_damaged(zone) {
153                return None;
154            }
155            let file = match fs.stat(zone, crate::backend::agent_session::OUTPUT_FILE) {
156                Ok(file) => file?,
157                Err(e) => {
158                    crate::backend::transcript::damage::note_if_shared(fs, zone, "history size", &e);
159                    return None;
160                }
161            };
162            let bytes = file.size.max(0) as u64;
163            (bytes > 0).then(|| HistoryUsageAgent {
164                definition_id: id.to_string(),
165                name: name_of(id).unwrap_or_else(|| id.to_string()),
166                bytes,
167            })
168        })
169        .collect();
170    agents.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name)));
171    agents.truncate(TOP);
172    agents
173}
174
175#[cfg(test)]
176#[path = "history_usage_tests.rs"]
177mod tests;