Skip to main content

agentmux_srv_core/backend/fs_ops/
container_folders.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The host folders a container agent can write, and where each is inside the agent's container.
5//!
6//! Git facts of a container agent are read inside its container: for such a folder, or anything inside it,
7//! [`super::git`] starts no git on the host and runs it in the agent's container instead, at the same folder
8//! there ([`place`]). So the work facts, the overlap and PR helpers and the Files pane's markers say what the
9//! agent's own git says.
10//!
11//! The folders are read from the panes in the store, the values a container's mounts are made from
12//! (`container::mounts::writable`): the workspace (`cmd:cwd` of a pane whose agent runs in a container), the
13//! agent's Personal Memory folder, and each host folder of its volumes that is not bound read-only. The list
14//! is reused for a moment so a burst of git runs reads the store once.
15//!
16//! A folder is asked about as it is spelled and as it resolves (links followed): either one inside a bound
17//! folder makes it the container's.
18
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23use crate::backend::blockcontroller::META_KEY_CMD_CWD;
24use crate::backend::obj::{self, Block};
25use crate::backend::storage::store::Store;
26use crate::backend::work_facts::paths::{normalize_path, relative_to};
27
28/// How long one read of the store's panes is reused: a new container agent's folders are known this soon.
29const REUSE: Duration = Duration::from_millis(250);
30
31/// One bound folder: its host spellings (as written, and as it resolves when that differs), the container
32/// it is bound into (empty when the pane names no agent) and its place there.
33#[derive(Debug, Clone, PartialEq, Eq)]
34struct Folder {
35    hosts: Vec<String>,
36    container: String,
37    target: String,
38}
39
40/// Where git for a folder runs.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Place {
43    /// On the host: no container agent can write the folder.
44    Host,
45    /// In a container agent's container.
46    Inside(Inside),
47    /// Not known (the panes can't be read and never were): nowhere.
48    Unknown,
49}
50
51/// A host folder as its container sees it.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Inside {
54    /// The container's name; empty when the pane names no agent, which no read answers for.
55    pub container: String,
56    /// The folder's absolute path inside the container.
57    pub dir: String,
58    /// The bound folder on the host, in the spelling the asked folder was found under.
59    host: String,
60    /// Where the bound folder is inside the container.
61    target: String,
62}
63
64impl Inside {
65    /// The bound folder on the host that holds the asked path, in the spelling it was found under.
66    pub fn bound(&self) -> &str {
67        &self.host
68    }
69
70    /// The host path of `inside`, an absolute path inside the container; `None` when it is not in the bound
71    /// folder this was found under.
72    pub fn host_path(&self, inside: &str) -> Option<String> {
73        let inside = crate::backend::cli_messaging::normalized(inside);
74        let target = self.target.trim_end_matches('/');
75        let rest = match inside.strip_prefix(target) {
76            Some("") => "",
77            Some(rest) if rest.starts_with('/') => &rest[1..],
78            _ => return None,
79        };
80        Some(if rest.is_empty() { self.host.clone() } else { format!("{}/{rest}", self.host.trim_end_matches('/')) })
81    }
82}
83
84#[derive(Default)]
85struct State {
86    store: Option<Arc<Store>>,
87    /// From the last read that worked.
88    folders: Option<Vec<Folder>>,
89    read_at: Option<Instant>,
90    #[cfg(test)]
91    for_tests: Vec<Folder>,
92}
93
94fn state() -> &'static parking_lot::Mutex<State> {
95    static STATE: std::sync::LazyLock<parking_lot::Mutex<State>> = std::sync::LazyLock::new(Default::default);
96    &STATE
97}
98
99/// Name the store the folders are read from. Called by everything that leads to a git run before it runs
100/// one (the work-facts loop, the Files pane's handler); the first call wins.
101pub fn install(store: &Arc<Store>) {
102    let mut s = state().lock();
103    if s.store.is_none() {
104        s.store = Some(Arc::clone(store));
105    }
106}
107
108/// `text` as one spelling for comparing: `/` separators, no long-path prefix, no trailing separator.
109fn one_spelling(text: &str) -> String {
110    let text = normalize_path(text);
111    text.strip_prefix("//?/").map(str::to_string).unwrap_or(text)
112}
113
114/// `dir` as it is written: absolute, with `.` and `..` taken out, and nothing looked up on the disk.
115fn spelled(dir: &Path) -> String {
116    let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());
117    let text = one_spelling(&absolute.to_string_lossy());
118    let resolved = crate::backend::cli_messaging::normalized(&text);
119    // A drive's own folder keeps its separator.
120    if resolved.ends_with(':') {
121        format!("{resolved}/")
122    } else {
123        resolved
124    }
125}
126
127/// `dir` as it resolves on the disk (links followed); `None` where it does not exist.
128fn resolved(dir: &Path) -> Option<String> {
129    std::fs::canonicalize(dir).ok().map(|real| one_spelling(&real.to_string_lossy()))
130}
131
132/// Both spellings of `dir`, the written one first.
133fn spellings(dir: &Path) -> Vec<String> {
134    let mut all = vec![spelled(dir)];
135    all.extend(resolved(dir).filter(|real| *real != all[0]));
136    all
137}
138
139/// The host folder of the Personal Memory of the agent of a container pane, as its container's mounts name it:
140/// after the workspace's own path (`written` says which folders a container agent can write).
141fn memory_of(store: &Store, meta: &obj::MetaMapType, written: &dyn Fn(&Path) -> bool) -> Option<PathBuf> {
142    if !crate::backend::runtime_adapter::RuntimeKind::of_block_meta(meta).is_container() {
143        return None;
144    }
145    let agent = obj::meta_get_string(meta, "agentId", "");
146    let cwd = obj::meta_get_string(meta, META_KEY_CMD_CWD, "");
147    if agent.is_empty() || cwd.trim().is_empty() {
148        return None;
149    }
150    let config = crate::backend::memory::native_files::agent_claude_config_dir(store, &agent);
151    Some(crate::backend::memory::native_files::memory_dir_for_cwd_with(&config, cwd.trim(), written))
152}
153
154/// The folders the pane `meta` binds writable into its agent's container.
155fn folders_of_pane(meta: &obj::MetaMapType, memory: Option<&Path>) -> Vec<Folder> {
156    let container = crate::backend::container::container_of_meta(meta).unwrap_or_default();
157    crate::backend::container::mounts::writable::writable_binds(meta, memory)
158        .into_iter()
159        .map(|bind| Folder { hosts: spellings(&bind.host), container: container.clone(), target: bind.target })
160        .collect()
161}
162
163/// Every folder a container agent of `store` can write.
164fn folders_of(store: &Store) -> Result<Vec<Folder>, crate::backend::storage::StoreError> {
165    let panes = store.get_all::<Block>()?;
166    // The workspaces and volumes first: they say which folders a memory folder may not be named from.
167    let bound: Vec<Folder> = panes.iter().flat_map(|b| folders_of_pane(&b.meta, None)).collect();
168    let written = |dir: &Path| inside_of(&spellings(dir), &bound).is_some();
169    let mut folders: Vec<Folder> =
170        panes.iter().flat_map(|b| folders_of_pane(&b.meta, memory_of(store, &b.meta, &written).as_deref())).collect();
171    folders.sort_by(|a, b| a.container.cmp(&b.container));
172    Ok(folders)
173}
174
175/// Where `asked` (the spellings of one folder) is inside `folders`: the deepest bound folder that holds it,
176/// the written spelling before the resolved one.
177fn inside_of(asked: &[String], folders: &[Folder]) -> Option<Inside> {
178    let mut best: Option<Inside> = None;
179    for spelling in asked {
180        for folder in folders {
181            for host in &folder.hosts {
182                let Some(rest) = relative_to(spelling, host) else { continue };
183                if best.as_ref().is_some_and(|b| b.host.len() >= host.len()) {
184                    continue;
185                }
186                let target = folder.target.trim_end_matches('/');
187                best = Some(Inside {
188                    container: folder.container.clone(),
189                    dir: if rest.is_empty() { folder.target.clone() } else { format!("{target}/{rest}") },
190                    host: host.clone(),
191                    target: folder.target.clone(),
192                });
193            }
194        }
195    }
196    best
197}
198
199/// Where `asked` is inside `container`, were `folder` bound into it at `target`: `None` when it is not in
200/// that folder, as written or as it resolves. Reads the disk for the spellings and nothing else.
201pub fn inside_one(asked: &Path, folder: &Path, container: &str, target: &str) -> Option<Inside> {
202    let bound = Folder { hosts: spellings(folder), container: container.to_string(), target: target.to_string() };
203    inside_of(&spellings(asked), &[bound])
204}
205
206/// Where git for `dir` runs.
207///
208/// Reads the disk and the store (blocking): call it off the async workers. When the panes can't be read and
209/// never were, the answer is [`Place::Unknown`]: no git runs anywhere until they can.
210pub fn place(dir: &str) -> Place {
211    thread_local! {
212        /// Set while this thread reads the panes.
213        static READING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
214    }
215    let asked = spellings(Path::new(dir));
216    #[cfg(test)]
217    if let Some(inside) = inside_of(&asked, &state().lock().for_tests) {
218        return Place::Inside(inside);
219    }
220    let (store, stale) = {
221        let s = state().lock();
222        (s.store.clone(), s.read_at.is_none_or(|at| at.elapsed() >= REUSE))
223    };
224    let Some(store) = store else {
225        return Place::Host;
226    };
227    if stale {
228        // The panes are read with no lock held. Asked again from inside that reading: not known.
229        if READING.replace(true) {
230            return Place::Unknown;
231        }
232        let read = folders_of(&store);
233        READING.set(false);
234        let mut s = state().lock();
235        match read {
236            Ok(folders) => s.folders = Some(folders),
237            Err(e) => tracing::warn!(error = %e, "container folders: can't read the panes; keeping the last list"),
238        }
239        s.read_at = Some(Instant::now());
240    }
241    let s = state().lock();
242    match &s.folders {
243        Some(folders) => inside_of(&asked, folders).map_or(Place::Host, Place::Inside),
244        None => Place::Unknown,
245    }
246}
247
248/// Whether a container agent can write `dir`: it is a folder bound writable into an agent's container, or
249/// inside one. Yes while that can't be told. Reads the disk and the store (see [`place`]).
250pub fn written_by_a_container_agent(dir: &Path) -> bool {
251    !matches!(place(&dir.to_string_lossy()), Place::Host)
252}
253
254/// What opening a file at `place` with the system's own app has to ask first: the id of the container agent that can
255/// write it (empty when the panes can't be read, so no agent can be named), or `None` for a path no container agent
256/// can write.
257pub fn open_asks_first(place: &Place) -> Option<String> {
258    match place {
259        Place::Host => None,
260        Place::Inside(inside) => Some(inside.container.strip_prefix("agentmux-").unwrap_or(&inside.container).to_string()),
261        Place::Unknown => Some(String::new()),
262    }
263}
264
265/// Count `folder` as bound writable into `container` at `target`, for the tests of this crate (each test
266/// names its own temp folder and container).
267#[cfg(test)]
268pub(crate) fn add_for_test(folder: &Path, container: &str, target: &str) {
269    state().lock().for_tests.push(Folder { hosts: spellings(folder), container: container.to_string(), target: target.to_string() });
270}
271
272/// Whether `a` and `b` are one folder, or one lies beneath the other, as written or as either resolves.
273pub fn overlap(a: &Path, b: &Path) -> bool {
274    let (a, b) = (spellings(a), spellings(b));
275    a.iter().any(|x| b.iter().any(|y| relative_to(x, y).is_some() || relative_to(y, x).is_some()))
276}
277
278/// Whether one of `folders` is `asked` (the spellings of one folder) or lies beneath it.
279fn holds_one_of(asked: &[String], folders: &[Folder]) -> bool {
280    folders.iter().flat_map(|folder| &folder.hosts).any(|host| asked.iter().any(|dir| relative_to(host, dir).is_some()))
281}
282
283/// Whether a folder a container agent can write is `dir` or lies beneath it. Yes while that can't be told.
284/// Reads the disk and the store, as [`place`] does.
285pub fn holds_a_container_agents_folder(dir: &str) -> bool {
286    // `place` reads the panes when its last read is old: the list it leaves is the one looked through here.
287    if matches!(place(dir), Place::Unknown) {
288        return true;
289    }
290    let asked = spellings(Path::new(dir));
291    let s = state().lock();
292    #[cfg(test)]
293    if holds_one_of(&asked, &s.for_tests) {
294        return true;
295    }
296    s.folders.as_deref().is_some_and(|folders| holds_one_of(&asked, folders))
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    fn folder(host: &str, container: &str, target: &str) -> Folder {
304        Folder { hosts: vec![host.to_string()], container: container.to_string(), target: target.to_string() }
305    }
306
307    fn asked(dir: &str) -> Vec<String> {
308        vec![dir.to_string()]
309    }
310
311    #[test]
312    fn a_folder_inside_a_bound_one_is_the_same_folder_in_the_container() {
313        let folders = [folder("/w/aria", "agentmux-a", "/workspace"), folder("/data/shared", "agentmux-a", "/data/")];
314        let top = inside_of(&asked("/w/aria"), &folders).unwrap();
315        assert_eq!((top.container.as_str(), top.dir.as_str()), ("agentmux-a", "/workspace"));
316        assert_eq!(inside_of(&asked("/w/aria/repo/src"), &folders).unwrap().dir, "/workspace/repo/src");
317        assert_eq!(inside_of(&asked("/data/shared/x"), &folders).unwrap().dir, "/data/x");
318        assert_eq!(inside_of(&asked("/w/aria2"), &folders), None, "a sibling with a longer name is outside");
319        assert_eq!(inside_of(&asked("/w"), &folders), None, "the folder above is outside");
320    }
321
322    #[test]
323    fn a_folder_holds_a_bound_one_that_is_it_or_lies_beneath_it() {
324        let folders = [folder("/p/proj/crates/foo", "agentmux-a", "/workspace"), folder("/w/aria", "agentmux-b", "/workspace")];
325        assert!(holds_one_of(&asked("/p/proj"), &folders), "a bound folder beneath it");
326        assert!(holds_one_of(&asked("/p/proj/crates/foo"), &folders), "the bound folder itself");
327        assert!(holds_one_of(&asked("/p"), &folders), "a bound folder deeper beneath it");
328        assert!(!holds_one_of(&asked("/p/proj/crates/foo/src"), &folders), "a folder inside a bound one holds none");
329        assert!(!holds_one_of(&asked("/p/proj/crates/fo"), &folders), "a sibling with a shorter name");
330        assert!(!holds_one_of(&asked("/p/other"), &folders), "a folder beside it");
331        // Either spelling of the folder asked about finds it.
332        assert!(holds_one_of(&["/links/proj".to_string(), "/p/proj".to_string()], &folders));
333        assert!(!holds_one_of(&asked("/p/proj"), &[]));
334    }
335
336    #[test]
337    fn the_deepest_bound_folder_holds_it_and_either_spelling_finds_it() {
338        let folders = [folder("/w", "agentmux-outer", "/workspace"), folder("/w/aria", "agentmux-inner", "/workspace")];
339        assert_eq!(inside_of(&asked("/w/aria/repo"), &folders).unwrap().container, "agentmux-inner");
340        assert_eq!(inside_of(&asked("/w/other"), &folders).unwrap().container, "agentmux-outer");
341        // Written outside every bound folder, resolving into one: the container's.
342        let by_link = inside_of(&["/links/aria/repo".to_string(), "/w/aria/repo".to_string()], &folders).unwrap();
343        assert_eq!((by_link.container.as_str(), by_link.dir.as_str()), ("agentmux-inner", "/workspace/repo"));
344        // Written inside one and resolving outside every one: still the container's, at the place it is written.
345        let out = inside_of(&["/w/aria/link".to_string(), "/elsewhere".to_string()], &folders).unwrap();
346        assert_eq!(out.dir, "/workspace/link");
347    }
348
349    #[test]
350    fn opening_with_the_systems_app_asks_first_only_for_a_folder_a_container_agent_can_write() {
351        let inside = inside_of(&asked("/w/aria/repo/a.docx"), &[folder("/w/aria", "agentmux-aria", "/workspace")]).unwrap();
352        assert_eq!(open_asks_first(&Place::Inside(inside)).as_deref(), Some("aria"), "the agent's id, from its container's name");
353        assert_eq!(open_asks_first(&Place::Host), None, "a path no container agent can write asks nothing");
354        assert_eq!(open_asks_first(&Place::Unknown).as_deref(), Some(""), "when that can't be told, it asks without a name");
355        let unnamed = inside_of(&asked("/v/x"), &[folder("/v", "", "/vol")]).unwrap();
356        assert_eq!(open_asks_first(&Place::Inside(unnamed)).as_deref(), Some(""), "a pane that names no agent asks without a name");
357    }
358
359    #[test]
360    fn a_path_inside_the_container_names_its_host_folder_only_inside_the_bound_one() {
361        let inside = inside_of(&asked("/w/aria/repo/src"), &[folder("/w/aria", "agentmux-a", "/workspace")]).unwrap();
362        assert_eq!(inside.host_path("/workspace/repo").as_deref(), Some("/w/aria/repo"));
363        assert_eq!(inside.host_path("/workspace").as_deref(), Some("/w/aria"));
364        assert_eq!(inside.host_path("/workspace/repo/../other/").as_deref(), Some("/w/aria/other"));
365        assert_eq!(inside.host_path("/workspace2/repo"), None);
366        assert_eq!(inside.host_path("/home/agent/repo"), None);
367        assert_eq!(inside.host_path("/workspace/../etc"), None, "a path that leaves the bound folder names nothing");
368    }
369
370    #[test]
371    fn a_folder_is_spelled_without_looking_at_the_disk() {
372        let base = std::env::temp_dir().join("agentmux-cf-spelled-nowhere");
373        let odd = base.join("a").join("..").join("b").join(".");
374        assert_eq!(spelled(&odd), spelled(&base.join("b")));
375        assert_eq!(resolved(&odd), None, "it is not there");
376    }
377
378    fn pane(mode: &str, agent: &str, cwd: &str, volumes: &str) -> Block {
379        let mut meta = obj::MetaMapType::new();
380        meta.insert("agentMode".to_string(), serde_json::json!(mode));
381        meta.insert("agentId".to_string(), serde_json::json!(agent));
382        meta.insert(META_KEY_CMD_CWD.to_string(), serde_json::json!(cwd));
383        meta.insert("agent:container_volumes".to_string(), serde_json::json!(volumes));
384        Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() }
385    }
386
387    #[test]
388    fn the_folders_are_what_the_container_agents_of_the_store_can_write() {
389        let store = Store::open_in_memory().unwrap();
390        let (work, shared, docs, host) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
391        let text = |d: &tempfile::TempDir| d.path().to_string_lossy().replace('\\', "/");
392        let volumes = serde_json::json!([format!("{}:/data", text(&shared)), format!("{}:/docs:ro", text(&docs))]).to_string();
393        store.insert(&mut pane("container", "aria", &text(&work), &volumes)).unwrap();
394        store.insert(&mut pane("host", "hugo", &text(&host), "[]")).unwrap();
395        let folders = folders_of(&store).unwrap();
396
397        let deep = work.path().join("repo").join("src");
398        std::fs::create_dir_all(&deep).unwrap();
399        let at = |dir: &Path| inside_of(&spellings(dir), &folders);
400        let in_work = at(&deep).expect("the workspace is the agent's");
401        assert_eq!((in_work.container.as_str(), in_work.dir.as_str()), ("agentmux-aria", "/workspace/repo/src"));
402        assert_eq!(at(shared.path()).expect("a writable volume is the agent's").dir, "/data");
403        assert_eq!(at(docs.path()), None, "a read-only volume is not");
404        assert_eq!(at(host.path()), None, "a host agent's folder is not");
405        let own = |dir: &Path| dir.starts_with(work.path());
406        let memory = memory_of(&store, &pane("container", "aria", &text(&work), "[]").meta, &own).expect("the agent has a memory folder");
407        assert_eq!(at(&memory).expect("its memory folder is the agent's").dir, crate::backend::container::mounts::container_memory_dir());
408        assert_eq!(memory_of(&store, &pane("host", "hugo", &text(&host), "[]").meta, &own), None);
409    }
410}