Skip to main content

agentmux_launcher/
data_dir.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Compatibility shim around `agentmux_common::DataPaths`.
5//!
6//! Historically the launcher computed its own paths via the
7//! launcher-local `resolve_paths()` function. After the data-dir
8//! unification (see docs/specs/archive/SPEC_DATA_DIR_UNIFICATION_2026-05-05.md
9//! and PR #695), path resolution is centralized in
10//! `agentmux_common::DataPaths`. This module keeps the launcher's
11//! existing public API surface (`DataPaths` struct with 4 fields,
12//! `resolve_paths()`, `ensure_dirs()`) so call sites in main.rs,
13//! diag.rs, srv_spawner.rs etc. don't need to be rewritten — they
14//! see the same shape, populated from the common implementation.
15//!
16//! Field mapping:
17//! - launcher.data_dir       = common.data_dir
18//! - launcher.config_dir     = common.config_dir
19//! - launcher.user_home_dir  = common.home_dir   (the agentmux root,
20//!                                                e.g. `~/.agentmux/`,
21//!                                                where `config.toml`
22//!                                                lives)
23//! - launcher.portable_root  = exe_dir when mode == Portable, else None
24//!
25//! The launcher continues to use these field names internally; the
26//! env vars it passes to host + srv are switched in main.rs to the
27//! canonical AGENTMUX_* names emitted by `DataPaths::to_env_vars`.
28
29use agentmux_common::{DataPaths as CommonDataPaths, RuntimeMode};
30use std::path::{Path, PathBuf};
31
32/// Resolved per-instance paths. Compat shape — see module doc.
33#[derive(Debug, Clone)]
34pub struct DataPaths {
35    pub data_dir: PathBuf,
36    pub config_dir: PathBuf,
37    pub user_home_dir: PathBuf,
38    pub portable_root: Option<PathBuf>,
39    /// Full common-paths value — exposes the new fields
40    /// (`cef_cache_dir`, `agents_dir`, `instance_runtime_dir`,
41    /// `logs_dir`, `instance_dir`, `mode`) for the launcher's
42    /// env-var passing in main.rs without re-resolving.
43    pub common: CommonDataPaths,
44}
45
46/// Resolve all paths from the launcher's vantage point.
47///
48/// Detects [`RuntimeMode`] from `launcher_exe_dir`, resolves the
49/// canonical paths via [`agentmux_common::DataPaths::resolve`], and
50/// projects them onto the launcher-local field names.
51///
52/// Mode detection is authoritative here — `cfg!(debug_assertions)` is
53/// unreliable across binaries built with different profiles, so we let
54/// `RuntimeMode::current` decide and propagate the answer downstream
55/// via the `AGENTMUX_RUNTIME_MODE` env var. The legacy `is_dev`
56/// parameter from the pre-PR-#695 signature has been removed; callers
57/// no longer need to compute it.
58pub fn resolve_paths(launcher_exe_dir: &Path, version: &str) -> Result<DataPaths, String> {
59    // Path-only when the exe is a dev build — see SPEC_DEV_ENV_ISOLATION.
60    // Prevents inheriting AGENTMUX_RUNTIME_MODE from a parent AgentMux
61    // process when `task dev` is launched from inside an existing pane.
62    let is_dev = agentmux_common::is_dev_build_exe(launcher_exe_dir);
63
64    // A portable/installed build launched from INSIDE another AgentMux pane
65    // inherits the parent's AGENTMUX_CHANNEL + AGENTMUX_RUNTIME_MODE (the srv
66    // sets AGENTMUX=1 and the full AGENTMUX_* path env for every pane shell —
67    // `crates/srv/.../blockcontroller/shell.rs`). Honoring that *leaked*
68    // channel makes the new build adopt the PARENT's data dir + cef-cache, so
69    // Chromium's user-data-dir singleton forwards it into the parent and it exits
70    // ("Opening in existing browser session", CEF exit 24) — the build you
71    // launched never runs. Treat a nested launch like a dev build: ignore the
72    // ambient channel/mode and resolve from this binary's BAKED per-build channel
73    // (`AGENTMUX_BUILD_CHANNEL_DEFAULT`). An EXPLICIT, *standalone*
74    // `AGENTMUX_CHANNEL=… ./agentmux` (not nested) is still honored — that is the
75    // intentional parallel-channel override (PR #1027); only the leak is
76    // suppressed. `AGENTMUX` is the canonical "inside a pane" sentinel.
77    let nested = std::env::var_os("AGENTMUX").is_some();
78    let ignore_ambient = is_dev || nested;
79
80    let mode = if ignore_ambient {
81        RuntimeMode::current_path_only(launcher_exe_dir)
82    } else {
83        RuntimeMode::current(launcher_exe_dir)
84    };
85    // The launcher MUST use `resolve_path_only` (not `resolve`) whenever it
86    // ignores the ambient channel — so AGENTMUX_CHANNEL is dropped symmetrically
87    // with the host's dev/nested branch in crates/cef/src/main.rs and
88    // sidecar.rs. Without this the launcher would honor a leaked `AGENTMUX_CHANNEL`
89    // and write the lockfile + IPC files into `channels/<override>/runtime/`,
90    // while the host (path-only) looks elsewhere — launcher/host disagreement on
91    // the single-instance lock breaks isolation. The launcher's resolved env is
92    // authoritative for the host + srv it spawns (`to_env_vars()` overwrites the
93    // inherited AGENTMUX_* at every spawn site), so fixing it here fixes the whole
94    // chain.
95    let common = if ignore_ambient {
96        CommonDataPaths::resolve_path_only(version, &mode)?
97    } else {
98        CommonDataPaths::resolve(version, &mode)?
99    };
100
101    let portable_root = if mode == RuntimeMode::Portable {
102        Some(launcher_exe_dir.to_path_buf())
103    } else {
104        None
105    };
106
107    Ok(DataPaths {
108        data_dir: common.data_dir.clone(),
109        config_dir: common.config_dir.clone(),
110        // The launcher's `config.toml` (saga retention etc.) lives
111        // at `~/.agentmux/config.toml` — account-wide, version-
112        // independent, predates the unified layout. Map onto the
113        // resolved root, NOT shared_dir or any version-keyed subdir.
114        user_home_dir: common.home_dir.clone(),
115        portable_root,
116        common,
117    })
118}
119
120/// This channel's `settings.json`, the file srv loads (#1903), resolved
121/// early and failure-tolerant for the launcher's own startup reads.
122pub fn settings_file() -> Option<PathBuf> {
123    let exe = std::env::current_exe().ok()?;
124    let version = env!("CARGO_PKG_VERSION");
125    resolve_paths(exe.parent()?, version).ok().map(|p| p.common.settings_file())
126}
127
128/// Create every directory the launcher + srv expect to exist.
129/// Idempotent. Delegates to the common implementation.
130///
131/// It puts no database in them: what a new version's data starts from is
132/// srv's to decide, on its first start (`crates/srv-core/src/migrations/carry_forward.rs`:
133/// the newest older version's databases, else the channel's pre-versioning
134/// `data/db/`). The launcher used to copy that pre-versioning folder here
135/// whenever a version's `data/db/` had no database yet, which is every
136/// upgrade: srv then found an `objects.db` in place and carried nothing
137/// forward, so each upgrade started from that old data instead of the
138/// previous version's, without the layout its quit had saved.
139pub fn ensure_dirs(paths: &DataPaths) -> Result<(), String> {
140    paths.common.ensure_dirs()
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    /// The launcher's paths for `version` of the `stable` channel under `root`.
148    fn paths(root: &Path, version: &str) -> DataPaths {
149        let channel_dir = root.join("channels").join("stable");
150        let version_dir = channel_dir.join("versions").join(version);
151        let common = CommonDataPaths {
152            home_dir: root.to_path_buf(),
153            instance_dir: channel_dir.clone(),
154            channel: "stable".to_string(),
155            data_dir: version_dir.join("data"),
156            config_dir: channel_dir.join("config"),
157            logs_dir: version_dir.join("logs"),
158            cef_cache_dir: version_dir.join("cef-cache"),
159            agents_dir: channel_dir.join("agents"),
160            instance_runtime_dir: version_dir.join("runtime"),
161            shared_dir: root.join("shared"),
162            mode: RuntimeMode::Installed,
163        };
164        DataPaths {
165            data_dir: common.data_dir.clone(),
166            config_dir: common.config_dir.clone(),
167            user_home_dir: common.home_dir.clone(),
168            portable_root: None,
169            common,
170        }
171    }
172
173    fn put_db(dir: &Path) {
174        std::fs::create_dir_all(dir).unwrap();
175        std::fs::write(dir.join("objects.db"), b"not opened").unwrap();
176    }
177
178    /// The launcher never seeds a version's databases: srv copies the
179    /// previous version's forward on its first start, and finding an
180    /// `objects.db` already there it copies nothing. A copy of the channel's
181    /// pre-versioning `data/db/` made here started every upgrade from that
182    /// months-old data instead, without the layout the quit had saved
183    /// (`docs/incident/RCA_UPGRADE_LOSES_LAYOUT_2026_10_22.md`).
184    #[test]
185    fn ensure_dirs_leaves_a_new_versions_databases_to_srv() {
186        let root = tempfile::tempdir().unwrap();
187        let channel_dir = root.path().join("channels").join("stable");
188        put_db(&channel_dir.join("data").join("db"));
189        put_db(&channel_dir.join("versions").join("0.59.38").join("data").join("db"));
190
191        let new = paths(root.path(), "0.59.39");
192        ensure_dirs(&new).unwrap();
193
194        let db_dir = new.data_dir.join("db");
195        let files: Vec<_> = std::fs::read_dir(&db_dir)
196            .map(|d| d.filter_map(|e| e.ok()).map(|e| e.file_name()).collect())
197            .unwrap_or_default();
198        assert!(files.is_empty(), "the launcher put {files:?} in {}", db_dir.display());
199    }
200}