Skip to main content

agentmux_srv_core/backend/slug_migration/
home.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a migration looks: the AgentMux root and every install on it, read
5//! from the disk rather than from the running instance, so every channel and
6//! version is covered, running or not (S2's "all channels and versions").
7
8use std::path::{Path, PathBuf};
9
10use rusqlite::{Connection, OpenFlags};
11
12/// The AgentMux root a migration works on.
13#[derive(Debug, Clone)]
14pub struct Home {
15    pub root: PathBuf,
16    /// `shared/`, beside `channels/` and `dev/`.
17    pub shared: PathBuf,
18    /// bashwrap's cwd files (K11). bashwrap reads `~/.agentmux` from the
19    /// user's home whatever the overrides say, so a test or an isolated
20    /// `task dev` gets one under its own root instead.
21    pub bashwrap_dir: PathBuf,
22}
23
24impl Home {
25    /// A root holding `shared/`, `channels/` and `dev/` (tests, fixtures).
26    pub fn at(root: &Path) -> Home {
27        Home {
28            root: root.to_path_buf(),
29            shared: root.join("shared"),
30            bashwrap_dir: root.join("state").join("bashwrap-cwd"),
31        }
32    }
33
34    /// The root this srv runs on: `AGENTMUX_HOME_OVERRIDE` when it is set,
35    /// else the root captured at startup.
36    pub fn from_env() -> Result<Home, String> {
37        if let Some(over) = std::env::var_os("AGENTMUX_HOME_OVERRIDE").filter(|s| !s.is_empty()) {
38            return Ok(Home::at(Path::new(&over)));
39        }
40        let root = crate::srv_info::agentmux_root().ok_or("the AgentMux root can't be resolved")?;
41        let mut home = Home::at(&root);
42        if let Some(shared) = crate::registry::resolve_global_shared_root() {
43            home.shared = shared;
44        }
45        if let Some(user) = dirs::home_dir() {
46            home.bashwrap_dir = user.join(".agentmux").join("state").join("bashwrap-cwd");
47        }
48        Ok(home)
49    }
50
51    pub fn definitions(&self) -> PathBuf {
52        self.shared.join("agents").join("definitions")
53    }
54    pub fn reactive(&self) -> PathBuf {
55        self.shared.join("agents").join("reactive")
56    }
57    pub fn leases(&self) -> PathBuf {
58        self.shared.join("agents").join("registry").join("leases")
59    }
60    pub fn lock_file(&self) -> PathBuf {
61        self.shared.join("locks").join("slug-migration.lock")
62    }
63    pub fn backups(&self) -> PathBuf {
64        self.shared.join("backups")
65    }
66
67    /// The host-wide stores that hold name-keyed rows: `store.db` (cron jobs,
68    /// MuxBus credentials) and `identity-store.db` (the work queue), plus an
69    /// install's own `identity-store.db` under isolated auth.
70    pub fn host_stores(&self, installs: &[Install]) -> Vec<PathBuf> {
71        let mut out: Vec<PathBuf> = ["store.db", "identity-store.db"].iter().map(|f| self.shared.join(f)).collect();
72        out.extend(installs.iter().map(|i| i.dir.join("identity-store.db")));
73        out.retain(|p| p.is_file());
74        out
75    }
76
77    /// Every install on this root, each with its versions' data directories:
78    /// `channels/<ch>/versions/<v>/data` (and `channels/<ch>/data`, a dev
79    /// build pointed at a channel), `dev/<branch>/data` and
80    /// `dev/<branch>/<clone>/data`. A directory that exists but can't be
81    /// listed is an error: a migration must not miss a copy of the slug.
82    pub fn installs(&self) -> Result<Vec<Install>, String> {
83        let mut out = Vec::new();
84        for ch in list_dirs(&self.root.join("channels"))? {
85            let name = format!("channels/{}", file_name(&ch));
86            let mut versions = Vec::new();
87            if has_objects_db(&ch.join("data")) {
88                versions.push(VersionData { label: String::new(), data: ch.join("data") });
89            }
90            for v in list_dirs(&ch.join("versions"))? {
91                if has_objects_db(&v.join("data")) {
92                    versions.push(VersionData { label: file_name(&v), data: v.join("data") });
93                }
94            }
95            out.push(Install { name, dir: ch, versions });
96        }
97        for branch in list_dirs(&self.root.join("dev"))? {
98            if has_objects_db(&branch.join("data")) {
99                let name = format!("dev/{}", file_name(&branch));
100                out.push(Install { name, versions: vec![VersionData { label: String::new(), data: branch.join("data") }], dir: branch });
101                continue;
102            }
103            for clone in list_dirs(&branch)? {
104                if has_objects_db(&clone.join("data")) {
105                    let name = format!("dev/{}/{}", file_name(&branch), file_name(&clone));
106                    out.push(Install { name, versions: vec![VersionData { label: String::new(), data: clone.join("data") }], dir: clone });
107                }
108            }
109        }
110        Ok(out)
111    }
112}
113
114/// One channel, or one dev checkout: what it shares across its versions.
115#[derive(Debug, Clone)]
116pub struct Install {
117    pub name: String,
118    pub dir: PathBuf,
119    pub versions: Vec<VersionData>,
120}
121
122impl Install {
123    /// Where its `gh-<slug>` folders live (K10).
124    pub fn config_dir(&self) -> PathBuf {
125        self.dir.join("config")
126    }
127    /// Its `wan.db` (K5), when it has one.
128    pub fn wan_db(&self) -> Option<PathBuf> {
129        Some(self.dir.join("wan-identity").join("wan.db")).filter(|p| p.is_file())
130    }
131}
132
133/// One version's data directory.
134#[derive(Debug, Clone)]
135pub struct VersionData {
136    /// The version folder's name; empty for a dev or unversioned install.
137    pub label: String,
138    pub data: PathBuf,
139}
140
141impl VersionData {
142    pub fn objects_db(&self) -> PathBuf {
143        self.data.join("db").join("objects.db")
144    }
145    /// Its per-version registrations (K9).
146    pub fn registrations(&self) -> PathBuf {
147        self.data.join("agents")
148    }
149    /// The srv lock, which holds the running srv's pid.
150    pub fn srv_lock(&self) -> PathBuf {
151        self.data.join(crate::backend::base::SRV_DATA_LOCK_FILE)
152    }
153    /// What the srv running here can do (`stamp.rs`).
154    pub fn stamp(&self) -> PathBuf {
155        self.data.join(super::stamp::STAMP_FILE)
156    }
157}
158
159/// `<install>` or `<install>@<version>`, for reports.
160pub fn place(install: &Install, version: &VersionData) -> String {
161    if version.label.is_empty() {
162        install.name.clone()
163    } else {
164        format!("{}@{}", install.name, version.label)
165    }
166}
167
168fn has_objects_db(data: &Path) -> bool {
169    data.join("db").join("objects.db").is_file()
170}
171
172fn file_name(p: &Path) -> String {
173    p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
174}
175
176/// The subdirectories of `dir`, sorted; none when it doesn't exist.
177fn list_dirs(dir: &Path) -> Result<Vec<PathBuf>, String> {
178    let entries = match std::fs::read_dir(dir) {
179        Ok(e) => e,
180        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
181        Err(e) => return Err(format!("{} can't be listed: {e}", dir.display())),
182    };
183    let mut out = Vec::new();
184    for entry in entries {
185        let path = entry.map_err(|e| format!("{} can't be listed: {e}", dir.display()))?.path();
186        if path.is_dir() {
187            out.push(path);
188        }
189    }
190    out.sort();
191    Ok(out)
192}
193
194/// A database opened to read, never to change: no schema step, no pragma
195/// that writes.
196pub fn open_ro(path: &Path) -> Result<Connection, String> {
197    let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)
198        .map_err(|e| format!("open {}: {e}", path.display()))?;
199    conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
200    Ok(conn)
201}
202
203/// A database opened to write, as it is: an existing file only, and no
204/// schema step. Another version's `objects.db` must not be upgraded by
205/// opening it through `Store::open`.
206pub fn open_rw(path: &Path) -> Result<Connection, String> {
207    let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX)
208        .map_err(|e| format!("open {}: {e}", path.display()))?;
209    conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
210    Ok(conn)
211}
212
213pub fn table_exists(conn: &Connection, table: &str) -> bool {
214    conn.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1", [table], |_| Ok(()))
215        .is_ok()
216}
217
218/// Whether an `objects.db` has agent slugs to read; one older than
219/// `db_agents.slug` (or `db_agents` itself) holds none.
220pub fn has_agent_slugs(conn: &Connection) -> bool {
221    has_column(conn, "db_agents", "slug")
222}
223
224pub fn has_column(conn: &Connection, table: &str, column: &str) -> bool {
225    let Ok(mut stmt) = conn.prepare(&format!("PRAGMA table_info({table})")) else { return false };
226    let Ok(rows) = stmt.query_map([], |r| r.get::<_, String>(1)) else { return false };
227    let columns: Vec<String> = rows.flatten().collect();
228    columns.iter().any(|c| c == column)
229}
230
231/// Run `f` in one `BEGIN IMMEDIATE` transaction: committed if it returns
232/// `Ok`, rolled back otherwise.
233pub fn in_tx<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T, String>) -> Result<T, String> {
234    conn.execute_batch("BEGIN IMMEDIATE").map_err(|e| e.to_string())?;
235    match f(conn) {
236        Ok(v) => {
237            conn.execute_batch("COMMIT").map_err(|e| e.to_string())?;
238            Ok(v)
239        }
240        Err(e) => {
241            let _ = conn.execute_batch("ROLLBACK");
242            Err(e)
243        }
244    }
245}
246
247/// Write `bytes` to `path` through a temporary file beside it and a rename,
248/// never wider than the file it replaces. On Unix the temporary file is
249/// created owner-only (0600) from the start, so the bytes are never readable
250/// by others for a moment. A file being replaced then keeps its own mode,
251/// except a `.mcp.json`, which holds signing keys and is always 0600, as
252/// AgentMux writes it (`Workdir::write(.., owner_only = true)`); a new file
253/// stays 0600. On Windows the file takes its folder's ACL, as every write
254/// through `Workdir` does: the profile's per-user ACL.
255pub fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
256    use std::io::Write as _;
257    let dir = path.parent().ok_or("no parent directory")?;
258    std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
259    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
260    let tmp = path.with_file_name(format!(".{name}.{}.slug-migration", uuid::Uuid::new_v4()));
261    let err = |e: std::io::Error| format!("{}: {e}", tmp.display());
262    #[cfg(unix)]
263    let keep = (name != ".mcp.json").then(|| std::fs::metadata(path).ok().map(|m| m.permissions())).flatten();
264    let mut opts = std::fs::OpenOptions::new();
265    opts.write(true).create_new(true);
266    #[cfg(unix)]
267    {
268        use std::os::unix::fs::OpenOptionsExt as _;
269        opts.mode(0o600);
270    }
271    let written = (|| {
272        let mut f = opts.open(&tmp).map_err(err)?;
273        #[cfg(unix)]
274        if let Some(perms) = keep {
275            f.set_permissions(perms).map_err(err)?;
276        }
277        f.write_all(bytes).map_err(err)?;
278        f.sync_all().map_err(err)
279    })();
280    let result = written.and_then(|()| {
281        crate::backend::workdir_fs::rename_with_retry(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
282    });
283    if result.is_err() {
284        let _ = std::fs::remove_file(&tmp);
285    }
286    result
287}
288
289/// Make `path` owner-only on Unix: 0700 for a folder, 0600 for a file. On
290/// Windows it keeps the per-user ACL of the profile it lives in.
291pub fn owner_only(path: &Path) -> Result<(), String> {
292    #[cfg(unix)]
293    {
294        use std::os::unix::fs::PermissionsExt as _;
295        let mode = if path.is_dir() { 0o700 } else { 0o600 };
296        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).map_err(|e| format!("{}: {e}", path.display()))?;
297    }
298    #[cfg(not(unix))]
299    let _ = path;
300    Ok(())
301}
302
303/// A name as every key table folds it.
304pub fn fold(name: &str) -> String {
305    name.trim().to_lowercase()
306}