Skip to main content

agentmux_srv_core/backend/
build_cache_service.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runs the build-cache cleanup (`build_cache.rs`) on a schedule and on a finished task, and
5//! warns agents when the disk runs low (`docs/specs/SPEC_BUILD_CACHE_CLEANUP_2026_10_26.md`).
6//!
7//! - Every 5 minutes: the free space of the disk that holds the agents' workspaces. When it is
8//!   low, a pass prunes orphans and abandoned clones at once; if it is still low afterwards, the
9//!   agents whose own workspace is large hear of it, about their own folders, and the host's
10//!   steward gets the summary for the whole computer. A note goes out again only after free space
11//!   falls a further few GB or the level gets worse, never on a timer alone, and only a critical
12//!   level starts a turn (`disk_notice.rs`; a file in the shared locks folder keeps the last
13//!   note, so two AgentMux channels do not both warn).
14//! - Every hour: the orphan pass over every local workspace.
15//! - When an agent completes a Kanban task: its own clones lose their `incremental` folders.
16
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::time::{Duration, SystemTime};
20
21use crate::backend::build_cache::{self as bc, Policy, Why};
22use crate::backend::disk_notice::{self as dn, Level};
23use crate::backend::obj::{self, Block};
24use crate::backend::storage::store::Store;
25use crate::backend::wconfig::ConfigState;
26
27const DISK_EVERY: Duration = Duration::from_secs(5 * 60);
28const HOURLY_EVERY: Duration = Duration::from_secs(3600);
29/// The first hourly pass waits this long after start, so it never competes with startup.
30const FIRST_HOURLY_AFTER: Duration = Duration::from_secs(10 * 60);
31/// After a warning that nobody received, the next attempt (which walks every build folder) waits
32/// this long.
33const RETRY_AFTER: Duration = Duration::from_secs(30 * 60);
34/// Unix seconds before which no warning is tried.
35static NEXT_TRY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
36/// How long a finished task's cleanup waits for another srv's pass, and how often it looks.
37const TASK_LOCK_WAIT: Duration = Duration::from_secs(15 * 60);
38const LOCK_POLL: Duration = Duration::from_millis(500);
39/// The key a held low-disk note is kept under: a newer one replaces it.
40const HOLD_KEY: &str = "low-disk";
41
42/// Where the agents' workspaces are: `~/.agentmux/agents`.
43pub fn agents_root() -> Option<PathBuf> {
44    if let Some(p) = std::env::var_os("AGENTMUX_AGENTS_ROOT").filter(|p| !p.is_empty()) {
45        return Some(PathBuf::from(p));
46    }
47    Some(dirs::home_dir()?.join(".agentmux").join("agents"))
48}
49
50/// How this srv was started, as far as the cleanup cares.
51#[derive(Default)]
52struct Start<'a> {
53    /// `AGENTMUX_HOME_OVERRIDE` is set: a test or capture instance with a home of its own.
54    own_home: bool,
55    /// `--headless` / `AGENTMUX_HEADLESS`: srv started directly, with no launcher.
56    headless: bool,
57    /// The binary sits in a source-tree output folder (`target/debug`, `target/release`, `dist/cef-dev*`),
58    /// whatever the environment it inherited says.
59    built_in_tree: bool,
60    /// The launcher's `AGENTMUX_RUNTIME_MODE` is `dev:<branch>`.
61    dev_mode: bool,
62    /// The data channel (`AGENTMUX_CHANNEL`): `stable` for a release, `local-<branch>` for a local
63    /// package, `dev-<branch>` for `task dev`.
64    channel: Option<&'a str>,
65    /// `AGENTMUX_BUILD_CACHE_CLEAN`: `Some(false)` never cleans, `Some(true)` cleans.
66    forced: Option<bool>,
67}
68
69/// What `AGENTMUX_BUILD_CACHE_CLEAN` says: `1`/`true`/`on` or `0`/`false`/`off`; anything else, or
70/// nothing, leaves the decision to how srv was started.
71fn forced_by(value: Option<&str>) -> Option<bool> {
72    match value?.trim().to_ascii_lowercase().as_str() {
73        "1" | "true" | "on" => Some(true),
74        "0" | "false" | "off" => Some(false),
75        _ => None,
76    }
77}
78
79/// Whether this srv may clean the real agents' folder: one started by its launcher on the real
80/// home, whatever its channel is called (the installed release, or a local package on a host that
81/// runs one: on such a host nothing else would ever clean). A `task dev` build, a headless srv, a
82/// binary run from a source tree, or an instance with a home of its own shares
83/// `~/.agentmux/agents` with the real instance but is not the one that should prune it (Kanban
84/// #4534). Decided from how srv was started; `AGENTMUX_BUILD_CACHE_CLEAN` overrides it: `0` never
85/// cleans, `1` cleans (except an instance with a home of its own, whose cleaning of the real
86/// folder is never wanted). Which one srv of several cleans at a time is [`host_lock`].
87fn may_clean(s: &Start) -> bool {
88    match s.forced {
89        Some(false) => false,
90        Some(true) => !s.own_home,
91        None => {
92            !s.own_home
93                && !s.headless
94                && !s.built_in_tree
95                && !s.dev_mode
96                && s.channel.is_some_and(|c| !c.starts_with("dev-"))
97        }
98    }
99}
100
101/// The lock that lets one srv on the host clean at a time, whatever channels are running. Held
102/// for the length of a pass; `None` when another srv holds it (its pass covers the same folders),
103/// when the file can't be opened, or when there is no home.
104fn host_lock() -> Option<std::fs::File> {
105    let path = dirs::home_dir()?.join(".agentmux").join("shared").join("locks").join("build-cache-clean.lock");
106    try_lock_file(&path)
107}
108
109/// [`host_lock`], waiting up to `wait` for the srv that holds it: for work only this pass does
110/// (an agent's finished task), which the holder's pass does not cover and nothing repeats.
111fn host_lock_within(wait: Duration) -> Option<std::fs::File> {
112    let path = dirs::home_dir()?.join(".agentmux").join("shared").join("locks").join("build-cache-clean.lock");
113    lock_file_within(&path, wait)
114}
115
116fn lock_file_within(path: &Path, wait: Duration) -> Option<std::fs::File> {
117    let deadline = std::time::Instant::now() + wait;
118    loop {
119        if let Some(file) = try_lock_file(path) {
120            return Some(file);
121        }
122        if std::time::Instant::now() >= deadline {
123            return None;
124        }
125        std::thread::sleep(LOCK_POLL);
126    }
127}
128
129fn try_lock_file(path: &Path) -> Option<std::fs::File> {
130    if let Some(dir) = path.parent() {
131        let _ = std::fs::create_dir_all(dir);
132    }
133    #[allow(clippy::suspicious_open_options)]
134    let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path).ok()?;
135    file.try_lock().ok()?;
136    Some(file)
137}
138
139/// [`may_clean`] for this process.
140pub fn this_srv_may_clean() -> bool {
141    let channel = agentmux_common::DataPaths::from_env().map(|p| p.channel);
142    may_clean(&Start {
143        own_home: std::env::var_os("AGENTMUX_HOME_OVERRIDE").is_some_and(|v| !v.is_empty()),
144        headless: crate::backend::startup_mode::headless(),
145        built_in_tree: agentmux_common::is_dev_self(),
146        dev_mode: matches!(agentmux_common::RuntimeMode::from_env(), Some(agentmux_common::RuntimeMode::Dev { .. })),
147        channel: channel.as_deref(),
148        forced: forced_by(std::env::var("AGENTMUX_BUILD_CACHE_CLEAN").ok().as_deref()),
149    })
150}
151
152/// Every folder directly in the agents' root.
153fn workspaces(root: &Path) -> Vec<PathBuf> {
154    let mut out: Vec<PathBuf> = std::fs::read_dir(root)
155        .into_iter()
156        .flatten()
157        .flatten()
158        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
159        .map(|e| e.path())
160        .collect();
161    out.sort();
162    out
163}
164
165fn same_path(a: &Path, b: &Path) -> bool {
166    let n = |p: &Path| p.to_string_lossy().replace('\\', "/").trim_end_matches('/').to_ascii_lowercase();
167    n(a) == n(b)
168}
169
170/// Whether `path` is a folder under `root`, ignoring case and slash style. The cleanup touches
171/// nothing outside the agents' root: an agent may work in a project folder of the user's.
172fn inside(root: &Path, path: &Path) -> bool {
173    let n = |p: &Path| p.to_string_lossy().replace('\\', "/").trim_end_matches('/').to_ascii_lowercase();
174    let (root, path) = (n(root), n(path));
175    path.len() > root.len() && path.starts_with(&root) && path.as_bytes()[root.len()] == b'/'
176}
177
178/// An agent running here, as the cleanup needs to know it.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct LocalAgent {
181    /// What notes are addressed to (its uid, else its id).
182    pub target: String,
183    /// The id it works under (`AGENTMUX_AGENT_ID`).
184    pub agent_id: String,
185    /// The name it is shown with.
186    pub name: String,
187    /// Its workspace.
188    pub workspace: PathBuf,
189    /// Whether its seat says it is this computer's steward, who gets the summary for the host.
190    pub steward: bool,
191}
192
193
194fn local_agents(mstore: &Store) -> Vec<LocalAgent> {
195    let defs = mstore.agent_def_list().unwrap_or_default();
196    let mut out: Vec<LocalAgent> = Vec::new();
197    for rec in crate::backend::reactive::get_global_handler().list_agents() {
198        let Some(block) = mstore.get::<Block>(&rec.block_id).ok().flatten() else { continue };
199        let def = defs.iter().find(|d| rec.uid.as_deref() == Some(d.id.as_str()) || d.slug == rec.agent_id || d.id == rec.agent_id);
200        let cwd = obj::meta_get_string(&block.meta, "cmd:cwd", "");
201        let cwd = if cwd.trim().is_empty() { def.map(|d| d.working_directory.clone()).unwrap_or_default() } else { cwd };
202        if cwd.trim().is_empty() {
203            continue;
204        }
205        let workspace = PathBuf::from(crate::backend::blockcontroller::core::expand_home_dir(&cwd));
206        if out.iter().any(|a| same_path(&a.workspace, &workspace) && a.target == rec.uid.clone().filter(|u| !u.is_empty()).unwrap_or(rec.agent_id.clone())) {
207            continue;
208        }
209        let steward = def.and_then(|d| crate::backend::agent_seat::effective_seat(mstore, d)).is_some_and(|seat| crate::backend::agent_seat::is_steward(&seat));
210        out.push(LocalAgent {
211            target: rec.uid.clone().filter(|u| !u.is_empty()).unwrap_or(rec.agent_id.clone()),
212            agent_id: rec.agent_id.clone(),
213            name: def.map(|d| d.name.clone()).unwrap_or_else(|| rec.agent_id.clone()),
214            workspace,
215            steward,
216        });
217    }
218    out
219}
220
221/// One workspace's build folders, as the note needs them.
222#[derive(Debug, Clone)]
223pub struct WorkspaceSize {
224    pub workspace: PathBuf,
225    pub target_bytes: u64,
226    pub incremental_bytes: u64,
227}
228
229/// The agents whose own workspace is large (build folders over `BIG_WORKSPACE`, or incremental
230/// caches over `BIG_INCREMENTAL`): they are the ones who can free the space, so they hear of it.
231/// A small workspace never does, however few others there are.
232pub fn big_owners(sizes: &[WorkspaceSize], agents: &[LocalAgent]) -> Vec<LocalAgent> {
233    let mut out: Vec<LocalAgent> = Vec::new();
234    for s in sizes.iter().filter(|s| s.target_bytes >= dn::BIG_WORKSPACE || s.incremental_bytes >= dn::BIG_INCREMENTAL) {
235        for owner in agents.iter().filter(|a| same_path(&a.workspace, &s.workspace)) {
236            if !out.iter().any(|o| o.target == owner.target) {
237                out.push(owner.clone());
238            }
239        }
240    }
241    out
242}
243
244/// Whether `clone` is `workspace` itself or a folder in it.
245fn in_workspace(workspace: &Path, clone: &Path) -> bool {
246    same_path(workspace, clone) || inside(workspace, clone)
247}
248
249/// The stewards, each once: an agent with panes in two folders is listed twice by `local_agents`,
250/// and a critical note would start two turns for it.
251pub fn stewards(agents: &[LocalAgent]) -> Vec<&LocalAgent> {
252    let mut out: Vec<&LocalAgent> = Vec::new();
253    for a in agents.iter().filter(|a| a.steward) {
254        if !out.iter().any(|o| o.target == a.target) {
255            out.push(a);
256        }
257    }
258    out
259}
260
261fn folder_line(s: &bc::TargetSize, owner: Option<&str>) -> String {
262    let who = owner.map_or(String::new(), |o| format!(" [{o}]"));
263    format!("- {} : {} ({} of it incremental){who}", s.clone.display(), bc::human(s.target_bytes), bc::human(s.incremental_bytes))
264}
265
266/// The note for one big workspace's owner: its own folders, largest first.
267fn owner_note(policy: &Policy, level: Level, free: u64, total: u64, agent: &LocalAgent, per_clone: &[bc::TargetSize]) -> String {
268    let own: Vec<String> = per_clone.iter().filter(|c| in_workspace(&agent.workspace, &c.clone)).take(6).map(|c| folder_line(c, None)).collect();
269    dn::note_text(policy, level, free, total, "Your largest cargo build folders:", &own)
270}
271
272/// The note for the host's steward: the largest folders on the computer, each with its owner.
273fn steward_note(policy: &Policy, level: Level, free: u64, total: u64, agents: &[LocalAgent], per_clone: &[bc::TargetSize]) -> String {
274    let all: Vec<String> = per_clone
275        .iter()
276        .take(6)
277        .map(|c| folder_line(c, agents.iter().find(|a| in_workspace(&a.workspace, &c.clone)).map(|a| a.name.as_str())))
278        .collect();
279    dn::note_text(policy, level, free, total, "Largest cargo build folders on this computer (owner in brackets):", &all)
280}
281
282/// Tells `agent`: a warning is held for its next turn, only a critical level starts one.
283fn tell(agent: &LocalAgent, level: Level, text: &str) -> bool {
284    let handler = crate::backend::reactive::get_global_handler();
285    let sent = if level == Level::Critical { handler.deliver_system_note(&agent.target, text) } else { handler.hold_system_note(&agent.target, HOLD_KEY, text) };
286    match sent {
287        Ok(()) => {
288            tracing::info!(agent = %agent.name, level = ?level, "build cache: low-disk note sent");
289            true
290        }
291        Err(e) => {
292            tracing::warn!(agent = %agent.name, error = %e, "build cache: low-disk note not delivered");
293            false
294        }
295    }
296}
297
298fn warn_marker() -> Option<PathBuf> {
299    Some(dirs::home_dir()?.join(".agentmux").join("shared").join("locks").join("build-cache-warn"))
300}
301
302/// Whether a build runs in `clone`, looking at the machine's processes afresh each time: a pass
303/// removes tens of GB, and a build may start in the clone while it does.
304fn fresh_busy_check(clone: &Path) -> bool {
305    bc::build_running_in(clone, &bc::snapshot_processes())
306}
307
308fn policy(config: &ConfigState) -> Policy {
309    Policy::from_extra(&config.get_settings().extra)
310}
311
312fn all_workspaces_pass(why: Why, policy: &Policy) -> bc::Report {
313    let Some(root) = agents_root() else { return bc::Report::default() };
314    let Some(_one_at_a_time) = host_lock() else {
315        tracing::debug!(why = ?why, "build cache: another srv on this host is cleaning");
316        return bc::Report::default();
317    };
318    pass_over(&root, why, policy)
319}
320
321/// A pass over every workspace under `root`; the caller holds the host lock.
322fn pass_over(root: &Path, why: Why, policy: &Policy) -> bc::Report {
323    let mut total = bc::Report::default();
324    let log = bc::log_path();
325    let busy = fresh_busy_check;
326    for ws in workspaces(root) {
327        let r = bc::run_pass(&ws, why, policy, &busy, SystemTime::now(), log.as_deref());
328        total.removed.extend(r.removed);
329        total.busy.extend(r.busy);
330    }
331    if !total.removed.is_empty() {
332        tracing::info!(why = ?why, removed = total.removed.len(), freed = %bc::human(total.bytes()), "build cache: pass done");
333    }
334    total
335}
336
337/// How long a cleanup that was asked for waits for another srv's pass.
338const ASKED_LOCK_WAIT: Duration = Duration::from_secs(5 * 60);
339
340/// The cleanup a `disk_cleanup` request runs once its countdown ended unvetoed: the pass a low disk
341/// runs (orphan incremental folders, and the whole `target` of a clone nobody built in for the
342/// policy's `stale` days), over every workspace, skipping a clone with a build running in it. Only an
343/// srv that cleans the real agents' folder does it, as on a schedule; it blocks, so call it from
344/// `spawn_blocking`. Says what it removed, in words, or why it did not run.
345pub fn clean_when_asked(config: &ConfigState) -> Result<String, String> {
346    if !this_srv_may_clean() {
347        return Err("this AgentMux is not the one that cleans build folders on this computer (a development, headless or test instance, or cleaning is turned off for it)".to_string());
348    }
349    let policy = policy(config);
350    if !policy.enabled {
351        return Err("build-folder cleanup is turned off in this AgentMux's settings (buildcache:enabled)".to_string());
352    }
353    let root = agents_root().ok_or("the agents' folder is not known on this computer")?;
354    let Some(_one_at_a_time) = host_lock_within(ASKED_LOCK_WAIT) else {
355        return Err("another AgentMux on this computer was cleaning for the whole wait; ask again later".to_string());
356    };
357    Ok(summary(&pass_over(&root, Why::Asked, &policy)))
358}
359
360fn summary(r: &bc::Report) -> String {
361    let busy = if r.busy.is_empty() { String::new() } else { format!("; left {} with a build running", r.busy.len()) };
362    format!("removed {} build folders ({} freed){busy}", r.removed.len(), bc::human(r.bytes()))
363}
364
365fn unix_now() -> u64 {
366    SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs())
367}
368
369/// One look at the disk: clean up when low, and if it is still low and worse than at the last
370/// note (`disk_notice::should_send`), tell the agents who can free space.
371fn disk_check(mstore: &Store, policy: &Policy) {
372    let Some(root) = agents_root() else { return };
373    let Some((free, total)) = bc::disk_of(&root) else { return };
374    let marker = warn_marker();
375    if !policy.is_low(free, total) {
376        // Back above the warning level with room to spare: the next drop is a new event.
377        if let Some(m) = marker.as_ref().filter(|_| dn::recovered(policy, free, total)) {
378            dn::clear_sent(m);
379        }
380        return;
381    }
382    tracing::warn!(free = %bc::human(free), total = %bc::human(total), "build cache: the disk is low");
383    if policy.enabled {
384        all_workspaces_pass(Why::LowDisk, policy);
385    }
386    let (free, total) = bc::disk_of(&root).unwrap_or((free, total));
387    if !policy.is_low(free, total) {
388        return;
389    }
390    let Some(marker) = marker else { return };
391    let level = dn::level(policy, free, total);
392    let prev = dn::read_sent(&marker, free);
393    if !dn::should_send(prev.as_ref(), level, free, unix_now()) {
394        // The record keeps the worst level reached until the disk has recovered: free space that
395        // bounces across the critical line is one event, not a new wake-up each time it dips.
396        return;
397    }
398    // The walk below reads every build folder: on a full disk, do not repeat it every check when
399    // there was nobody to tell.
400    let now_s = unix_now();
401    if now_s < NEXT_TRY.load(std::sync::atomic::Ordering::Relaxed) {
402        return;
403    }
404    NEXT_TRY.store(now_s + RETRY_AFTER.as_secs(), std::sync::atomic::Ordering::Relaxed);
405    let mut per_clone: Vec<bc::TargetSize> = Vec::new();
406    let mut sizes: Vec<WorkspaceSize> = Vec::new();
407    for ws in workspaces(&root) {
408        let clones = bc::target_sizes(&ws);
409        let target_bytes: u64 = clones.iter().map(|s| s.target_bytes).sum();
410        if target_bytes > 0 {
411            sizes.push(WorkspaceSize { workspace: ws, target_bytes, incremental_bytes: clones.iter().map(|s| s.incremental_bytes).sum() });
412        }
413        per_clone.extend(clones);
414    }
415    sizes.sort_by(|a, b| b.target_bytes.cmp(&a.target_bytes));
416    per_clone.sort_by(|a, b| b.target_bytes.cmp(&a.target_bytes));
417    let agents = local_agents(mstore);
418    let (mut attempted, mut delivered) = (0, 0);
419    // The steward gets the whole computer's summary, so an owner who is the steward is told once.
420    for owner in big_owners(&sizes, &agents).iter().filter(|a| !a.steward) {
421        attempted += 1;
422        if tell(owner, level, &owner_note(policy, level, free, total, owner, &per_clone)) {
423            delivered += 1;
424        }
425    }
426    for steward in stewards(&agents) {
427        attempted += 1;
428        if tell(steward, level, &steward_note(policy, level, free, total, &agents, &per_clone)) {
429            delivered += 1;
430        }
431    }
432    if attempted == 0 {
433        // No workspace is large and no steward is here: nothing to say. That is handled, not a
434        // failure, so it is recorded and the folders are not walked again until the disk drops further.
435        tracing::info!("build cache: the disk is low but no agent has large build folders and no steward is here; nobody to tell");
436        dn::write_sent(&marker, &dn::Sent { level, free, at: unix_now() });
437    } else if delivered > 0 {
438        dn::write_sent(&marker, &dn::Sent { level, free, at: unix_now() });
439    } else {
440        tracing::warn!("build cache: the disk is low and no agent could be told; trying again in 30 minutes");
441    }
442}
443
444/// An agent completed a task: clear its own clones' incremental folders. `agent` is the id the
445/// task was completed under. Runs in the background; never fails the completion.
446pub fn agent_task_done(mstore: Arc<Store>, config: Arc<ConfigState>, agent: String) {
447    if !this_srv_may_clean() {
448        return;
449    }
450    tokio::task::spawn_blocking(move || {
451        let policy = policy(&config);
452        if !policy.enabled {
453            return;
454        }
455        let Some(root) = agents_root() else { return };
456        let mine: Vec<LocalAgent> = local_agents(&mstore)
457            .into_iter()
458            .filter(|a| a.agent_id == agent || a.target == agent || a.name.eq_ignore_ascii_case(&agent))
459            // Only workspaces under the agents' root: a project folder is not ours to clean.
460            .filter(|a| inside(&root, &a.workspace))
461            .collect();
462        if mine.is_empty() {
463            return;
464        }
465        let Some(_one_at_a_time) = host_lock_within(TASK_LOCK_WAIT) else {
466            tracing::warn!(agent = %agent, "build cache: task cleanup skipped, another srv kept the host lock for too long");
467            return;
468        };
469        let log = bc::log_path();
470        let busy = fresh_busy_check;
471        let mut seen: Vec<PathBuf> = Vec::new();
472        for a in mine {
473            if seen.iter().any(|s| same_path(s, &a.workspace)) {
474                continue;
475            }
476            seen.push(a.workspace.clone());
477            let r = bc::run_pass(&a.workspace, Why::TaskDone, &policy, &busy, SystemTime::now(), log.as_deref());
478            if !r.removed.is_empty() || !r.busy.is_empty() {
479                tracing::info!(agent = %a.name, freed = %bc::human(r.bytes()), removed = r.removed.len(), busy = r.busy.len(), "build cache: task done");
480            }
481        }
482    });
483}
484
485/// Starts the schedule. Safe to call once at boot.
486pub fn install(mstore: Arc<Store>, config: Arc<ConfigState>) {
487    // Only an srv started by its launcher on the real home cleans the real workspaces: not a dev,
488    // headless or test instance (see `may_clean`).
489    if !this_srv_may_clean() {
490        tracing::debug!("build cache: not an srv that cleans; no cleanup or disk warning from this srv");
491        return;
492    }
493    tokio::spawn(async move {
494        let started = tokio::time::Instant::now();
495        let mut disk = tokio::time::interval(DISK_EVERY);
496        let mut next_hourly = started + FIRST_HOURLY_AFTER;
497        loop {
498            disk.tick().await;
499            let (store, cfg) = (mstore.clone(), config.clone());
500            let hourly_due = tokio::time::Instant::now() >= next_hourly;
501            if hourly_due {
502                next_hourly = tokio::time::Instant::now() + HOURLY_EVERY;
503            }
504            let _ = tokio::task::spawn_blocking(move || {
505                let policy = policy(&cfg);
506                if hourly_due && policy.enabled && policy.orphans {
507                    all_workspaces_pass(Why::Hourly, &policy);
508                }
509                disk_check(&store, &policy);
510            })
511            .await;
512        }
513    });
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    const GB: u64 = 1 << 30;
521
522    fn agent(target: &str, ws: &str, steward: bool) -> LocalAgent {
523        LocalAgent { target: target.into(), agent_id: target.into(), name: target.into(), workspace: PathBuf::from(ws), steward }
524    }
525
526    fn ws(path: &str, target_gb: f64, incremental_gb: f64) -> WorkspaceSize {
527        WorkspaceSize { workspace: PathBuf::from(path), target_bytes: (target_gb * GB as f64) as u64, incremental_bytes: (incremental_gb * GB as f64) as u64 }
528    }
529
530    fn clone_of(path: &str, target_gb: u64, incremental_gb: u64) -> bc::TargetSize {
531        bc::TargetSize { clone: PathBuf::from(path), target_bytes: target_gb * GB, incremental_bytes: incremental_gb * GB }
532    }
533
534    #[test]
535    fn only_an_owner_of_a_large_workspace_hears_of_it() {
536        // charlie's case: three agents with folders of 24.8, 14 and 3.5 GB (no incremental left).
537        let agents = vec![agent("parlo", "/a/parlo", false), agent("maricon", "/a/maricon", false), agent("opaz", "/a/opaz", false)];
538        let sizes = vec![ws("/a/parlo", 24.8, 1.0), ws("/a/maricon", 14.0, 0.5), ws("/a/opaz", 3.5, 0.0)];
539        let who: Vec<String> = big_owners(&sizes, &agents).into_iter().map(|a| a.target).collect();
540        assert_eq!(who, ["parlo", "maricon"], "the 3.5 GB folder with nothing incremental is not told");
541    }
542
543    #[test]
544    fn a_small_workspace_with_a_big_incremental_cache_is_told_and_the_line_is_exact() {
545        let agents = vec![agent("a", "/a/a", false), agent("b", "/a/b", false), agent("c", "/a/c", false)];
546        let sizes = vec![ws("/a/a", 9.9, 1.9), ws("/a/b", 10.0, 0.0), ws("/a/c", 6.0, 2.0)];
547        let who: Vec<String> = big_owners(&sizes, &agents).into_iter().map(|a| a.target).collect();
548        assert_eq!(who, ["b", "c"], "10 GB of build folders counts, 9.9 GB does not; 2 GB incremental counts, 1.9 does not");
549        assert!(big_owners(&[], &agents).is_empty());
550        assert!(big_owners(&[ws("/elsewhere", 50.0, 5.0)], &agents).is_empty(), "a workspace with no agent here");
551    }
552
553    #[test]
554    fn two_agents_in_one_big_workspace_both_hear_of_it_once() {
555        let agents = vec![agent("a1", "/a/shared", false), agent("a2", "/a/shared", false), agent("a1", "/a/shared", false)];
556        let who: Vec<String> = big_owners(&[ws("/a/shared", 30.0, 0.0)], &agents).into_iter().map(|a| a.target).collect();
557        assert_eq!(who, ["a1", "a2"]);
558    }
559
560    #[test]
561    fn an_owner_is_told_of_its_own_folders_and_the_steward_of_all_with_their_owners() {
562        let agents = vec![agent("w1", "/a/w1", false), agent("w2", "/a/w2", false), agent("clamk", "/a/clamk", true)];
563        let per_clone = vec![clone_of("/a/w1/agentmux", 24, 3), clone_of("/a/w2/agentmux", 14, 1), clone_of("/a/w2", 3, 0)];
564        let p = Policy::default();
565        let own = owner_note(&p, Level::Warning, 43 * GB, 440 * GB, &agents[0], &per_clone);
566        assert!(own.contains("- /a/w1/agentmux : 24.0 GB (3.0 GB of it incremental)") || own.contains("- /a/w1/agentmux : 24 GB"), "{own}");
567        assert!(!own.contains("/a/w2"), "an owner is not told about other agents' folders: {own}");
568        let all = steward_note(&p, Level::Warning, 43 * GB, 440 * GB, &agents, &per_clone);
569        assert!(all.contains("/a/w1/agentmux") && all.contains("[w1]"), "{all}");
570        assert!(all.contains("[w2]"), "{all}");
571        assert!(all.contains("owner in brackets"), "{all}");
572        let w2 = owner_note(&p, Level::Warning, 43 * GB, 440 * GB, &agents[1], &per_clone);
573        assert!(w2.contains("- /a/w2 :"), "a clone that is the workspace itself counts as in it: {w2}");
574    }
575
576    #[test]
577    fn a_steward_with_panes_in_two_folders_is_told_once() {
578        let agents = vec![agent("clamk", "/a/clamk", true), agent("w1", "/a/w1", false), agent("clamk", "/a/clamk-2", true)];
579        let who: Vec<&str> = stewards(&agents).into_iter().map(|a| a.target.as_str()).collect();
580        assert_eq!(who, ["clamk"]);
581        assert!(stewards(&[agent("w1", "/a/w1", false)]).is_empty());
582    }
583
584    #[test]
585    fn a_seat_that_names_a_steward_makes_a_steward() {
586        use crate::backend::agent_seat::is_steward as seat_is_steward;
587        use crate::registry::AgentSeat;
588        let seat =|q: Option<&str>, area: Option<&str>| AgentSeat { role: "worker".into(), qualifier: q.map(str::to_string), area: area.map(str::to_string), ..Default::default() };
589        assert!(seat_is_steward(&seat(Some("Steward"), None)));
590        assert!(seat_is_steward(&seat(None, Some("narko's steward (see below); tasks AgentY gives it"))));
591        assert!(!seat_is_steward(&seat(Some("product"), Some("agent pane, identity, accounts"))));
592        assert!(!seat_is_steward(&seat(None, None)));
593    }
594
595    #[test]
596    fn only_a_folder_under_the_agents_root_is_inside_it() {
597        let root = Path::new("C:\\Users\\a\\.agentmux\\agents");
598        assert!(inside(root, Path::new("c:/users/a/.agentmux/agents/loap-3-0822g")));
599        assert!(inside(root, Path::new("C:\\Users\\a\\.agentmux\\agents\\x\\agentmux\\")));
600        assert!(!inside(root, Path::new("C:\\Users\\a\\.agentmux\\agents")), "the root itself is not a workspace");
601        assert!(!inside(root, Path::new("C:\\Users\\a\\.agentmux\\agents-old\\x")), "a sibling that shares the prefix");
602        assert!(!inside(root, Path::new("C:\\Users\\a\\projects\\site")));
603    }
604
605    #[test]
606    fn paths_compare_without_regard_to_case_slashes_or_a_trailing_one() {
607        assert!(same_path(Path::new("C:\\Users\\a\\x\\"), Path::new("c:/users/a/x")));
608        assert!(!same_path(Path::new("/a/x"), Path::new("/a/xy")));
609    }
610
611    #[test]
612    fn a_launcher_started_srv_on_the_real_home_may_clean_whatever_its_channel_is_called() {
613        let started = |channel| Start { channel: Some(channel), ..Default::default() };
614        assert!(may_clean(&started("stable")), "the installed release cleans");
615        assert!(may_clean(&started("local-HEAD-7138a5-bd7e7fdf")), "a local package on a host that runs one");
616        assert!(may_clean(&started("local-loap-3-x")));
617        // Each way of not being one, alone:
618        assert!(!may_clean(&Start { own_home: true, ..started("stable") }), "an instance with a home of its own");
619        assert!(!may_clean(&Start { headless: true, ..started("stable") }), "a headless srv");
620        assert!(!may_clean(&Start { built_in_tree: true, ..started("stable") }), "a binary from target/debug or target/release");
621        assert!(!may_clean(&Start { dev_mode: true, ..started("local-x") }), "a task dev build");
622        assert!(!may_clean(&started("dev-main-0123456789abcdef")), "a dev channel");
623        assert!(!may_clean(&Start::default()), "no channel at all: not started by a launcher");
624    }
625
626    #[test]
627    fn the_override_turns_cleaning_off_or_on_but_never_for_an_instance_with_its_own_home() {
628        let local = || Start { channel: Some("local-x"), ..Default::default() };
629        assert!(!may_clean(&Start { forced: Some(false), channel: Some("stable"), ..Default::default() }), "0 stops the installed release");
630        assert!(!may_clean(&Start { forced: Some(false), ..local() }));
631        assert!(may_clean(&Start { forced: Some(true), headless: true, ..Default::default() }), "1 lets a headless host clean");
632        assert!(may_clean(&Start { forced: Some(true), dev_mode: true, ..local() }));
633        assert!(!may_clean(&Start { forced: Some(true), own_home: true, ..local() }), "a home of its own never cleans the real folder");
634        assert_eq!(forced_by(None), None);
635        assert_eq!(forced_by(Some("1")), Some(true));
636        assert_eq!(forced_by(Some(" On ")), Some(true));
637        assert_eq!(forced_by(Some("0")), Some(false));
638        assert_eq!(forced_by(Some("FALSE")), Some(false));
639        assert_eq!(forced_by(Some("")), None, "empty: left to how srv was started");
640        assert_eq!(forced_by(Some("maybe")), None);
641    }
642
643    #[test]
644    fn one_srv_on_the_host_cleans_at_a_time() {
645        let t = tempfile::tempdir().unwrap();
646        let path = t.path().join("locks").join("build-cache-clean.lock");
647        let first = try_lock_file(&path).expect("the first srv takes the lock");
648        assert!(try_lock_file(&path).is_none(), "a second srv waits for the next pass");
649        drop(first);
650        assert!(try_lock_file(&path).is_some(), "free again once the pass is done");
651    }
652
653    #[test]
654    fn a_finished_tasks_cleanup_waits_for_the_pass_that_holds_the_lock() {
655        let t = tempfile::tempdir().unwrap();
656        let path = t.path().join("build-cache-clean.lock");
657        let held = try_lock_file(&path).unwrap();
658        assert!(lock_file_within(&path, Duration::from_millis(50)).is_none(), "gives up when the pass outlasts the wait");
659        let releaser = std::thread::spawn(move || {
660            std::thread::sleep(Duration::from_millis(200));
661            drop(held);
662        });
663        assert!(lock_file_within(&path, Duration::from_secs(10)).is_some(), "takes the lock once the pass is done");
664        releaser.join().unwrap();
665    }
666
667    #[test]
668    fn this_test_binary_does_not_clean() {
669        // It runs from target/debug (or release), with no launcher: the real check refuses it.
670        assert!(!this_srv_may_clean());
671    }
672
673    #[test]
674    fn a_cleanup_that_was_asked_for_does_not_run_in_a_srv_that_does_not_clean_and_says_what_it_did() {
675        let config = ConfigState::new();
676        let err = clean_when_asked(&config).unwrap_err();
677        assert!(err.contains("not the one that cleans"), "{err}");
678
679        let removed = |bytes| bc::Removed { path: PathBuf::from("/a/w/agentmux/target"), bytes, what: "stale target" };
680        let report = bc::Report { removed: vec![removed(3 << 30), removed(1 << 30)], busy: vec![PathBuf::from("/a/x/agentmux")] };
681        assert_eq!(summary(&report), "removed 2 build folders (4.0 GB freed); left 1 with a build running");
682        assert_eq!(summary(&bc::Report::default()), "removed 0 build folders (0 MB freed)");
683    }
684}