Skip to main content

agentmux_srv_core/backend/
base.rs

1#![allow(dead_code)]
2// Copyright 2025, Command Line Inc.
3// Copyright 2025-2026, AgentMux Corp.
4// SPDX-License-Identifier: Apache-2.0
5
6//! AgentMux base utilities: directory management, lock files, environment, platform detection.
7//! Port of Go's pkg/base/.
8
9
10use std::env;
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::OnceLock;
14
15// ---- Environment variable names ----
16
17pub const MUX_CONFIG_HOME_ENV: &str = "AGENTMUX_CONFIG_HOME";
18pub const MUX_DATA_HOME_ENV: &str = "AGENTMUX_DATA_HOME";
19pub const MUX_APP_PATH_ENV: &str = "AGENTMUX_APP_PATH";
20pub const MUX_DEV_ENV: &str = "AGENTMUX_DEV";
21pub const MUX_DEV_VITE_ENV: &str = "AGENTMUX_DEV_VITE";
22pub const MUX_JWT_TOKEN_ENV: &str = "AGENTMUX_JWT";
23pub const MUX_SWAP_TOKEN_ENV: &str = "AGENTMUX_SWAPTOKEN";
24
25// ---- File/directory constants ----
26
27pub const MUX_LOCK_FILE: &str = "wave.lock";
28pub const DOMAIN_SOCKET_BASE_NAME: &str = "wave.sock";
29pub const REMOTE_DOMAIN_SOCKET_BASE_NAME: &str = "wave-remote.sock";
30pub const MUX_DB_DIR: &str = "db";
31pub const CONFIG_DIR: &str = "config";
32pub const REMOTE_MUX_HOME_DIR_NAME: &str = ".agentmux";
33pub const REMOTE_FULL_DOMAIN_SOCKET_PATH: &str = "~/.agentmux/wave-remote.sock";
34
35// ---- Version info (set at startup) ----
36
37static MUX_VERSION: OnceLock<String> = OnceLock::new();
38static BUILD_TIME: OnceLock<String> = OnceLock::new();
39
40/// Set the application version (called once at startup).
41pub fn set_version(version: &str) {
42    let _ = MUX_VERSION.set(version.to_string());
43}
44
45/// Set the build time (called once at startup).
46pub fn set_build_time(time: &str) {
47    let _ = BUILD_TIME.set(time.to_string());
48}
49
50/// Get the application version.
51pub fn get_version() -> &'static str {
52    MUX_VERSION.get().map_or("0.0.0", |v| v.as_str())
53}
54
55/// Get the build time.
56pub fn get_build_time() -> &'static str {
57    BUILD_TIME.get().map_or("0", |v| v.as_str())
58}
59
60// ---- Directory paths ----
61
62/// Get the user's home directory.
63pub fn get_home_dir() -> PathBuf {
64    dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"))
65}
66
67/// Get the AgentMux root directory (`~/.agentmux`).
68///
69/// Delegates to `agentmux_common::data_paths::agentmux_root`, which is the
70/// single resolver for this path. This function used to compute it itself,
71/// reading `AGENTMUX_DATA_HOME` where the common crate read
72/// `AGENTMUX_HOME_OVERRIDE` — two resolvers, two env vars, and two different
73/// answers if either was set. Both are now honoured by the one resolver, so
74/// an existing install finds its data exactly where it did before.
75/// A10 of docs/analysis/TRACKING_ARCHITECTURE_REFACTOR_A1_A15_2026_06_18.md.
76///
77/// The old local copy fell back to `PathBuf::from("/")` when `home_dir()`
78/// returned `None`, which meant a host with no resolvable home silently
79/// wrote to `/.agentmux`. That fallback is deliberately NOT preserved: the
80/// resolver returns `Err`, and rather than inventing a path this keeps the
81/// pre-existing shape of the API by falling back to the same `~/.agentmux`
82/// expression only when a home DOES exist. If it does not, writing to the
83/// filesystem root is never the right answer.
84pub fn get_mux_data_dir() -> PathBuf {
85    match agentmux_common::data_paths::agentmux_root() {
86        Ok(p) => p,
87        Err(e) => {
88            tracing::error!(
89                "cannot resolve the AgentMux root ({e}); falling back to a relative .agentmux rather than /"
90            );
91            PathBuf::from(".agentmux")
92        }
93    }
94}
95
96/// Migrate data from `~/.waveterm` to `~/.agentmux` if needed.
97/// Called once at startup. No-op if `~/.agentmux` already exists.
98pub fn migrate_legacy_data_dir() {
99    let new_dir = get_mux_data_dir();
100    if new_dir.exists() {
101        return; // already migrated or freshly created
102    }
103    let old_dir = get_home_dir().join(".waveterm");
104    if !old_dir.exists() {
105        return; // nothing to migrate
106    }
107    tracing::info!(
108        "Migrating data directory from {} to {}",
109        old_dir.display(),
110        new_dir.display()
111    );
112    if let Err(e) = copy_dir_all(&old_dir, &new_dir) {
113        tracing::warn!("Data migration failed (continuing with empty dir): {}", e);
114    } else {
115        tracing::info!("Migration complete");
116    }
117}
118
119/// Recursively copy a directory tree.
120fn copy_dir_all(src: &Path, dst: &Path) -> Result<(), String> {
121    fs::create_dir_all(dst)
122        .map_err(|e| format!("cannot create {}: {}", dst.display(), e))?;
123    for entry in fs::read_dir(src)
124        .map_err(|e| format!("cannot read {}: {}", src.display(), e))?
125    {
126        let entry = entry.map_err(|e| format!("read_dir entry error: {}", e))?;
127        let src_path = entry.path();
128        let dst_path = dst.join(entry.file_name());
129        if src_path.is_dir() {
130            copy_dir_all(&src_path, &dst_path)?;
131        } else {
132            fs::copy(&src_path, &dst_path)
133                .map_err(|e| format!("copy {} → {}: {}", src_path.display(), dst_path.display(), e))?;
134        }
135    }
136    Ok(())
137}
138
139/// Get the AgentMux config directory.
140/// Uses `AGENTMUX_CONFIG_HOME` env var, or defaults to `~/.agentmux/config`.
141pub fn get_mux_config_dir() -> PathBuf {
142    if let Some(dir) = env::var_os(MUX_CONFIG_HOME_ENV) {
143        if !dir.is_empty() {
144            return PathBuf::from(dir);
145        }
146    }
147    get_mux_data_dir().join(CONFIG_DIR)
148}
149
150/// Get the AgentMux DB directory (`~/.agentmux/db`).
151pub fn get_mux_db_dir() -> PathBuf {
152    get_mux_data_dir().join(MUX_DB_DIR)
153}
154
155/// Get the AgentMux app path from env.
156pub fn get_mux_app_path() -> Option<PathBuf> {
157    env::var(MUX_APP_PATH_ENV).ok().map(PathBuf::from)
158}
159
160/// Get the AgentMux app bin path.
161pub fn get_mux_app_bin_path() -> Option<PathBuf> {
162    get_mux_app_path().map(|p| p.join("bin"))
163}
164
165/// Get the domain socket path.
166pub fn get_domain_socket_name() -> PathBuf {
167    get_mux_data_dir().join(DOMAIN_SOCKET_BASE_NAME)
168}
169
170/// Get the AgentMux lock file path.
171pub fn get_mux_lock_file() -> PathBuf {
172    get_mux_data_dir().join(MUX_LOCK_FILE)
173}
174
175// ---- Directory creation ----
176
177/// Ensure a directory exists with the given permissions.
178pub fn ensure_dir(dir: &Path) -> Result<(), String> {
179    if dir.exists() {
180        return Ok(());
181    }
182    fs::create_dir_all(dir).map_err(|e| format!("cannot create directory {}: {}", dir.display(), e))
183}
184
185/// Ensure the AgentMux data directory exists.
186pub fn ensure_mux_data_dir() -> Result<(), String> {
187    ensure_dir(&get_mux_data_dir())
188}
189
190/// Ensure the AgentMux DB directory exists.
191pub fn ensure_mux_db_dir() -> Result<(), String> {
192    ensure_dir(&get_mux_db_dir())
193}
194
195/// Ensure the AgentMux config directory exists.
196pub fn ensure_mux_config_dir() -> Result<(), String> {
197    ensure_dir(&get_mux_config_dir())
198}
199
200/// Ensure the AgentMux presets directory exists.
201pub fn ensure_mux_presets_dir() -> Result<(), String> {
202    ensure_dir(&get_mux_config_dir().join("presets"))
203}
204
205// ---- Lock file ----
206
207/// Why [`MuxLock::acquire_at`] could not take the lock.
208#[derive(Debug, PartialEq, Eq)]
209pub enum MuxLockError {
210    /// Another process holds it.
211    Held,
212    /// The file could not be opened or locked for another reason (permissions, a full disk).
213    Failed(String),
214}
215
216/// File-based lock for single-instance enforcement. Exclusive for the life of the process:
217/// a non-blocking `flock` on Unix and a `LockFileEx` on Windows (both released when the handle
218/// closes, including when the holder crashes).
219pub struct MuxLock {
220    #[allow(dead_code)]
221    file: fs::File,
222}
223
224impl MuxLock {
225    /// Acquire an exclusive lock on the AgentMux lock file.
226    /// Returns error if another instance is already running.
227    pub fn acquire() -> Result<Self, MuxLockError> {
228        Self::acquire_at(&get_mux_lock_file())
229    }
230
231    /// Acquire an exclusive lock on `lock_path` (created if missing).
232    #[cfg(unix)]
233    pub fn acquire_at(lock_path: &Path) -> Result<Self, MuxLockError> {
234        use std::os::unix::io::AsRawFd;
235
236        ensure_dir(lock_path.parent().unwrap_or(Path::new("/"))).map_err(MuxLockError::Failed)?;
237
238        let file = fs::OpenOptions::new()
239            .create(true)
240            .write(true)
241            .truncate(false)
242            .open(lock_path)
243            .map_err(|e| MuxLockError::Failed(format!("cannot open lock file {}: {}", lock_path.display(), e)))?;
244
245        let fd = file.as_raw_fd();
246        let result = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
247        if result != 0 {
248            let err = std::io::Error::last_os_error();
249            return match err.kind() {
250                std::io::ErrorKind::WouldBlock => Err(MuxLockError::Held),
251                _ => Err(MuxLockError::Failed(format!("cannot lock {}: {err}", lock_path.display()))),
252            };
253        }
254
255        Ok(MuxLock { file })
256    }
257
258    /// Windows: an exclusive `LockFileEx` on a byte range far past the PID `srv.lock` holds, taken by the
259    /// handle for the process's life. This used to only check that the file could be opened, so two srvs
260    /// could share one data folder and both write its databases (task #49109); it is the same rule as the
261    /// Unix `flock`.
262    ///
263    /// The range starts past any PID a reader could care about because a Windows byte-range lock is
264    /// mandatory: locking the bytes that hold the PID would make `srv.lock` unreadable to every other
265    /// process that looks for a live srv there (`old_versions`, `slug_migration`), which used to read it
266    /// while a server ran.
267    #[cfg(not(unix))]
268    pub fn acquire_at(lock_path: &Path) -> Result<Self, MuxLockError> {
269        ensure_dir(lock_path.parent().unwrap_or(Path::new("/"))).map_err(MuxLockError::Failed)?;
270
271        let file = fs::OpenOptions::new()
272            .create(true)
273            .write(true)
274            .truncate(false)
275            .open(lock_path)
276            .map_err(|e| MuxLockError::Failed(format!("cannot open lock file {}: {}", lock_path.display(), e)))?;
277
278        match crate::registry::try_lock_exclusive_range(&file, LOCK_RANGE_OFFSET, 1) {
279            Ok(true) => Ok(MuxLock { file }),
280            Ok(false) => Err(MuxLockError::Held),
281            Err(e) => Err(MuxLockError::Failed(format!("cannot lock {}: {e}", lock_path.display()))),
282        }
283    }
284}
285
286/// The byte a Windows lock takes, far past the PID `srv.lock` records at its start (see
287/// [`MuxLock::acquire_at`]). Unix takes the whole file with `flock`, which does not block reads.
288#[cfg(not(unix))]
289const LOCK_RANGE_OFFSET: u64 = u32::MAX as u64;
290
291/// File srv locks in the directory holding its databases.
292pub const SRV_DATA_LOCK_FILE: &str = "srv.lock";
293
294/// Data-dir locks this process holds, kept for its lifetime.
295static DATA_DIR_LOCKS: std::sync::Mutex<Vec<(PathBuf, MuxLock)>> = std::sync::Mutex::new(Vec::new());
296
297/// Why srv could not take its data-dir lock.
298#[derive(Debug, PartialEq, Eq)]
299pub enum DataDirLockError {
300    /// Another AgentMux server holds this folder's lock: one srv per set of databases.
301    Held { dir: PathBuf, lock: PathBuf },
302    /// The lock file could not be opened or locked (permissions, a full disk).
303    Failed { dir: PathBuf, why: String },
304}
305
306impl std::fmt::Display for DataDirLockError {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        match self {
309            Self::Held { dir, lock } => write!(f, "another agentmux-srv is already using {} (lock {})", dir.display(), lock.display()),
310            Self::Failed { dir, why } => write!(f, "cannot take the data-dir lock of {}: {why}", dir.display()),
311        }
312    }
313}
314
315/// Take srv's exclusive lock on `data_dir` (`<data_dir>/srv.lock`): one srv per
316/// set of databases, however each was started — launcher, host or `--headless`
317/// (SPEC_SRV_HEADLESS_MODE §3.2; Codex P1 on #3893). Idempotent within a
318/// process, so headless setup can take it early and bootstrap again later.
319/// Advisory `flock` on Unix, `LockFileEx` on Windows (see `MuxLock`).
320pub fn acquire_data_dir_lock(data_dir: &Path) -> Result<(), DataDirLockError> {
321    let mut held = DATA_DIR_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
322    if held.iter().any(|(p, _)| p == data_dir) {
323        return Ok(());
324    }
325    let lock_path = data_dir.join(SRV_DATA_LOCK_FILE);
326    let mut lock = MuxLock::acquire_at(&lock_path).map_err(|e| match e {
327        MuxLockError::Held => DataDirLockError::Held { dir: data_dir.to_path_buf(), lock: lock_path.clone() },
328        MuxLockError::Failed(why) => DataDirLockError::Failed { dir: data_dir.to_path_buf(), why },
329    })?;
330    // Record who holds it, so a launcher that finds the lock held by an srv
331    // its own launcher left behind can stop that srv instead of failing to
332    // start (crates/launcher/src/stale_srv.rs). Best effort: the lock itself
333    // is the lock, not the contents.
334    {
335        use std::io::{Seek, Write};
336        let _ = lock.file.set_len(0);
337        let _ = lock.file.seek(std::io::SeekFrom::Start(0));
338        let _ = write!(lock.file, "{}", std::process::id());
339    }
340    held.push((data_dir.to_path_buf(), lock));
341    Ok(())
342}
343
344// ---- Environment helpers ----
345
346/// Check if AgentMux is in dev mode.
347pub fn is_dev_mode() -> bool {
348    env::var(MUX_DEV_ENV)
349        .map(|v| !v.is_empty())
350        .unwrap_or(false)
351}
352
353/// A `~/.agentmux[/…]` path re-rooted under `AGENTMUX_HOME_OVERRIDE`, when
354/// that is set; `None` for any other path or when it is not set.
355///
356/// An isolated srv (a test or dev instance started with the override) keeps
357/// its data under that root, but its `$HOME` is still the real one, so a
358/// stored `~/.agentmux/agents/<slug>` workspace expanded against `$HOME` and
359/// was created under the real `~/.agentmux/agents/`. Every `~` expander that
360/// can see such a path goes through this first.
361pub fn expand_under_home_override(path: &str) -> Option<PathBuf> {
362    let root = PathBuf::from(env::var_os("AGENTMUX_HOME_OVERRIDE").filter(|v| !v.is_empty())?);
363    let rest = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\"))?;
364    let below = if rest == ".agentmux" {
365        ""
366    } else {
367        rest.strip_prefix(".agentmux/").or_else(|| rest.strip_prefix(".agentmux\\"))?
368    };
369    Some(root.join(below.trim_start_matches(['/', '\\'])))
370}
371
372/// Expand `~` at the start of a path to the home directory.
373/// Rejects `~user/` and paths containing `..` components (path traversal).
374pub fn expand_home_dir(path: &str) -> Result<PathBuf, String> {
375    // Reject paths with .. components regardless of ~ prefix
376    if path.split(['/', '\\']).any(|c| c == "..") {
377        return Err(format!("cannot expand path: '..' traversal in {}", path));
378    }
379    if let Some(under_override) = expand_under_home_override(path) {
380        return Ok(under_override);
381    }
382
383    if let Some(rest) = path.strip_prefix('~') {
384        let home = get_home_dir();
385        if rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\') {
386            Ok(home.join(rest.trim_start_matches(['/', '\\'])))
387        } else {
388            Err(format!("cannot expand ~: invalid ~user in {}", path))
389        }
390    } else {
391        Ok(PathBuf::from(path))
392    }
393}
394
395/// Safe version of expand_home_dir that returns the original on error.
396pub fn expand_home_dir_safe(path: &str) -> PathBuf {
397    expand_home_dir(path).unwrap_or_else(|_| PathBuf::from(path))
398}
399
400/// Convert an MSYS / Git-Bash POSIX drive path to a native Windows path.
401///
402/// Agents on Windows typically run inside a bash shell (MSYS2 / Git Bash),
403/// so they naturally emit paths like `/c/Users/user/project` or the WSL
404/// form `/mnt/c/Users/user/project`. Passing one of those straight to
405/// `std::process::Command::current_dir` makes `CreateProcess` fail with
406/// `os error 267` (ERROR_DIRECTORY, "The directory name is invalid").
407///
408/// Recognised forms (case-insensitive drive letter):
409/// - `/c`            → `C:\`
410/// - `/c/Users/x`    → `C:\Users\x`
411/// - `/mnt/c/Users/x`→ `C:\Users\x`
412///
413/// Anything that isn't a POSIX drive path is returned unchanged. This is a
414/// no-op on non-Windows targets (the input is already a valid POSIX path).
415pub fn msys_to_windows_path(path: &str) -> String {
416    #[cfg(windows)]
417    {
418        // Strip an optional WSL `/mnt` prefix so both `/c/...` and
419        // `/mnt/c/...` reduce to the same `/<drive>/<rest>` shape.
420        let stripped = path.strip_prefix("/mnt").unwrap_or(path);
421        let bytes = stripped.as_bytes();
422        let is_drive_path = bytes.len() >= 2
423            && bytes[0] == b'/'
424            && (bytes[1] as char).is_ascii_alphabetic()
425            && (bytes.len() == 2 || bytes[2] == b'/');
426        if is_drive_path {
427            let drive = (bytes[1] as char).to_ascii_uppercase();
428            let rest = stripped[2..].replace('/', "\\"); // "" or "\Users\x"
429            return format!("{drive}:{}", if rest.is_empty() { "\\" } else { &rest });
430        }
431    }
432    let _ = path; // silence unused on non-windows
433    path.to_string()
434}
435
436/// Normalize a user/agent-supplied working directory for use with
437/// `Command::current_dir`: first convert MSYS/Git-Bash POSIX drive paths to
438/// native Windows form (see [`msys_to_windows_path`]), then expand a leading
439/// `~`. Returns `None` for an empty/whitespace input.
440pub fn normalize_working_dir(raw: &str) -> Option<String> {
441    let raw = raw.trim();
442    if raw.is_empty() {
443        return None;
444    }
445    let win = msys_to_windows_path(raw);
446    Some(expand_home_dir_safe(&win).to_string_lossy().into_owned())
447}
448
449/// After a lexical join, verify that no symlinked ancestor of the
450/// candidate path escapes `base_canonical`. The lexical helper alone
451/// can't catch this: if `<base>/.claude` is a symlink to `/tmp/outside`
452/// and the caller writes `<base>/.claude/commands/startup.md`, the
453/// final write follows the symlink and lands outside the working dir.
454///
455/// Walks from `final_path` upward and canonicalizes the deepest
456/// existing ancestor — that resolution dereferences any symlink in
457/// the chain. If the resolved path stays under `base_canonical`, no
458/// symlink in the existing portion escapes. Non-existent components
459/// are safe by definition (nothing to resolve, nothing to follow).
460///
461/// Returns Ok(()) if safe, Err with a human-readable message otherwise.
462///
463/// Caller invariant: the directory rooted at `base_canonical` must
464/// exist (so the upward walk is guaranteed to find it before reaching
465/// the filesystem root). `writeagentconfig` satisfies this — the
466/// working dir is created via `allocate_agent_workdir` or `mkdir_p`
467/// immediately before this is called.
468pub fn verify_no_symlink_escape(
469    final_path: &Path,
470    base_canonical: &Path,
471) -> Result<(), String> {
472    let mut p = final_path;
473    loop {
474        match p.canonicalize() {
475            Ok(canonical) => {
476                if !canonical.starts_with(base_canonical) {
477                    return Err(format!(
478                        "symlinked ancestor escapes working dir: {} → {}",
479                        p.display(),
480                        canonical.display()
481                    ));
482                }
483                return Ok(());
484            }
485            Err(_) => match p.parent() {
486                Some(parent) if !parent.as_os_str().is_empty() => p = parent,
487                _ => {
488                    // Walked past every existing ancestor without finding
489                    // one inside `base_canonical`. This violates the
490                    // caller invariant (base should exist) — fail closed.
491                    return Err(format!(
492                        "no existing ancestor found under base: {}",
493                        final_path.display()
494                    ));
495                }
496            },
497        }
498    }
499}
500
501/// True if `s` starts with `<ASCII letter>:` — a Windows drive-letter
502/// prefix. Both rooted (`C:\foo`) and drive-relative (`C:foo`) forms
503/// match. Used by `safe_join_within_base` to reject paths that would
504/// rebase off the working directory under Windows path semantics.
505fn has_drive_letter_prefix(s: &str) -> bool {
506    let mut chars = s.chars();
507    matches!(
508        (chars.next(), chars.next()),
509        (Some(c), Some(':')) if c.is_ascii_alphabetic()
510    )
511}
512
513/// Lexically join `relative` onto `base` while guaranteeing the result
514/// stays inside `base`. No filesystem access — does not require either
515/// path to exist, which matters on Windows where `Path::canonicalize`
516/// adds the `\\?\` UNC prefix and breaks naive `starts_with` checks
517/// against not-yet-created files.
518///
519/// The relative path:
520/// - must be non-empty
521/// - must NOT be absolute (rooted, drive-prefixed, or starting with `/`/`\`)
522/// - must NOT contain a `..` component
523/// - may contain `.` components (silently dropped)
524/// - is treated as forward- or back-slash separated; both are accepted
525///
526/// Returns `base.join(<cleaned>)` on success.
527pub fn safe_join_within_base(base: &Path, relative: &str) -> Result<PathBuf, String> {
528    if relative.is_empty() {
529        return Err("safe_join_within_base: empty relative path".into());
530    }
531    let rel_path = Path::new(relative);
532    if rel_path.is_absolute() {
533        return Err(format!("safe_join_within_base: absolute path not allowed: {relative}"));
534    }
535    // On Windows `Path::is_absolute` covers drive-letter and UNC roots,
536    // but a leading `/` or `\` (without drive) is technically "rooted but
537    // not absolute". Reject those too — they'd resolve onto the current
538    // drive's root, escaping `base`.
539    if matches!(relative.chars().next(), Some('/') | Some('\\')) {
540        return Err(format!("safe_join_within_base: rooted path not allowed: {relative}"));
541    }
542    // Windows drive-letter prefix (e.g. `C:foo`, `D:\bar`). `is_absolute()`
543    // requires both prefix AND root, so a drive-relative path like
544    // `C:payload.txt` slips through unless we reject it explicitly.
545    // `Path::join` would otherwise replace the base with the drive's CWD
546    // on Windows, escaping the working directory.
547    if has_drive_letter_prefix(relative) {
548        return Err(format!(
549            "safe_join_within_base: drive-letter prefix not allowed: {relative}"
550        ));
551    }
552    let mut cleaned = PathBuf::new();
553    for segment in relative.split(['/', '\\']) {
554        match segment {
555            "" | "." => continue,
556            ".." => {
557                return Err(format!(
558                    "safe_join_within_base: '..' traversal not allowed: {relative}"
559                ));
560            }
561            // A drive-letter prefix on any segment (not just the first
562            // one) is rejected — `PathBuf::push("C:foo")` on Windows
563            // discards the accumulated path and rebases on the C drive's
564            // CWD, so a nested input like `safe/C:payload.txt` would
565            // escape `base` despite the upfront whole-string guard.
566            other if has_drive_letter_prefix(other) => {
567                return Err(format!(
568                    "safe_join_within_base: drive-letter prefix in segment {other:?}: {relative}"
569                ));
570            }
571            other => cleaned.push(other),
572        }
573    }
574    if cleaned.as_os_str().is_empty() {
575        return Err(format!(
576            "safe_join_within_base: relative path resolves to empty: {relative}"
577        ));
578    }
579    Ok(base.join(cleaned))
580}
581
582/// Replace the home directory prefix with `~`.
583pub fn replace_home_dir(path: &str) -> String {
584    let home = get_home_dir();
585    let home_str = home.to_string_lossy();
586    if path.starts_with(home_str.as_ref()) {
587        format!("~{}", &path[home_str.len()..])
588    } else {
589        path.to_string()
590    }
591}
592
593// ---- Platform detection ----
594
595/// Get the client architecture string ("os/arch").
596pub fn client_arch() -> String {
597    format!("{}/{}", std::env::consts::OS, std::env::consts::ARCH)
598}
599
600/// Get a system summary string.
601pub fn get_system_summary() -> String {
602    format!(
603        "{} {} ({})",
604        std::env::consts::OS,
605        std::env::consts::ARCH,
606        whoami::distro()
607    )
608}
609
610/// Determine the system language.
611pub fn determine_lang() -> String {
612    env::var("LANG")
613        .or_else(|_| env::var("LC_ALL"))
614        .or_else(|_| env::var("LANGUAGE"))
615        .unwrap_or_else(|_| "en_US".to_string())
616}
617
618// ---- Tests ----
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623
624    #[test]
625    fn test_env_var_constants() {
626        assert_eq!(MUX_CONFIG_HOME_ENV, "AGENTMUX_CONFIG_HOME");
627        assert_eq!(MUX_DATA_HOME_ENV, "AGENTMUX_DATA_HOME");
628        assert_eq!(MUX_DEV_ENV, "AGENTMUX_DEV");
629    }
630
631    #[test]
632    fn test_file_constants() {
633        assert_eq!(MUX_LOCK_FILE, "wave.lock");
634        assert_eq!(DOMAIN_SOCKET_BASE_NAME, "wave.sock");
635        assert_eq!(MUX_DB_DIR, "db");
636        assert_eq!(CONFIG_DIR, "config");
637    }
638
639    #[test]
640    fn test_version_management() {
641        // Version defaults to "0.0.0" before being set
642        // Can't test set_version since OnceLock can only be set once per process
643        assert!(!get_version().is_empty());
644    }
645
646    #[test]
647    fn test_mux_data_dir_default() {
648        // `agentmux_root()` returns AGENTMUX_HOME_OVERRIDE verbatim, and other
649        // test modules (m0020/m0021 backfills, agent_resolve, registry paths)
650        // set it to a tempdir whose path contains neither ".agentmux" nor
651        // "AGENTMUX". Without this lock the assertion below depends on whether
652        // one of them happens to be mid-test — latent since those tests were
653        // written, and reliably hit once another env-setting module was added.
654        // Same crate-wide guard they take; a local mutex would not help.
655        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK
656            .lock()
657            .unwrap_or_else(|e| e.into_inner());
658        // When env var is not set, should be ~/.agentmux
659        let dir = get_mux_data_dir();
660        assert!(dir.to_string_lossy().contains(".agentmux") || dir.to_string_lossy().contains("AGENTMUX"));
661    }
662
663    /// An isolated srv's `~/.agentmux/...` paths (agent workspaces) follow
664    /// `AGENTMUX_HOME_OVERRIDE`, not the real `$HOME`; anything else under `~`
665    /// still expands to the real home.
666    #[test]
667    fn tilde_agentmux_paths_follow_the_home_override() {
668        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK
669            .lock()
670            .unwrap_or_else(|e| e.into_inner());
671        let fake = tempfile::tempdir().unwrap();
672        let prior = env::var_os("AGENTMUX_HOME_OVERRIDE");
673        let real_home = get_home_dir();
674
675        env::set_var("AGENTMUX_HOME_OVERRIDE", fake.path());
676        let workspace = expand_home_dir_safe("~/.agentmux/agents/aria");
677        let via_core = PathBuf::from(crate::backend::blockcontroller::core::expand_home_dir("~/.agentmux/agents/aria"));
678        let root = expand_home_dir_safe("~/.agentmux");
679        let elsewhere = expand_home_dir_safe("~/projects/x");
680        let lookalike = expand_home_dir_safe("~/.agentmux-other/x");
681
682        env::remove_var("AGENTMUX_HOME_OVERRIDE");
683        let real = expand_home_dir_safe("~/.agentmux/agents/aria");
684        if let Some(p) = prior {
685            env::set_var("AGENTMUX_HOME_OVERRIDE", p);
686        }
687
688        assert_eq!(workspace, fake.path().join("agents").join("aria"));
689        assert_eq!(via_core, workspace);
690        assert_eq!(root, fake.path());
691        assert!(!workspace.starts_with(real_home.join(".agentmux")), "must not land under the real home");
692        assert_eq!(elsewhere, real_home.join("projects/x"));
693        assert_eq!(lookalike, real_home.join(".agentmux-other/x"));
694        assert_eq!(real, real_home.join(".agentmux/agents/aria"), "unchanged without the override");
695    }
696
697    #[test]
698    fn test_mux_db_dir() {
699        let db_dir = get_mux_db_dir();
700        assert!(db_dir.to_string_lossy().ends_with("db"));
701    }
702
703    #[test]
704    fn test_mux_config_dir() {
705        let config_dir = get_mux_config_dir();
706        assert!(config_dir.to_string_lossy().contains("config") || config_dir.to_string_lossy().contains("AGENTMUX"));
707    }
708
709    #[test]
710    fn test_domain_socket_name() {
711        let sock = get_domain_socket_name();
712        assert!(sock.to_string_lossy().ends_with("wave.sock"));
713    }
714
715    #[test]
716    fn test_lock_file_path() {
717        let lock = get_mux_lock_file();
718        assert!(lock.to_string_lossy().ends_with("wave.lock"));
719    }
720
721    /// The data-dir lock, on every platform: held by this process (re-entrant), refusing another handle,
722    /// and — on Windows, where a byte-range lock is mandatory — leaving the recorded PID readable to
723    /// another process, which `old_versions::recorded_srv_pid` and `slug_migration` rely on (task #49109).
724    #[test]
725    fn the_data_dir_lock_refuses_a_second_holder_and_keeps_the_pid_readable() {
726        let dir = tempfile::tempdir().unwrap();
727        acquire_data_dir_lock(dir.path()).expect("the first holder takes it");
728        let lock = dir.path().join(SRV_DATA_LOCK_FILE);
729        let pid = std::fs::read_to_string(&lock).expect("the PID is readable while the lock is held");
730        assert_eq!(pid.trim().parse::<u32>().ok(), Some(std::process::id()));
731        assert_eq!(MuxLock::acquire_at(&lock).err(), Some(MuxLockError::Held), "another handle is refused");
732    }
733
734    #[test]
735    fn test_expand_home_dir_tilde() {
736        let path = expand_home_dir("~/docs").unwrap();
737        assert!(path.to_string_lossy().contains("docs"));
738        assert!(!path.to_string_lossy().starts_with('~'));
739    }
740
741    #[test]
742    fn test_expand_home_dir_tilde_only() {
743        let path = expand_home_dir("~").unwrap();
744        assert!(!path.to_string_lossy().starts_with('~'));
745    }
746
747    #[test]
748    fn test_expand_home_dir_no_tilde() {
749        let path = expand_home_dir("/etc/hosts").unwrap();
750        assert_eq!(path, PathBuf::from("/etc/hosts"));
751    }
752
753    #[test]
754    fn test_expand_home_dir_traversal() {
755        // ~user should fail (path traversal)
756        let result = expand_home_dir("~otheruser/docs");
757        assert!(result.is_err());
758    }
759
760    #[test]
761    fn test_expand_home_dir_dotdot_traversal() {
762        // .. components should fail
763        assert!(expand_home_dir("~/../../etc/passwd").is_err());
764        assert!(expand_home_dir("../../../root").is_err());
765        assert!(expand_home_dir("/tmp/../etc/shadow").is_err());
766        // But normal dots are fine
767        assert!(expand_home_dir("~/.config").is_ok());
768        assert!(expand_home_dir("/tmp/.hidden").is_ok());
769    }
770
771    #[test]
772    fn test_safe_join_within_base_simple() {
773        let base = PathBuf::from("/home/user/agent");
774        let p = safe_join_within_base(&base, "CLAUDE.md").unwrap();
775        assert_eq!(p, PathBuf::from("/home/user/agent/CLAUDE.md"));
776    }
777
778    #[test]
779    fn test_safe_join_within_base_nested() {
780        let base = PathBuf::from("/home/user/agent");
781        let p = safe_join_within_base(&base, ".claude/commands/startup.md").unwrap();
782        assert_eq!(p, PathBuf::from("/home/user/agent/.claude/commands/startup.md"));
783    }
784
785    #[test]
786    fn test_safe_join_within_base_backslash_separator() {
787        // Frontends running on Windows may send `\\` separators; accept them.
788        let base = PathBuf::from("C:\\agent");
789        let p = safe_join_within_base(&base, ".claude\\commands\\startup.md").unwrap();
790        // The cleaned components are joined as native segments — final path
791        // should contain all three trailing pieces in order.
792        let s = p.to_string_lossy();
793        assert!(s.contains(".claude"));
794        assert!(s.contains("commands"));
795        assert!(s.contains("startup.md"));
796    }
797
798    #[test]
799    fn test_safe_join_within_base_dot_segments_skipped() {
800        let base = PathBuf::from("/base");
801        let p = safe_join_within_base(&base, "./a/./b").unwrap();
802        assert_eq!(p, PathBuf::from("/base/a/b"));
803    }
804
805    #[test]
806    fn test_safe_join_within_base_rejects_dotdot() {
807        let base = PathBuf::from("/base");
808        assert!(safe_join_within_base(&base, "..").is_err());
809        assert!(safe_join_within_base(&base, "../etc").is_err());
810        assert!(safe_join_within_base(&base, "a/../b").is_err());
811        assert!(safe_join_within_base(&base, "a/b/..").is_err());
812    }
813
814    #[test]
815    fn test_safe_join_within_base_rejects_absolute() {
816        let base = PathBuf::from("/base");
817        assert!(safe_join_within_base(&base, "/etc/passwd").is_err());
818        assert!(safe_join_within_base(&base, "\\Windows\\System32").is_err());
819        // Bare leading slash on a relative-looking path is also rooted.
820        assert!(safe_join_within_base(&base, "/foo").is_err());
821        #[cfg(windows)]
822        assert!(safe_join_within_base(&base, "C:\\Windows").is_err());
823    }
824
825    #[test]
826    fn test_safe_join_within_base_rejects_drive_letter_prefix() {
827        // Drive-relative (no root) — Path::is_absolute() returns false on
828        // Windows, but Path::join would still replace base with the
829        // drive's CWD. Must be rejected on every platform so the helper
830        // behaves consistently regardless of where the validation runs.
831        let base = PathBuf::from("/base");
832        assert!(safe_join_within_base(&base, "C:foo").is_err());
833        assert!(safe_join_within_base(&base, "D:payload.txt").is_err());
834        assert!(safe_join_within_base(&base, "z:relative\\file").is_err());
835        // Rooted drive paths also rejected (already covered by is_absolute
836        // on Windows; on Unix the drive-letter check catches them).
837        assert!(safe_join_within_base(&base, "C:\\Windows\\System32").is_err());
838    }
839
840    #[test]
841    fn test_safe_join_within_base_rejects_drive_letter_in_inner_segment() {
842        // The whole-string drive-letter guard misses nested cases like
843        // `safe/C:payload.txt` because the prefix isn't at position 0.
844        // `PathBuf::push` on Windows would still rebase on a drive when
845        // it sees `C:payload.txt`, so the per-segment guard inside the
846        // loop must also reject these.
847        let base = PathBuf::from("/base");
848        assert!(safe_join_within_base(&base, "safe/C:payload.txt").is_err());
849        assert!(safe_join_within_base(&base, "a/b/D:malicious").is_err());
850        assert!(safe_join_within_base(&base, "subdir\\E:nested").is_err());
851        // First segment is also covered by the inner check (defense in
852        // depth — both upfront + per-segment guards reject it).
853        assert!(safe_join_within_base(&base, "C:foo/bar").is_err());
854    }
855
856    #[test]
857    fn test_verify_no_symlink_escape_existing_inside_base() {
858        // If the existing ancestor is the base itself, canonicalize
859        // succeeds and starts_with passes. Use the OS temp dir as a
860        // base that's guaranteed to exist on every CI/dev box.
861        let base = std::env::temp_dir();
862        let canonical_base = base.canonicalize().unwrap();
863        let target = base.join("nonexistent-subdir").join("file.md");
864        assert!(verify_no_symlink_escape(&target, &canonical_base).is_ok());
865    }
866
867    #[test]
868    #[cfg(unix)]
869    fn test_verify_no_symlink_escape_rejects_symlinked_ancestor() {
870        // Build a temp base, create a symlink under it pointing OUTSIDE
871        // the base, and verify the helper rejects writes through it.
872        // Unix-only because std::os::unix::fs::symlink is the simplest
873        // way to set this up; the cross-platform behavior is identical.
874        use std::os::unix::fs::symlink;
875        let tmp = std::env::temp_dir();
876        let base = tmp.join("agentmux-symlink-test-base");
877        let outside = tmp.join("agentmux-symlink-test-outside");
878        let _ = std::fs::remove_dir_all(&base);
879        let _ = std::fs::remove_dir_all(&outside);
880        std::fs::create_dir_all(&base).unwrap();
881        std::fs::create_dir_all(&outside).unwrap();
882        let canonical_base = base.canonicalize().unwrap();
883        symlink(&outside, base.join(".claude")).unwrap();
884        let target = base.join(".claude").join("commands").join("startup.md");
885        assert!(verify_no_symlink_escape(&target, &canonical_base).is_err());
886        // Cleanup
887        let _ = std::fs::remove_dir_all(&base);
888        let _ = std::fs::remove_dir_all(&outside);
889    }
890
891    #[test]
892    fn test_has_drive_letter_prefix() {
893        assert!(has_drive_letter_prefix("C:foo"));
894        assert!(has_drive_letter_prefix("c:bar"));
895        assert!(has_drive_letter_prefix("Z:\\baz"));
896        assert!(!has_drive_letter_prefix(":foo"));
897        assert!(!has_drive_letter_prefix("foo"));
898        assert!(!has_drive_letter_prefix("12:not-a-drive"));
899        assert!(!has_drive_letter_prefix(""));
900        // Multibyte first char: the check requires ASCII letter, so
901        // non-ASCII letters do NOT match (they wouldn't be valid drive
902        // letters on Windows anyway).
903        assert!(!has_drive_letter_prefix("Ω:foo"));
904    }
905
906    #[test]
907    #[cfg(windows)]
908    fn test_msys_to_windows_path() {
909        assert_eq!(msys_to_windows_path("/c/Users/user/p"), "C:\\Users\\user\\p");
910        assert_eq!(msys_to_windows_path("/mnt/c/Users/user/p"), "C:\\Users\\user\\p");
911        assert_eq!(msys_to_windows_path("/d/work"), "D:\\work");
912        assert_eq!(msys_to_windows_path("/c"), "C:\\");
913        // Already-native paths pass through untouched.
914        assert_eq!(msys_to_windows_path("C:\\Users\\user"), "C:\\Users\\user");
915        // Not a drive path: leading `/usr` is not `/<letter>/`.
916        assert_eq!(msys_to_windows_path("/usr/bin"), "/usr/bin");
917        // `/ab/...` — second segment is multi-char, not a drive.
918        assert_eq!(msys_to_windows_path("/ab/c"), "/ab/c");
919    }
920
921    #[test]
922    fn test_normalize_working_dir_empty() {
923        assert_eq!(normalize_working_dir(""), None);
924        assert_eq!(normalize_working_dir("   "), None);
925    }
926
927    #[test]
928    fn test_safe_join_within_base_rejects_empty() {
929        let base = PathBuf::from("/base");
930        assert!(safe_join_within_base(&base, "").is_err());
931        // After stripping `.` segments, an effectively-empty path also fails.
932        assert!(safe_join_within_base(&base, "./.").is_err());
933    }
934
935    #[test]
936    fn test_expand_home_dir_safe() {
937        let path = expand_home_dir_safe("~/test");
938        assert!(!path.to_string_lossy().starts_with('~'));
939
940        // On error, returns original
941        let path = expand_home_dir_safe("~otheruser/test");
942        assert_eq!(path, PathBuf::from("~otheruser/test"));
943    }
944
945    #[test]
946    fn test_replace_home_dir() {
947        let home = get_home_dir();
948        let path = format!("{}/documents/file.txt", home.display());
949        let replaced = replace_home_dir(&path);
950        assert!(replaced.starts_with('~'));
951        assert!(replaced.contains("documents/file.txt"));
952    }
953
954    #[test]
955    fn test_replace_home_dir_no_match() {
956        let result = replace_home_dir("/etc/hosts");
957        assert_eq!(result, "/etc/hosts");
958    }
959
960    #[test]
961    fn test_client_arch() {
962        let arch = client_arch();
963        assert!(arch.contains('/'));
964    }
965
966    #[test]
967    fn test_system_summary() {
968        let summary = get_system_summary();
969        assert!(!summary.is_empty());
970    }
971
972    #[test]
973    fn test_determine_lang() {
974        let lang = determine_lang();
975        assert!(!lang.is_empty());
976    }
977
978    #[test]
979    fn test_is_dev_mode() {
980        // Default should be false in test environment (unless set)
981        let _ = is_dev_mode(); // Just verify it doesn't panic
982    }
983
984    #[test]
985    fn test_ensure_dir_existing() {
986        // /tmp should already exist
987        assert!(ensure_dir(Path::new("/tmp")).is_ok());
988    }
989}