Skip to main content

agentmux_srv/server/remote_ops/
move_capacity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What this computer has to take an agent in, for the preflight and the offer
5//! (docs/specs/SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER_2026_11_24.md section 7, row m). The preflight reports the numbers; an
6//! offer for an archive this computer cannot hold is refused with them and what to free, and there is no override.
7//! A figure that cannot be read is not a refusal: it is reported as unknown.
8
9use std::path::{Path, PathBuf};
10
11use serde_json::{json, Value};
12
13use crate::server::state::AppState;
14
15/// Kept free after the archive is stored and placed: the archive is written twice (staged, then placed).
16const DISK_RESERVE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
17/// Memory that must be free for the agent's harness to start on top of what runs here already.
18const MEMORY_FLOOR_BYTES: u64 = 2 * 1024 * 1024 * 1024;
19
20/// What this computer has now. `None` is a figure that could not be read.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub(super) struct Capacity {
23    pub free_disk_bytes: Option<u64>,
24    pub free_memory_bytes: Option<u64>,
25    pub agents_running: u64,
26}
27
28impl Capacity {
29    /// What the preflight tells the asker.
30    pub(super) fn facts(&self) -> Value {
31        json!({
32            "free_disk_bytes": self.free_disk_bytes,
33            "free_memory_bytes": self.free_memory_bytes,
34            "agents_running": self.agents_running,
35        })
36    }
37}
38
39/// The free space of the volume that holds `path`: the disk whose mount point is the longest prefix of it.
40pub(super) fn free_on(path: &Path, volumes: &[(PathBuf, u64)]) -> Option<u64> {
41    volumes.iter().filter(|(mount, _)| path.starts_with(mount)).max_by_key(|(mount, _)| mount.components().count()).map(|(_, free)| *free)
42}
43
44/// `path` as the filesystem resolves it, so it can be matched against the volumes' mount points: a link in it (the data directory, or
45/// a parent of it, pointing to another volume) is followed, and Windows' verbatim prefix is dropped, as the mount points have none.
46/// The folder may not exist yet: the nearest one that does is resolved and the rest put back after it.
47pub(super) fn resolved(path: &Path) -> PathBuf {
48    let mut rest = Vec::new();
49    let mut at = path;
50    loop {
51        if let Ok(real) = at.canonicalize() {
52            let mut out = without_verbatim_prefix(real);
53            out.extend(rest.iter().rev());
54            return out;
55        }
56        match (at.parent(), at.file_name()) {
57            (Some(parent), Some(name)) => {
58                rest.push(name.to_os_string());
59                at = parent;
60            }
61            _ => return path.to_path_buf(),
62        }
63    }
64}
65
66/// `\\?\C:\x` as `C:\x` and `\\?\UNC\host\share` as `\\host\share`; anything else as it is.
67pub(super) fn without_verbatim_prefix(path: PathBuf) -> PathBuf {
68    let text = path.to_string_lossy().into_owned();
69    if let Some(unc) = text.strip_prefix(r"\\?\UNC\") {
70        return PathBuf::from(format!(r"\\{unc}"));
71    }
72    match text.strip_prefix(r"\\?\") {
73        Some(plain) => PathBuf::from(plain),
74        None => path,
75    }
76}
77
78#[cfg(test)]
79thread_local! {
80    /// What a test says this computer has; without it a test machine has plenty, whatever it really has.
81    pub(super) static PRETEND: std::cell::RefCell<Option<Capacity>> = const { std::cell::RefCell::new(None) };
82}
83
84/// This computer's figures: free disk where incoming agents are staged, free memory, and the agents running now.
85pub(super) fn measure(state: &AppState) -> Capacity {
86    #[cfg(test)]
87    {
88        let plenty = Capacity { free_disk_bytes: Some(u64::MAX / 4), free_memory_bytes: Some(u64::MAX / 4), agents_running: 0 };
89        return PRETEND.with(|p| p.borrow().clone()).unwrap_or(plenty);
90    }
91    #[cfg(not(test))]
92    measure_here(state)
93}
94
95#[cfg(not(test))]
96fn measure_here(state: &AppState) -> Capacity {
97    let staging = resolved(&crate::backend::base::get_mux_data_dir().join("move-staging"));
98    let disks = sysinfo::Disks::new_with_refreshed_list();
99    let volumes: Vec<(PathBuf, u64)> = disks.list().iter().map(|d| (d.mount_point().to_path_buf(), d.available_space())).collect();
100    let mut sys = sysinfo::System::new();
101    sys.refresh_memory();
102    let memory = sys.available_memory();
103    let running = crate::server::agent_runtime::list(state, agentmux_common::time::now_ms_u64())
104        .into_iter()
105        .filter(|r| r.state != crate::server::agent_runtime::AgentRuntimeState::Stopped)
106        .count() as u64;
107    Capacity { free_disk_bytes: free_on(&staging, &volumes), free_memory_bytes: (memory > 0).then_some(memory), agents_running: running }
108}
109
110fn gib(bytes: u64) -> String {
111    format!("{:.1} GiB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
112}
113
114/// Why this computer cannot take an archive of `archive_bytes`, in numbers and what to free; none when it can (or when a
115/// figure is unknown: that is not a reason to refuse).
116pub(super) fn shortfall(c: &Capacity, archive_bytes: u64) -> Option<String> {
117    let needs_disk = archive_bytes.saturating_mul(2).saturating_add(DISK_RESERVE_BYTES);
118    if let Some(free) = c.free_disk_bytes.filter(|free| *free < needs_disk) {
119        return Some(format!(
120            "this computer has {} free where an incoming agent is kept and needs {} for an archive of {}: free disk space here, then ask again",
121            gib(free),
122            gib(needs_disk),
123            gib(archive_bytes)
124        ));
125    }
126    if let Some(free) = c.free_memory_bytes.filter(|free| *free < MEMORY_FLOOR_BYTES) {
127        return Some(format!(
128            "this computer has {} of memory free and needs at least {} for the agent to start; it already runs {} agent(s): stop something here, then ask again",
129            gib(free),
130            gib(MEMORY_FLOOR_BYTES),
131            c.agents_running
132        ));
133    }
134    None
135}
136
137#[cfg(test)]
138#[path = "move_capacity_tests.rs"]
139mod tests;