Skip to main content

agentmux_srv_core/backend/slug_migration/
preconditions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What must hold before a run writes anything (ยง4 Phase 2, "Preconditions"):
5//! the agents run nowhere on this host, every AgentMux running here
6//! understands former slugs, and no other migration is under way.
7
8use std::collections::HashSet;
9use std::fs::{File, OpenOptions, TryLockError};
10
11use super::home::{place, Home, Install};
12use super::stamp;
13use crate::backend::process_identity::srv_alive;
14use crate::backend::reactive::registry::AgentEntry;
15use crate::backend::rpc_types::{ForkSlugBlocker, ForkSlugBlockerKind as Kind, ForkSlugCandidate};
16
17/// Everything that would refuse a run of `candidates` now, worded for the
18/// operator, each with its kind: only a running agent is cleared by
19/// stopping its pane. Empty when a run may start.
20pub(super) fn blockers(home: &Home, installs: &[Install], candidates: &[ForkSlugCandidate], check_lock: bool) -> Vec<ForkSlugBlocker> {
21    let mut out = Vec::new();
22    for c in candidates.iter().filter(|c| c.refused.is_none()) {
23        for r in &c.running {
24            let at = if r.channel.is_empty() { String::new() } else { format!(" in {}", r.channel) };
25            out.push(ForkSlugBlocker::new(Kind::Running, format!("{} is running{at} ({}): stop it first", c.name, r.how)));
26        }
27    }
28    out.extend(old_instances(home, installs).into_iter().map(|m| ForkSlugBlocker::new(Kind::OldInstance, m)));
29    if check_lock && lock_held(home) {
30        out.push(ForkSlugBlocker::new(Kind::Locked, "Another agent id update is under way. Wait for it to finish."));
31    }
32    out
33}
34
35/// Every running AgentMux on this host that doesn't say it understands
36/// former slugs (`stamp.rs`): a live srv lock whose stamp is missing, names
37/// another pid or lacks the feature; and a live srv in the cross-channel
38/// registry with no such stamp anywhere (one too old to lock its data
39/// directory).
40pub(super) fn old_instances(home: &Home, installs: &[Install]) -> Vec<String> {
41    let mut out = Vec::new();
42    let mut stamped: HashSet<u32> = HashSet::new();
43    let mut seen: HashSet<u32> = HashSet::new();
44    for install in installs {
45        for version in &install.versions {
46            let lock = version.srv_lock();
47            let written = std::fs::metadata(&lock).and_then(|m| m.modified()).ok();
48            let Some(pid) = stamp::lock_pid(&lock).filter(|p| *p != 0 && srv_alive(*p, written)) else { continue };
49            seen.insert(pid);
50            match stamp::read(&version.stamp()) {
51                Some(s) if s.pid == pid && s.has(stamp::FORMER_SLUGS) => {
52                    stamped.insert(pid);
53                }
54                Some(s) if s.pid == pid => out.push(format!(
55                    "An older AgentMux ({}) is running: {} (pid {pid}). It doesn't know former slugs. Update or quit it first.",
56                    s.version,
57                    place(install, version)
58                )),
59                _ => out.push(format!(
60                    "An older AgentMux is running: {} (pid {pid}). Update or quit it first.",
61                    place(install, version)
62                )),
63            }
64        }
65    }
66    let Ok(names) = std::fs::read_dir(home.reactive()) else { return out };
67    for dir in names.flatten().filter(|d| d.path().is_dir()) {
68        let Ok(files) = std::fs::read_dir(dir.path()) else { continue };
69        for file in files.flatten() {
70            let Some(entry) = std::fs::read(file.path()).ok().and_then(|b| serde_json::from_slice::<AgentEntry>(&b).ok()) else {
71                continue;
72            };
73            if entry.pid == 0 || stamped.contains(&entry.pid) || !seen.insert(entry.pid) || !srv_alive(entry.pid, None) {
74                continue;
75            }
76            out.push(format!(
77                "An older AgentMux is running: channel {} (pid {}), which doesn't say which version it is. Update or quit it first.",
78                entry.channel, entry.pid
79            ));
80        }
81    }
82    out
83}
84
85/// Whether another process holds the migration lock now. Reads only: a lock
86/// file that doesn't exist isn't created.
87fn lock_held(home: &Home) -> bool {
88    let path = home.lock_file();
89    let Ok(file) = OpenOptions::new().read(true).write(true).open(&path) else { return false };
90    matches!(file.try_lock(), Err(TryLockError::WouldBlock))
91}
92
93/// The host-wide migration lock, held until the file is dropped. One run or
94/// rollback at a time, whatever process starts it.
95pub(super) fn take_lock(home: &Home) -> Result<File, String> {
96    let path = home.lock_file();
97    if let Some(dir) = path.parent() {
98        std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
99    }
100    #[allow(clippy::suspicious_open_options)]
101    let file = OpenOptions::new()
102        .read(true)
103        .write(true)
104        .create(true)
105        .truncate(false)
106        .open(&path)
107        .map_err(|e| format!("{}: {e}", path.display()))?;
108    match file.try_lock() {
109        Ok(()) => Ok(file),
110        Err(TryLockError::WouldBlock) => Err("another fork slug migration is under way".to_string()),
111        Err(TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
112    }
113}