Skip to main content

agentmux_srv_core/backend/
old_versions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Clears the version folders an upgrade leaves behind, and the portables it unpacked.
5//!
6//! Every upgrade starts the new version on a copy of the old version's data
7//! (`channels/<channel>/versions/<v>/`), and the updater unpacks a new portable beside the running
8//! one. Nothing removes the old ones, so a machine that upgrades daily gains 0.5-1 GB of each a day.
9//!
10//! A folder of this srv's own channel goes only when ALL hold:
11//!
12//! - it is older than the version this srv runs (a newer one is another build's, or a rollback
13//!   already taken: not ours to judge);
14//! - it is not one of the newest `keep_previous` older versions (the way back, one by default);
15//! - no running process names it: not in its command line, its working folder, its program path or
16//!   its environment (every agent's shell carries `AGENTMUX_DATA_DIR`), and the pid its `srv.lock`
17//!   records is not a live AgentMux process;
18//! - nothing in it was written for `idle` (a day by default);
19//! - the machine's processes could be read at all. A scan that fails keeps everything: a guard that
20//!   cannot see must not approve.
21//!
22//! Before a version folder goes, its `data/attachments` (the images and files old conversations
23//! show) are copied into the running version's attachments store, so no old image vanishes; a
24//! copy that cannot finish keeps the folder.
25//!
26//! A removal renames the folder first, which Windows refuses while any file in it is open, and only
27//! then deletes it, so a crash leaves a `*.removing-<pid>` folder the next pass finishes. Portable
28//! folders (`agentmux-<v>-x64-portable`) are the user's: they are listed, and removed only when
29//! `oldversions:portables` is on, and only those the updater unpacked for this channel (they record
30//! it). Nothing here follows a symlink, and a name that is not a plain `x.y.z` is left alone.
31//!
32//! [`run`] with `dry_run` only reads. `old_versions_service` calls it daily and the
33//! `/agentmux/old-versions` route lets an agent look at the plan, or carry out what it shows.
34
35use std::collections::HashMap;
36use std::path::{Path, PathBuf};
37use std::time::{Duration, SystemTime};
38
39use serde::Serialize;
40
41/// Settings keys (the free-form part of the settings file).
42pub const KEY_CLEAN: &str = "oldversions:clean";
43pub const KEY_KEEP_PREVIOUS: &str = "oldversions:keep_previous";
44pub const KEY_IDLE_HOURS: &str = "oldversions:idle_hours";
45pub const KEY_PORTABLES: &str = "oldversions:portables";
46
47/// What goes, and whether the daily pass removes it or only reports it.
48#[derive(Debug, Clone, PartialEq)]
49pub struct Policy {
50    /// The daily pass removes what it finds. Off: it only logs the plan.
51    pub clean: bool,
52    /// How many of the newest older versions are kept as the way back; never fewer than one.
53    pub keep_previous: usize,
54    /// A folder written to within this long is in use.
55    pub idle: Duration,
56    /// Unpacked portable folders are removed too.
57    pub portables: bool,
58}
59
60impl Default for Policy {
61    fn default() -> Self {
62        // Packaged installs remove by default: the operator asked for the 24 GB of old version
63        // folders to go. Every guard below still decides what is safe, and `oldversions:clean:
64        // false` turns removal off.
65        Self { clean: true, keep_previous: 1, idle: Duration::from_secs(24 * 3600), portables: false }
66    }
67}
68
69impl Policy {
70    /// The policy the settings ask for; a missing or mistyped key keeps its default.
71    pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
72        Self::from_extra_for(extra, false)
73    }
74
75    /// [`from_extra`](Self::from_extra). Removal is on by default for every packaged install;
76    /// `hosted` is kept for callers and no longer changes that default. An explicit
77    /// `oldversions:clean` still wins.
78    pub fn from_extra_for(extra: &HashMap<String, serde_json::Value>, _hosted: bool) -> Self {
79        let d = Self::default();
80        let num = |key: &str| extra.get(key).and_then(|v| v.as_f64()).filter(|n| n.is_finite() && *n >= 0.0);
81        Self {
82            clean: extra.get(KEY_CLEAN).and_then(|v| v.as_bool()).unwrap_or(d.clean),
83            keep_previous: num(KEY_KEEP_PREVIOUS).map_or(d.keep_previous, |n| (n as usize).max(1)),
84            idle: num(KEY_IDLE_HOURS).and_then(|h| Duration::try_from_secs_f64(h * 3600.0).ok()).unwrap_or(d.idle),
85            portables: extra.get(KEY_PORTABLES).and_then(|v| v.as_bool()).unwrap_or(d.portables),
86        }
87    }
88}
89
90/// Where the folders are, and which version this srv is.
91#[derive(Debug, Clone)]
92pub struct Layout {
93    /// `channels/<channel>/versions`.
94    pub versions_root: PathBuf,
95    /// The folder name of the version this srv runs.
96    pub running: String,
97    /// This srv's data channel, which an unpacked portable records.
98    pub channel: String,
99    /// Folders holding unpacked portables: beside the running install, and the channel's `updates/<v>/`.
100    pub portable_parents: Vec<PathBuf>,
101}
102
103/// The layout of this srv, or `None` when it has no per-version folders (a `task dev` build, a
104/// test home).
105pub fn layout_from_env() -> Option<Layout> {
106    let paths = agentmux_common::DataPaths::from_env()?;
107    let version_dir = paths.data_dir.parent()?;
108    let versions_root = version_dir.parent()?;
109    if versions_root.file_name()? != "versions" || versions_root.parent()? != paths.instance_dir {
110        return None;
111    }
112    let mut portable_parents = Vec::new();
113    match crate::backend::update::install::detect() {
114        crate::backend::update::install::InstallKind::WindowsPortable { root } | crate::backend::update::install::InstallKind::LinuxPortable { root } => {
115            portable_parents.extend(root.parent().map(Path::to_path_buf));
116        }
117        _ => {}
118    }
119    if let Ok(entries) = std::fs::read_dir(paths.instance_dir.join("updates")) {
120        portable_parents.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
121    }
122    Some(Layout {
123        versions_root: versions_root.to_path_buf(),
124        running: version_dir.file_name()?.to_string_lossy().into_owned(),
125        channel: paths.channel,
126        portable_parents,
127    })
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
131#[serde(rename_all = "snake_case")]
132pub enum Kind {
133    /// `versions/<v>/`: an old version's data, logs and caches.
134    VersionData,
135    /// An unpacked portable of an old version.
136    Portable,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
140#[serde(rename_all = "snake_case")]
141pub enum Keep {
142    /// The version this srv runs.
143    Running,
144    /// Newer than the running version.
145    NotOlder,
146    /// One of the newest older versions, kept as the way back.
147    Rollback,
148    /// A running process names it.
149    InUse,
150    /// The processes could not be read, so nothing can be shown to be unused.
151    ScanFailed,
152    /// Written to within the idle time.
153    RecentlyActive,
154    /// A folder that is not an AgentMux version or not one the updater unpacked for this channel,
155    /// or a symlink.
156    NotOurs,
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
160pub struct Candidate {
161    pub dir: PathBuf,
162    pub version: String,
163    pub kind: Kind,
164    pub bytes: u64,
165}
166
167#[derive(Debug, Clone, Default, Serialize)]
168pub struct Plan {
169    pub removable: Vec<Candidate>,
170    /// `(folder, why)`.
171    pub kept: Vec<(PathBuf, Keep)>,
172}
173
174impl Plan {
175    pub fn reclaimable_bytes(&self) -> u64 {
176        self.removable.iter().map(|c| c.bytes).sum()
177    }
178}
179
180/// One running process, as the guard needs it.
181#[derive(Debug, Clone, Default)]
182pub struct ProcView {
183    pub pid: u32,
184    /// Its program name.
185    pub name: String,
186    /// Its program path, working folder, arguments and environment entries.
187    pub strings: Vec<String>,
188}
189
190/// What is running right now.
191#[derive(Debug, Clone, Default)]
192pub struct InUse {
193    /// `None` when the processes could not be read.
194    pub procs: Option<Vec<ProcView>>,
195}
196
197fn normal(s: &str) -> String {
198    let s = s.replace('\\', "/").to_ascii_lowercase();
199    // `canonicalize` on Windows gives a `\\?\C:\...` path.
200    s.strip_prefix("//?/").map_or_else(|| s.clone(), str::to_string)
201}
202
203impl InUse {
204    /// Everything about the processes this machine runs.
205    pub fn scan() -> Self {
206        let mut sys = sysinfo::System::new();
207        sys.refresh_processes_specifics(
208            sysinfo::ProcessesToUpdate::All,
209            true,
210            sysinfo::ProcessRefreshKind::nothing()
211                .with_cwd(sysinfo::UpdateKind::Always)
212                .with_exe(sysinfo::UpdateKind::Always)
213                .with_cmd(sysinfo::UpdateKind::Always)
214                .with_environ(sysinfo::UpdateKind::Always),
215        );
216        let procs: Vec<ProcView> = sys
217            .processes()
218            .iter()
219            .map(|(pid, p)| {
220                let mut strings: Vec<String> = Vec::new();
221                strings.extend(p.exe().map(|e| e.to_string_lossy().into_owned()));
222                strings.extend(p.cwd().map(|c| c.to_string_lossy().into_owned()));
223                strings.extend(p.cmd().iter().map(|a| a.to_string_lossy().into_owned()));
224                strings.extend(p.environ().iter().map(|e| e.to_string_lossy().into_owned()));
225                ProcView { pid: pid.as_u32(), name: p.name().to_string_lossy().into_owned(), strings }
226            })
227            .collect();
228        // Even a nearly idle machine runs dozens: an empty list means the scan did not work.
229        Self { procs: (!procs.is_empty()).then_some(procs) }
230    }
231
232    /// Whether any process names `dir` or something inside it. A name that continues the last
233    /// component (`0.60.10` for `0.60.1`) is not a mention.
234    pub fn mentions(&self, dir: &Path) -> bool {
235        let needle = normal(&dir.to_string_lossy());
236        let needle = needle.trim_end_matches('/');
237        if needle.is_empty() {
238            return false;
239        }
240        self.procs.iter().flatten().flat_map(|p| p.strings.iter()).any(|s| {
241            let hay = normal(s);
242            hay.match_indices(needle).any(|(i, _)| {
243                hay[i + needle.len()..].chars().next().is_none_or(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+')))
244            })
245        })
246    }
247
248    /// Whether `pid` is a live AgentMux process.
249    fn agentmux_alive(&self, pid: u32) -> bool {
250        self.procs.iter().flatten().any(|p| p.pid == pid && p.name.to_ascii_lowercase().contains("agentmux"))
251    }
252}
253
254/// `x.y.z`, three numbers and nothing else: a local build's `0.60.2+g...` is not a release.
255fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
256    let mut it = s.split('.');
257    let mut next = || it.next().filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())).and_then(|p| p.parse::<u64>().ok());
258    let v = (next()?, next()?, next()?);
259    it.next().is_none().then_some(v)
260}
261
262/// The version in an unpacked portable's folder name.
263fn portable_version(name: &str) -> Option<&str> {
264    if cfg!(windows) {
265        name.strip_prefix("agentmux-")?.strip_suffix("-x64-portable")
266    } else {
267        name.strip_prefix("AgentMux-")
268    }
269}
270
271/// `name` without the `.removing-<pid>` a removal renames a folder to.
272fn leftover_stem(name: &str) -> Option<&str> {
273    let (stem, pid) = name.rsplit_once(".removing-")?;
274    (!pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())).then_some(stem)
275}
276
277/// Whether `stem` is the name of a folder of `kind` that this module removes.
278fn stem_is_ours(kind: Kind, stem: &str) -> bool {
279    match kind {
280        Kind::Portable => portable_version(stem).and_then(parse_version).is_some(),
281        Kind::VersionData => parse_version(stem).is_some(),
282    }
283}
284
285/// Total size of the files under `dir`, never following a symlink.
286fn dir_size(dir: &Path) -> u64 {
287    let mut total = 0;
288    let mut stack = vec![dir.to_path_buf()];
289    while let Some(d) = stack.pop() {
290        let Ok(rd) = std::fs::read_dir(&d) else { continue };
291        for entry in rd.flatten() {
292            let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
293            if meta.is_dir() {
294                stack.push(entry.path());
295            } else {
296                total += meta.len();
297            }
298        }
299    }
300    total
301}
302
303/// The newest write to any file or folder under `dir`, symlinks not followed. A running version
304/// writes its databases and logs; one that stopped has been still since. A folder's own time moves
305/// only when an entry is added or removed, so the files themselves are looked at.
306fn last_activity(dir: &Path) -> Option<SystemTime> {
307    let mut newest: Option<SystemTime> = None;
308    let mut stack = vec![dir.to_path_buf()];
309    while let Some(d) = stack.pop() {
310        if let Ok(t) = std::fs::symlink_metadata(&d).and_then(|m| m.modified()) {
311            newest = Some(newest.map_or(t, |n| n.max(t)));
312        }
313        let Ok(rd) = std::fs::read_dir(&d) else { continue };
314        for e in rd.flatten() {
315            let Ok(meta) = e.metadata() else { continue };
316            if meta.is_dir() && !meta.file_type().is_symlink() {
317                stack.push(e.path());
318            } else if let Ok(t) = meta.modified() {
319                newest = Some(newest.map_or(t, |n| n.max(t)));
320            }
321        }
322    }
323    newest
324}
325
326/// The pid `srv.lock` records, if the folder has one.
327fn recorded_srv_pid(dir: &Path) -> Option<u32> {
328    std::fs::read_to_string(dir.join("data").join(crate::backend::base::SRV_DATA_LOCK_FILE)).ok()?.trim().parse().ok()
329}
330
331/// The reason `dir` must stay although it is old enough and beyond the way back, if there is one.
332fn in_use_reason(dir: &Path, policy: &Policy, now: SystemTime, in_use: &InUse) -> Option<Keep> {
333    if in_use.procs.is_none() {
334        return Some(Keep::ScanFailed);
335    }
336    if in_use.mentions(dir) || recorded_srv_pid(dir).is_some_and(|p| in_use.agentmux_alive(p)) {
337        return Some(Keep::InUse);
338    }
339    let idle = last_activity(dir).and_then(|t| now.duration_since(t).ok()).unwrap_or(Duration::ZERO); // unreadable or in the future: just used
340    (idle < policy.idle).then_some(Keep::RecentlyActive)
341}
342
343struct Entry {
344    dir: PathBuf,
345    version: String,
346    key: (u64, u64, u64),
347}
348
349/// Folders of `kind` named by version in `parent`, plus what is kept without being judged.
350fn scan_dir(parent: &Path, kind: Kind, layout: &Layout, kept: &mut Vec<(PathBuf, Keep)>, leftovers: &mut Vec<(PathBuf, Kind)>) -> Vec<Entry> {
351    let Ok(rd) = std::fs::read_dir(parent) else { return Vec::new() };
352    let mut out = Vec::new();
353    for e in rd.flatten() {
354        let path = e.path();
355        let name = e.file_name().to_string_lossy().into_owned();
356        let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
357        if meta.file_type().is_symlink() {
358            kept.push((path, Keep::NotOurs));
359            continue;
360        }
361        if !meta.is_dir() {
362            continue;
363        }
364        if name.contains(".removing-") {
365            // Only what a removal of ours renamed: `<a version folder's name>.removing-<pid>`. A
366            // portable's parent is the user's, and holds other things.
367            if leftover_stem(&name).is_some_and(|stem| stem_is_ours(kind, stem)) {
368                leftovers.push((path, kind));
369            }
370            continue;
371        }
372        let version = match kind {
373            Kind::Portable => portable_version(&name).map(str::to_owned),
374            _ => Some(name.clone()),
375        };
376        let Some(key) = version.as_deref().and_then(parse_version) else {
377            // Not ours to judge, unless it looks like a portable of some other kind: stay quiet
378            // about unrelated folders in a parent the user owns.
379            if kind != Kind::Portable || name.to_ascii_lowercase().starts_with("agentmux") {
380                kept.push((path, Keep::NotOurs));
381            }
382            continue;
383        };
384        let version = version.unwrap_or_default();
385        if kind == Kind::Portable
386            && !(crate::backend::update::download::is_staged_portable(&path, &version)
387                && agentmux_common::runtime_mode::recorded_channel_in(&path).as_deref() == Some(layout.channel.as_str()))
388        {
389            kept.push((path, Keep::NotOurs));
390            continue;
391        }
392        out.push(Entry { dir: path, version, key });
393    }
394    out
395}
396
397fn judge(plan: &mut Plan, kind: Kind, mut entries: Vec<Entry>, running: (u64, u64, u64), policy: &Policy, now: SystemTime, in_use: &InUse) {
398    entries.sort_by(|a, b| b.key.cmp(&a.key));
399    let mut older = 0;
400    for e in entries {
401        let keep = if e.key == running {
402            Some(Keep::Running)
403        } else if e.key > running {
404            Some(Keep::NotOlder)
405        } else {
406            older += 1;
407            if older <= policy.keep_previous {
408                Some(Keep::Rollback)
409            } else {
410                in_use_reason(&e.dir, policy, now, in_use)
411            }
412        };
413        match keep {
414            Some(k) => plan.kept.push((e.dir, k)),
415            None => plan.removable.push(Candidate { bytes: dir_size(&e.dir), dir: e.dir, version: e.version, kind }),
416        }
417    }
418}
419
420/// Decides what could go. Reads only.
421pub fn plan(layout: &Layout, policy: &Policy, now: SystemTime, in_use: &InUse) -> Plan {
422    let mut plan = Plan::default();
423    let Some(running) = parse_version(&layout.running) else {
424        // A running version that is not a plain release (a local build): no basis to judge by.
425        return plan;
426    };
427    let mut leftovers = Vec::new();
428    let entries = scan_dir(&layout.versions_root, Kind::VersionData, layout, &mut plan.kept, &mut leftovers);
429    judge(&mut plan, Kind::VersionData, entries, running, policy, now, in_use);
430    let mut portables = Vec::new();
431    for parent in &layout.portable_parents {
432        portables.extend(scan_dir(parent, Kind::Portable, layout, &mut plan.kept, &mut leftovers));
433    }
434    judge(&mut plan, Kind::Portable, portables, running, policy, now, in_use);
435    for (dir, kind) in leftovers {
436        match in_use_reason(&dir, policy, now, in_use) {
437            Some(k) => plan.kept.push((dir, k)),
438            None => plan.removable.push(Candidate { bytes: dir_size(&dir), version: String::new(), dir, kind }),
439        }
440    }
441    plan
442}
443
444#[derive(Debug, Default, Serialize)]
445pub struct Report {
446    pub removed: Vec<(PathBuf, u64)>,
447    /// Candidates left alone at removal time, and why.
448    pub skipped: Vec<(PathBuf, String)>,
449}
450
451/// Removes what [`plan`] found, asking again for each folder at the last moment: a process may
452/// have started in it since.
453pub fn remove(plan: &Plan, layout: &Layout, policy: &Policy, now: SystemTime, in_use: &dyn Fn() -> InUse) -> Report {
454    let mut report = Report::default();
455    let current_data = layout.versions_root.join(&layout.running).join("data");
456    for c in &plan.removable {
457        // A portable's leftover counts as a portable: the user's, so only when turned on.
458        if c.kind == Kind::Portable && !policy.portables {
459            report.skipped.push((c.dir.clone(), "portable cleanup is off (oldversions:portables)".into()));
460            continue;
461        }
462        if std::fs::symlink_metadata(&c.dir).map_or(true, |m| m.file_type().is_symlink() || !m.is_dir()) {
463            report.skipped.push((c.dir.clone(), "no longer a plain folder".into()));
464            continue;
465        }
466        if let Some(why) = in_use_reason(&c.dir, policy, now, &in_use()) {
467            report.skipped.push((c.dir.clone(), format!("{why:?}: in use now")));
468            continue;
469        }
470        // Images and files an old conversation shows live in that version's attachments store;
471        // carry them into the running version before the folder goes, so no old image vanishes.
472        if c.kind == Kind::VersionData {
473            if let Err(e) = carry_attachments(&c.dir, &current_data) {
474                report.skipped.push((c.dir.clone(), format!("could not carry its attachments forward: {e}")));
475                continue;
476            }
477        }
478        let target = if c.dir.file_name().is_some_and(|n| n.to_string_lossy().contains(".removing-")) {
479            c.dir.clone()
480        } else {
481            let name = c.dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
482            let renamed = c.dir.with_file_name(format!("{name}.removing-{}", std::process::id()));
483            // Windows refuses this while any file inside is open: one more look at "in use".
484            if let Err(e) = std::fs::rename(&c.dir, &renamed) {
485                report.skipped.push((c.dir.clone(), format!("could not be renamed, so something has it open: {e}")));
486                continue;
487            }
488            renamed
489        };
490        match std::fs::remove_dir_all(&target) {
491            Ok(()) => report.removed.push((c.dir.clone(), c.bytes)),
492            Err(e) => report.skipped.push((target, format!("removal started, finishing on the next pass: {e}"))),
493        }
494    }
495    report
496}
497
498/// Copy an old version's `data/attachments` into the running version's, keeping what is already
499/// there. A file, directory or link that cannot be read stops the copy: the caller then keeps the
500/// old folder rather than lose something an old conversation shows. Returns the bytes copied.
501fn carry_attachments(from_version: &Path, current_data: &Path) -> Result<u64, String> {
502    fn copy(src: &Path, dst: &Path) -> Result<u64, String> {
503        std::fs::create_dir_all(dst).map_err(|e| format!("create {}: {e}", dst.display()))?;
504        let mut bytes = 0;
505        for entry in std::fs::read_dir(src).map_err(|e| format!("read {}: {e}", src.display()))? {
506            let entry = entry.map_err(|e| format!("entry of {}: {e}", src.display()))?;
507            let file_type = entry.file_type().map_err(|e| format!("type of {}: {e}", entry.path().display()))?;
508            if file_type.is_symlink() {
509                // Its target may be outside the version folder; keep the whole folder rather than
510                // drop an attachment an old conversation shows.
511                return Err(format!("{} is a symlink, so it is not carried", entry.path().display()));
512            }
513            let to = dst.join(entry.file_name());
514            if file_type.is_dir() {
515                bytes += copy(&entry.path(), &to)?;
516                continue;
517            }
518            // A file already in the running version's store is the newer one (derived metadata and
519            // session files are mutable): leave it untouched.
520            if to.exists() {
521                continue;
522            }
523            let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
524            // Copy under a temporary name and publish on success: a copy cut short never leaves a
525            // partial file that the next pass would take for the finished one.
526            let tmp = dst.join(format!(".{}.copying-{}", entry.file_name().to_string_lossy(), std::process::id()));
527            if let Err(e) = std::fs::copy(entry.path(), &tmp) {
528                let _ = std::fs::remove_file(&tmp);
529                return Err(format!("copy to {}: {e}", to.display()));
530            }
531            match publish(&tmp, &to) {
532                Ok(true) => bytes += size,
533                // The running store wrote the same file after the check above: its newer copy
534                // keeps the name and this one is dropped (#8930).
535                Ok(false) => {}
536                Err(e) => return Err(format!("publish to {}: {e}", to.display())),
537            }
538        }
539        Ok(bytes)
540    }
541    let src = from_version.join("data").join("attachments");
542    if !src.is_dir() {
543        return Ok(0);
544    }
545    copy(&src, &current_data.join("attachments"))
546}
547
548/// Give a finished copy its real name only if nothing has that name, and drop the temporary copy.
549/// Returns whether this copy took the name, or the error that kept the old folder.
550///
551/// The running attachment store writes under the same folder while cleanup runs (a session's
552/// inline bytes, regenerated metadata), so a file can appear between the caller's `exists` check
553/// and here. A hard link fails atomically on an existing name, where the rename this replaces
554/// would have put the old version's copy over the newer one (#8930, #8937).
555///
556/// A filesystem without hard links (FAT, some network shares) is an error, not a reason to write
557/// the real name in place: a crash mid-copy would leave a partial file that the next pass takes
558/// for the finished one, and then removes the old folder holding the complete original. The
559/// caller keeps that folder instead.
560fn publish(tmp: &Path, to: &Path) -> std::io::Result<bool> {
561    match std::fs::hard_link(tmp, to) {
562        Ok(()) => {
563            let _ = std::fs::remove_file(tmp);
564            Ok(true)
565        }
566        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists || to.exists() => {
567            let _ = std::fs::remove_file(tmp);
568            Ok(false)
569        }
570        Err(e) => {
571            let _ = std::fs::remove_file(tmp);
572            Err(e)
573        }
574    }
575}
576
577/// The outcome of one [`run`].
578#[derive(Debug, Serialize)]
579pub struct Run {
580    pub plan: Plan,
581    /// `None` for a dry run.
582    pub report: Option<Report>,
583    /// The processes could be read. When they could not, nothing is removable.
584    pub scan_ok: bool,
585}
586
587/// Plans, and unless `dry_run`, removes. `only` limits a removal to folders an earlier dry run
588/// listed: what became removable since is left alone, so a removal is what the caller was shown.
589pub fn run(layout: &Layout, policy: &Policy, dry_run: bool, only: Option<&[String]>, now: SystemTime) -> Run {
590    let in_use = InUse::scan();
591    let scan_ok = in_use.procs.is_some();
592    let mut plan = plan(layout, policy, now, &in_use);
593    if let Some(only) = only {
594        plan.removable.retain(|c| only.iter().any(|d| Path::new(d) == c.dir));
595    }
596    let report = (!dry_run).then(|| remove(&plan, layout, policy, now, &InUse::scan));
597    Run { plan, report, scan_ok }
598}
599
600#[cfg(test)]
601#[path = "old_versions_tests.rs"]
602mod tests;