Skip to main content

agentmux_srv_core/backend/
folder_overlap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A host agent whose folder a container agent can write.
5//!
6//! A container agent changes the files of its workspace and of every writable volume. A host agent that works in
7//! one of those folders, or in a folder that holds one, runs what the container agent left there, as the person.
8//! Where a host agent is opened or created, or a container agent's workspace or volumes are saved, so that the two
9//! share a folder, the person is asked and the choice is kept for that pair of agents. Nothing but the person's
10//! window records the choice ([`accept`]); a caller that is not the person is refused with [`refusal`].
11//!
12//! A choice is a file, and a file is not proof that the person made it: each go-ahead is also recorded as a row of
13//! the audit log made by the window, written before the file, and a choice file with no such row does not count
14//! ([`accepted`]): the pair asks again and says why ([`Overlap::untrusted`]).
15//!
16//! The folders are those of the two agents' definitions: a container agent's workspace and its writable host
17//! volumes (`container::mounts::writable`), a host agent's working folder.
18
19use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::sync::Mutex;
22
23use serde::{Deserialize, Serialize};
24
25use crate::backend::obj::MetaMapType;
26use crate::backend::storage::agents::AgentDefinition;
27use crate::backend::storage::store::Store;
28
29/// A host agent and a container agent whose folders overlap.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32pub struct Overlap {
33    pub host_id: String,
34    pub host_name: String,
35    pub container_id: String,
36    pub container_name: String,
37    /// A choice for this pair is kept, but the audit log has no record that the person made it, so it does not
38    /// count and the pair asks again.
39    #[serde(default)]
40    pub untrusted: bool,
41}
42
43/// The folder an agent definition works in as set, expanded; `None` when it names none.
44fn working_folder(def: &AgentDefinition) -> Option<PathBuf> {
45    let dir = def.working_directory.trim();
46    (!dir.is_empty()).then(|| crate::backend::base::expand_home_dir_safe(dir))
47}
48
49/// The host folders a container agent's definition binds writable: its workspace and its volumes that are host
50/// folders not bound read-only. Asked of the same rule a running pane's container is made by.
51fn writable_folders(def: &AgentDefinition) -> Vec<PathBuf> {
52    if !crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&def.agent_type).is_container() {
53        return Vec::new();
54    }
55    let mut meta = MetaMapType::new();
56    meta.insert("agentMode".to_string(), serde_json::json!("container"));
57    meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(def.working_directory));
58    meta.insert("agent:container_volumes".to_string(), serde_json::json!(def.container_volumes));
59    crate::backend::container::mounts::writable::writable_binds(&meta, None).into_iter().map(|bind| bind.host).collect()
60}
61
62fn is_container(def: &AgentDefinition) -> bool {
63    crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&def.agent_type).is_container()
64}
65
66fn between(host: &AgentDefinition, folder: &Path, container: &AgentDefinition) -> Option<Overlap> {
67    writable_folders(container)
68        .iter()
69        .any(|bound| crate::backend::fs_ops::container_folders::overlap(folder, bound))
70        .then(|| Overlap {
71            host_id: host.id.clone(),
72            host_name: host.name.clone(),
73            container_id: container.id.clone(),
74            container_name: container.name.clone(),
75            untrusted: untrusted(&host.id, &container.id),
76        })
77}
78
79/// The container agents whose writable folders overlap `folder`, the folder the host agent `host` works in.
80pub fn for_host_in(store: &Store, host: &AgentDefinition, folder: &Path) -> Vec<Overlap> {
81    if is_container(host) {
82        return Vec::new();
83    }
84    let all = store.agent_def_list().unwrap_or_default();
85    all.iter().filter(|other| other.id != host.id && is_container(other)).filter_map(|c| between(host, folder, c)).collect()
86}
87
88/// The overlaps of `def` as it is saved or opened: for a host agent, with the container agents; for a container
89/// agent, with the host agents. `host_folder` is the folder a host agent opens in when it is not the one its
90/// definition names (a blank one opens in the agent's own folder).
91pub fn of(store: &Store, def: &AgentDefinition, host_folder: Option<&Path>) -> Vec<Overlap> {
92    if !is_container(def) {
93        let folder = host_folder.map(Path::to_path_buf).or_else(|| working_folder(def));
94        return folder.map_or_else(Vec::new, |folder| for_host_in(store, def, &folder));
95    }
96    let all = store.agent_def_list().unwrap_or_default();
97    all.iter()
98        .filter(|other| other.id != def.id && !is_container(other))
99        .filter_map(|host| working_folder(host).and_then(|folder| between(host, &folder, def)))
100        .collect()
101}
102
103/// The directory the choices are kept in; a test sets its own.
104fn choices_dir() -> Option<PathBuf> {
105    #[cfg(any(test, feature = "test-support"))]
106    return CHOICES_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()).clone();
107    #[cfg(not(any(test, feature = "test-support")))]
108    return crate::registry::paths::resolve_shared_folder_overlap_choices_dir();
109}
110
111#[cfg(any(test, feature = "test-support"))]
112static CHOICES_DIR_FOR_TEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
113
114/// Sets the folder a test's choices are kept in, and returns the one set before.
115#[cfg(any(test, feature = "test-support"))]
116pub fn set_choices_dir_for_test(dir: Option<PathBuf>) -> Option<PathBuf> {
117    std::mem::replace(&mut *CHOICES_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()), dir)
118}
119
120fn choice_file(host_id: &str, container_id: &str) -> Option<PathBuf> {
121    let key = agentmux_common::mcp_config_path::spelling_key(&format!("{host_id}\n{container_id}"));
122    Some(choices_dir()?.join(key))
123}
124
125/// The audit action that records the person's go-ahead for a pair.
126pub const GO_AHEAD_ACTION: &str = "folder-overlap.go-ahead";
127
128/// The note of an audit row about a pair: the action and the two agents' ids, which find the row (a name changes), then
129/// the names, for whoever reads the Audit view.
130pub fn row_note(action: &str, host: (&str, &str), container: (&str, &str)) -> String {
131    format!("{action} {} {}: host agent {} and container agent {}", host.0, container.0, host.1, container.1)
132}
133
134fn row_prefix(host_id: &str, container_id: &str) -> String {
135    format!("{GO_AHEAD_ACTION} {host_id} {container_id}:")
136}
137
138/// Whether `entry` is the window's record of a go-ahead for the pair `prefix` names: an action row, made by the window
139/// (no agent made it), that went through.
140fn is_go_ahead_row(entry: &crate::backend::reactive::AuditLogEntry, prefix: &str) -> bool {
141    entry.event_kind == "action"
142        && entry.outcome.as_deref() == Some(GO_AHEAD_ACTION)
143        && entry.source_agent.is_none()
144        && entry.success
145        && entry.reason.as_deref().is_some_and(|reason| reason.starts_with(prefix))
146}
147
148/// The audit files to read for a record: the one every srv on this machine shares, and this channel's own.
149fn audit_files() -> Vec<PathBuf> {
150    #[cfg(any(test, feature = "test-support"))]
151    return AUDIT_FILES_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()).clone();
152    #[cfg(not(any(test, feature = "test-support")))]
153    return [super::reactive::audit_store::shared_path_for_reading(), super::reactive::audit_store::own_path()].into_iter().flatten().collect();
154}
155
156#[cfg(any(test, feature = "test-support"))]
157static AUDIT_FILES_FOR_TEST: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
158
159/// Sets the audit files a test reads a record from (none by default), and returns the ones set before.
160#[cfg(any(test, feature = "test-support"))]
161pub fn set_audit_files_for_test(files: Vec<PathBuf>) -> Vec<PathBuf> {
162    std::mem::replace(&mut *AUDIT_FILES_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()), files)
163}
164
165/// Whether any line of the audit file at `path` is the record `prefix` names. The file is never rotated, so a line
166/// is parsed only when it holds the prefix.
167fn file_has_record(path: &Path, prefix: &str) -> bool {
168    use std::io::BufRead;
169    let Ok(file) = std::fs::File::open(path) else { return false };
170    std::io::BufReader::new(file)
171        .lines()
172        .map_while(Result::ok)
173        .filter(|line| line.contains(prefix))
174        .filter_map(|line| serde_json::from_str::<crate::backend::reactive::AuditLogEntry>(&line).ok())
175        .any(|entry| is_go_ahead_row(&entry, prefix))
176}
177
178/// The pairs whose go-ahead was found on record in this process, as `host\ncontainer`: a record does not go away, so it
179/// is looked for once.
180fn recorded_pairs() -> &'static Mutex<HashSet<String>> {
181    static RECORDED: std::sync::OnceLock<Mutex<HashSet<String>>> = std::sync::OnceLock::new();
182    RECORDED.get_or_init(Mutex::default)
183}
184
185fn recorded_key(host_id: &str, container_id: &str) -> String {
186    format!("{host_id}\n{container_id}")
187}
188
189/// Whether the audit log records the person's go-ahead for the pair: in the rows this srv still holds in memory (the
190/// row is on its way to the file when the person has only just gone ahead), or in the audit file, which survives a
191/// restart.
192fn recorded(host_id: &str, container_id: &str) -> bool {
193    let key = recorded_key(host_id, container_id);
194    if recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).contains(&key) {
195        return true;
196    }
197    let prefix = row_prefix(host_id, container_id);
198    let in_memory = super::reactive::get_global_handler().get_audit_log(usize::MAX).iter().any(|entry| is_go_ahead_row(entry, &prefix));
199    let found = in_memory || audit_files().iter().any(|file| file_has_record(file, &prefix));
200    if found {
201        recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).insert(key);
202    }
203    found
204}
205
206fn has_choice_file(host_id: &str, container_id: &str) -> bool {
207    choice_file(host_id, container_id).is_some_and(|file| file.is_file())
208}
209
210/// Whether the person has gone ahead with this host agent and this container agent sharing a folder: a choice is kept
211/// and the audit log records that the person made it.
212pub fn accepted(host_id: &str, container_id: &str) -> bool {
213    has_choice_file(host_id, container_id) && recorded(host_id, container_id)
214}
215
216/// Whether a choice is kept for the pair that the audit log has no record of: it does not count.
217pub fn untrusted(host_id: &str, container_id: &str) -> bool {
218    has_choice_file(host_id, container_id) && !recorded(host_id, container_id)
219}
220
221/// Keeps the person's choice for the pair, naming both agents by their ids. Only the person's window calls this
222/// (`app_api::folder_overlap`).
223pub fn accept(host_id: &str, container_id: &str) -> Result<(), String> {
224    accept_as((host_id, host_id), (container_id, container_id))
225}
226
227/// [`accept`], with the agents' names (id, name) for the record. The audit row is written first and the file after, so a
228/// file is never kept without the record of who made it.
229pub fn accept_as(host: (&str, &str), container: (&str, &str)) -> Result<(), String> {
230    let file = choice_file(host.0, container.0).ok_or("the choice can't be kept: AgentMux has no shared folder here")?;
231    if let Some(dir) = file.parent() {
232        std::fs::create_dir_all(dir).map_err(|e| format!("the choice can't be kept: {e}"))?;
233    }
234    let note = row_note(GO_AHEAD_ACTION, host, container);
235    super::reactive::get_global_handler().log_fleet_action_audit(None, host.1, "", GO_AHEAD_ACTION, true, None, &uuid::Uuid::new_v4().to_string(), Some(&note));
236    recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).insert(recorded_key(host.0, container.0));
237    std::fs::write(&file, format!("{}\n{}\n", host.0, container.0)).map_err(|e| format!("the choice can't be kept: {e}"))
238}
239
240/// A choice file with no audit row, as an agent that wrote the folder would leave it.
241#[cfg(any(test, feature = "test-support"))]
242pub fn write_choice_without_a_record_for_test(host_id: &str, container_id: &str) {
243    let file = choice_file(host_id, container_id).expect("a choices folder is set");
244    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
245    std::fs::write(&file, format!("{host_id}\n{container_id}\n")).unwrap();
246}
247
248/// Forgets which pairs were found on record, as a restart does.
249#[cfg(any(test, feature = "test-support"))]
250pub fn forget_what_was_recorded_for_test() {
251    recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).clear();
252}
253
254/// Forgets every choice the person made for a pair that includes agent `id`: the agent is deleted.
255pub fn forget_agent(id: &str) {
256    recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).retain(|key| !key.lines().any(|line| line == id));
257    let Some(dir) = choices_dir() else { return };
258    let Ok(entries) = std::fs::read_dir(&dir) else { return };
259    for entry in entries.flatten() {
260        let path = entry.path();
261        if std::fs::read_to_string(&path).is_ok_and(|text| text.lines().any(|line| line == id)) {
262            let _ = std::fs::remove_file(path);
263        }
264    }
265}
266
267/// The overlaps the person has not gone ahead with.
268pub fn unchosen(overlaps: Vec<Overlap>) -> Vec<Overlap> {
269    overlaps.into_iter().filter(|o| !accepted(&o.host_id, &o.container_id)).collect()
270}
271
272/// What the person is told, and what a caller that is not the person is refused with: both agents, what the shared
273/// folder means, and what to do instead.
274pub fn refusal(overlaps: &[Overlap]) -> String {
275    let pairs = overlaps
276        .iter()
277        .map(|o| format!("{} (host) and {} (container)", o.host_name, o.container_name))
278        .collect::<Vec<_>>()
279        .join("; ");
280    let untrusted = overlaps.iter().filter(|o| o.untrusted).map(|o| format!("{} and {}", o.host_name, o.container_name)).collect::<Vec<_>>().join("; ");
281    let why = if untrusted.is_empty() {
282        String::new()
283    } else {
284        format!(" A choice is kept for {untrusted}, but AgentMux has no record that the person made it, so it does not count.")
285    };
286    format!(
287        "{pairs} share a folder, so the container agent can change what the host agent runs.{why} Only the person can go ahead with that, from the AgentMux window. Give them separate workspaces, or bind the shared folder read-only into the container agent (a volume ending in :ro)"
288    )
289}
290
291/// `Err` with [`refusal`] when `def`, as saved or opened, shares a folder with an agent of the other kind that
292/// the person has not gone ahead with.
293pub fn check(store: &Store, def: &AgentDefinition, host_folder: Option<&Path>) -> Result<(), String> {
294    let pending = unchosen(of(store, def, host_folder));
295    if pending.is_empty() { Ok(()) } else { Err(refusal(&pending)) }
296}
297
298/// What an `agent.open` refusal for a shared folder starts with, so the window knows to ask the person and try again.
299pub const OPEN_REFUSAL_CODE: &str = "SHARED_FOLDER";
300
301/// The folder `agent.open` runs a host agent in, expanded: the one it names, else its own folder.
302pub fn open_folder(def: &AgentDefinition) -> PathBuf {
303    let named = def.working_directory.trim();
304    let dir = if named.is_empty() { crate::backend::storage::agents::default_agent_working_dir(&def.name) } else { named.to_string() };
305    crate::backend::base::expand_home_dir_safe(&dir)
306}
307
308/// [`check`] for an agent being opened, in [`open_folder`], with the refusal marked [`OPEN_REFUSAL_CODE`]. A container
309/// agent is not refused here: it is asked when its own folders are saved.
310pub fn check_open(store: &Store, def: &AgentDefinition) -> Result<(), String> {
311    if is_container(def) {
312        return Ok(());
313    }
314    check(store, def, Some(&open_folder(def))).map_err(|refusal| format!("{OPEN_REFUSAL_CODE}: {refusal}"))
315}
316
317/// Why the start of host agent `def` waits, for an agent that asks what its state is: the pairs it shares a folder with
318/// that the person has not gone ahead with. `None` when nothing waits.
319pub fn waiting_reason(store: &Store, def: &AgentDefinition) -> Option<String> {
320    if is_container(def) {
321        return None;
322    }
323    let pending = unchosen(of(store, def, Some(&open_folder(def))));
324    if pending.is_empty() {
325        return None;
326    }
327    let pairs = pending.iter().map(|o| format!("{} (host) and {} (container)", o.host_name, o.container_name)).collect::<Vec<_>>().join("; ");
328    Some(format!("{OPEN_REFUSAL_CODE}: waits for the person's go-ahead for a shared folder: {pairs}"))
329}
330
331/// Whether a save of `new` over `old` changes a folder an agent works in or can write.
332pub fn folders_changed(old: &AgentDefinition, new: &AgentDefinition) -> bool {
333    old.working_directory != new.working_directory || old.agent_type != new.agent_type || old.container_volumes != new.container_volumes
334}
335
336/// Whether `host_id` names a host agent and `container_id` a container agent.
337pub fn is_a_pair(store: &Store, host_id: &str, container_id: &str) -> bool {
338    let kind = |id: &str| store.agent_def_get(id).ok().flatten().map(|def| is_container(&def));
339    kind(host_id) == Some(false) && kind(container_id) == Some(true)
340}
341
342#[cfg(test)]
343#[path = "folder_overlap_tests.rs"]
344mod tests;