Skip to main content

agentmux_common/
dev_home_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A dev build started by hand must not run on the real AgentMux home.
5//!
6//! `task dev` gives each dev build a data home of its own (`scripts/dev-home.mjs`) and says so in
7//! `AGENTMUX_DEV_HOME_MODE` (`isolated` or `real`) and `AGENTMUX_HOME_OVERRIDE`. A launcher or host
8//! started by hand from a dev output folder (`dist/cef-dev*`, `target/debug`, `target/release`)
9//! has neither, resolves `~/.agentmux`, creates its `dev/<branch>/<clone>` folders there and
10//! starts a srv on the person's own home. This refuses that start with one plain line.
11//!
12//! The way in on purpose is `AGENTMUX_DEV_USE_REAL_HOME=1`, the same switch `task dev` honours.
13
14use std::path::Path;
15
16const MODE: &str = "AGENTMUX_DEV_HOME_MODE";
17const OVERRIDE: &str = "AGENTMUX_HOME_OVERRIDE";
18const USE_REAL_HOME: &str = "AGENTMUX_DEV_USE_REAL_HOME";
19
20/// What the guard reads from the environment, as set values only (an empty value is unset).
21#[derive(Debug, Default, Clone, PartialEq, Eq)]
22pub struct DevHomeEnv {
23    pub mode: Option<String>,
24    pub home_override: Option<String>,
25    pub use_real_home: bool,
26}
27
28impl DevHomeEnv {
29    pub fn from_process() -> Self {
30        let get = |name| {
31            std::env::var(name)
32                .ok()
33                .map(|v| v.trim().to_string())
34                .filter(|v| !v.is_empty())
35        };
36        Self {
37            mode: get(MODE),
38            home_override: get(OVERRIDE),
39            use_real_home: get(USE_REAL_HOME).as_deref() == Some("1"),
40        }
41    }
42}
43
44/// Why a dev build must not start, or `None`. `real_home` is the person's own `~/.agentmux`.
45pub fn refusal(env: &DevHomeEnv, real_home: Option<&Path>) -> Option<String> {
46    if env.use_real_home || matches!(env.mode.as_deref(), Some("isolated" | "real")) {
47        return None;
48    }
49    let Some(given) = env.home_override.as_deref() else {
50        return Some(format!(
51            "this dev build has no isolated data home, so it would run on your real AgentMux home. \
52             Start it with `task dev`, or set {OVERRIDE}=<empty folder>; to use the real home on purpose set {USE_REAL_HOME}=1."
53        ));
54    };
55    let is_real = real_home.is_some_and(|real| same_folder(Path::new(given), real));
56    is_real.then(|| {
57        format!(
58            "{OVERRIDE} names your real AgentMux home; to use it on purpose set {USE_REAL_HOME}=1."
59        )
60    })
61}
62
63fn same_folder(a: &Path, b: &Path) -> bool {
64    let norm = |p: &Path| {
65        p.to_string_lossy()
66            .replace('\\', "/")
67            .trim_end_matches('/')
68            .to_lowercase()
69    };
70    norm(a) == norm(b)
71}
72
73/// [`refusal`] for this process when it runs from a dev build folder. `exe_dir` is the binary's folder.
74pub fn refusal_for_process(exe_dir: &Path) -> Option<String> {
75    if !crate::is_dev_build_exe(exe_dir) {
76        return None;
77    }
78    refusal(
79        &DevHomeEnv::from_process(),
80        dirs::home_dir().map(|h| h.join(".agentmux")).as_deref(),
81    )
82}
83
84/// Exits with code 2 and one line on stderr when [`refusal_for_process`] applies. Call first, before
85/// anything creates a folder, opens a store or starts a child.
86pub fn refuse_or_continue(exe_dir: &Path) {
87    if let Some(why) = refusal_for_process(exe_dir) {
88        eprintln!("agentmux: {why}");
89        std::process::exit(2);
90    }
91}
92
93/// [`refuse_or_continue`] for the folder this binary runs from.
94pub fn refuse_or_continue_current_exe() {
95    if let Some(dir) = std::env::current_exe()
96        .ok()
97        .and_then(|p| p.parent().map(Path::to_path_buf))
98    {
99        refuse_or_continue(&dir);
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    fn real() -> &'static Path {
108        Path::new("C:/Users/me/.agentmux")
109    }
110
111    fn env(mode: Option<&str>, home_override: Option<&str>, use_real_home: bool) -> DevHomeEnv {
112        DevHomeEnv {
113            mode: mode.map(Into::into),
114            home_override: home_override.map(Into::into),
115            use_real_home,
116        }
117    }
118
119    #[test]
120    fn a_start_with_nothing_said_about_the_home_is_refused_with_what_to_run() {
121        let why = refusal(&env(None, None, false), Some(real())).expect("refuses");
122        assert!(
123            why.contains("task dev") && why.contains(OVERRIDE) && why.contains(USE_REAL_HOME),
124            "{why}"
125        );
126        assert!(!why.contains('\n'), "one line");
127    }
128
129    #[test]
130    fn task_dev_and_an_isolated_override_start() {
131        assert_eq!(
132            refusal(
133                &env(Some("isolated"), Some("C:/clone/.dev-home/5300"), false),
134                Some(real())
135            ),
136            None
137        );
138        assert_eq!(
139            refusal(&env(None, Some("C:/tmp/iso"), false), Some(real())),
140            None
141        );
142        assert_eq!(refusal(&env(Some("real"), None, false), Some(real())), None);
143    }
144
145    #[test]
146    fn the_real_home_needs_the_explicit_switch() {
147        assert_eq!(refusal(&env(None, None, true), Some(real())), None);
148        let named = refusal(
149            &env(None, Some("c:\\Users\\me\\.agentmux\\"), false),
150            Some(real()),
151        );
152        assert!(named.is_some_and(|w| w.contains(USE_REAL_HOME)));
153        assert_eq!(
154            refusal(
155                &env(None, Some("C:/Users/me/.agentmux"), true),
156                Some(real())
157            ),
158            None
159        );
160    }
161
162    #[test]
163    fn an_empty_or_odd_value_is_not_a_choice() {
164        assert!(refusal(&env(Some("whatever"), None, false), Some(real())).is_some());
165    }
166
167    #[test]
168    fn only_a_dev_build_folder_is_guarded() {
169        assert_eq!(
170            refusal_for_process(Path::new("C:/Program Files/AgentMux")),
171            None
172        );
173    }
174}