Skip to main content

agentmux_srv_core/registry/
shared_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Two AgentMux installs of different versions must not write the shared stores together.
5//!
6//! `~/.agentmux/shared/` is account-wide on purpose: the agents' definitions, history
7//! (`agents/transcripts/filestore.db`), accounts and identities follow the person across installs
8//! and channels. Each install is otherwise isolated, so a Store install and a portable one could
9//! run side by side and both write those files, each with its own SQLite and schema.
10//!
11//! Two guards:
12//! - **One writer version.** Each srv that uses the shared folder takes the next place in
13//!   `locks/srv-writers/<n>.json` (its pid, start time, version and channel). A srv that finds a live
14//!   srv of another version in an earlier place waits [`WAIT`] for it to exit (an upgrade restarts srv, and the old one may still be
15//!   leaving), and then runs without the shared folder, as it does when there is none: its agents,
16//!   accounts and history are this channel's own until it is restarted alone. It records an incident
17//!   that says so. Same-version srvs share as before: one SQLite, one schema, WAL across processes.
18//! - **A newer store than this build.** A store whose `user_version` is above this build's was
19//!   refused already (`check_schema_compat`) and the srv fell back, with a line in the log only. It
20//!   now records an incident too, so the person is told to update.
21//!
22//! A srv that registered later never makes an earlier one defer, so the earliest live srv of a version
23//! keeps the folder for as long as it runs. The order is the order of registration, not process age:
24//! a srv that started later but registered first is the owner.
25
26use std::path::{Path, PathBuf};
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::time::{Duration, Instant};
29
30use serde::{Deserialize, Serialize};
31
32use crate::backend::storage::error::StoreError;
33
34/// How long a srv waits for an earlier srv of another version to exit before it runs without the
35/// shared folder.
36const WAIT: Duration = Duration::from_secs(20);
37const POLL: Duration = Duration::from_millis(500);
38
39/// Set when this srv runs without the shared folder (`registry::resolve_global_shared_root` reads it).
40static DEFERRED: AtomicBool = AtomicBool::new(false);
41
42/// Set once the person has been told this start that the shared files are newer than this build.
43static TOLD_TOO_NEW: AtomicBool = AtomicBool::new(false);
44
45/// Whether this srv gave the shared folder up to an earlier srv of another version.
46pub(crate) fn deferred() -> bool {
47    DEFERRED.load(Ordering::Relaxed)
48}
49
50/// The account-wide shared folder for the files srv keeps there itself (bookmarks, browser profiles,
51/// layouts, task media), or `None` while this srv has given the folder up, as with the shared stores.
52pub fn shared_dir() -> Option<PathBuf> {
53    if deferred() {
54        return None;
55    }
56    agentmux_common::DataPaths::from_env().map(|p| p.shared_dir)
57}
58
59/// A srv that uses the shared folder.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub(super) struct Writer {
62    pub pid: u32,
63    /// The process start time (seconds): a reused pid does not pass for the srv that wrote the file.
64    pub started_s: u64,
65    pub version: String,
66    pub channel: String,
67}
68
69impl Writer {
70    fn this(sys: &sysinfo::System, version: &str) -> Writer {
71        let pid = std::process::id();
72        Writer {
73            pid,
74            started_s: crate::backend::transcript::framer::start_time(sys, pid).unwrap_or(0),
75            version: version.to_string(),
76            channel: std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default(),
77        }
78    }
79
80    fn label(&self) -> String {
81        if self.channel.is_empty() {
82            format!("AgentMux {}", self.version)
83        } else {
84            format!("AgentMux {} ({})", self.version, self.channel)
85        }
86    }
87}
88
89/// How a start went.
90#[derive(Debug, PartialEq, Eq)]
91pub(super) enum Claim {
92    /// This srv uses the shared folder.
93    Owner,
94    /// An earlier srv of another version has it; this one runs without.
95    Deferred(Writer),
96}
97
98/// A registered srv: its place in the order of registration, and who it is.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub(super) struct Entry {
101    pub seq: u64,
102    pub writer: Writer,
103}
104
105fn writers_dir(shared_root: &Path) -> PathBuf {
106    shared_root.join("locks").join("srv-writers")
107}
108
109fn seq_of(path: &Path) -> Option<u64> {
110    if path.extension()? != "json" {
111        return None;
112    }
113    path.file_stem()?.to_str()?.parse().ok()
114}
115
116/// The registered srvs other than `me` that are still running; a file whose process is gone is
117/// removed.
118fn live_others(dir: &Path, me: u32, alive: &dyn Fn(&Writer) -> bool) -> Vec<Entry> {
119    let mut out = Vec::new();
120    let Ok(entries) = std::fs::read_dir(dir) else { return out };
121    for entry in entries.flatten() {
122        let path = entry.path();
123        let Some(seq) = seq_of(&path) else { continue };
124        let Some(writer) = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::<Writer>(&b).ok()) else { continue };
125        if writer.pid == me {
126            continue;
127        }
128        if alive(&writer) {
129            out.push(Entry { seq, writer });
130        } else {
131            let _ = std::fs::remove_file(&path);
132        }
133    }
134    out
135}
136
137/// The highest place taken, or 0.
138fn highest(dir: &Path) -> std::io::Result<u64> {
139    Ok(std::fs::read_dir(dir)?.flatten().filter_map(|e| seq_of(&e.path())).max().unwrap_or(0))
140}
141
142/// Link `aside` into place `start`, or the next free one: a hard link fails if another srv took that
143/// number, so two srvs never share a place. Returns the place.
144fn link_from(dir: &Path, aside: &Path, start: u64) -> std::io::Result<u64> {
145    let mut seq = start;
146    loop {
147        match std::fs::hard_link(aside, dir.join(format!("{seq}.json"))) {
148            Ok(()) => return Ok(seq),
149            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => seq += 1,
150            Err(e) => return Err(e),
151        }
152    }
153}
154
155/// Take the next place in the order, as a file `<seq>.json` that is whole from the moment it exists
156/// (written aside and linked into place). A srv that picked its number, then stalled while others
157/// registered, finds a higher place taken once it is linked: it gives its place back and takes a new
158/// one, so a place never ranks a srv ahead of one that was already running when it was published.
159fn register(dir: &Path, me: &Writer) -> std::io::Result<u64> {
160    std::fs::create_dir_all(dir)?;
161    let aside = dir.join(format!("{}.tmp", me.pid));
162    std::fs::write(&aside, serde_json::to_vec(me).unwrap_or_default())?;
163    let placed = settle(dir, &aside, highest(dir)? + 1);
164    let _ = std::fs::remove_file(&aside);
165    placed
166}
167
168/// [`link_from`] `start`, repeated while a higher place than the one got is already taken.
169fn settle(dir: &Path, aside: &Path, start: u64) -> std::io::Result<u64> {
170    let mut seq = link_from(dir, aside, start)?;
171    for _ in 0..8 {
172        if highest(dir)? <= seq {
173            break;
174        }
175        let _ = std::fs::remove_file(dir.join(format!("{seq}.json")));
176        seq = link_from(dir, aside, highest(dir)? + 1)?;
177    }
178    Ok(seq)
179}
180
181/// The srv of another version that registered before `my_seq`, if any: the one `me` gives the
182/// folder to.
183fn blocker(my_seq: u64, me: &Writer, others: &[Entry]) -> Option<Writer> {
184    others.iter().filter(|o| o.writer.version != me.version && o.seq < my_seq).min_by_key(|o| o.seq).map(|o| o.writer.clone())
185}
186
187/// Register `me` in `dir`, then wait up to `wait` for an earlier-registered srv of another version
188/// to exit. A srv that gives the folder up removes its file.
189pub(crate) fn claim_in(dir: &Path, me: &Writer, alive: &dyn Fn(&Writer) -> bool, wait: Duration, poll: Duration) -> Claim {
190    let seq = match register(dir, me) {
191        Ok(seq) => seq,
192        Err(e) => {
193            tracing::warn!(error = %e, dir = %dir.display(), "shared guard: couldn't register this srv; the shared folder is used unguarded");
194            return Claim::Owner;
195        }
196    };
197    let started = Instant::now();
198    loop {
199        match blocker(seq, me, &live_others(dir, me.pid, alive)) {
200            None => return Claim::Owner,
201            Some(b) if started.elapsed() >= wait => {
202                let _ = std::fs::remove_file(dir.join(format!("{seq}.json")));
203                return Claim::Deferred(b);
204            }
205            Some(_) => std::thread::sleep(poll),
206        }
207    }
208}
209
210/// The words the person is told when this srv gives the folder up.
211pub(crate) fn deferred_incident(me: &Writer, owner: &Writer) -> agentmux_common::incidents::Incident {
212    let mut i = agentmux_common::incidents::Incident::new(
213        "shared_stores_in_use",
214        format!(
215            "{} is using your shared agents, accounts and history, so {} started without them. Close {} and restart this one to use them.",
216            owner.label(),
217            me.label(),
218            owner.label()
219        ),
220        "srv",
221    );
222    i.cause = Some("Two AgentMux installs of different versions must not write the same files at the same time.".to_string());
223    i.did = vec!["This AgentMux left your shared files alone.".to_string()];
224    i.lost = vec!["Until it is restarted alone, it shows only its own channel's agents and history.".to_string()];
225    i
226}
227
228/// The words the person is told when the shared files are newer than this build.
229pub(crate) fn too_new_incident(db: &str, found: i64, expected: i64, me: &Writer) -> agentmux_common::incidents::Incident {
230    let mut i = agentmux_common::incidents::Incident::new(
231        "shared_store_newer",
232        format!("{} is older than your data ({db} is at version {found}; this one reads up to {expected}). Update AgentMux to use it.", me.label()),
233        "srv",
234    );
235    i.cause = Some("A newer AgentMux changed your shared files.".to_string());
236    i.did = vec![format!("This AgentMux did not open {db}, so it did not change it.")];
237    i.lost = vec!["Until it is updated, it shows only its own channel's agents, accounts and history.".to_string()];
238    i
239}
240
241fn record(incident: &agentmux_common::incidents::Incident) {
242    tracing::warn!(target: "incidents", kind = %incident.kind, what = %incident.what, "incident recorded");
243    let Some(paths) = agentmux_common::DataPaths::from_env() else { return };
244    let path = paths.data_dir.join(agentmux_common::incidents::FILE_NAME);
245    if let Err(e) = agentmux_common::incidents::append(&path, incident) {
246        tracing::warn!(error = %e, "shared guard: couldn't write the incident");
247    }
248}
249
250/// A shared store that did not open: when it is because the files are newer than this build, say so.
251pub fn note_open_failure(e: &StoreError) {
252    if let StoreError::SchemaTooNew { db, found, expected } = e {
253        // Up to three stores fail the same way in one start; one notice says it.
254        if TOLD_TOO_NEW.swap(true, Ordering::Relaxed) {
255            return;
256        }
257        let sys = crate::backend::transcript::framer::scan_processes();
258        record(&too_new_incident(db, *found, *expected, &Writer::this(&sys, env!("CARGO_PKG_VERSION"))));
259    }
260}
261
262/// Claim the shared folder for this srv, or give it up to an earlier srv of another version.
263/// Before any shared store is opened. A srv with no shared folder (a bare run) has nothing to claim.
264pub fn claim_at_boot(version: &str) {
265    let Some((me, claim)) = claim_this_process(version) else { return };
266    match claim {
267        Claim::Owner => tracing::info!(version, "shared guard: this srv uses the shared folder"),
268        Claim::Deferred(owner) => {
269            record(&deferred_incident(&me, &owner));
270            // Without the shared folder this srv cannot prepare its own data either, so it must not
271            // start on data that needs it: it would run on files no migration has touched.
272            if let Some(reason) = agentmux_common::DataPaths::from_env().and_then(|p| crate::migrations::data_needs_preparing(&p.data_dir, version)) {
273                tracing::error!(%reason, "shared guard: this srv's data needs preparing and the shared folder is held by another version; not starting");
274                std::process::exit(refuse_beside(&owner, &reason));
275            }
276            DEFERRED.store(true, Ordering::Relaxed);
277            tracing::warn!(owner_pid = owner.pid, owner_version = %owner.version, "shared guard: another version holds the shared folder; running without it");
278        }
279    }
280}
281
282/// Registers this process with the writers of the shared folder; `None` when there is no shared folder.
283fn claim_this_process(version: &str) -> Option<(Writer, Claim)> {
284    let root = crate::registry::resolve_global_shared_root()?;
285    let sys = crate::backend::transcript::framer::scan_processes();
286    let me = Writer::this(&sys, version);
287    let alive = |w: &Writer| {
288        let sys = crate::backend::transcript::framer::scan_processes();
289        sys.process(sysinfo::Pid::from_u32(w.pid))
290            .is_some_and(|p| crate::backend::transcript::framer::is_srv(&p.name().to_string_lossy()) && p.start_time().abs_diff(w.started_s) <= 1)
291    };
292    let claim = claim_in(&writers_dir(&root), &me, &alive, WAIT, POLL);
293    Some((me, claim))
294}
295
296/// `migrate` (applying, or `--prepare`) changes the shared stores, so it takes the same claim a srv does.
297/// Returns the exit code when it must not run. It records no notice: the srv the launcher starts next
298/// claims on its own and tells the person about the same conflict.
299pub(crate) fn claim_for_migrate(data_dir: &Path) -> Option<i32> {
300    let version = env!("CARGO_PKG_VERSION");
301    let (_, Claim::Deferred(owner)) = claim_this_process(version)? else { return None };
302    Some(migrate_exit_code(&owner, crate::migrations::data_needs_preparing(data_dir, version)))
303}
304
305/// `SHARED_FOLDER_HELD_EXIT` when another version holds the shared folder and this data needs preparing, `0` (nothing to do)
306/// when it holds it and the data is ready.
307fn migrate_exit_code(owner: &Writer, needs_preparing: Option<String>) -> i32 {
308    let Some(reason) = needs_preparing else { return 0 };
309    refuse_beside(owner, &reason)
310}
311
312/// Say why this srv does not start (to the person, and as a line the supervisor reads) and return the exit code
313/// that tells a supervisor the refusal will not clear by itself.
314fn refuse_beside(owner: &Writer, reason: &str) -> i32 {
315    eprintln!("agentmux-srv: {} is using the shared folder and this data needs preparing ({reason}). Close it and start this one again.", owner.label());
316    eprintln!("{}", agentmux_common::srv_stderr::shared_folder_held_line(&owner.label(), reason));
317    agentmux_common::srv_stderr::SHARED_FOLDER_HELD_EXIT
318}
319
320#[cfg(test)]
321#[path = "shared_guard_tests.rs"]
322mod tests;