Skip to main content

agentmux_srv/server/remote_ops/
disk_ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `app.disk.report`: what is filling this machine's disk that AgentMux made (spec ยง4.3), a read.
5//! The free space of the volumes AgentMux uses, the largest build folders (`target`) in the agents'
6//! workspaces with the agent that owns each, and the folders of older versions in this channel.
7//! Paths are relative to the AgentMux home or the agents' folder; nothing outside them is named.
8//!
9//! Measuring a large `target` takes long, so the walk has a time budget and says when it stopped
10//! early (`complete: false`): the sizes it gives are then lower bounds. It deletes nothing.
11
12use std::path::{Path, PathBuf};
13use std::time::{Duration, Instant};
14
15use serde_json::{json, Value};
16
17use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
18use crate::backend::build_cache as bc;
19
20/// How long the measuring may take, inside the transport's 25 s limit.
21const BUDGET: Duration = Duration::from_secs(18);
22/// How many build folders and old versions are listed (largest first).
23const LISTED: usize = 20;
24
25/// How many entries are read between two looks at the clock.
26const CHECK_EVERY: u32 = 512;
27
28/// The size of everything under `p`, stopping at `deadline`: (bytes, whether the whole tree was counted).
29/// A folder or file that cannot be read makes the count a lower bound, as running out of time does; one that
30/// vanished meanwhile (a build removing it) does not.
31fn dir_size_until(p: &Path, deadline: Instant) -> (u64, bool) {
32    if Instant::now() >= deadline {
33        return (0, false);
34    }
35    let mut total = 0u64;
36    let mut whole = true;
37    let mut stack = vec![p.to_path_buf()];
38    let mut seen = 0u32;
39    while let Some(d) = stack.pop() {
40        let entries = match std::fs::read_dir(&d) {
41            Ok(entries) => entries,
42            Err(e) => {
43                whole &= e.kind() == std::io::ErrorKind::NotFound;
44                continue;
45            }
46        };
47        for entry in entries {
48            seen += 1;
49            if seen % CHECK_EVERY == 0 && Instant::now() >= deadline {
50                return (total, false);
51            }
52            let Ok(e) = entry else {
53                whole = false;
54                continue;
55            };
56            match e.file_type() {
57                Ok(t) if t.is_dir() => stack.push(e.path()),
58                Ok(_) => match e.metadata() {
59                    Ok(m) => total += m.len(),
60                    Err(err) => whole &= err.kind() == std::io::ErrorKind::NotFound,
61                },
62                Err(err) => whole &= err.kind() == std::io::ErrorKind::NotFound,
63            }
64        }
65    }
66    (total, whole)
67}
68
69/// A relative path with forward slashes, or just the last name when `p` is not under `base`.
70fn relative(p: &Path, base: &Path) -> String {
71    let shown = p.strip_prefix(base).unwrap_or_else(|_| Path::new(p.file_name().unwrap_or_default()));
72    shown.to_string_lossy().replace('\\', "/")
73}
74
75fn volume(path: &Path) -> Value {
76    match bc::disk_of(path) {
77        Some((free, total)) => json!({ "free_bytes": free, "total_bytes": total }),
78        None => Value::Null,
79    }
80}
81
82/// The `target` folders under `agents_root`, one entry per cargo clone, largest first.
83fn build_folders(agents_root: &Path, deadline: Instant) -> (Vec<Value>, u64, bool) {
84    let mut found: Vec<(u64, Value)> = Vec::new();
85    let mut complete = true;
86    let mut total = 0u64;
87    let workspaces: Vec<PathBuf> = std::fs::read_dir(agents_root)
88        .into_iter()
89        .flatten()
90        .flatten()
91        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
92        .map(|e| e.path())
93        .collect();
94    for workspace in workspaces {
95        for clone in bc::clones_in(&workspace) {
96            if Instant::now() >= deadline {
97                complete = false;
98                break;
99            }
100            let target = clone.join("target");
101            let (bytes, whole) = dir_size_until(&target, deadline);
102            let (mut incremental, mut whole) = (0u64, whole);
103            for root in bc::incremental_roots(&target) {
104                let (bytes, ok) = dir_size_until(&root, deadline);
105                incremental += bytes;
106                whole &= ok;
107            }
108            complete &= whole;
109            total += bytes;
110            found.push((
111                bytes,
112                json!({
113                    "clone": relative(&clone, agents_root),
114                    "target_bytes": bytes,
115                    "incremental_bytes": incremental,
116                    "complete": whole,
117                }),
118            ));
119        }
120    }
121    found.sort_by(|a, b| b.0.cmp(&a.0));
122    (found.into_iter().take(LISTED).map(|(_, v)| v).collect(), total, complete)
123}
124
125/// The other version folders of `channel` (`channels/<channel>/versions/<version>`), largest first.
126fn old_versions(home: &Path, channel: &str, live: &str, deadline: Instant) -> (Vec<Value>, bool) {
127    let versions = home.join("channels").join(channel).join("versions");
128    let mut complete = true;
129    let mut found: Vec<(u64, Value)> = std::fs::read_dir(&versions)
130        .into_iter()
131        .flatten()
132        .flatten()
133        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name().to_string_lossy() != live)
134        .map(|e| {
135            let (bytes, whole) = dir_size_until(&e.path(), deadline);
136            complete &= whole;
137            (bytes, json!({ "version": e.file_name().to_string_lossy(), "bytes": bytes, "complete": whole }))
138        })
139        .collect();
140    found.sort_by(|a, b| b.0.cmp(&a.0));
141    (found.into_iter().take(LISTED).map(|(_, v)| v).collect(), complete)
142}
143
144fn report(live_version: &str) -> Value {
145    let deadline = Instant::now() + BUDGET;
146    let paths = agentmux_common::data_paths::DataPaths::from_env();
147    let home = agentmux_common::data_paths::agentmux_root().ok();
148    let agents_root = crate::backend::build_cache_service::agents_root();
149    let (build, build_total, build_complete) = match &agents_root {
150        Some(root) => build_folders(root, deadline),
151        None => (Vec::new(), 0, true),
152    };
153    let (versions, versions_complete) = match (&home, &paths) {
154        (Some(home), Some(p)) => old_versions(home, &p.channel, live_version, deadline),
155        _ => (Vec::new(), true),
156    };
157    json!({
158        "data_volume": paths.as_ref().map_or(Value::Null, |p| volume(&p.data_dir)),
159        "agents_volume": agents_root.as_deref().map_or(Value::Null, volume),
160        "build_folders": build,
161        "build_folders_total_bytes": build_total,
162        "older_versions": versions,
163        "complete": build_complete && versions_complete && Instant::now() < deadline,
164        "note": "Build folders (cargo target) are rebuilt on demand; the hourly pass already prunes orphaned incremental folders. Older version folders are removed by a person, after checking nothing runs from them.",
165    })
166}
167
168pub(super) async fn disk_report(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
169    let version = state.version.clone();
170    tokio::task::spawn_blocking(move || report(&version))
171        .await
172        .map_err(|e| RemoteRefusal::failed(format!("measuring the disk: {e}")))
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn a_tree_is_counted_and_a_passed_deadline_stops_the_walk() {
181        let dir = tempfile::tempdir().unwrap();
182        std::fs::create_dir_all(dir.path().join("a/b")).unwrap();
183        std::fs::write(dir.path().join("a/one"), vec![0u8; 1000]).unwrap();
184        std::fs::write(dir.path().join("a/b/two"), vec![0u8; 500]).unwrap();
185        assert_eq!(dir_size_until(dir.path(), Instant::now() + Duration::from_secs(10)), (1500, true));
186        // Past its deadline nothing is walked at all, so a later walk after the budget ran out costs nothing.
187        assert_eq!(dir_size_until(dir.path(), Instant::now() - Duration::from_secs(1)), (0, false));
188        // A folder that is not there was removed meanwhile: counted as nothing, not as a gap.
189        assert_eq!(dir_size_until(&dir.path().join("gone"), Instant::now() + Duration::from_secs(10)), (0, true));
190        // A file where a folder was asked for cannot be read as one: the count is a lower bound.
191        let (_, whole) = dir_size_until(&dir.path().join("a/one"), Instant::now() + Duration::from_secs(10));
192        assert!(!whole);
193    }
194
195    #[test]
196    fn paths_are_relative_to_their_base_and_never_absolute() {
197        let base = Path::new("/home/u/.agentmux/agents");
198        assert_eq!(relative(&base.join("korp/agentmux"), base), "korp/agentmux");
199        assert_eq!(relative(Path::new("/elsewhere/clone"), base), "clone", "outside the base only the last name is given");
200    }
201
202    #[test]
203    fn older_versions_leave_out_the_live_one_and_are_largest_first() {
204        let home = tempfile::tempdir().unwrap();
205        let versions = home.path().join("channels/stable/versions");
206        for (v, size) in [("0.60.7", 100usize), ("0.60.8", 5000), ("0.60.9", 40)] {
207            std::fs::create_dir_all(versions.join(v)).unwrap();
208            std::fs::write(versions.join(v).join("f"), vec![0u8; size]).unwrap();
209        }
210        let (listed, complete) = old_versions(home.path(), "stable", "0.60.9", Instant::now() + Duration::from_secs(10));
211        assert!(complete);
212        let names: Vec<&str> = listed.iter().filter_map(|v| v["version"].as_str()).collect();
213        assert_eq!(names, ["0.60.8", "0.60.7"]);
214        assert_eq!(listed[0]["bytes"], 5000);
215    }
216}