Skip to main content

agentmux_common/
data_paths.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Unified data-path resolution for AgentMux.
5//!
6//! Single source of truth for where state lives on disk. Replaces the
7//! launcher / host / sidecar trio of independent path computations
8//! (see docs/specs/archive/SPEC_DATA_DIR_UNIFICATION_2026-05-05.md §3) and the
9//! per-version isolation pattern it set up (data was keyed on the
10//! build version so My Agents reset on every patch bump). The current
11//! model keys data on a *channel* — a stable identifier that spans
12//! versions within the same compat band, so agents survive rebuilds.
13//! See docs/specs/SPEC_DATA_CHANNELS_2026_05_24.md and discussion
14//! #1026 for the channel design and rationale.
15//!
16//! Layout:
17//!
18//! ```text
19//! ~/.agentmux/
20//! ├── shared/                       (cookies, credentials, account-wide)
21//! ├── channels/<channel>/           (installed + portable + custom)
22//! │   ├── data/, config/, logs/, cef-cache/, agents/
23//! │   └── runtime/                  (lock + IPC, single instance per channel)
24//! └── dev/<branch>/                 (per-branch dev isolation)
25//!     └── (same children as channels/<channel>/)
26//! ```
27//!
28//! Channel resolution (via [`DataPaths::resolve`]):
29//! - `AGENTMUX_CHANNEL=<name>` env override wins for `Installed` /
30//!   `Portable` modes — lets the operator point a released binary at
31//!   any channel for parallel-channel testing.
32//! - `RuntimeMode::Installed` / `Portable` w/o override → a portable folder's
33//!   recorded channel (`runtime/agentmux-channel`, after an upgrade), else the build-time
34//!   default from `AGENTMUX_BUILD_CHANNEL_DEFAULT` (set by the
35//!   packaging script; defaults to `"stable"` if unset, e.g. for
36//!   `cargo run`).
37//! - `RuntimeMode::Dev { branch }` → channel name is `dev-<branch>`
38//!   for diagnostics; on-disk path stays at `~/.agentmux/dev/<branch>/`
39//!   (NOT under `channels/`). Both the host (`agentmux-cef`) and
40//!   launcher (`agentmux-launcher`) use [`DataPaths::resolve_path_only`]
41//!   for dev builds to ignore `AGENTMUX_CHANNEL` — a dev session
42//!   launched from inside a parent agentmux pane mustn't inherit
43//!   the parent's channel and break per-branch isolation. Channel
44//!   override is intentionally NOT supported in dev mode; if you
45//!   want a different channel, use a portable build.
46
47use crate::RuntimeMode;
48use std::path::{Path, PathBuf};
49
50mod dir_links;
51mod isolation;
52
53pub use dir_links::{ensure_history_link, ensure_owner_only_dir, OwnerOnlyOutcome};
54pub use isolation::{
55    isolated_auth_enabled, isolated_auth_reason, isolated_settings_enabled, isolated_settings_reason,
56    IsolatedAuthReason, IsolatedSettingsReason,
57};
58
59/// Build-time default channel for `Installed` / `Portable` modes.
60/// Set by the packaging script (`task package` exports
61/// `AGENTMUX_BUILD_CHANNEL_DEFAULT=local-<branch>`; release CI exports
62/// `stable`). Falls back to `"stable"` when the binary is built
63/// without the env (e.g. plain `cargo build` / `cargo run` for tests).
64const BUILD_CHANNEL_DEFAULT: &str =
65    match option_env!("AGENTMUX_BUILD_CHANNEL_DEFAULT") {
66        Some(s) => s,
67        None => "stable",
68    };
69
70/// The channel this binary was built for (`stable` for a release, a
71/// `local-…` channel of its own for a local package build). A constant of the
72/// binary; the channel an instance runs on can differ (an upgrade's recorded
73/// channel, `AGENTMUX_CHANNEL`). For `build_kind`, not for finding data.
74pub fn build_channel_default() -> &'static str {
75    BUILD_CHANNEL_DEFAULT
76}
77
78/// Channel names that would collide with sibling dirs at
79/// `~/.agentmux/` or with reserved subdir names inside a channel.
80/// Rejected by [`sanitize_channel_name`].
81const RESERVED_CHANNEL_NAMES: &[&str] = &[
82    "shared",
83    "snapshots",
84    "dev",
85    "versions",
86    "channels",
87    "runtime",
88];
89
90/// All paths a launcher / host / srv needs. Computed once by the
91/// launcher; downstream binaries read paths from env vars set by the
92/// launcher rather than recomputing (avoids the legacy desync risk
93/// where each binary made its own portable / dev-mode determination).
94#[derive(Debug, Clone)]
95pub struct DataPaths {
96    /// `~/.agentmux/` itself — the resolved root. Account-wide config
97    /// that predates the unified layout (e.g. the launcher's
98    /// `config.toml`) lives directly here. Honors
99    /// `AGENTMUX_HOME_OVERRIDE` for tests.
100    pub home_dir: PathBuf,
101
102    /// Top-level dir for this channel+mode. All per-channel paths
103    /// below are children. Either `~/.agentmux/channels/<channel>/`
104    /// (installed / portable / AGENTMUX_CHANNEL override) or
105    /// `~/.agentmux/dev/<branch>/` (dev mode without env override).
106    ///
107    /// Note: the field name is `instance_dir` for backward compat with
108    /// downstream call sites; semantically it's now the *channel* root,
109    /// not the *version* root.
110    pub instance_dir: PathBuf,
111
112    /// Channel identifier this resolution used (e.g. `"stable"`,
113    /// `"local-main"`, `"dev-main"`, or a user-specified custom
114    /// channel from `AGENTMUX_CHANNEL`). Surfaced for diagnostics,
115    /// logging, and the launcher splash; downstream binaries usually
116    /// don't need it (paths are passed via env vars).
117    pub channel: String,
118
119    /// `instance_dir/data/` — srv DB (objects.db, sagas.db, …).
120    pub data_dir: PathBuf,
121
122    /// `instance_dir/config/` — settings.json, repos.json, etc.
123    pub config_dir: PathBuf,
124
125    /// `instance_dir/logs/` — host + srv + launcher logs (rotated).
126    pub logs_dir: PathBuf,
127
128    /// `instance_dir/cef-cache/` — Chromium runtime cache (regenerable).
129    pub cef_cache_dir: PathBuf,
130
131    /// `instance_dir/agents/` — agent workspace state.
132    pub agents_dir: PathBuf,
133
134    /// `instance_dir/runtime/` — single-instance lock + IPC (pid,
135    /// lockfile, ipc-port, named-pipe). One set per version+mode.
136    pub instance_runtime_dir: PathBuf,
137
138    /// `~/.agentmux/shared/` — version-independent, account-wide
139    /// state (cookies, OAuth tokens, API keys, dictionary downloads).
140    pub shared_dir: PathBuf,
141
142    /// Snapshot of the [`RuntimeMode`] this resolution used. Helpful
143    /// for logging and feature gates.
144    pub mode: RuntimeMode,
145}
146
147impl DataPaths {
148    /// Resolve all paths for the given version + mode. Honors
149    /// `AGENTMUX_HOME_OVERRIDE` for tests (replaces `~/.agentmux` root).
150    ///
151    /// Returns `Err` if the input contains values that cannot be
152    /// represented as a safe single-segment subpath — e.g. `..` in the
153    /// version string, or a Dev branch that sanitizes to empty. This
154    /// is belt-and-braces safety: parse-time sanitization in
155    /// [`crate::RuntimeMode`] should already have caught these, but a
156    /// `RuntimeMode::Dev { branch }` constructed directly (e.g. by a
157    /// test or future caller) is also rejected here.
158    pub fn resolve(version: &str, mode: &RuntimeMode) -> Result<Self, String> {
159        Self::resolve_internal(version, mode, /* honor_env_channel = */ true)
160    }
161
162    /// Like [`Self::resolve`], but ignores the `AGENTMUX_CHANNEL` env
163    /// override and uses only the mode-based default channel. Mirror
164    /// of [`RuntimeMode::current_path_only`] for path resolution.
165    ///
166    /// Used by dev-build self-detection paths in `agentmux-cef`'s
167    /// `main.rs` and `sidecar.rs`. Those paths run when a dev host
168    /// has been launched from inside a parent AgentMux instance (e.g.
169    /// `task dev` invoked from inside an agent pane in a portable
170    /// build), where the child would otherwise inherit the parent's
171    /// `AGENTMUX_*` env — including `AGENTMUX_CHANNEL` — and write
172    /// into the parent's channel instead of `dev/<branch>/`. That
173    /// cross-contamination would also trip the channel's single-
174    /// instance lock and route every "open" back to the parent
175    /// window. Path-based mode detection is authoritative for dev
176    /// builds; channel resolution here mirrors that discipline.
177    /// Codex P1 follow-up on PR #1027.
178    pub fn resolve_path_only(version: &str, mode: &RuntimeMode) -> Result<Self, String> {
179        Self::resolve_internal(version, mode, /* honor_env_channel = */ false)
180    }
181
182    fn resolve_internal(
183        version: &str,
184        mode: &RuntimeMode,
185        honor_env_channel: bool,
186    ) -> Result<Self, String> {
187        let root = resolve_root()?;
188        // `version` is still validated for path safety even though it
189        // no longer appears in the on-disk path — it flows into
190        // logging, the migration framework (Increment B), and
191        // `meta.json` records, so a traversal-laced value mustn't
192        // round-trip into a future path build by accident.
193        sanitize_path_segment(version)
194            .ok_or_else(|| format!("invalid version string for path: {:?}", version))?;
195
196        // Channel resolution: env override > mode default. Dev mode's
197        // *channel name* and *path* diverge intentionally — name is
198        // `dev-<branch>` for diagnostics; path stays at
199        // `~/.agentmux/dev/<branch>/` so per-branch isolation works
200        // unchanged from Phase 1.
201        let (channel, instance_dir) =
202            resolve_channel_and_dir(mode, &root, honor_env_channel)?;
203
204        // For Installed/Portable builds, version-scope the mutable
205        // runtime dirs so two concurrent release versions don't share
206        // SQLite DBs or Chromium caches. Dev builds are already
207        // branch-isolated via their path; no extra scoping needed.
208        //
209        // Layout after this change:
210        //   channels/<ch>/versions/<v>/data/      ← objects.db, sagas.db …
211        //   channels/<ch>/versions/<v>/logs/
212        //   channels/<ch>/versions/<v>/cef-cache/
213        //   channels/<ch>/versions/<v>/runtime/   ← ipc-port, lock
214        //   channels/<ch>/config/                 ← settings (channel-wide)
215        //   channels/<ch>/agents/                 ← agent defs (survive upgrades)
216        //
217        // See SPEC_VERSION_ISOLATION_2026_06_01.md §5 Phase 2.
218        let version_dir = match mode {
219            RuntimeMode::Installed | RuntimeMode::Portable => {
220                instance_dir.join("versions").join(version)
221            }
222            RuntimeMode::Dev { .. } => instance_dir.clone(),
223        };
224
225        let data_dir = version_dir.join("data");
226        let logs_dir = version_dir.join("logs");
227        let cef_cache_dir = version_dir.join("cef-cache");
228        let instance_runtime_dir = version_dir.join("runtime");
229        // config and agents stay channel-wide so settings and agent
230        // definitions persist across version upgrades.
231        let config_dir = instance_dir.join("config");
232        let agents_dir = instance_dir.join("agents");
233        let shared_dir = root.join("shared");
234
235        Ok(Self {
236            home_dir: root,
237            instance_dir,
238            channel,
239            data_dir,
240            config_dir,
241            logs_dir,
242            cef_cache_dir,
243            agents_dir,
244            instance_runtime_dir,
245            shared_dir,
246            mode: mode.clone(),
247        })
248    }
249
250    /// Create every directory that may be written to. Idempotent.
251    /// Safe to call on every launch.
252    ///
253    /// Makes the AgentMux root owner-only first (issue #3682): it holds
254    /// per-agent jekt HMAC keys and LAN private keys (in the DBs), provider
255    /// login state (identity dirs) and logs, and on Unix every directory
256    /// below it was otherwise created with the process umask — typically
257    /// `0755`, readable by other local users wherever the home dir is
258    /// traversable (macOS `/Users/<name>` is `0755` by default). Tightening
259    /// the root blocks traversal into everything beneath it, including dirs
260    /// srv creates later with plain `create_dir_all` (`shared/`, `archives/`).
261    /// Best-effort: a root this process cannot chmod (owned by another user,
262    /// read-only mount) is logged and the launch continues, as before.
263    pub fn ensure_dirs(&self) -> Result<(), String> {
264        match ensure_owner_only_dir(&self.home_dir) {
265            Ok(OwnerOnlyOutcome::Tightened { previous_mode }) => tracing::warn!(
266                root = %self.home_dir.display(),
267                previous_mode = format!("{previous_mode:o}"),
268                "AgentMux data root was readable by other local users; tightened it to owner-only (0700)"
269            ),
270            Ok(OwnerOnlyOutcome::Created) => tracing::info!(
271                root = %self.home_dir.display(),
272                "created AgentMux data root owner-only (0700)"
273            ),
274            Ok(OwnerOnlyOutcome::AlreadyPrivate | OwnerOnlyOutcome::NotApplicable) => {}
275            Err(e) => tracing::warn!(
276                root = %self.home_dir.display(),
277                error = %e,
278                "could not make the AgentMux data root owner-only; continuing"
279            ),
280        }
281        for d in [
282            &self.instance_dir,
283            &self.data_dir,
284            &self.config_dir,
285            &self.logs_dir,
286            &self.cef_cache_dir,
287            &self.agents_dir,
288            &self.instance_runtime_dir,
289            &self.shared_dir,
290        ] {
291            std::fs::create_dir_all(d)
292                .map_err(|e| format!("failed to create {}: {}", d.display(), e))?;
293        }
294        // The data dir's `db/` subdir is the canonical srv DB home;
295        // mirrors legacy ensure_dirs() and lets srv unconditionally
296        // open `data_dir/db/objects.db`.
297        std::fs::create_dir_all(self.data_dir.join("db"))
298            .map_err(|e| format!("failed to create db dir: {}", e))?;
299        Ok(())
300    }
301
302    /// Env vars to pass to host + srv subprocesses. The launcher
303    /// computes `DataPaths` once and exports these; downstream
304    /// binaries read them via [`Self::from_env`] instead of
305    /// recomputing.
306    ///
307    /// Returns `OsString` (not `String`) so paths with non-UTF-8 bytes
308    /// — possible on Linux/macOS for users with exotic home dirs —
309    /// round-trip losslessly. `Command::env(k, v)` accepts any
310    /// `AsRef<OsStr>`, so the OsString flows through to children
311    /// unchanged. The mode value is the only `String`-typed entry
312    /// (it's a fixed ASCII vocabulary).
313    pub fn to_env_vars(&self) -> Vec<(&'static str, std::ffi::OsString)> {
314        use std::ffi::OsString;
315        let mut vars: Vec<(&'static str, OsString)> = vec![
316            ("AGENTMUX_INSTANCE_DIR", self.instance_dir.clone().into_os_string()),
317            ("AGENTMUX_DATA_DIR", self.data_dir.clone().into_os_string()),
318            ("AGENTMUX_CONFIG_DIR", self.config_dir.clone().into_os_string()),
319            ("AGENTMUX_LOG_DIR", self.logs_dir.clone().into_os_string()),
320            ("AGENTMUX_CEF_CACHE_DIR", self.cef_cache_dir.clone().into_os_string()),
321            ("AGENTMUX_AGENTS_DIR", self.agents_dir.clone().into_os_string()),
322            (
323                "AGENTMUX_INSTANCE_RUNTIME_DIR",
324                self.instance_runtime_dir.clone().into_os_string(),
325            ),
326            ("AGENTMUX_SHARED_DIR", self.shared_dir.clone().into_os_string()),
327            ("AGENTMUX_RUNTIME_MODE", OsString::from(self.mode.to_env_string())),
328            // Channel propagated so downstream binaries can log it +
329            // surface in diagnostics. NOT used to recompute paths
330            // (paths flow through the dir vars above).
331            ("AGENTMUX_CHANNEL", OsString::from(self.channel.clone())),
332        ];
333        // Dev mode also exports AGENTMUX_CLONE_ID so child processes
334        // (host, srv) can reconstruct the full `Dev { branch, clone_id }`
335        // variant via [`RuntimeMode::from_env_with_clone`]. The
336        // mode-string format (`dev:<branch>`) was kept backward-compatible
337        // and doesn't carry clone_id itself — see runtime_mode.rs.
338        if let RuntimeMode::Dev { clone_id: Some(id), .. } = &self.mode {
339            vars.push(("AGENTMUX_CLONE_ID", OsString::from(id.clone())));
340        }
341        vars
342    }
343
344    /// Reconstruct from env vars set by the launcher. Returns
345    /// `None` if any required var is missing — fail-fast vs.
346    /// silently falling back to legacy paths the way the old
347    /// sidecar.rs did.
348    ///
349    /// Uses `var_os` (not `var`) so non-UTF-8 path bytes survive.
350    pub fn from_env() -> Option<Self> {
351        let instance_dir = std::env::var_os("AGENTMUX_INSTANCE_DIR")?;
352        let data_dir = std::env::var_os("AGENTMUX_DATA_DIR")?;
353        let config_dir = std::env::var_os("AGENTMUX_CONFIG_DIR")?;
354        let logs_dir = std::env::var_os("AGENTMUX_LOG_DIR")?;
355        let cef_cache_dir = std::env::var_os("AGENTMUX_CEF_CACHE_DIR")?;
356        let agents_dir = std::env::var_os("AGENTMUX_AGENTS_DIR")?;
357        let instance_runtime_dir = std::env::var_os("AGENTMUX_INSTANCE_RUNTIME_DIR")?;
358        let shared_dir = std::env::var_os("AGENTMUX_SHARED_DIR")?;
359        // Pair AGENTMUX_RUNTIME_MODE with AGENTMUX_CLONE_ID so the Dev
360        // variant carries its clone discriminator. Legacy single-var
361        // form (no AGENTMUX_CLONE_ID set) leaves clone_id as None,
362        // which falls back to the pre-PR two-level dev path layout.
363        let mode = RuntimeMode::from_env_with_clone()?;
364        // Channel is required from the launcher (same fail-fast
365        // discipline as every other dir var). Missing AGENTMUX_CHANNEL
366        // means the launcher didn't export it — that's a launcher /
367        // srv version skew, surface it loudly rather than silently
368        // defaulting and risking a wrong-channel write.
369        let channel = std::env::var("AGENTMUX_CHANNEL").ok()?;
370
371        // Re-resolve home_dir (the agentmux root) on the consumer
372        // side rather than transmitting it via env — it's a function
373        // of the AGENTMUX_HOME_OVERRIDE env (test only) and the OS
374        // home dir, which are stable across the launcher → host hop.
375        let home_dir = resolve_root().ok()?;
376
377        Some(Self {
378            home_dir,
379            instance_dir: PathBuf::from(instance_dir),
380            channel,
381            data_dir: PathBuf::from(data_dir),
382            config_dir: PathBuf::from(config_dir),
383            logs_dir: PathBuf::from(logs_dir),
384            cef_cache_dir: PathBuf::from(cef_cache_dir),
385            agents_dir: PathBuf::from(agents_dir),
386            instance_runtime_dir: PathBuf::from(instance_runtime_dir),
387            shared_dir: PathBuf::from(shared_dir),
388            mode,
389        })
390    }
391
392    /// `~/.agentmux/shared/identities/` — root for per-bundle OAuth
393    /// credential directories. Lives under `shared_dir` so it's
394    /// account-wide and version-independent: upgrading agentmux does
395    /// not move a user's bundle credentials. Per
396    /// `docs/specs/archive/SPEC_OAUTH_IDENTITY_BUNDLES_2026_05_22.md` §4.1.
397    ///
398    /// When [`isolated_auth_enabled`] is set, this resolves to
399    /// `instance_dir/identities/` instead — a channel-scoped credential
400    /// tree, used only with `AGENTMUX_ISOLATED_AUTH=1`: auth is shared on
401    /// every channel by default
402    /// (`docs/specs/SPEC_SHARED_AUTH_ACROSS_CHANNELS_2026_10_03.md`).
403    /// Originally scoped to destructive
404    /// account testing (delete-account flows) that must never touch the
405    /// real global identity store other channels/instances use.
406    ///
407    /// **Isolating this directory isolates a provider's conversation
408    /// transcripts too**, since e.g. Claude Code's `projects/` lives
409    /// inside the same per-bundle directory tree as its credentials —
410    /// see [`identity_history_dir`] for the always-global path those
411    /// transcripts are kept reachable at regardless of this flag, and
412    /// `docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md`
413    /// §4.1 for why that split exists.
414    /// See `docs/specs/SPEC_ISOLATED_AUTH_DEV_TESTING_2026_07_27.md`.
415    pub fn identities_dir(&self) -> PathBuf {
416        if isolated_auth_enabled() {
417            self.instance_dir.join("identities")
418        } else {
419            self.shared_dir.join("identities")
420        }
421    }
422
423    /// `~/.agentmux/shared/identities/<bundle_id>/<provider_dir>/<history_subdir>/`
424    /// — ALWAYS this location, regardless of [`isolated_auth_enabled`].
425    /// Conversation transcripts must survive a channel/build change even
426    /// when the surrounding credential directory ([`identities_dir`]) is
427    /// isolated per-channel for account testing — history and credentials
428    /// are different data-persistence categories (CONVERSATION HISTORY
429    /// vs CREDENTIAL in
430    /// `docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md`
431    /// P1) and must not share one isolation switch just because they
432    /// happen to live under the same directory as far as the provider
433    /// CLI is concerned. Callers that isolate credentials are expected
434    /// to redirect the isolated `<bundle_id>/<provider_dir>/<history_subdir>`
435    /// subpath to this location via [`ensure_history_link`] rather than
436    /// letting the provider CLI write real session data there directly.
437    ///
438    /// `history_subdir` is caller-supplied rather than hardcoded — it is
439    /// NOT the same directory name for every provider (reagentx P1 on PR
440    /// #2605: this used to hardcode `"projects"`, which is Claude-
441    /// specific; Codex uses `"sessions"`, Gemini uses `"history"`, per
442    /// `docs/specs/SPEC_UNIFIED_AGENT_HISTORY_STORE_2026-06-10.md` §2.1).
443    /// Callers should read this from
444    /// `ProviderConfig::history_native_subdir`, the single source of
445    /// truth for which providers have a linkable directory at all.
446    ///
447    /// `bundle_id`/`provider_dir` are not path-validated here — callers
448    /// must use [`sanitize_path_segment`]-checked values, same
449    /// requirement as [`identity_dir`].
450    pub fn identity_history_dir(&self, bundle_id: &str, provider_dir: &str, history_subdir: &str) -> PathBuf {
451        self.shared_dir
452            .join("identities")
453            .join(bundle_id)
454            .join(provider_dir)
455            .join(history_subdir)
456    }
457
458    /// `~/.agentmux/shared/identities/<bundle_id>/` — a specific
459    /// bundle's credential root, when `bundle_id` is a safe path
460    /// segment. Returns `None` for empty / `.` / `..` / any segment
461    /// containing `/`, `\`, drive-letter colons, or Windows-reserved
462    /// characters (same rules as the version/branch sanitizer in
463    /// `resolve`).
464    ///
465    /// Defensive return type: `bundle_id` flows from `auth.start`
466    /// request bodies (PR C) into `create_dir_all`, so an
467    /// unvalidated `PathBuf::join` would let a crafted id escape the
468    /// identities root and write outside the bundle area. codex P1
469    /// follow-up on #981.
470    ///
471    /// Per-provider subdirectories (e.g. `claude/`, `codex/`) hang
472    /// off this when the bundle gains an OAuth binding (PR C). The
473    /// directory is created lazily by the bundle / OAuth flow that
474    /// needs it — `ensure_dirs()` does not pre-create it.
475    pub fn identity_dir(&self, bundle_id: &str) -> Option<PathBuf> {
476        sanitize_path_segment(bundle_id).map(|safe| self.identities_dir().join(safe))
477    }
478
479    /// `~/.agentmux/shared/providers/<auth_dir_name>/` — the DEFAULT provider
480    /// config + auth dir. Lives under `shared_dir`, so it is account-wide,
481    /// version-independent, AND channel-independent: every instance / channel /
482    /// version logs in ONCE and shares it. This is the structural fix for the
483    /// per-channel "validate-spin" regression — there is no empty-per-instance
484    /// auth dir to spin on. The per-identity override (`identity_dir`) still
485    /// takes precedence for explicit multi-account bundles. `auth_dir_name`
486    /// comes from the static provider registry (e.g. "claude"), never user
487    /// input. Retro:
488    /// `docs/retro/retro-provider-auth-isolation-regression-2026-06-05.md`.
489    pub fn provider_auth_dir(&self, auth_dir_name: &str) -> PathBuf {
490        self.shared_dir.join("providers").join(auth_dir_name)
491    }
492
493    /// `instance_dir/wan-identity/` — the channel-wide WAN identity store
494    /// (`wan.db`: the instance key, agent WAN keys, and WAN verification
495    /// state). Beside `config/` and `agents/` rather than under the
496    /// per-version `data_dir`, so an upgrade keeps the same instance and the
497    /// same agent keys. Deliberately not `identity/`, which would sit next to
498    /// the unrelated `identities/`. For dev builds this is the branch (or
499    /// clone) dir, so each dev checkout is its own instance.
500    /// `SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.2.
501    pub fn wan_identity_dir(&self) -> PathBuf {
502        self.instance_dir.join("wan-identity")
503    }
504}
505
506// The MuxBus reconnect flag lives in its own module; re-exported so callers
507// keep reaching it here.
508pub use crate::muxbus_reconnect::{
509    isolated_muxbus_reconnect_enabled, isolated_muxbus_reconnect_reason, keychain_prompts_per_build,
510    IsolatedMuxbusReconnectReason,
511};
512
513/// The AgentMux root (`~/.agentmux`) — the single resolver for it.
514///
515/// Public because srv had its own copy (`backend/base.rs::get_mux_data_dir`)
516/// reading a *different* env var and failing differently: where this returns
517/// `Err`, that one fell back to `PathBuf::from("/")`, so a host with no
518/// resolvable home directory wrote to `/.agentmux` instead of refusing.
519/// A10 of docs/analysis/TRACKING_ARCHITECTURE_REFACTOR_A1_A15_2026_06_18.md.
520///
521/// Two env vars are honoured, in this order, because both already exist in
522/// the wild and silently dropping either would move where a live install
523/// finds its data:
524///
525/// - `AGENTMUX_HOME_OVERRIDE` — this module's own, used by tests. It wins over
526///   `AGENTMUX_DATA_HOME`, except for a data home inside it (`data_home.rs`).
527/// - `AGENTMUX_DATA_HOME` — srv's own, read at startup and relied on by the
528///   MSIX packaging path (`blockcontroller/shell/lifecycle.rs`). It is
529///   deliberately **stripped** from pane environments, not exported into them:
530///   it is one of the identity vars invariant I7 removes so a pane cannot
531///   inherit and resolve another instance's data dir
532///   (`backend/pane_env.rs`, test `the_identity_vars_that_caused_the_breach_are_stripped`).
533///
534/// NOT to be confused with `AGENTMUX_DATA_DIR`, which the launcher exports
535/// and which names the per-channel *data* directory
536/// (`<root>/channels/<channel>/data`), not the root. The similar names are
537/// exactly why srv ended up with a second resolver.
538pub fn agentmux_root() -> Result<PathBuf, String> {
539    // An isolated instance keeps the versioned layout (data_home.rs, task #3569).
540    if let Some(data) = crate::data_home::inside_override() {
541        return Ok(data);
542    }
543    // `var_os`: a root that isn't valid UTF-8 must not read as unset.
544    for var in ["AGENTMUX_HOME_OVERRIDE", "AGENTMUX_DATA_HOME"] {
545        if let Some(s) = std::env::var_os(var) {
546            if !s.is_empty() {
547                return Ok(PathBuf::from(s));
548            }
549        }
550    }
551    let home = dirs::home_dir().ok_or_else(|| "dirs::home_dir() returned None".to_string())?;
552    Ok(home.join(".agentmux"))
553}
554
555fn resolve_root() -> Result<PathBuf, String> {
556    agentmux_root()
557}
558
559/// Sanitize a string for use as a single filesystem path segment.
560/// Rejects empty, `.`, `..`, segments containing path separators, and
561/// any character that has filesystem-special meaning on Windows (which
562/// is the most restrictive of the platforms we target). Used as belt-
563/// and-braces protection in `DataPaths::resolve` to prevent traversal
564/// even when callers pass a directly-constructed `RuntimeMode::Dev` or
565/// odd version string.
566///
567/// Why `:` is rejected: on Windows `C:temp` is a drive-relative path,
568/// not a literal filename, so `PathBuf::join("versions").join("C:temp")`
569/// would resolve OUTSIDE the intended `~/.agentmux/versions/` subtree.
570fn sanitize_path_segment(s: &str) -> Option<String> {
571    // Reject whitespace padding rather than silently normalizing it
572    // away — otherwise distinct caller-supplied ids like "foo" and
573    // " foo " would alias to the same directory. bundle_id is a real
574    // caller-supplied identifier (passed through RPC payloads), so
575    // this matters for credential isolation. codex P2 follow-up on
576    // #981. Internally-generated version strings + branch names
577    // shouldn't carry padding anyway, so this is no-op for them.
578    if s != s.trim() {
579        return None;
580    }
581    if s.is_empty() || s == "." || s == ".." {
582        return None;
583    }
584    // Filesystem separators + Windows-reserved characters + NUL.
585    if s
586        .chars()
587        .any(|c| matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0'))
588    {
589        return None;
590    }
591    Some(s.to_string())
592}
593
594/// Sanitize a string for use as a channel name. Same path-segment
595/// safety rules as [`sanitize_path_segment`] plus:
596/// - Length capped at 64 chars (channel names show up in logs + the
597///   launcher splash + may eventually be displayed in a picker, so
598///   the cap is for UI sanity, not security).
599/// - Rejects names in [`RESERVED_CHANNEL_NAMES`] that would collide
600///   with sibling dirs at `~/.agentmux/` or reserved subdir names
601///   inside a channel.
602/// - The synonym `"default"` maps to `"stable"` (per
603///   `SPEC_DATA_CHANNELS_2026_05_24.md` §7.5).
604fn sanitize_channel_name(s: &str) -> Option<String> {
605    let base = sanitize_path_segment(s)?;
606    if base.len() > 64 {
607        return None;
608    }
609    if RESERVED_CHANNEL_NAMES.contains(&base.as_str()) {
610        return None;
611    }
612    if base == "default" {
613        return Some("stable".to_string());
614    }
615    Some(base)
616}
617
618/// Resolve the channel name and on-disk channel dir for a given mode.
619/// Pure function over (env, mode, root). When `honor_env_channel` is
620/// `true`, `AGENTMUX_CHANNEL` overrides the mode default; when `false`,
621/// the env is ignored and resolution depends only on `mode` +
622/// build-time defaults. The `false` path is used by dev-build self-
623/// detection (see [`DataPaths::resolve_path_only`]).
624///
625/// Resolution order (mirrors `SPEC_DATA_CHANNELS_2026_05_24.md` §2.2):
626///   1. (only if `honor_env_channel`) `AGENTMUX_CHANNEL` env override —
627///      any mode → path is `<root>/channels/<channel>/`. Lets the
628///      operator point any binary at any channel for parallel-channel
629///      testing.
630///   2. No override (or env-channel disallowed), mode = Dev { branch }
631///      → channel name is `dev-<branch>`, path stays at
632///      `<root>/dev/<branch>/` (unchanged from Phase 1).
633///   3. Same conditions, mode = Installed | Portable → channel name is
634///      [`BUILD_CHANNEL_DEFAULT`] (set at build time by the packaging
635///      script), path is `<root>/channels/<channel>/`.
636fn resolve_channel_and_dir(
637    mode: &RuntimeMode,
638    root: &Path,
639    honor_env_channel: bool,
640) -> Result<(String, PathBuf), String> {
641    // (1) Explicit env override — only when caller opted in.
642    if honor_env_channel {
643        if let Ok(raw) = std::env::var("AGENTMUX_CHANNEL") {
644            if !raw.is_empty() {
645                let channel = sanitize_channel_name(&raw).ok_or_else(|| {
646                    format!("invalid AGENTMUX_CHANNEL value: {:?}", raw)
647                })?;
648                let dir = root.join("channels").join(&channel);
649                return Ok((channel, dir));
650            }
651        }
652    }
653
654    // (2) Dev mode default: dev-<branch>[-<clone_id>], path under
655    // dev/<branch>/[<clone_id>/]. The clone_id nests one level deeper
656    // so two clones of the same branch don't collide on data dir,
657    // lockfile, or named-pipe IPC. When clone_id is None (legacy
658    // env-string round-trip or direct test construction) the layout
659    // falls back to the original two-level form for back-compat.
660    // See SPEC_DATA_CHANNELS_2026_05_24.md §2.4 and
661    // docs/analysis/ANALYSIS_MULTI_CLONE_TASK_DEV_ISOLATION_2026-05-26.md.
662    if let RuntimeMode::Dev { branch, clone_id } = mode {
663        let safe_branch = sanitize_path_segment(branch).ok_or_else(|| {
664            format!("invalid dev branch for path: {:?}", branch)
665        })?;
666        let safe_clone = clone_id
667            .as_deref()
668            .and_then(sanitize_path_segment)
669            .filter(|s| !s.is_empty());
670        let (channel, dir) = match safe_clone {
671            Some(c) => (
672                format!("dev-{}-{}", safe_branch, c),
673                root.join("dev").join(safe_branch).join(c),
674            ),
675            None => (
676                format!("dev-{}", safe_branch),
677                root.join("dev").join(safe_branch),
678            ),
679        };
680        return Ok((channel, dir));
681    }
682
683    // (3) Installed / Portable default: the channel an upgrade recorded for this
684    // install (`runtime_mode::recorded_channel`), else the build-time one.
685    let recorded = crate::runtime_mode::recorded_channel();
686    let channel = recorded.as_deref().and_then(sanitize_channel_name).or_else(|| sanitize_channel_name(BUILD_CHANNEL_DEFAULT));
687    let channel = channel.ok_or_else(|| format!("compile-time AGENTMUX_BUILD_CHANNEL_DEFAULT is invalid: {BUILD_CHANNEL_DEFAULT:?}"))?;
688    let dir = root.join("channels").join(&channel);
689    Ok((channel, dir))
690}
691
692#[cfg(test)]
693mod tests;