Skip to main content

agentmux_srv_core/backend/
mcp_json_identity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agent id in a workspace `.mcp.json`
5//! (`docs/specs/SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` P0.3).
6//!
7//! `mcpServers.agentmux.env.AGENTMUX_AGENT_ID` is the name the agent's
8//! `agentmux-mcp` process routes and signs as, beside the signing keys filed
9//! under that name. The file is written at launch and then reused by every
10//! respawn, so after a rename it names the old id until something rewrites
11//! it. Both writers of that entry correct it from the definition: the
12//! launch's `writeagentconfig` before it injects the keys, and each host
13//! spawn ([`realign_workspace_mcp_json`]).
14
15use serde_json::Value;
16
17const AGENT_ID: &str = "/mcpServers/agentmux/env/AGENTMUX_AGENT_ID";
18
19/// The keys filed under the name `.mcp.json` carried. They sign as that name
20/// only, so they go with it; `inject_jekt_signing_keys_into_mcp_json` adds
21/// the new name's.
22const NAME_KEYED: [&str; 4] = ["AGENTMUX_JEKT_KEY", "AGENTMUX_LAN_KEY", "AGENTMUX_WAN_KEY", "AGENTMUX_HOST_LABEL"];
23
24/// The signing values no start file holds, for any runtime: the file holds references, not values.
25/// A container sees its workspace through a mount and srv signs its jekts itself, by its token; a host
26/// agent's MCP server asks srv for its keys with its own token.
27pub(crate) const SIGNING_SECRETS: [&str; 3] = ["AGENTMUX_JEKT_KEY", "AGENTMUX_LAN_KEY", "AGENTMUX_WAN_KEY"];
28
29/// `content` without the signing keys of its agentmux server. `None` when it carries none, or isn't JSON.
30pub(crate) fn strip_signing_keys(content: &str) -> Option<String> {
31    let mut json: Value = serde_json::from_str(content).ok()?;
32    let env = json.pointer_mut("/mcpServers/agentmux/env")?.as_object_mut()?;
33    let mut removed = false;
34    for key in SIGNING_SECRETS {
35        removed |= env.remove(key).is_some();
36    }
37    removed.then(|| serde_json::to_string_pretty(&json).ok()).flatten()
38}
39
40/// A container agent's workspace `.mcp.json`, with the signing keys an earlier launch wrote taken out.
41/// Run at each container start, under the lock the launch writes the file with. Only those keys are
42/// removed, and only when the file has them, so a file with none is left byte-for-byte as it was.
43/// This also covers a user's project: keys an older launch wrote there must not ride the workspace
44/// mount into the container (a launch no longer writes any, #3680). Best-effort: a failure is
45/// logged and the start goes on.
46pub fn strip_workspace_signing_keys(work_dir: &str) -> bool {
47    if work_dir.trim().is_empty() {
48        return false;
49    }
50    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
51    let Ok(wd) = crate::backend::workdir_fs::Workdir::open(std::path::Path::new(&expanded)) else { return false };
52    let Ok(path) = wd.resolve(".mcp.json") else { return false };
53    let Ok(content) = std::fs::read_to_string(&path) else { return false };
54    if strip_signing_keys(&content).is_none() {
55        return false;
56    }
57    let _lock = match wd
58        .open_lock_file(crate::backend::agent_config::MCP_JSON_WRITE_LOCK)
59        .and_then(|f| f.lock().map(|()| f))
60    {
61        Ok(lock) => lock,
62        Err(e) => {
63            tracing::warn!(work_dir, error = %e, "container start: .mcp.json lock unavailable; signing keys not removed this start");
64            return false;
65        }
66    };
67    // Read again under the lock: a launch may have rewritten it meanwhile.
68    let Ok(content) = std::fs::read_to_string(&path) else { return false };
69    let Some(body) = strip_signing_keys(&content) else { return false };
70    match wd.write(".mcp.json", body.as_bytes(), true) {
71        Ok(()) => {
72            tracing::info!(work_dir, "removed signing keys from the workspace .mcp.json");
73            true
74        }
75        Err(e) => {
76            tracing::warn!(work_dir, error = %e, "could not remove signing keys from the workspace .mcp.json");
77            false
78        }
79    }
80}
81
82/// [`strip_workspace_signing_keys`] for each of `folders`, each folder once: how many files lost keys. A blank folder
83/// is skipped, and so is one with no `.mcp.json` or none that holds a key, which are left exactly as they are.
84pub fn strip_signing_keys_in_folders<'a>(folders: impl IntoIterator<Item = &'a str>) -> usize {
85    let mut seen = std::collections::HashSet::new();
86    folders
87        .into_iter()
88        .filter(|dir| !dir.trim().is_empty() && seen.insert(dir.to_string()))
89        .filter(|dir| strip_workspace_signing_keys(dir))
90        .count()
91}
92
93/// At srv start: the signing keys an older launch wrote are taken out of the `.mcp.json` of every agent's working folder
94/// that holds them, not only of the folders a container agent starts in. Launches no longer write them (the agent's MCP
95/// server asks srv for its keys), so a file that still has them belongs to an agent that has not launched since. Only the
96/// keys in the file go: nothing is re-keyed, and no trust pin changes. Best effort; returns how many files changed.
97pub fn strip_known_agents_signing_keys(store: &crate::backend::storage::store::Store) -> usize {
98    let Ok(defs) = store.agent_def_list() else { return 0 };
99    let dirs: Vec<String> = defs
100        .iter()
101        .map(|d| match d.working_directory.trim() {
102            "" => crate::backend::storage::agents::default_agent_working_dir(&d.name),
103            dir => dir.to_string(),
104        })
105        .collect();
106    strip_signing_keys_in_folders(dirs.iter().map(String::as_str))
107}
108
109/// `content` with its agentmux server's `AGENTMUX_AGENT_ID` set to `slug`,
110/// and the id it replaced. `None` when it already is `slug`, when there is no
111/// such entry (a `.mcp.json` of the user's own, or none of AgentMux's), or
112/// when `content` isn't JSON.
113pub(crate) fn set_agent_id(content: &str, slug: &str) -> Option<(String, String)> {
114    let mut json: Value = serde_json::from_str(content).ok()?;
115    let current = json.pointer(AGENT_ID)?.as_str()?.to_string();
116    if current == slug {
117        return None;
118    }
119    let env = json.pointer_mut("/mcpServers/agentmux/env")?.as_object_mut()?;
120    env.insert("AGENTMUX_AGENT_ID".to_string(), Value::String(slug.to_string()));
121    for key in NAME_KEYED {
122        env.remove(key);
123    }
124    Some((serde_json::to_string_pretty(&json).ok()?, current))
125}
126
127/// The id a launch's generated `.mcp.json` signs as (`writeagentconfig`): the
128/// slug of definition `agent_id` when it has one, `content` rewritten to it
129/// if the launch computed another; else the id `content` carries. `None`
130/// when `content` has no agentmux entry.
131pub(crate) fn launch_agent_id(
132    content: &mut String,
133    mstore: &crate::backend::storage::store::Store,
134    agent_id: Option<&str>,
135) -> Option<String> {
136    let slug = agent_id
137        .filter(|id| !id.is_empty())
138        .and_then(|id| mstore.agent_def_get(id).ok().flatten())
139        .map(|def| def.slug)
140        .filter(|s| !s.trim().is_empty());
141    if let Some((patched, previous)) = slug.as_deref().and_then(|s| set_agent_id(content, s)) {
142        tracing::info!(previous = %previous, agent_id = ?slug, "writeagentconfig: the launch's .mcp.json named another agent id; using the definition's");
143        *content = patched;
144    }
145    let json: Value = serde_json::from_str(content).ok()?;
146    json.pointer(AGENT_ID)?.as_str().map(str::to_string)
147}
148
149/// For a host agent's spawn: when its workspace `.mcp.json` names another
150/// id than the definition's `slug`, or names it with a signing value an older version wrote, rewrite
151/// it with `slug`, holding no signing value, under the same directory lock the
152/// launch writes it with.
153/// Best-effort: a failure is logged, never a spawn failure, and a container
154/// agent (whose workspace path means nothing on the host) or an empty
155/// `cmd:cwd` is left alone.
156pub(crate) fn realign_workspace_mcp_json(
157    mstore: &crate::backend::storage::store::Store,
158    work_dir: &str,
159    agent_mode: &str,
160    slug: &str,
161) {
162    if crate::backend::operator_config_seed::agent_kind(agent_mode) != "host" || work_dir.trim().is_empty() {
163        return;
164    }
165    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
166    // A user's project keeps its own `.mcp.json` (#3680): the agent's file is AgentMux's
167    // relocated one, and that is the one a spawn may realign. So is the file of a host agent in a
168    // folder a container agent can write.
169    if let Some(path) = crate::backend::mcp_config_file::host_relocated_path(&expanded) {
170        let Ok(content) = std::fs::read_to_string(&path) else {
171            return;
172        };
173        let (patched, previous) = match set_agent_id(&content, slug) {
174            Some((patched, previous)) => (patched, Some(previous)),
175            None if carries_a_signing_value(&content, slug) => (content.clone(), None),
176            None => return,
177        };
178        let Some(body) = crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&patched, mstore, slug) else {
179            tracing::warn!(work_dir, agent_id = slug, "spawn: the agent's keys could not be ensured; its MCP config keeps its id and loses any signing value");
180            if let Some(stripped) = strip_signing_keys(&content) {
181                let body = crate::backend::mcp_config_file::host_content(&expanded, stripped);
182                let _ = crate::backend::mcp_config_file::write_relocated(&path, &body);
183            }
184            return;
185        };
186        let body = crate::backend::mcp_config_file::host_content(&expanded, body);
187        if serde_json::from_str::<Value>(&body).ok() == serde_json::from_str::<Value>(&content).ok() {
188            return;
189        }
190        match crate::backend::mcp_config_file::write_relocated(&path, &body) {
191            Ok(()) => tracing::info!(
192                work_dir,
193                previous = ?previous,
194                agent_id = slug,
195                "spawn: rewrote the agent's MCP config from the definition"
196            ),
197            Err(e) => tracing::warn!(work_dir, error = %e, "spawn: could not rewrite the agent's MCP config"),
198        }
199        return;
200    }
201    let Ok(wd) = crate::backend::workdir_fs::Workdir::open(std::path::Path::new(&expanded)) else {
202        return;
203    };
204    let Ok(path) = wd.resolve(".mcp.json") else {
205        return;
206    };
207    // The common spawn has nothing to change: the file already names the agent. That is decided from one read, with no lock, so
208    // spawns into one folder (several agents may share a project folder) do not queue on it. A change is planned before the lock
209    // too: planning ensures the agent's keys in the store, which can take a while, and a lock held across it made every other
210    // spawn into the folder wait for it.
211    let Ok(first) = std::fs::read_to_string(&path) else {
212        return;
213    };
214    let mut plan = plan_realign(&first, mstore, slug, work_dir);
215    if matches!(plan, Realign::Leave) {
216        return;
217    }
218    // Held from the read to the write, so a launch writing the file at the
219    // same time is not overwritten with this spawn's older copy. Without it,
220    // no rewrite: the next spawn tries again.
221    let _lock = match wd
222        .open_lock_file(crate::backend::agent_config::MCP_JSON_WRITE_LOCK)
223        .and_then(|f| f.lock().map(|()| f))
224    {
225        Ok(lock) => lock,
226        Err(e) => {
227            tracing::warn!(work_dir, error = %e, "spawn: .mcp.json lock unavailable; its agent id is not realigned this spawn");
228            return;
229        }
230    };
231    let Ok(content) = std::fs::read_to_string(&path) else {
232        return;
233    };
234    if content != first {
235        // Another launch wrote it while this one waited: plan again from what is there now (rare, so it is done under the lock).
236        plan = plan_realign(&content, mstore, slug, work_dir);
237    }
238    match plan {
239        Realign::Leave => {}
240        Realign::Strip(stripped) => {
241            let _ = wd.write(".mcp.json", stripped.as_bytes(), true);
242        }
243        Realign::Write { body, previous } => match wd.write(".mcp.json", body.as_bytes(), true) {
244            Ok(()) => tracing::info!(
245                work_dir,
246                previous = ?previous,
247                agent_id = slug,
248                "spawn: rewrote the workspace .mcp.json from the definition"
249            ),
250            Err(e) => tracing::warn!(work_dir, error = %e, "spawn: could not rewrite the workspace .mcp.json's agent id"),
251        },
252    }
253}
254
255/// What a spawn does to the workspace `.mcp.json` it read.
256enum Realign {
257    /// Nothing: the file already names the agent, is not AgentMux's, or the new body would be the same.
258    Leave,
259    /// The keys could not be ensured: the file keeps its id and loses any signing value an older version wrote.
260    Strip(String),
261    /// Rewrite it with `body` (`previous`: the id it named).
262    Write { body: String, previous: Option<String> },
263}
264
265/// Decides what to do with `content` for `slug`. Reads and writes the store (ensures the agent's keys), never the file.
266fn plan_realign(content: &str, mstore: &crate::backend::storage::store::Store, slug: &str, work_dir: &str) -> Realign {
267    let (patched, previous) = match set_agent_id(content, slug) {
268        Some((patched, previous)) => (patched, Some(previous)),
269        None if carries_a_signing_value(content, slug) => (content.to_string(), None),
270        None => return Realign::Leave,
271    };
272    // Never written without the new name's keys: a later spawn would find the
273    // id already matching and leave the agent unsigned. Left as it was, the
274    // next spawn tries again.
275    let Some(body) = crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&patched, mstore, slug) else {
276        tracing::warn!(work_dir, agent_id = slug, "spawn: the agent's keys could not be ensured; workspace .mcp.json keeps its id and loses any signing value");
277        return strip_signing_keys(content).map_or(Realign::Leave, Realign::Strip);
278    };
279    if serde_json::from_str::<Value>(&body).ok() == serde_json::from_str::<Value>(content).ok() {
280        return Realign::Leave;
281    }
282    Realign::Write { body, previous }
283}
284
285/// `content`'s agentmux entry names `slug` but still holds a signing value an older version wrote, or
286/// lacks the channel, so the file is rewritten at the next spawn.
287fn carries_a_signing_value(content: &str, slug: &str) -> bool {
288    let Ok(json) = serde_json::from_str::<Value>(content) else { return false };
289    let Some(env) = json.pointer("/mcpServers/agentmux/env") else { return false };
290    env.get("AGENTMUX_AGENT_ID").and_then(Value::as_str) == Some(slug)
291        && (SIGNING_SECRETS.iter().any(|k| env.get(*k).is_some()) || env.get("AGENTMUX_CHANNEL").is_none())
292}
293
294/// `agent_open`'s generated `.mcp.json`: no signing value for any agent (the file holds references, not
295/// values), the keys ensured in the store for a host agent, and any value an earlier launch wrote taken out.
296pub fn keys_for_agent_open(
297    content: &mut String,
298    mstore: &crate::backend::storage::store::Store,
299    agent_slug: &str,
300    agent: &crate::backend::storage::agents::AgentDefinition,
301) {
302    if !agent.runtime().adapter().carries_signing_keys() {
303        if let Some(stripped) = strip_signing_keys(content) {
304            *content = stripped;
305        }
306        return;
307    }
308    crate::backend::agent_resolve::record_config_id_drift("m4d.config_id_drift.agent_open", agent_slug, Some(&agent.slug));
309    match crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(content, mstore, agent_slug) {
310        Some(rewritten) => *content = rewritten,
311        None => {
312            tracing::warn!(agent_id = %agent.id, "agent_open: the agent's signing keys could not be ensured");
313            if let Some(stripped) = strip_signing_keys(content) {
314                *content = stripped; // a legacy blob's own agentmux entry may carry values
315            }
316        }
317    }
318}
319
320/// A launch's generated `.mcp.json` (`writeagentconfig`): named for the definition's agent id, holding
321/// no signing value, and, when `hands_out_keys`, with that agent's keys ensured in the store.
322///
323/// Keys are ensured only for the AgentMux window, proven by its host (`RpcContext::operator_only`): a
324/// caller that could name any agent would otherwise have keys made for it. The agent's MCP fetches its
325/// own keys from srv with its token (`/agentmux/agents/self/keys`).
326pub fn finish_launch(
327    files: &mut [crate::backend::rpc_types::AgentConfigFile],
328    mstore: &crate::backend::storage::store::Store,
329    agent_id: Option<&str>,
330    hands_out_keys: bool,
331) {
332    let Some(pos) = files.iter().position(|f| f.path == ".mcp.json") else { return };
333    // The definition's slug, over one the launch computed (P0.3).
334    let Some(agent_slug) = launch_agent_id(&mut files[pos].content, mstore, agent_id) else { return };
335    crate::backend::agent_resolve::record_config_id_drift(
336        "m4d.config_id_drift.write_agent_config",
337        &agent_slug,
338        crate::backend::agent_resolve::single_row_slug_folded(mstore, &agent_slug).as_deref(),
339    );
340    // A container agent gets none: the file is mounted into its container.
341    let in_container = agent_id
342        .and_then(|id| mstore.agent_def_get(id).ok().flatten())
343        .is_some_and(|def| !def.runtime().adapter().carries_signing_keys());
344    if in_container {
345        if let Some(stripped) = strip_signing_keys(&files[pos].content) {
346            files[pos].content = stripped;
347        }
348        return;
349    }
350    if !hands_out_keys {
351        // No value is written either way: an older value the launch's content carries is taken out.
352        if let Some(stripped) = strip_signing_keys(&files[pos].content) {
353            files[pos].content = stripped;
354        }
355        tracing::info!(agent_slug = %agent_slug, "WriteAgentConfig: keys not ensured: the caller isn't the AgentMux window");
356        return;
357    }
358    match crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&files[pos].content, mstore, &agent_slug) {
359        Some(rewritten) => files[pos].content = rewritten,
360        None => {
361            tracing::warn!(agent_slug = %agent_slug, "WriteAgentConfig: the agent's signing keys could not be ensured");
362            if let Some(stripped) = strip_signing_keys(&files[pos].content) {
363                files[pos].content = stripped; // a legacy blob's own agentmux entry may carry values
364            }
365        }
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    fn file_with_keys() -> String {
374        mcp("some-agent")
375    }
376
377    /// The start-up sweep: each folder once, only a file that holds keys changes, and a second pass finds nothing.
378    #[test]
379    fn the_sweep_takes_the_keys_out_of_every_folder_that_holds_them_once() {
380        let (a, b, clean, empty) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
381        for d in [&a, &b] {
382            std::fs::write(d.path().join(".mcp.json"), file_with_keys()).unwrap();
383        }
384        let theirs = r#"{"mcpServers":{"theirs":{"command":"x"}}}"#;
385        std::fs::write(clean.path().join(".mcp.json"), theirs).unwrap();
386        let s = |d: &tempfile::TempDir| d.path().to_string_lossy().into_owned();
387        let folders = [s(&a), s(&a), s(&b), s(&clean), s(&empty), String::new(), "  ".into()];
388        assert_eq!(strip_signing_keys_in_folders(folders.iter().map(String::as_str)), 2, "a listed twice counts once");
389        for d in [&a, &b] {
390            let v: Value = serde_json::from_str(&std::fs::read_to_string(d.path().join(".mcp.json")).unwrap()).unwrap();
391            let env = v.pointer("/mcpServers/agentmux/env").unwrap();
392            assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none() && env.get("AGENTMUX_WAN_KEY").is_none());
393            assert_eq!(env["AGENTMUX_AGENT_ID"], "some-agent", "the rest of the file stays");
394            assert_eq!(v.pointer("/mcpServers/theirs/command").and_then(Value::as_str), Some("x"));
395        }
396        assert_eq!(std::fs::read_to_string(clean.path().join(".mcp.json")).unwrap(), theirs, "a file with no keys is left byte for byte");
397        assert!(!empty.path().join(".mcp.json").exists() && !empty.path().join(".claude").exists(), "a folder with no file gets nothing");
398        assert_eq!(strip_signing_keys_in_folders(folders.iter().map(String::as_str)), 0, "a second pass finds nothing");
399    }
400
401
402    fn mcp(agent_id: &str) -> String {
403        serde_json::json!({
404            "mcpServers": {
405                "agentmux": { "command": "agentmux-mcp", "env": {
406                    "AGENTMUX_AGENT_ID": agent_id, "AGENTMUX_AGENT_BUS_ID": "bus-1",
407                    "AGENTMUX_JEKT_KEY": "old-key", "AGENTMUX_LAN_KEY": "old-lan"
408                }},
409                "theirs": { "command": "x" }
410            }
411        })
412        .to_string()
413    }
414
415    #[test]
416    fn the_id_is_replaced_with_its_keys_and_nothing_else() {
417        let (out, previous) = set_agent_id(&mcp("loap-loap-2"), "loap-2").unwrap();
418        assert_eq!(previous, "loap-loap-2");
419        let v: Value = serde_json::from_str(&out).unwrap();
420        assert_eq!(v.pointer(AGENT_ID).and_then(Value::as_str), Some("loap-2"));
421        let env = v.pointer("/mcpServers/agentmux/env").unwrap();
422        assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none());
423        assert_eq!(env["AGENTMUX_AGENT_BUS_ID"], "bus-1");
424        assert_eq!(v.pointer("/mcpServers/theirs/command").and_then(Value::as_str), Some("x"));
425    }
426
427    #[test]
428    fn a_matching_or_foreign_file_is_left_alone() {
429        assert!(set_agent_id(&mcp("loap-2"), "loap-2").is_none());
430        assert!(set_agent_id(r#"{"mcpServers":{"theirs":{}}}"#, "loap-2").is_none());
431        assert!(set_agent_id("not json", "loap-2").is_none());
432    }
433
434    /// P0.3 on spawn: a stale workspace file is rewritten for a host agent,
435    /// and a container agent's is not touched.
436    #[test]
437    fn a_host_spawn_rewrites_a_stale_workspace_file() {
438        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
439        let data = tempfile::tempdir().unwrap();
440        let dir = tempfile::tempdir().unwrap();
441        let work_dir = dir.path().to_string_lossy().into_owned();
442        crate::backend::mcp_config_file::with_data_home(data.path(), || {
443            // A user project's config is AgentMux's relocated file (#3680).
444            let file = crate::backend::mcp_config_file::config_path(&work_dir);
445            crate::backend::mcp_config_file::write_relocated(&file, &mcp("loap-loap-2")).unwrap();
446
447            realign_workspace_mcp_json(&store, &work_dir, "container", "loap-2");
448            assert_eq!(std::fs::read_to_string(&file).unwrap(), mcp("loap-loap-2"));
449
450            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-2");
451            let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
452            assert_eq!(v.pointer(AGENT_ID).and_then(Value::as_str), Some("loap-2"));
453            assert!(
454                holds_no_key(&std::fs::read_to_string(&file).unwrap()),
455                "the old name's key is gone and the new name's is not written: the file holds references, not values"
456            );
457            assert!(!dir.path().join(".mcp.json").exists(), "the project's own file is never written");
458        });
459    }
460
461    fn file_id_and_channel(file: &std::path::Path) -> (String, Option<String>) {
462        let v: Value = serde_json::from_str(&std::fs::read_to_string(file).unwrap()).unwrap();
463        let env = v.pointer("/mcpServers/agentmux/env").unwrap();
464        (env["AGENTMUX_AGENT_ID"].as_str().unwrap().to_string(), env.get("AGENTMUX_CHANNEL").and_then(Value::as_str).map(str::to_string))
465    }
466
467    /// When the new name's keys can't be ensured, the file is left as it was (old
468    /// id, old values), and the next spawn finishes the job. A file already
469    /// naming the slug, with no channel or with a value an older version wrote, is rewritten.
470    #[test]
471    fn a_rewrite_without_keys_is_not_persisted_and_is_retried() {
472        let data = tempfile::tempdir().unwrap();
473        let dir = tempfile::tempdir().unwrap();
474        let work_dir = dir.path().to_string_lossy().into_owned();
475        crate::backend::mcp_config_file::with_data_home(data.path(), || {
476            let file = crate::backend::mcp_config_file::config_path(&work_dir);
477            crate::backend::mcp_config_file::write_relocated(&file, &mcp("loap-loap-2")).unwrap();
478
479            let broken = crate::backend::storage::store::Store::open_in_memory().unwrap();
480            broken.test_break_name_key_tables().unwrap();
481            realign_workspace_mcp_json(&broken, &work_dir, "host", "loap-2");
482            let text = std::fs::read_to_string(&file).unwrap();
483            assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), serde_json::from_str::<Value>(&strip_signing_keys(&mcp("loap-loap-2")).unwrap()).unwrap(), "not half-realigned, but no value is left in it");
484            assert!(holds_no_key(&text));
485            crate::backend::mcp_config_file::write_relocated(&file, &mcp("loap-loap-2")).unwrap();
486
487            let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
488            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-2");
489            let (id, channel) = file_id_and_channel(&file);
490            assert_eq!(id, "loap-2");
491            assert!(channel.is_some() && holds_no_key(&std::fs::read_to_string(&file).unwrap()));
492            assert!(store.agent_jekt_key_load("loap-2").unwrap().is_some(), "the keys are ensured in the store for the agent's fetch");
493
494            let (stripped, _) = set_agent_id(&mcp("old"), "loap-3").unwrap();
495            crate::backend::mcp_config_file::write_relocated(&file, &stripped).unwrap();
496            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-3");
497            assert!(file_id_and_channel(&file).1.is_some(), "a matching id with no channel gets it");
498
499            let mut one_value: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
500            one_value["mcpServers"]["agentmux"]["env"]
501                .as_object_mut()
502                .unwrap()
503                .insert("AGENTMUX_LAN_KEY".into(), Value::String("old-lan".into()));
504            crate::backend::mcp_config_file::write_relocated(&file, &one_value.to_string()).unwrap();
505            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-3");
506            assert!(holds_no_key(&std::fs::read_to_string(&file).unwrap()), "a matching id with a value an older version wrote loses it");
507        });
508    }
509
510    /// A start file an older version wrote (the id already right, both values in it) is rewritten at the
511    /// agent's next spawn, and after it no file under the agent's workspace or the data home holds either
512    /// value, though the keys are in the store.
513    #[test]
514    fn an_old_start_file_is_rewritten_and_no_file_holds_either_value() {
515        use base64::Engine as _;
516        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
517        let data = tempfile::tempdir().unwrap();
518        let dir = tempfile::tempdir().unwrap();
519        let work_dir = dir.path().to_string_lossy().into_owned();
520        let jekt = store.agent_jekt_key_ensure("loap-2").unwrap();
521        let jekt = base64::engine::general_purpose::STANDARD.encode(jekt);
522        let lan = store.agent_lan_key_ensure("loap-2").unwrap().private_key;
523        crate::backend::mcp_config_file::with_data_home(data.path(), || {
524            let file = crate::backend::mcp_config_file::config_path(&work_dir);
525            let old = serde_json::json!({
526                "mcpServers": { "agentmux": { "command": "agentmux-mcp", "env": {
527                    "AGENTMUX_AGENT_ID": "loap-2", "AGENTMUX_JEKT_KEY": jekt, "AGENTMUX_LAN_KEY": lan, "AGENTMUX_CHANNEL": "stable"
528                }}}
529            })
530            .to_string();
531            crate::backend::mcp_config_file::write_relocated(&file, &old).unwrap();
532
533            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-2");
534
535            assert!(holds_no_key(&std::fs::read_to_string(&file).unwrap()));
536            for root in [data.path(), dir.path()] {
537                for found in files_under(root) {
538                    let text = std::fs::read_to_string(&found).unwrap_or_default();
539                    assert!(!text.contains(&jekt) && !text.contains(&lan), "{} holds a signing value", found.display());
540                }
541            }
542        });
543    }
544
545    fn files_under(root: &std::path::Path) -> Vec<std::path::PathBuf> {
546        let mut out = Vec::new();
547        for entry in std::fs::read_dir(root).into_iter().flatten().flatten() {
548            let path = entry.path();
549            if path.is_dir() {
550                out.extend(files_under(&path));
551            } else {
552                out.push(path);
553            }
554        }
555        out
556    }
557
558    /// No value, and none of the names that carry one (the file holds references, not values).
559    fn holds_no_key(content: &str) -> bool {
560        SIGNING_SECRETS.iter().all(|k| !content.contains(k)) && !content.contains("old-key") && !content.contains("old-lan")
561    }
562
563    #[test]
564    fn stripping_takes_out_the_signing_keys_and_only_them() {
565        let out = strip_signing_keys(&mcp("loap-2")).unwrap();
566        assert!(holds_no_key(&out));
567        let v: Value = serde_json::from_str(&out).unwrap();
568        assert_eq!(v.pointer(AGENT_ID).and_then(Value::as_str), Some("loap-2"));
569        assert_eq!(v.pointer("/mcpServers/theirs/command").and_then(Value::as_str), Some("x"));
570        assert!(strip_signing_keys(&out).is_none(), "a file with none is left alone");
571        assert!(strip_signing_keys("not json").is_none());
572    }
573
574    #[test]
575    fn a_container_start_removes_keys_an_earlier_launch_wrote_to_the_mounted_workspace() {
576        // A user's project too: keys an older launch wrote there must not reach the container.
577        let dir = tempfile::tempdir().unwrap();
578        let file = dir.path().join(".mcp.json");
579        std::fs::write(&file, mcp("loap-2")).unwrap();
580        strip_workspace_signing_keys(&dir.path().to_string_lossy());
581        assert!(holds_no_key(&std::fs::read_to_string(&file).unwrap()));
582
583        // A file with none of our keys is left byte-for-byte, and nothing there makes none.
584        let clean_body = r#"{ "mcpServers": { "mine": { "command": "mine-mcp" } } }"#;
585        let clean_dir = tempfile::tempdir().unwrap();
586        std::fs::write(clean_dir.path().join(".mcp.json"), clean_body).unwrap();
587        strip_workspace_signing_keys(&clean_dir.path().to_string_lossy());
588        assert_eq!(std::fs::read_to_string(clean_dir.path().join(".mcp.json")).unwrap(), clean_body);
589        let empty = tempfile::tempdir().unwrap();
590        strip_workspace_signing_keys(&empty.path().to_string_lossy());
591        assert!(!empty.path().join(".mcp.json").exists());
592    }
593
594    fn agent_of_type(store: &crate::backend::storage::store::Store, agent_type: &str) -> (String, String) {
595        let mut def: crate::backend::storage::agents::AgentDefinition = serde_json::from_value(serde_json::json!({
596            "id": uuid::Uuid::new_v4().to_string(), "name": "Loap", "icon": "", "provider": "claude", "description": "",
597            "created_at": 0, "agent_type": agent_type,
598        }))
599        .unwrap();
600        store.agent_def_insert(&mut def).unwrap();
601        (def.id, def.slug)
602    }
603
604    fn launch(store: &crate::backend::storage::store::Store, id: &str, slug: &str, hands_out_keys: bool) -> String {
605        let mut files = vec![crate::backend::rpc_types::AgentConfigFile {
606            path: ".mcp.json".into(),
607            content: mcp(slug),
608        }];
609        finish_launch(&mut files, store, Some(id), hands_out_keys);
610        files.remove(0).content
611    }
612
613    /// The file a launch writes is mounted into a container agent's container, so no key reaches it
614    /// there, even for the AgentMux window that is otherwise handed them, and a host agent still gets its own.
615    #[test]
616    fn a_launch_writes_no_signing_key_for_a_container_agent() {
617        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
618        let (boxed_id, boxed_slug) = agent_of_type(&store, "container");
619        let written = launch(&store, &boxed_id, &boxed_slug, true);
620        assert!(holds_no_key(&written), "{written}");
621        assert!(store.agent_jekt_key_load(&boxed_slug).unwrap().is_none(), "and none minted for it");
622
623        let (host_id, host_slug) = agent_of_type(&store, "host");
624        let written = launch(&store, &host_id, &host_slug, true);
625        assert!(holds_no_key(&written), "a host agent's file holds references, not values: {written}");
626        let v: Value = serde_json::from_str(&written).unwrap();
627        assert!(v.pointer("/mcpServers/agentmux/env/AGENTMUX_CHANNEL").is_some());
628        assert!(store.agent_jekt_key_load(&host_slug).unwrap().is_some() && store.agent_lan_key_load(&host_slug).unwrap().is_some(), "its keys are ensured for its fetch");
629
630        // The window is the one that has keys made; a launch from any other caller makes none, and writes no value either.
631        let (other_id, other_slug) = agent_of_type(&store, "host");
632        let written = launch(&store, &other_id, &other_slug, false);
633        assert!(holds_no_key(&written), "{written}");
634        assert!(store.agent_jekt_key_load(&other_slug).unwrap().is_none());
635    }
636
637    /// `agent_open` writes the same file: no value for either kind of agent; keys ensured only for a host agent.
638    #[test]
639    fn an_agent_open_writes_no_signing_value_for_any_agent() {
640        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
641        for (agent_type, keyed) in [("container", false), ("host", true)] {
642            let (id, slug) = agent_of_type(&store, agent_type);
643            let agent = store.agent_def_get(&id).unwrap().unwrap();
644            let mut content = mcp(&slug);
645            keys_for_agent_open(&mut content, &store, &slug, &agent);
646            assert!(holds_no_key(&content), "{agent_type}: {content}");
647            assert_eq!(store.agent_jekt_key_load(&slug).unwrap().is_some(), keyed, "{agent_type}");
648        }
649    }
650
651    /// A legacy blob's own agentmux entry may carry values; they are taken out even when the keys cannot be ensured.
652    #[test]
653    fn a_launch_removes_values_a_legacy_entry_carries_even_when_the_keys_cannot_be_ensured() {
654        let broken = crate::backend::storage::store::Store::open_in_memory().unwrap();
655        let (id, slug) = agent_of_type(&broken, "host");
656        broken.test_break_name_key_tables().unwrap();
657        assert!(holds_no_key(&launch(&broken, &id, &slug, true)));
658        let agent = broken.agent_def_get(&id).unwrap().unwrap();
659        let mut content = mcp(&slug);
660        keys_for_agent_open(&mut content, &broken, &slug, &agent);
661        assert!(holds_no_key(&content), "{content}");
662    }
663
664    /// No lock, no rewrite: a `.claude` that is a file makes the lock
665    /// unopenable, and the stale file stays for the next spawn.
666    #[test]
667    fn no_rewrite_without_the_lock() {
668        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
669        let data = tempfile::tempdir().unwrap();
670        crate::backend::mcp_config_file::with_data_home(data.path(), || {
671            let dir = data.path().join("agents").join("loap");
672            std::fs::create_dir_all(&dir).unwrap();
673            let file = dir.join(".mcp.json");
674            std::fs::write(&file, mcp("loap-loap-2")).unwrap();
675            std::fs::write(dir.join(".claude"), "not a folder").unwrap();
676            realign_workspace_mcp_json(&store, &dir.to_string_lossy(), "host", "loap-2");
677            assert_eq!(std::fs::read_to_string(&file).unwrap(), mcp("loap-loap-2"));
678        });
679    }
680    /// An agent's own folder (the workspace file is in it, so a spawn locks it), the data home set for the test.
681    fn own_folder(data: &std::path::Path, name: &str) -> (String, std::path::PathBuf) {
682        let dir = data.join("agents").join(name);
683        std::fs::create_dir_all(&dir).unwrap();
684        (dir.to_string_lossy().into_owned(), dir.join(".mcp.json"))
685    }
686
687    /// Holds the folder's write lock, as a launch writing the file would.
688    fn hold_write_lock(work_dir: &str) -> std::fs::File {
689        let wd = crate::backend::workdir_fs::Workdir::open(std::path::Path::new(work_dir)).unwrap();
690        let f = wd.open_lock_file(crate::backend::agent_config::MCP_JSON_WRITE_LOCK).unwrap();
691        f.lock().unwrap();
692        f
693    }
694
695    /// Runs `f` on a thread and says whether it finished within `secs`.
696    fn finishes_within(secs: u64, f: impl FnOnce() + Send + 'static) -> bool {
697        let (tx, rx) = std::sync::mpsc::channel();
698        std::thread::spawn(move || {
699            f();
700            let _ = tx.send(());
701        });
702        rx.recv_timeout(std::time::Duration::from_secs(secs)).is_ok()
703    }
704
705    /// The common spawn (the file already names the agent) decides from one read: a lock another launch holds
706    /// does not make it wait, so spawns into one folder do not queue behind it.
707    #[test]
708    fn a_spawn_that_has_nothing_to_change_does_not_wait_for_the_lock() {
709        let data = tempfile::tempdir().unwrap();
710        let (work_dir, file) = own_folder(data.path(), "aria");
711        crate::backend::mcp_config_file::with_data_home(data.path(), || {
712            let store = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
713            std::fs::write(&file, mcp("loap-loap-2")).unwrap();
714            realign_workspace_mcp_json(&store, &work_dir, "host", "loap-2");
715            let settled = std::fs::read_to_string(&file).unwrap();
716            assert_eq!(file_id_and_channel(&file).0, "loap-2");
717
718            let _held = hold_write_lock(&work_dir);
719            let (s, w) = (store.clone(), work_dir.clone());
720            assert!(
721                finishes_within(5, move || realign_workspace_mcp_json(&s, &w, "host", "loap-2")),
722                "a spawn with nothing to change waited for the folder's lock"
723            );
724            assert_eq!(std::fs::read_to_string(&file).unwrap(), settled, "nothing was written");
725        });
726    }
727
728    /// A rewrite that finds the file changed while it waited for the lock plans again from what is there.
729    #[test]
730    fn a_rewrite_that_waited_for_the_lock_follows_a_file_changed_meanwhile() {
731        let data = tempfile::tempdir().unwrap();
732        let (work_dir, file) = own_folder(data.path(), "aria");
733        crate::backend::mcp_config_file::with_data_home(data.path(), || {
734            let store = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
735            std::fs::write(&file, mcp("loap-loap-2")).unwrap();
736            let held = hold_write_lock(&work_dir);
737            let (s, w) = (store.clone(), work_dir.clone());
738            let spawn = std::thread::spawn(move || realign_workspace_mcp_json(&s, &w, "host", "loap-2"));
739            std::thread::sleep(std::time::Duration::from_millis(300));
740            assert!(!spawn.is_finished(), "a spawn with a rewrite to make waits for the lock");
741            // The launch that held the lock wrote the file with another stale id.
742            std::fs::write(&file, mcp("some-other-name")).unwrap();
743            drop(held);
744            spawn.join().unwrap();
745            let (id, channel) = file_id_and_channel(&file);
746            assert_eq!(id, "loap-2", "planned again from the file as the launch left it");
747            assert!(channel.is_some() && holds_no_key(&std::fs::read_to_string(&file).unwrap()));
748        });
749    }
750
751    /// Several agents sharing one folder, spawning at once: none waits for another's key work, and the file ends valid
752    /// and naming one of them.
753    #[test]
754    fn agents_sharing_one_folder_spawn_without_queueing_on_each_other() {
755        let data = tempfile::tempdir().unwrap();
756        let (work_dir, file) = own_folder(data.path(), "shared");
757        crate::backend::mcp_config_file::with_data_home(data.path(), || {
758            let store = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
759            std::fs::write(&file, mcp("loap-loap-2")).unwrap();
760            let slugs: Vec<String> = (1..=8).map(|n| format!("agent-{n}")).collect();
761            let started = std::time::Instant::now();
762            let handles: Vec<_> = slugs
763                .iter()
764                .cloned()
765                .map(|slug| {
766                    let (s, w) = (store.clone(), work_dir.clone());
767                    std::thread::spawn(move || {
768                        for _ in 0..3 {
769                            realign_workspace_mcp_json(&s, &w, "host", &slug);
770                        }
771                    })
772                })
773                .collect();
774            for h in handles {
775                h.join().unwrap();
776            }
777            assert!(started.elapsed() < std::time::Duration::from_secs(20), "8 agents x 3 spawns took {:?}", started.elapsed());
778            let (id, _) = file_id_and_channel(&file);
779            assert!(slugs.contains(&id), "the file names one of the agents, whole: {id}");
780            assert!(holds_no_key(&std::fs::read_to_string(&file).unwrap()));
781        });
782    }
783}