Skip to main content

agentmux_srv_core/backend/fs_ops/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The filesystem layer behind the generic `fs.*` RPCs and the Files pane:
5//! paginated listing, known places, name validation, the
6//! mutation safety policy, and the mutations themselves.
7//!
8//! Everything here is blocking and is called from `spawn_blocking` (or the
9//! trash thread): on macOS the first access to a protected folder blocks the
10//! calling thread while a privacy prompt is on screen (spec §9.1.1 fact 10).
11//!
12//! Spec: docs/specs/SPEC_FILE_BROWSER_PANE_2026_10_01.md §6.3, §7, §9.
13
14pub mod container_folders;
15pub mod host_jobs;
16pub mod remote;
17pub mod git;
18pub mod jobs;
19pub mod platform;
20pub mod trash_worker;
21
22use std::collections::HashMap;
23use std::io;
24use std::iter::Peekable;
25use std::path::{Component, Path, PathBuf};
26use std::sync::{LazyLock, Mutex};
27use std::time::{Duration, Instant};
28
29use crate::backend::rpc_types::{
30    FsCreateKind, FsCreateReq, FsCreateResult, FsEntry, FsError, FsErrorKind, FsListReq,
31    FsListResult, FsPlace, FsPlaceKind, FsRenameReq, FsRenameResult,
32};
33
34use platform::display_path;
35
36// ── Paths ────────────────────────────────────────────────────────────────
37
38/// A request path as an absolute host path: `~` expanded, an MSYS-style
39/// `/c/…` converted on Windows, NUL refused, relative refused (a relative
40/// path would resolve against srv's own working directory, which means
41/// nothing to the user).
42pub fn resolve_request_path(raw: &str) -> Result<PathBuf, String> {
43    if raw.contains('\0') {
44        return Err("That path contains an invalid character.".to_string());
45    }
46    if raw.is_empty() {
47        return Err("No path was given.".to_string());
48    }
49    let converted = crate::backend::base::msys_to_windows_path(raw);
50    let expanded = crate::backend::base::expand_home_dir_safe(&converted);
51    if !expanded.is_absolute() {
52        return Err(format!("“{raw}” isn't a full path."));
53    }
54    Ok(expanded)
55}
56
57/// The path a mutation acts on: the request path with its PARENT
58/// canonicalized and its own last component kept as given.
59///
60/// Canonicalizing the whole path would resolve a final symlink to its
61/// target, and a rename or delete would then act on the target instead of
62/// the link. Canonicalizing the parent still resolves `..`, `~` and any
63/// linked folder above it, so protection checks see where the entry really
64/// is.
65pub fn resolve_entry_path(raw: &str) -> Result<PathBuf, String> {
66    let path = resolve_request_path(raw)?;
67    let name = path.file_name().ok_or_else(|| {
68        if path.parent().is_none() {
69            ROOT_REFUSAL.to_string()
70        } else {
71            format!("“{raw}” isn't a valid path.")
72        }
73    })?;
74    let parent = path.parent().ok_or_else(|| ROOT_REFUSAL.to_string())?;
75    let canonical_parent = parent.canonicalize().map_err(|e| match e.kind() {
76        io::ErrorKind::NotFound => "The folder it's in doesn't exist anymore.".to_string(),
77        _ => format!("Couldn't open the folder it's in: {e}"),
78    })?;
79    Ok(canonical_parent.join(name))
80}
81
82/// Comparison key for paths: the display form, case-folded on Windows,
83/// whose filesystems are case-insensitive. Component-wise `starts_with` on
84/// these is a correct "is inside" test.
85fn path_key(path: &Path) -> PathBuf {
86    if cfg!(windows) {
87        PathBuf::from(display_path(path).to_lowercase())
88    } else {
89        path.to_path_buf()
90    }
91}
92
93fn file_name_string(path: &Path) -> String {
94    path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
95}
96
97// ── Listing ──────────────────────────────────────────────────────────────
98
99/// Page size when the request names none.
100pub const DEFAULT_LIST_LIMIT: u32 = 1000;
101/// Largest page a request may ask for.
102pub const MAX_LIST_LIMIT: u32 = 5000;
103/// A cursor is dropped after this long without a page being asked for. The
104/// frontend navigating away simply stops asking, so this is the
105/// cancellation (spec §6.3).
106pub const CURSOR_TTL: Duration = Duration::from_secs(30);
107/// Open listings held at once. Each holds an OS directory handle, so a
108/// burst of abandoned listings is bounded rather than left to the TTL.
109const MAX_CURSORS: usize = 256;
110/// Consecutive unreadable directory entries after which a listing gives up,
111/// so a directory whose iterator keeps failing ends instead of looping.
112const MAX_CONSECUTIVE_ENTRY_ERRORS: usize = 64;
113
114/// An open listing between pages.
115pub struct ListCursor {
116    iter: Peekable<std::fs::ReadDir>,
117    display: String,
118    last_used: Instant,
119}
120
121/// Open listings by cursor id.
122#[derive(Default)]
123pub struct CursorStore {
124    cursors: HashMap<String, ListCursor>,
125}
126
127impl CursorStore {
128    /// Remove and return the cursor `id`, unless it has expired.
129    fn take(&mut self, id: &str, now: Instant) -> Option<ListCursor> {
130        let cursor = self.cursors.remove(id)?;
131        (now.saturating_duration_since(cursor.last_used) <= CURSOR_TTL).then_some(cursor)
132    }
133
134    /// Store `cursor` under a new id and return the id. Drops expired
135    /// cursors first, then the least recently used if still at capacity.
136    fn put(&mut self, mut cursor: ListCursor, now: Instant) -> String {
137        self.sweep(now);
138        while self.cursors.len() >= MAX_CURSORS {
139            let Some(oldest) = self
140                .cursors
141                .iter()
142                .min_by_key(|(_, c)| c.last_used)
143                .map(|(id, _)| id.clone())
144            else {
145                break;
146            };
147            self.cursors.remove(&oldest);
148        }
149        cursor.last_used = now;
150        let id = uuid::Uuid::new_v4().to_string();
151        self.cursors.insert(id.clone(), cursor);
152        id
153    }
154
155    /// Drop every cursor idle for longer than the TTL, closing its directory
156    /// handle.
157    pub fn sweep(&mut self, now: Instant) {
158        self.cursors
159            .retain(|_, c| now.saturating_duration_since(c.last_used) <= CURSOR_TTL);
160    }
161
162    #[cfg(test)]
163    fn len(&self) -> usize {
164        self.cursors.len()
165    }
166}
167
168/// The process-wide cursor store. Process-wide rather than per connection
169/// because a window reload reconnects; a cursor id is a random UUID, so one
170/// connection can't guess another's.
171pub static CURSORS: LazyLock<Mutex<CursorStore>> = LazyLock::new(|| Mutex::new(CursorStore::default()));
172
173/// Start the periodic cursor sweep, once per process. Without it, cursors
174/// abandoned after the last `fs.list` call would keep their directory
175/// handles open until the next call.
176pub fn ensure_cursor_sweeper() {
177    static STARTED: std::sync::Once = std::sync::Once::new();
178    STARTED.call_once(|| {
179        tokio::spawn(async {
180            let mut tick = tokio::time::interval(Duration::from_secs(10));
181            loop {
182                tick.tick().await;
183                lock_store(&CURSORS).sweep(Instant::now());
184            }
185        });
186    });
187}
188
189/// One page of `fs.list`, against the process-wide cursor store.
190pub fn list_page(req: &FsListReq) -> FsListResult {
191    list_page_in(&CURSORS, req, Instant::now())
192}
193
194/// One page of `fs.list`. A failure to open the directory is an `Ok`
195/// answer with `error` set, never an `Err` (spec §9: a denied folder must
196/// never look empty, and must never fail the pane).
197pub fn list_page_in(store: &Mutex<CursorStore>, req: &FsListReq, now: Instant) -> FsListResult {
198    let limit = req.limit.unwrap_or(DEFAULT_LIST_LIMIT).clamp(1, MAX_LIST_LIMIT) as usize;
199
200    let mut cursor = match req.cursor.as_deref() {
201        Some(id) => {
202            let taken = lock_store(store).take(id, now);
203            match taken {
204                Some(c) => c,
205                None => {
206                    let path = resolve_request_path(&req.path)
207                        .map(|p| display_path(&p))
208                        .unwrap_or_else(|_| req.path.clone());
209                    return list_failure(path, FsErrorKind::Expired, "This listing expired. Reload the folder.".to_string());
210                }
211            }
212        }
213        None => match open_listing(&req.path) {
214            Ok(c) => c,
215            Err(failure) => return failure,
216        },
217    };
218
219    let mut entries = Vec::with_capacity(limit.min(1024));
220    let mut consecutive_errors = 0usize;
221    let mut gave_up = false;
222    while entries.len() < limit {
223        match cursor.iter.next() {
224            None => break,
225            Some(Ok(de)) => {
226                consecutive_errors = 0;
227                entries.push(build_entry(&de));
228            }
229            // An unreadable directory entry has no name to show a row for.
230            Some(Err(e)) => {
231                tracing::debug!(dir = %cursor.display, error = %e, "fs.list: skipping an unreadable directory entry");
232                consecutive_errors += 1;
233                if consecutive_errors >= MAX_CONSECUTIVE_ENTRY_ERRORS {
234                    tracing::warn!(dir = %cursor.display, "fs.list: too many unreadable entries in a row; ending the listing");
235                    gave_up = true;
236                    break;
237                }
238            }
239        }
240    }
241
242    let display = cursor.display.clone();
243    let done = gave_up || cursor.iter.peek().is_none();
244    let next = if done {
245        None
246    } else {
247        Some(lock_store(store).put(cursor, now))
248    };
249    FsListResult { path: display, entries, cursor: next, error: None }
250}
251
252/// The store's lock, recovered if a panic elsewhere poisoned it: the map is
253/// left consistent by every operation on it, and a poisoned lock must not
254/// silently end every listing.
255fn lock_store(store: &Mutex<CursorStore>) -> std::sync::MutexGuard<'_, CursorStore> {
256    store.lock().unwrap_or_else(|e| e.into_inner())
257}
258
259fn list_failure(path: String, kind: FsErrorKind, message: String) -> FsListResult {
260    FsListResult { path, entries: Vec::new(), cursor: None, error: Some(FsError { kind, message }) }
261}
262
263/// Canonicalize and open the directory for a first page.
264fn open_listing(raw: &str) -> Result<ListCursor, FsListResult> {
265    let path = resolve_request_path(raw)
266        .map_err(|msg| list_failure(raw.to_string(), FsErrorKind::Other, msg))?;
267    let canonical = path.canonicalize().map_err(|e| folder_failure(display_path(&path), &e))?;
268    let display = display_path(&canonical);
269    match std::fs::metadata(&canonical) {
270        Ok(meta) if !meta.is_dir() => {
271            return Err(list_failure(display, FsErrorKind::NotADirectory, "This isn't a folder.".to_string()));
272        }
273        Ok(_) => {}
274        Err(e) => return Err(folder_failure(display, &e)),
275    }
276    let iter = std::fs::read_dir(&canonical).map_err(|e| folder_failure(display.clone(), &e))?;
277    Ok(ListCursor { iter: iter.peekable(), display, last_used: Instant::now() })
278}
279
280/// The `fs.list` error for a folder that couldn't be opened.
281fn folder_failure(display: String, err: &io::Error) -> FsListResult {
282    let (kind, message) = classify_folder_error(err);
283    list_failure(display, kind, message)
284}
285
286pub fn classify_folder_error(err: &io::Error) -> (FsErrorKind, String) {
287    match err.kind() {
288        io::ErrorKind::NotFound => (FsErrorKind::NotFound, "This folder doesn't exist.".to_string()),
289        io::ErrorKind::PermissionDenied if platform::is_os_blocked(err) => (
290            FsErrorKind::OsBlocked,
291            "macOS blocked AgentMux from reading this folder. Open System Settings → Privacy & Security → \
292             Files & Folders, turn AgentMux on, then try again."
293                .to_string(),
294        ),
295        io::ErrorKind::PermissionDenied => (
296            FsErrorKind::PermissionDenied,
297            "You don't have permission to open this folder.".to_string(),
298        ),
299        io::ErrorKind::NotADirectory => (FsErrorKind::NotADirectory, "This isn't a folder.".to_string()),
300        _ => (FsErrorKind::Other, format!("Couldn't open this folder: {err}")),
301    }
302}
303
304/// One listing row. Never fails: what can't be read becomes the row's
305/// `error`, and the page goes on (spec §9: errors are per entry).
306fn build_entry(de: &std::fs::DirEntry) -> FsEntry {
307    let name = de.file_name().to_string_lossy().into_owned();
308    let mut entry = FsEntry {
309        hidden: name.starts_with('.'),
310        name,
311        is_dir: false,
312        is_symlink: false,
313        size: None,
314        mtime: None,
315        readonly: false,
316        link_target: None,
317        error: None,
318    };
319
320    // `DirEntry::metadata` never follows a link: this is the entry's own
321    // metadata, which is where the hidden/system attributes and the link
322    // type live. On Windows it costs no extra system call.
323    let own = match de.metadata() {
324        Ok(m) => m,
325        Err(e) => {
326            if let Ok(ft) = de.file_type() {
327                entry.is_symlink = ft.is_symlink();
328                entry.is_dir = ft.is_dir();
329            }
330            entry.error = Some(entry_error_message(&e));
331            return entry;
332        }
333    };
334    entry.hidden |= platform::has_hidden_attribute(&own);
335    entry.is_symlink = own.file_type().is_symlink();
336
337    let effective = if entry.is_symlink {
338        let path = de.path();
339        entry.link_target = std::fs::read_link(&path).ok().map(|t| display_path(&t));
340        match std::fs::metadata(&path) {
341            Ok(m) => m,
342            Err(e) => {
343                entry.error = Some(match e.kind() {
344                    io::ErrorKind::NotFound => "The link's target doesn't exist.".to_string(),
345                    _ => format!("Couldn't follow the link: {e}"),
346                });
347                return entry;
348            }
349        }
350    } else {
351        own
352    };
353
354    entry.is_dir = effective.is_dir();
355    if !entry.is_dir {
356        entry.size = Some(effective.len());
357    }
358    entry.mtime = effective
359        .modified()
360        .ok()
361        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
362        .map(|d| d.as_millis() as u64);
363    // Windows ignores the read-only attribute on folders (Explorer uses it
364    // to mark customized folders such as Documents), so only files report it.
365    entry.readonly = !(cfg!(windows) && entry.is_dir) && effective.permissions().readonly();
366    entry
367}
368
369fn entry_error_message(err: &io::Error) -> String {
370    match err.kind() {
371        io::ErrorKind::NotFound => "It was removed while the folder was being read.".to_string(),
372        io::ErrorKind::PermissionDenied => "Access denied.".to_string(),
373        _ => err.to_string(),
374    }
375}
376
377// ── Places ───────────────────────────────────────────────────────────────
378
379/// Home and the known folders, by name only. Nothing here reads or stats a
380/// known folder: on macOS that alone can raise a privacy prompt the user
381/// didn't ask for (spec §9.1.5). A folder `dirs` can't name is left out.
382pub fn home_and_known_places() -> (String, Vec<FsPlace>) {
383    let home = dirs::home_dir().map(|h| display_path(&h)).unwrap_or_default();
384    let mut places = Vec::new();
385    if !home.is_empty() {
386        places.push(FsPlace { id: "home".to_string(), label: "Home".to_string(), path: home.clone(), kind: FsPlaceKind::Home });
387    }
388    let known: [(&str, &str, Option<PathBuf>); 4] = [
389        ("desktop", "Desktop", dirs::desktop_dir()),
390        ("documents", "Documents", dirs::document_dir()),
391        ("downloads", "Downloads", dirs::download_dir()),
392        ("pictures", "Pictures", dirs::picture_dir()),
393    ];
394    for (id, label, dir) in known {
395        if let Some(dir) = dir {
396            places.push(FsPlace { id: id.to_string(), label: label.to_string(), path: display_path(&dir), kind: FsPlaceKind::Known });
397        }
398    }
399    (home, places)
400}
401
402// ── Names ────────────────────────────────────────────────────────────────
403
404/// Validate a new file or folder name with the current platform's rules.
405pub fn validate_new_name(name: &str) -> Result<(), String> {
406    validate_name_rules(name, cfg!(windows))
407}
408
409/// Device names Windows reserves in every folder, with or without an
410/// extension (`nul.txt` is still the null device). The superscript digits
411/// are reserved too.
412const WINDOWS_RESERVED: &[&str] = &[
413    "con", "prn", "aux", "nul", "conin$", "conout$", "com0", "com1", "com2", "com3", "com4", "com5", "com6", "com7",
414    "com8", "com9", "com¹", "com²", "com³", "lpt0", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8",
415    "lpt9", "lpt¹", "lpt²", "lpt³",
416];
417
418/// Longest name most filesystems accept (NTFS: 255 UTF-16 units; ext4 and
419/// APFS: 255 bytes). Checked as UTF-16 units and bytes both.
420const MAX_NAME_LEN: usize = 255;
421
422/// The name rules (spec §7.4), with the Windows-only ones switched by
423/// `windows` so every rule can be tested on any platform. Errors are
424/// sentences, shown to the user as they are.
425pub fn validate_name_rules(name: &str, windows: bool) -> Result<(), String> {
426    if name.trim().is_empty() {
427        return Err("A name can't be empty.".to_string());
428    }
429    if name == "." || name == ".." {
430        return Err("“.” and “..” can't be used as names.".to_string());
431    }
432    if name.contains('/') || name.contains('\\') {
433        return Err("A name can't contain / or \\.".to_string());
434    }
435    if name.contains('\0') {
436        return Err("A name can't contain a NUL character.".to_string());
437    }
438    if name.len() > MAX_NAME_LEN || name.encode_utf16().count() > MAX_NAME_LEN {
439        return Err("That name is too long.".to_string());
440    }
441    if windows {
442        if let Some(c) = name.chars().find(|c| matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')) {
443            return Err(format!("Windows doesn't allow {c} in a name."));
444        }
445        if name.chars().any(|c| (c as u32) < 0x20) {
446            return Err("A name can't contain control characters.".to_string());
447        }
448        // Windows silently strips these, so the file would get a different
449        // name from the one typed (and a verbatim path would create one that
450        // most programs then can't open).
451        if name.ends_with('.') || name.ends_with(' ') {
452            return Err("Windows doesn't allow a name to end with a dot or a space.".to_string());
453        }
454        let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ').to_lowercase();
455        if WINDOWS_RESERVED.contains(&stem.as_str()) {
456            return Err(format!("“{name}” is reserved by Windows. Pick another name."));
457        }
458    }
459    Ok(())
460}
461
462// ── Mutation safety ──────────────────────────────────────────────────────
463
464const ROOT_REFUSAL: &str = "AgentMux won't change the root of a drive.";
465
466/// What a mutation must never touch (spec §9, "Security"): a filesystem
467/// root, the home folder itself, AgentMux's own data and installation, the
468/// OS's system folders, and the inside of a macOS app bundle. Nor anything
469/// that CONTAINS one of those: deleting `C:\Users` would delete the home
470/// folder too.
471///
472/// Every path held here is in `path_key` form.
473#[derive(Debug, Clone, Default)]
474pub struct ProtectedPaths {
475    home: Option<PathBuf>,
476    /// `~/.agentmux`. Inside it only agents' own workspaces
477    /// (`agents/<name>/…`) may be changed; the rest is AgentMux's state.
478    data_root: Option<PathBuf>,
479    install_dirs: Vec<PathBuf>,
480    system_roots: Vec<PathBuf>,
481    /// Inside these the system list doesn't apply: the temp folder, which
482    /// on macOS lives under `/var`.
483    exempt_roots: Vec<PathBuf>,
484}
485
486impl ProtectedPaths {
487    /// The protected set for this machine, computed afresh so a check made
488    /// right before a mutation reflects the filesystem as it is then.
489    pub fn current() -> Self {
490        let canon = |p: PathBuf| -> PathBuf { path_key(&p.canonicalize().unwrap_or(p)) };
491        let home = dirs::home_dir().map(canon);
492        let data_root = Some(canon(crate::backend::base::get_mux_data_dir()));
493
494        // A binary sitting directly in home (or anywhere above it) must not
495        // turn the whole home folder read-only: protect just the binary then.
496        let covers_home = |dir: &Path| home.as_ref().is_some_and(|h| h.starts_with(dir));
497        let mut install_dirs = Vec::new();
498        if let Ok(exe) = std::env::current_exe() {
499            let exe = exe.canonicalize().unwrap_or(exe);
500            if let Some(dir) = install_dir_of(&exe).map(path_key) {
501                install_dirs.push(if covers_home(&dir) { path_key(&exe) } else { dir });
502            }
503        }
504        if let Some(app) = crate::backend::base::get_mux_app_path().map(canon) {
505            if !covers_home(&app) {
506                install_dirs.push(app);
507            }
508        }
509
510        let system_roots = system_roots().into_iter().map(canon).collect();
511        let exempt_roots = vec![canon(std::env::temp_dir())];
512        Self { home, data_root, install_dirs, system_roots, exempt_roots }
513    }
514
515    /// `Ok` if a mutation may act on `target` (a `resolve_entry_path`
516    /// result). The error is a sentence for the user.
517    pub fn check(&self, target: &Path) -> Result<(), String> {
518        if target.parent().is_none() {
519            return Err(ROOT_REFUSAL.to_string());
520        }
521        if let Some(share) = crate::backend::remote::wsl_fs::share_of(target) {
522            return self.check_in_distro(&share);
523        }
524        let key = path_key(target);
525        let contains = |protected: &Path| protected.starts_with(&key);
526
527        if let Some(home) = &self.home {
528            if *home == key {
529                return Err("AgentMux won't rename, move or delete your home folder.".to_string());
530            }
531            if contains(home) {
532                return Err("This folder contains your home folder, so AgentMux won't change it.".to_string());
533            }
534        }
535
536        if let Some(data) = &self.data_root {
537            if contains(data) {
538                return Err("This is, or contains, AgentMux's own data folder; AgentMux won't change it.".to_string());
539            }
540            if let Ok(rel) = key.strip_prefix(data) {
541                let parts: Vec<Component<'_>> = rel.components().collect();
542                let in_workspace = parts.len() >= 3 && parts[0].as_os_str() == "agents";
543                if !in_workspace {
544                    return Err(
545                        "This is part of AgentMux's own data. Only files inside an agent's workspace can be changed here."
546                            .to_string(),
547                    );
548                }
549            }
550        }
551
552        for dir in &self.install_dirs {
553            if key.starts_with(dir) || contains(dir) {
554                return Err("This is part of the AgentMux installation; AgentMux won't change it.".to_string());
555            }
556        }
557
558        // The inside of a macOS app bundle: changing it breaks the app's
559        // signature, and for apps in /Applications raises an App Management
560        // prompt (spec §9.1.5). The bundle itself is treated as a file.
561        if cfg!(target_os = "macos")
562            && key
563                .ancestors()
564                .skip(1)
565                .any(|a| a.extension().is_some_and(|e| e.eq_ignore_ascii_case("app")))
566        {
567            return Err("AgentMux won't change the inside of an app bundle.".to_string());
568        }
569
570        let inside_home = self.home.as_ref().is_some_and(|h| key.starts_with(h));
571        let exempt = self.exempt_roots.iter().any(|r| key.starts_with(r));
572        if !inside_home && !exempt {
573            for root in &self.system_roots {
574                if key.starts_with(root) || contains(root) {
575                    return Err("This is a protected system folder; AgentMux won't change it.".to_string());
576                }
577            }
578        }
579        Ok(())
580    }
581
582    /// [`Self::check`] for a WSL distro's file through `\\wsl.localhost`
583    /// (`remote::wsl_fs`). Its `/mnt/<letter>` is a Windows drive, so the
584    /// Windows rules decide; its own system folders and home folders are
585    /// protected as this machine's are.
586    fn check_in_distro(&self, share: &crate::backend::remote::wsl_fs::SharePath) -> Result<(), String> {
587        use crate::backend::remote::wsl_fs;
588        if share.linux == "/" {
589            return Err(ROOT_REFUSAL.to_string());
590        }
591        if let Some(windows) = wsl_fs::drive_path(&share.linux) {
592            return self.check(Path::new(&windows));
593        }
594        if wsl_fs::is_system_path(&share.linux) {
595            return Err(format!(
596                "This is a system folder of the {} WSL distribution; AgentMux won't change it.",
597                share.distro
598            ));
599        }
600        if share.linux == "/home" || wsl_fs::is_home(&share.linux) {
601            return Err("AgentMux won't rename, move or delete a home folder.".to_string());
602        }
603        Ok(())
604    }
605
606    #[cfg(test)]
607    fn for_test(home: &Path, data_root: &Path, install: &[&Path], system: &[&Path], exempt: &[&Path]) -> Self {
608        Self {
609            home: Some(path_key(home)),
610            data_root: Some(path_key(data_root)),
611            install_dirs: install.iter().map(|p| path_key(p)).collect(),
612            system_roots: system.iter().map(|p| path_key(p)).collect(),
613            exempt_roots: exempt.iter().map(|p| path_key(p)).collect(),
614        }
615    }
616}
617
618/// The installation a (canonical) executable belongs to: on macOS the whole
619/// bundle, not just Contents/MacOS. The outermost `.app`, because srv's real
620/// file sits in a nested helper app (`AgentMux.app/Contents/Helpers/AgentMux
621/// Server.app`, scripts/package-macos.sh), and protecting only that would
622/// leave the rest of AgentMux.app open to changes.
623fn install_dir_of(exe: &Path) -> Option<&Path> {
624    exe.ancestors()
625        .skip(1)
626        .filter(|a| a.extension().is_some_and(|e| e.eq_ignore_ascii_case("app")))
627        .last()
628        .or_else(|| exe.parent())
629}
630
631/// The OS's own folders (spec §9).
632fn system_roots() -> Vec<PathBuf> {
633    #[cfg(windows)]
634    {
635        let mut roots = Vec::new();
636        for (var, fallback) in [
637            ("SystemRoot", r"C:\Windows"),
638            ("ProgramFiles", r"C:\Program Files"),
639            ("ProgramFiles(x86)", r"C:\Program Files (x86)"),
640            ("ProgramW6432", r"C:\Program Files"),
641            ("ProgramData", r"C:\ProgramData"),
642        ] {
643            let dir = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| PathBuf::from(fallback));
644            if !roots.contains(&dir) {
645                roots.push(dir);
646            }
647        }
648        roots
649    }
650    #[cfg(not(windows))]
651    {
652        let mut roots: Vec<PathBuf> = ["/usr", "/bin", "/sbin", "/etc", "/var", "/boot", "/lib", "/lib32", "/lib64", "/proc", "/sys", "/dev"]
653            .iter()
654            .map(PathBuf::from)
655            .collect();
656        if cfg!(target_os = "macos") {
657            // /etc and /var are links into /private, so their canonical
658            // forms are what a resolved path will start with.
659            roots.extend(["/System", "/Library", "/private/etc", "/private/var"].iter().map(PathBuf::from));
660        }
661        roots
662    }
663}
664
665// ── Mutations ────────────────────────────────────────────────────────────
666//
667// Each re-resolves and re-checks its target immediately before acting, on
668// the thread that acts (spec §9: "re-validated at execution time"), and
669// logs one info line per operation for audit.
670
671pub fn exists_message(name: &str) -> String {
672    format!("Something named “{name}” already exists here.")
673}
674
675/// What to say when another program holds the file (Windows: a sharing or a lock violation).
676pub const IN_USE: &str = "Another program is using this file. Close it there and try again.";
677
678/// Whether `err` is Windows refusing because another program has the file open without sharing it.
679fn in_use(err: &io::Error) -> bool {
680    cfg!(windows) && matches!(err.raw_os_error(), Some(32 | 33))
681}
682
683/// The no-replace rename, tried once more after a moment when another program holds the file: a virus
684/// scan or a search indexer lets go within milliseconds, an editor doesn't.
685fn rename_patiently(from: &Path, to: &Path) -> io::Result<()> {
686    match platform::rename_no_replace(from, to) {
687        Err(e) if in_use(&e) => {
688            std::thread::sleep(Duration::from_millis(200));
689            platform::rename_no_replace(from, to)
690        }
691        done => done,
692    }
693}
694
695/// `raw` as `fs.rename` resolves and reports it: what a rename event names as the path before.
696pub fn entry_display_path(raw: &str) -> Option<String> {
697    resolve_entry_path(raw).ok().map(|p| display_path(&p))
698}
699
700fn missing_or(err: io::Error, what: &str) -> String {
701    if in_use(&err) {
702        return IN_USE.to_string();
703    }
704    match err.kind() {
705        io::ErrorKind::NotFound => "It doesn't exist anymore.".to_string(),
706        io::ErrorKind::PermissionDenied => format!("You don't have permission to {what} it."),
707        _ => format!("Couldn't {what} it: {err}"),
708    }
709}
710
711/// `fs.rename`: a new name in the same folder. Never overwrites; a
712/// case-only rename goes through a temporary name, because on a
713/// case-insensitive filesystem the new name already "exists" (it is the
714/// file itself) and some filesystems ignore a direct case-only rename
715/// (spec §7.4).
716pub fn rename(req: &FsRenameReq) -> Result<FsRenameResult, String> {
717    let protect = ProtectedPaths::current();
718    let src = resolve_entry_path(&req.path)?;
719    validate_new_name(&req.new_name)?;
720    std::fs::symlink_metadata(&src).map_err(|e| missing_or(e, "rename"))?;
721    protect.check(&src)?;
722    let parent = src.parent().ok_or_else(|| ROOT_REFUSAL.to_string())?.to_path_buf();
723    let dest = parent.join(&req.new_name);
724    protect.check(&dest)?;
725
726    let old_name = file_name_string(&src);
727    if old_name == req.new_name {
728        return Ok(FsRenameResult { new_path: display_path(&dest) });
729    }
730
731    let result = if old_name.to_lowercase() == req.new_name.to_lowercase() {
732        rename_case_only(&src, &dest, &parent, &req.new_name)
733    } else {
734        rename_patiently(&src, &dest).map_err(|e| match e.kind() {
735            io::ErrorKind::AlreadyExists => exists_message(&req.new_name),
736            _ => missing_or(e, "rename"),
737        })
738    };
739    tracing::info!(
740        op = "fs.rename",
741        from = %display_path(&src),
742        to = %display_path(&dest),
743        outcome = if result.is_ok() { "ok" } else { "error" },
744        error = result.as_ref().err().map(String::as_str).unwrap_or(""),
745        "fs mutation"
746    );
747    result.map(|()| FsRenameResult { new_path: display_path(&dest) })
748}
749
750fn rename_case_only(src: &Path, dest: &Path, parent: &Path, new_name: &str) -> Result<(), String> {
751    // On a case-sensitive filesystem a differently-cased name can be a
752    // different, existing entry; only an exact match tells.
753    let taken = std::fs::read_dir(parent)
754        .map_err(|e| missing_or(e, "rename"))?
755        .flatten()
756        .any(|e| e.file_name() == std::ffi::OsStr::new(new_name));
757    if taken {
758        return Err(exists_message(new_name));
759    }
760    let tmp = parent.join(format!(".agentmux-rename-{}", uuid::Uuid::new_v4().simple()));
761    rename_patiently(src, &tmp).map_err(|e| missing_or(e, "rename"))?;
762    if let Err(e) = platform::rename_no_replace(&tmp, dest) {
763        // Put it back under its old name rather than strand it under the
764        // temporary one.
765        let _ = platform::rename_no_replace(&tmp, src);
766        return Err(match e.kind() {
767            io::ErrorKind::AlreadyExists => exists_message(new_name),
768            _ => missing_or(e, "rename"),
769        });
770    }
771    Ok(())
772}
773
774/// `fs.create`: a new empty file or folder. Creation itself is the
775/// existence check (`create_new` / `create_dir` fail if the name is taken),
776/// so nothing can be overwritten.
777pub fn create(req: &FsCreateReq) -> Result<FsCreateResult, String> {
778    let protect = ProtectedPaths::current();
779    validate_new_name(&req.name)?;
780    let parent = resolve_request_path(&req.parent)?.canonicalize().map_err(|e| match e.kind() {
781        io::ErrorKind::NotFound => "That folder doesn't exist anymore.".to_string(),
782        _ => format!("Couldn't open that folder: {e}"),
783    })?;
784    if !parent.is_dir() {
785        return Err("That isn't a folder.".to_string());
786    }
787    let target = parent.join(&req.name);
788    protect.check(&target)?;
789
790    let result = match req.kind {
791        FsCreateKind::File => std::fs::OpenOptions::new().write(true).create_new(true).open(&target).map(|_| ()),
792        FsCreateKind::Dir => std::fs::create_dir(&target),
793    }
794    .map_err(|e| match e.kind() {
795        io::ErrorKind::AlreadyExists => exists_message(&req.name),
796        io::ErrorKind::PermissionDenied => "You don't have permission to create something here.".to_string(),
797        _ => format!("Couldn't create it: {e}"),
798    });
799    tracing::info!(
800        op = "fs.create",
801        kind = ?req.kind,
802        path = %display_path(&target),
803        outcome = if result.is_ok() { "ok" } else { "error" },
804        error = result.as_ref().err().map(String::as_str).unwrap_or(""),
805        "fs mutation"
806    );
807    result.map(|()| FsCreateResult { path: display_path(&target) })
808}
809
810/// `fs.delete`, one path: PERMANENT. A link is unlinked, never followed.
811pub fn delete_permanently(raw: &str) -> Result<(), String> {
812    let protect = ProtectedPaths::current();
813    let target = resolve_entry_path(raw)?;
814    std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "delete"))?;
815    protect.check(&target)?;
816    let result = platform::remove_entry_no_follow(&target).map_err(|e| missing_or(e, "delete"));
817    tracing::info!(
818        op = "fs.delete",
819        path = %display_path(&target),
820        outcome = if result.is_ok() { "ok" } else { "error" },
821        error = result.as_ref().err().map(String::as_str).unwrap_or(""),
822        "fs mutation"
823    );
824    result
825}
826
827/// `fs.trash`, one path. Must run on the trash thread
828/// (`trash_worker::run`).
829pub fn trash(raw: &str) -> Result<(), String> {
830    let protect = ProtectedPaths::current();
831    let target = resolve_entry_path(raw)?;
832    std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "move"))?;
833    protect.check(&target)?;
834    let result = match platform::trash_unavailable_reason(&target) {
835        Some(reason) => Err(reason.to_string()),
836        None => trash_worker::trash_path(&target),
837    };
838    tracing::info!(
839        op = "fs.trash",
840        path = %display_path(&target),
841        outcome = if result.is_ok() { "ok" } else { "error" },
842        error = result.as_ref().err().map(String::as_str).unwrap_or(""),
843        "fs mutation"
844    );
845    result
846}
847
848/// `fs.restore`: put each path back from the Trash. The paths are the
849/// original locations. Must run on the trash thread (`trash_worker::run`).
850/// One result per path, in order.
851pub fn restore(raws: &[String]) -> Vec<Result<(), String>> {
852    let protect = ProtectedPaths::current();
853    // Validate every path first, then hand the valid ones to the trash
854    // crate in one go, so the Trash is listed once per request.
855    let checked: Vec<Result<PathBuf, String>> = raws
856        .iter()
857        .map(|raw| {
858            let target = resolve_entry_path(raw)?;
859            protect.check(&target)?;
860            Ok(target)
861        })
862        .collect();
863    let valid: Vec<PathBuf> = checked.iter().filter_map(|c| c.as_ref().ok().cloned()).collect();
864    let mut restored = trash_worker::restore_paths(&valid).into_iter();
865    checked
866        .into_iter()
867        .map(|c| {
868            let target = c?;
869            let result = restored.next().unwrap_or_else(|| Err("Couldn't put it back.".to_string()));
870            tracing::info!(
871                op = "fs.restore",
872                path = %display_path(&target),
873                outcome = if result.is_ok() { "ok" } else { "error" },
874                error = result.as_ref().err().map(String::as_str).unwrap_or(""),
875                "fs mutation"
876            );
877            result
878        })
879        .collect()
880}
881
882/// `fs.open` / `fs.reveal`: hand an existing path to the OS. Not limited to
883/// home (unlike `openinshell`): opening and revealing change nothing.
884pub fn open_or_reveal(raw: &str, reveal: bool) -> Result<(), String> {
885    let path = resolve_request_path(raw)?;
886    // A drive root has no parent to canonicalize; it is opened as it is.
887    let target = if path.parent().is_none() { path } else { resolve_entry_path(raw)? };
888    std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "open"))?;
889    // Both go through the strict external-process policy (I7): `spawn_detached`, and `platform::reveal`'s D-Bus
890    // step on Linux (SPEC_EDITOR_TAB_REVEAL_IN_FILE_MANAGER_2026_11_17.md §3.4).
891    let started = if reveal { platform::reveal(&target) } else { platform::spawn_detached(platform::open_command(&target)) };
892    let result = started.map_err(|e| format!("Couldn't open it: {e}"));
893    tracing::info!(
894        op = if reveal { "fs.reveal" } else { "fs.open" },
895        path = %display_path(&target),
896        outcome = if result.is_ok() { "ok" } else { "error" },
897        "fs action"
898    );
899    result
900}
901
902#[cfg(test)]
903mod tests;