Skip to main content

agentmux_srv_core/identity/
foreign_dir.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A config dir inside another channel's `identities/` folder.
5//!
6//! Auth is shared across channels (`<home>/shared/identities/<account>/…`) unless a build opts into
7//! `AGENTMUX_ISOLATED_AUTH=1`, which keeps its accounts' dirs under `<home>/channels/<channel>/identities/`.
8//! A dir recorded by one of those builds (an account row, or a pane's `cmd:env`) is no place for
9//! another channel's agent to run: it holds no sign-in this channel can see, and a session recorded
10//! there can't be resumed from the shared dir. Two readings of the same agent that disagree on it
11//! made its watched config dir (and, with it, its spawn) flip between the two.
12
13use std::collections::HashMap;
14use std::path::{Component, Path};
15
16use crate::backend::obj::{Block, MetaMapType};
17use crate::backend::storage::store::Store;
18
19/// The variable Claude Code reads its config dir from.
20const VAR: &str = "CLAUDE_CONFIG_DIR";
21
22/// Whether `dir` lies in `<…>/channels/<name>/identities/…` for a `<name>` other than `own_channel`.
23/// Lexical, case-insensitive (Windows paths), and false for any dir not in that shape.
24pub fn is_other_channel_identity_dir(dir: &Path, own_channel: &str) -> bool {
25    let parts: Vec<String> = dir
26        .components()
27        .filter_map(|c| match c {
28            Component::Normal(s) => Some(s.to_string_lossy().to_ascii_lowercase()),
29            _ => None,
30        })
31        .collect();
32    let own = own_channel.to_ascii_lowercase();
33    parts.windows(3).any(|w| w[0] == "channels" && w[2] == "identities" && w[1] != own)
34}
35
36/// [`is_other_channel_identity_dir`] for the channel this srv runs in. `own_channel` is
37/// `AGENTMUX_CHANNEL` and `own_instance_dir` is `AGENTMUX_INSTANCE_DIR` (what the launcher gives srv).
38/// A srv that doesn't know its channel treats no dir as foreign, and a dir under its own instance
39/// dir never is.
40fn is_foreign_in(dir: &Path, own_channel: Option<&str>, own_instance_dir: Option<&Path>) -> bool {
41    let Some(own) = own_channel.map(str::trim).filter(|c| !c.is_empty()) else { return false };
42    if own_instance_dir.is_some_and(|own_dir| dir.starts_with(own_dir)) {
43        return false;
44    }
45    is_other_channel_identity_dir(dir, own)
46}
47
48/// [`is_foreign_in`] for this process's environment.
49pub fn is_foreign_to_this_channel(dir: &Path) -> bool {
50    let channel = std::env::var("AGENTMUX_CHANNEL").ok();
51    let instance_dir = std::env::var_os("AGENTMUX_INSTANCE_DIR").map(std::path::PathBuf::from);
52    is_foreign_in(dir, channel.as_deref(), instance_dir.as_deref())
53}
54
55/// The pane's `cmd:env` with its `CLAUDE_CONFIG_DIR` pointed at `bound`, when the value it holds is
56/// a dir of another channel's (`None` when there is nothing to heal).
57fn env_with_bound_config_dir(
58    env: &HashMap<String, String>,
59    bound: &Path,
60    is_foreign: impl Fn(&Path) -> bool,
61) -> Option<HashMap<String, String>> {
62    let held = env.get(VAR)?;
63    if !is_foreign(Path::new(held)) || is_foreign(bound) {
64        return None;
65    }
66    let mut healed = env.clone();
67    healed.insert(VAR.to_string(), bound.to_string_lossy().into_owned());
68    Some(healed)
69}
70
71/// Heals a pane whose `cmd:env` names another channel's config dir: rewritten to `bound`, the dir its
72/// account really spawns in. The window's auth re-check and login recovery read `cmd:env` as it is.
73pub fn heal_block_config_dir_env(mstore: &Store, block: Option<&Block>, bound: Option<&Path>) {
74    let (Some(block), Some(bound)) = (block, bound) else { return };
75    let Some(healed) = env_with_bound_config_dir(&crate::backend::blockcontroller::cmd_env_of(&block.meta), bound, is_foreign_to_this_channel) else {
76        return;
77    };
78    let mut update = MetaMapType::new();
79    update.insert("cmd:env".to_string(), serde_json::json!(healed));
80    match crate::backend::wcore::object_meta::update_object_meta(mstore, &format!("block:{}", block.oid), &update) {
81        Ok(()) => tracing::info!(block_id = %block.oid, dir = %bound.display(), "healed a pane's config dir that named another channel's identities folder"),
82        Err(e) => tracing::warn!(block_id = %block.oid, error = %e, "could not heal a pane's config dir"),
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn a_pane_env_naming_another_channels_dir_is_pointed_at_the_bound_dir() {
92        let mut env = HashMap::from([("CLAUDE_CONFIG_DIR".to_string(), OTHER.to_string()), ("X".to_string(), "1".to_string())]);
93        let bound = Path::new(SHARED);
94        let foreign = |dir: &Path| is_other_channel_identity_dir(dir, "this-channel");
95        let healed = env_with_bound_config_dir(&env, bound, foreign).expect("foreign dir is healed");
96        assert_eq!(healed["CLAUDE_CONFIG_DIR"], SHARED);
97        assert_eq!(healed["X"], "1", "the rest of the env is kept");
98        // Nothing to heal: a shared dir, no variable, or a bound dir that is itself foreign.
99        env.insert("CLAUDE_CONFIG_DIR".to_string(), SHARED.to_string());
100        assert_eq!(env_with_bound_config_dir(&env, bound, foreign), None);
101        assert_eq!(env_with_bound_config_dir(&HashMap::new(), bound, foreign), None);
102        env.insert("CLAUDE_CONFIG_DIR".to_string(), OTHER.to_string());
103        assert_eq!(env_with_bound_config_dir(&env, Path::new(OTHER), foreign), None);
104    }
105
106    const OTHER: &str = "C:/Users/u/.agentmux/channels/local-main-b28b7a-051fbf53/identities/322f5f07-40a2/claude";
107    const SHARED: &str = "C:/Users/u/.agentmux/shared/identities/b860809b-8bc2/claude";
108
109    #[test]
110    fn a_dir_in_another_channels_identities_folder_is_foreign() {
111        assert!(is_other_channel_identity_dir(Path::new(OTHER), "local-loap-3-memory-lab-f5abd5-76d6ee20"));
112        assert!(is_other_channel_identity_dir(Path::new("/h/.agentmux/channels/stable/identities/a/claude"), "dev"));
113    }
114
115    #[test]
116    fn this_channels_own_dir_and_the_shared_dir_are_not() {
117        assert!(!is_other_channel_identity_dir(Path::new(OTHER), "local-main-b28b7a-051fbf53"));
118        assert!(!is_other_channel_identity_dir(Path::new(OTHER), "LOCAL-MAIN-B28B7A-051FBF53"));
119        assert!(!is_other_channel_identity_dir(Path::new(SHARED), "stable"));
120    }
121
122    #[test]
123    fn a_srv_that_does_not_know_its_channel_calls_nothing_foreign() {
124        assert!(!is_foreign_in(Path::new(OTHER), None, None));
125        assert!(!is_foreign_in(Path::new(OTHER), Some("  "), None));
126        assert!(is_foreign_in(Path::new(OTHER), Some("stable"), None));
127    }
128
129    #[test]
130    fn a_dir_under_this_srvs_own_instance_dir_is_never_foreign() {
131        let own = Path::new("C:/Users/u/.agentmux/channels/local-main-b28b7a-051fbf53");
132        assert!(!is_foreign_in(Path::new(OTHER), Some("renamed"), Some(own)));
133        assert!(is_foreign_in(Path::new(OTHER), Some("renamed"), Some(Path::new("C:/Users/u/.agentmux/channels/stable"))));
134    }
135
136    #[test]
137    fn only_the_identities_folder_of_a_channel_counts() {
138        // A channel's other folders (agents, config) and unrelated paths named alike.
139        assert!(!is_other_channel_identity_dir(Path::new("/h/.agentmux/channels/stable/agents/a1"), "dev"));
140        assert!(!is_other_channel_identity_dir(Path::new("/h/channels/identities"), "dev"));
141        assert!(!is_other_channel_identity_dir(Path::new("/h/.config/claude-agent2"), "dev"));
142        assert!(!is_other_channel_identity_dir(Path::new(""), "dev"));
143    }
144}