Skip to main content

agentmux_srv_core/backend/slug_migration/
steps_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The file steps: S1 (the shared definition, through its record lock), the
5//! workspace `.mcp.json` half of S7, and S8 (the `gh-<slug>` folders, the
6//! bashwrap cwd file, stale registrations). Writes go through a temporary file
7//! and a rename. An undo restores the backup's bytes when the file is still
8//! what the step left, so a reverted file is byte-identical; a file changed
9//! since is reverted field by field (S1) or left as it is, and said so.
10
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16use super::home::{fold, write_file, Home};
17use super::steps::{parse, to_value, Agent, Ctx};
18use crate::registry::{record_bytes, DefStoreError, DefinitionStore};
19
20fn io(msg: String) -> DefStoreError {
21    DefStoreError::Io(std::io::Error::other(msg))
22}
23
24pub(super) fn def_path(home: &Home, uid: &str) -> PathBuf {
25    home.definitions().join(format!("{uid}.json"))
26}
27
28// ── S1: the shared definition ────────────────────────────────────────
29
30#[derive(Debug, Serialize, Deserialize)]
31struct S1Before {
32    slug: String,
33    had_former: bool,
34}
35
36fn former_has(value: &Value, slug: &str) -> bool {
37    value
38        .pointer("/data/former_slugs")
39        .and_then(Value::as_array)
40        .is_some_and(|l| l.iter().any(|f| f.get("slug").and_then(Value::as_str).is_some_and(|s| fold(s) == fold(slug))))
41}
42
43/// `value` renamed: slug the new one, the old one appended to the former
44/// slugs (lowercased, `retired_at` the run's). Whether it changed.
45fn renamed(value: &mut Value, a: &Agent, retired_at: i64) -> Result<bool, String> {
46    let had = former_has(value, &a.old);
47    let data = value.get_mut("data").and_then(Value::as_object_mut).ok_or("the definition has no `data`")?;
48    let mut changed = false;
49    if data.get("slug").and_then(Value::as_str) != Some(a.new.as_str()) {
50        data.insert("slug".into(), Value::String(a.new.clone()));
51        changed = true;
52    }
53    if !had {
54        let list = data.entry("former_slugs").or_insert_with(|| Value::Array(Vec::new()));
55        let list = list.as_array_mut().ok_or("`former_slugs` isn't a list")?;
56        list.push(serde_json::json!({ "slug": fold(&a.old), "retired_at": retired_at }));
57        changed = true;
58    }
59    Ok(changed)
60}
61
62fn read_json(bytes: &[u8]) -> Result<Value, String> {
63    serde_json::from_slice(bytes).map_err(|e| format!("the definition isn't JSON: {e}"))
64}
65
66pub(super) fn s1_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
67    let path = def_path(ctx.home, &a.uid);
68    let value = read_json(&std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?)?;
69    let slug = value.pointer("/data/slug").and_then(Value::as_str).unwrap_or_default().to_string();
70    to_value(&S1Before { slug, had_former: former_has(&value, &a.old) })
71}
72
73fn with_def<T>(ctx: &Ctx, a: &Agent, f: impl FnOnce(&crate::registry::LockedRecord<'_>) -> Result<T, String>) -> Result<T, String> {
74    let store = DefinitionStore::open(ctx.home.definitions()).map_err(|e| e.to_string())?;
75    store.with_record_locked(&a.uid, |rec| f(rec).map_err(io)).map_err(|e| e.to_string())
76}
77
78pub(super) fn s1_apply(ctx: &Ctx, a: &Agent, _before: &Value) -> Result<Vec<String>, String> {
79    with_def(ctx, a, |rec| {
80        let bytes = rec.raw().map_err(|e| e.to_string())?.ok_or("the agent's shared definition is gone")?;
81        let mut value = read_json(&bytes)?;
82        if !renamed(&mut value, a, ctx.retired_at)? {
83            return Ok(Vec::new());
84        }
85        rec.replace_raw(&record_bytes(&value).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
86        Ok(vec![format!("shared definition: slug {} -> {}, {} kept as a former slug", a.old, a.new, fold(&a.old))])
87    })
88}
89
90pub(super) fn s1_undo(ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
91    let b: S1Before = parse(before)?;
92    let original = std::fs::read(ctx.backup_of(&def_path(ctx.home, &a.uid))?).map_err(|e| e.to_string())?;
93    with_def(ctx, a, |rec| {
94        let Some(bytes) = rec.raw().map_err(|e| e.to_string())? else {
95            return Ok(vec!["shared definition: gone since the run (deleted); nothing to revert".into()]);
96        };
97        let current = read_json(&bytes)?;
98        let mut expected = read_json(&original)?;
99        renamed(&mut expected, a, ctx.retired_at)?;
100        if current == expected || bytes == original {
101            if bytes != original {
102                rec.replace_raw(&original).map_err(|e| e.to_string())?;
103            }
104            return Ok(vec!["shared definition: restored exactly as it was".into()]);
105        }
106        let mut value = current;
107        let data = value.get_mut("data").and_then(Value::as_object_mut).ok_or("the definition has no `data`")?;
108        data.insert("slug".into(), Value::String(b.slug.clone()));
109        if !b.had_former {
110            if let Some(list) = data.get_mut("former_slugs").and_then(Value::as_array_mut) {
111                list.retain(|f| f.get("slug").and_then(Value::as_str).is_none_or(|s| fold(s) != fold(&a.old)));
112                if list.is_empty() {
113                    data.remove("former_slugs");
114                }
115            }
116        }
117        rec.replace_raw(&record_bytes(&value).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
118        Ok(vec![format!("shared definition: slug back to {}; edited since the run, so its other changes are kept", b.slug)])
119    })
120}
121
122// ── S7: the workspace .mcp.json ──────────────────────────────────────
123
124/// The `.mcp.json` files that sign as the old id: in the definition's
125/// working folder and in each of the agent's panes' `cmd:cwd`.
126pub(super) fn mcp_files(ctx: &Ctx, a: &Agent) -> Result<Vec<PathBuf>, String> {
127    let def = std::fs::read(def_path(ctx.home, &a.uid)).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok());
128    let mut dirs: Vec<String> =
129        def.and_then(|d| d.pointer("/data/working_directory").and_then(Value::as_str).map(str::to_string)).into_iter().collect();
130    dirs.extend(super::steps_db::block_cwds(ctx, a)?);
131    let mut out: Vec<PathBuf> = Vec::new();
132    for dir in dirs.iter().filter(|d| !d.trim().is_empty()) {
133        let path = PathBuf::from(crate::backend::blockcontroller::core::expand_home_dir(dir)).join(".mcp.json");
134        if !out.contains(&path) && names(&path, &a.old) {
135            out.push(path);
136        }
137    }
138    Ok(out)
139}
140
141/// Whether the file's AgentMux entry signs as `id`.
142fn names(path: &Path, id: &str) -> bool {
143    let Some(json) = std::fs::read(path).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) else { return false };
144    json.pointer("/mcpServers/agentmux/env/AGENTMUX_AGENT_ID").and_then(Value::as_str).is_some_and(|v| fold(v) == fold(id))
145}
146
147/// `content` with its AgentMux entry signing as the new id, and the old
148/// id's keys dropped: the next spawn writes the new id's
149/// (`mcp_json_identity::realign_workspace_mcp_json`). The rest of the file,
150/// the user's own servers included, is kept.
151fn retargeted(content: &str, a: &Agent) -> Option<String> {
152    crate::backend::mcp_json_identity::set_agent_id(content, &a.new).map(|(patched, _)| patched)
153}
154
155pub(super) fn s7_files_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
156    let files: Vec<String> = mcp_files(ctx, a)?.iter().map(|p| p.display().to_string()).collect();
157    to_value(&files)
158}
159
160pub(super) fn s7_files_apply(a: &Agent, before: &Value) -> Result<Vec<String>, String> {
161    let mut changes = Vec::new();
162    for file in parse::<Vec<String>>(before)? {
163        let Ok(content) = std::fs::read_to_string(&file) else { continue };
164        if !names(Path::new(&file), &a.old) {
165            continue;
166        }
167        if let Some(patched) = retargeted(&content, a) {
168            write_file(Path::new(&file), patched.as_bytes())?;
169            changes.push(format!("{file}: signs as {} (its keys come at the next spawn)", a.new));
170        }
171    }
172    Ok(changes)
173}
174
175pub(super) fn s7_files_undo(ctx: &Ctx, a: &Agent, before: &Value) -> Result<Vec<String>, String> {
176    let mut changes = Vec::new();
177    for file in parse::<Vec<String>>(before)? {
178        let path = Path::new(&file);
179        let original = std::fs::read(ctx.backup_of(path)?).map_err(|e| e.to_string())?;
180        let current = std::fs::read(path).ok();
181        let left_by_run = String::from_utf8(original.clone()).ok().and_then(|o| retargeted(&o, a)).map(String::into_bytes);
182        if current.as_deref() == Some(original.as_slice()) {
183            continue;
184        }
185        if current.is_none() || current == left_by_run {
186            write_file(path, &original)?;
187            changes.push(format!("{file}: restored exactly as it was"));
188        } else {
189            changes.push(format!("{file}: changed since the run (a relaunch rewrites it), left as it is"));
190        }
191    }
192    Ok(changes)
193}
194
195// ── S8: folders and files named after the slug ───────────────────────
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
198struct Move {
199    from: String,
200    to: String,
201    to_existed: bool,
202}
203
204#[derive(Debug, Default, Serialize, Deserialize)]
205struct S8Before {
206    moves: Vec<Move>,
207    /// Stale registrations, deleted; their copies are in the backup.
208    deletes: Vec<String>,
209}
210
211/// bashwrap's file name for an id (`cwd_state.rs`).
212fn cwd_key(id: &str) -> String {
213    id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect()
214}
215
216/// The stale registrations S8 deletes: each version's `data/agents/<old>.json`
217/// and the cross-channel registry's `<old>/` entries.
218pub(super) fn stale_registrations(ctx: &Ctx, a: &Agent) -> Vec<PathBuf> {
219    let stem = agentmux_common::slug::file_stem(&a.old);
220    let mut out: Vec<PathBuf> = ctx
221        .installs
222        .iter()
223        .flat_map(|i| i.versions.iter().map(|v| v.registrations().join(format!("{stem}.json"))))
224        .filter(|p| p.is_file())
225        .collect();
226    if let Ok(files) = std::fs::read_dir(ctx.home.reactive().join(&stem)) {
227        let mut shared: Vec<PathBuf> = files.flatten().map(|f| f.path()).filter(|p| p.is_file()).collect();
228        shared.sort();
229        out.extend(shared);
230    }
231    out
232}
233
234pub(super) fn cwd_file(home: &Home, id: &str) -> PathBuf {
235    home.bashwrap_dir.join(format!("{}.cwd", cwd_key(id)))
236}
237
238pub(super) fn s8_before(ctx: &Ctx, a: &Agent) -> Result<Value, String> {
239    let mut moves = Vec::new();
240    for install in ctx.installs {
241        let from = crate::backend::gh_guard::agent_gh_config_dir(&install.config_dir(), Some(&a.old));
242        let to = crate::backend::gh_guard::agent_gh_config_dir(&install.config_dir(), Some(&a.new));
243        if from.is_dir() {
244            moves.push(Move { to_existed: to.exists(), from: from.display().to_string(), to: to.display().to_string() });
245        }
246    }
247    let (from, to) = (cwd_file(ctx.home, &a.old), cwd_file(ctx.home, &a.new));
248    if from.is_file() {
249        moves.push(Move { to_existed: to.exists(), from: from.display().to_string(), to: to.display().to_string() });
250    }
251    let deletes = stale_registrations(ctx, a).iter().map(|p| p.display().to_string()).collect();
252    to_value(&S8Before { moves, deletes })
253}
254
255pub(super) fn s8_apply(before: &Value) -> Result<Vec<String>, String> {
256    let b: S8Before = parse(before)?;
257    let mut changes = Vec::new();
258    for m in &b.moves {
259        let (from, to) = (Path::new(&m.from), Path::new(&m.to));
260        if !from.exists() {
261            continue;
262        }
263        if to.exists() {
264            tracing::warn!(from = %m.from, to = %m.to, "fork slug migration: the new name's folder exists; both kept");
265            changes.push(format!("{} kept beside {}, which already existed", m.from, m.to));
266            continue;
267        }
268        std::fs::rename(from, to).map_err(|e| format!("move {} to {}: {e}", m.from, m.to))?;
269        changes.push(format!("moved {} to {}", m.from, m.to));
270    }
271    for file in &b.deletes {
272        let path = Path::new(file);
273        match std::fs::remove_file(path) {
274            Ok(()) => changes.push(format!("deleted the stale registration {file}")),
275            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
276            Err(e) => return Err(format!("delete {file}: {e}")),
277        }
278        if let Some(dir) = path.parent().filter(|d| d.parent().is_some_and(|p| p.ends_with("reactive"))) {
279            let _ = std::fs::remove_dir(dir);
280        }
281    }
282    Ok(changes)
283}
284
285pub(super) fn s8_undo(ctx: &Ctx, before: &Value) -> Result<Vec<String>, String> {
286    let b: S8Before = parse(before)?;
287    let mut changes = Vec::new();
288    for m in b.moves.iter().rev() {
289        let (from, to) = (Path::new(&m.from), Path::new(&m.to));
290        if !m.to_existed && to.exists() && !from.exists() {
291            std::fs::rename(to, from).map_err(|e| format!("move {} back to {}: {e}", m.to, m.from))?;
292            changes.push(format!("moved {} back to {}", m.to, m.from));
293        }
294    }
295    for file in &b.deletes {
296        let path = Path::new(file);
297        if !path.exists() {
298            let bytes = std::fs::read(ctx.backup_of(path)?).map_err(|e| e.to_string())?;
299            write_file(path, &bytes)?;
300            changes.push(format!("restored {file}"));
301        }
302    }
303    Ok(changes)
304}