Skip to main content

agentmux_srv_core/backend/spawn_env/
identity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agent's identity variables in its spawn environment, beyond what
5//! `input.rs`'s `split_agent_identity_env` and `carry_agent_uid_env` set.
6//!
7//! **The server wins on identity** (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md`
8//! P0.3): when the agent's row has a slug, `AGENTMUX_AGENT_ID`,
9//! `MUXBUS_AGENT_ID` and the git identity AgentMux derived from the id come
10//! from that slug, whatever a persisted `cmd:env` says. `cmd:env` is a
11//! launch-time snapshot, so after a rename it names the old id, and the agent
12//! would keep answering to it. `AGENTMUX_AGENT_SLUG` is set the same way
13//! (`split_agent_identity_env`), and `GH_CONFIG_DIR` follows the slug
14//! (`gh_guard`). An agent with no row or no slug keeps its `cmd:env` values.
15
16use std::collections::HashMap;
17
18/// Per-agent git commit identity env vars for a spawned agent process
19/// (2026-08-22, docs/retro/retro-shared-git-identity-committer-misattribution-2026-08-22.md).
20///
21/// Without this, `git commit` falls through to whatever user.name/
22/// user.email happens to be sitting in a shared multi-agent host's
23/// `~/.gitconfig` -- one agent's real identity, silently baked into every
24/// OTHER agent's commits too. `agentmux-cloud`'s review-notification
25/// consumer resolves "who committed this" via GitHub's own commit->account
26/// auto-linking (`commit.author.login`), not the raw git commit metadata
27/// directly -- so whichever agent's *real, GitHub-verified* email is
28/// sitting in the shared config silently receives every other agent's
29/// committer notifications too (confirmed live: every commit across 9+
30/// PRs from 4 different agents on one host resolved to a single agent's
31/// account this way).
32///
33/// `GIT_AUTHOR_*`/`GIT_COMMITTER_*` env vars take precedence over
34/// config-file `user.name`/`user.email` at commit time (git's own
35/// behavior) -- scoped to just the spawned process tree, same pattern as
36/// `AGENTMUX_AGENT_ID`. The email intentionally uses a non-existent
37/// `.local` domain: GitHub can't link it to any real account, so an agent
38/// with no dedicated PAT registered (the common case -- see this repo's
39/// `CLAUDE.md`, "Which GitHub account am I acting as?") simply drops out
40/// of `commit.author.login` lookups entirely instead of resolving to
41/// someone else's real, verified identity.
42pub(crate) fn git_identity_env_vars(agent_id: &str) -> [(&'static str, String); 4] {
43    let git_email = format!("{}@agentmux.local", agent_id.to_lowercase());
44    [
45        ("GIT_AUTHOR_NAME", agent_id.to_string()),
46        ("GIT_COMMITTER_NAME", agent_id.to_string()),
47        ("GIT_AUTHOR_EMAIL", git_email.clone()),
48        ("GIT_COMMITTER_EMAIL", git_email),
49    ]
50}
51
52/// The slug's whole identity on an env built outside
53/// `build_persistent_spawn_env` (an ACP or App Server spawn, the agent's Shell
54/// and PTY shell): `AGENTMUX_AGENT_SLUG`, then [`carry_agent_identity_env`].
55pub(crate) fn carry_slug_identity_env(env_vars: &mut HashMap<String, String>, slug: &str) {
56    super::block_identity::split_agent_identity_env(env_vars, "", Some(slug));
57    carry_agent_identity_env(env_vars, "", Some(slug));
58}
59
60/// The definition's slug for the agent on `block_id`, if its row has one.
61/// For an env built from the agent's stored `cmd:env` outside a spawn, so
62/// it skips the token mint and key ensure a spawn's lookup does. A store
63/// error reads as no slug.
64pub fn block_agent_slug(mstore: &crate::backend::storage::store::Store, block_id: &str) -> Option<String> {
65    let instance = mstore.instance_get_active_for_block(block_id).ok().flatten()?;
66    let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
67    Some(def.slug).filter(|s| !s.trim().is_empty())
68}
69
70/// [`carry_slug_identity_env`] for the agent on `block_id`; nothing for a
71/// block with no row slug.
72pub fn carry_block_slug_identity_env(
73    mstore: &crate::backend::storage::store::Store,
74    block_id: &str,
75    env_vars: &mut HashMap<String, String>,
76) {
77    if let Some(slug) = block_agent_slug(mstore, block_id) {
78        carry_slug_identity_env(env_vars, &slug);
79    }
80}
81
82/// The identity an agent's PtyShell child carries, as its `cmd:env`, from
83/// the agent's env after [`carry_slug_identity_env`]: its slug and git
84/// identity, so a commit typed there is the agent's. Deliberately not
85/// `AGENTMUX_AGENT_ID` or `MUXBUS_AGENT_ID`: those are the agent's address, and
86/// an interactive shell exporting `AGENTMUX_AGENT_ID` reports it through its
87/// shell integration (OSC 16162 `E`), which registers that pane as the agent
88/// for message delivery (`termagent.ts`), beside the agent's own pane.
89pub fn pty_child_identity_env(agent_env: &HashMap<String, String>) -> serde_json::Map<String, serde_json::Value> {
90    ["AGENTMUX_AGENT_SLUG", "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL"]
91        .into_iter()
92        .filter_map(|k| agent_env.get(k).map(|v| (k.to_string(), serde_json::Value::String(v.clone()))))
93        .collect()
94}
95
96/// The agent's id and git identity: [`carry_agent_id_env`], then
97/// [`carry_git_identity_env`] with the id it replaced.
98pub(crate) fn carry_agent_identity_env(
99    env_vars: &mut HashMap<String, String>,
100    display_name: &str,
101    persisted_slug: Option<&str>,
102) {
103    let replaced = carry_agent_id_env(env_vars, display_name, persisted_slug);
104    carry_git_identity_env(env_vars, replaced.as_deref());
105}
106
107/// `AGENTMUX_AGENT_ID` and its `MUXBUS_AGENT_ID` mirror. It is the
108/// canonical, app-wide agent-identity variable (MCP tool routing, native
109/// memory, shell OSC titling, jekt auto-registration, gh-agent; see this
110/// repo's CLAUDE.md Naming Conventions table). With a row slug it is that
111/// slug, overriding `cmd:env` (P0.3, see the module doc): the slug is what
112/// every launch path sets and what the name-keyed signing keys are filed
113/// under (identity M4d, `agent_self_keys.rs`). Without one, a `cmd:env` value
114/// is kept, and a pane with no row (quick launch) falls back to its display
115/// name as a route name, since a name that isn't a valid agent id (a fork's
116/// "Loap #3") fails every registration
117/// (REPORT_FORK_AGENT_ISOLATION_2026_10_12.md F3). `MUXBUS_AGENT_ID` mirrors
118/// it so muxbus-client picks it up under the prefix it checks first; scoped to
119/// that one hand-off point, not a second source of truth (ARCH-002).
120///
121/// Returns the `cmd:env` `AGENTMUX_AGENT_ID` the slug replaced, if it did.
122pub(crate) fn carry_agent_id_env(
123    env_vars: &mut HashMap<String, String>,
124    display_name: &str,
125    persisted_slug: Option<&str>,
126) -> Option<String> {
127    if let Some(slug) = persisted_slug.map(str::trim).filter(|s| !s.is_empty()) {
128        let replaced = set_server_value(env_vars, "AGENTMUX_AGENT_ID", slug);
129        set_server_value(env_vars, "MUXBUS_AGENT_ID", slug);
130        return replaced;
131    }
132    if !env_vars.contains_key("AGENTMUX_AGENT_ID") && !display_name.trim().is_empty() {
133        env_vars.insert("AGENTMUX_AGENT_ID".to_string(), agentmux_common::slug::agent_route_name(display_name));
134    }
135    if !env_vars.contains_key("MUXBUS_AGENT_ID") {
136        if let Some(agent_id) = env_vars.get("AGENTMUX_AGENT_ID").cloned() {
137            env_vars.insert("MUXBUS_AGENT_ID".to_string(), agent_id);
138        }
139    }
140    None
141}
142
143/// Set `key` to the server's `value`, logging when that changes what
144/// `cmd:env` carried. Returns the replaced value.
145fn set_server_value(env_vars: &mut HashMap<String, String>, key: &str, value: &str) -> Option<String> {
146    let previous = env_vars.insert(key.to_string(), value.to_string());
147    let replaced = previous.filter(|p| !p.trim().is_empty() && p != value)?;
148    tracing::info!(key, cmd_env = %replaced, server = %value, "spawn env: persisted identity differs from the definition; the definition's wins");
149    Some(replaced)
150}
151
152/// The git identity: each of [`git_identity_env_vars`] that `cmd:env` lacks
153/// is set from `AGENTMUX_AGENT_ID`. One it carries is the user's to keep,
154/// unless it names `replaced`, the stale id [`carry_agent_id_env`] overrode:
155/// a name equal to it, or an email whose local part is it (the launch writes
156/// `<slug>@agents.local`), is rewritten to the current id, keeping the email's
157/// domain.
158pub(crate) fn carry_git_identity_env(env_vars: &mut HashMap<String, String>, replaced: Option<&str>) {
159    let Some(agent_id) = env_vars.get("AGENTMUX_AGENT_ID").cloned() else {
160        return;
161    };
162    for (key, value) in git_identity_env_vars(&agent_id) {
163        let Some(existing) = env_vars.get(key) else {
164            env_vars.insert(key.to_string(), value);
165            continue;
166        };
167        let Some(stale) = replaced else { continue };
168        let rewritten = match existing.split_once('@') {
169            Some((local, domain)) if key.ends_with("_EMAIL") && local.eq_ignore_ascii_case(stale) => {
170                format!("{}@{domain}", agent_id.to_lowercase())
171            }
172            _ if existing == stale => agent_id.clone(),
173            _ => continue,
174        };
175        set_server_value(env_vars, key, &rewritten);
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::{carry_agent_id_env, carry_agent_identity_env, git_identity_env_vars};
182    use std::collections::HashMap;
183
184    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
185        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
186    }
187
188    /// With no `AGENTMUX_AGENT_ID` in `cmd:env`, the row's slug: what the
189    /// launch sets and the signing keys are filed under. A fork's display
190    /// name is never used when the row is known.
191    #[test]
192    fn a_missing_agent_id_is_the_rows_slug() {
193        let mut e = env(&[]);
194        carry_agent_id_env(&mut e, "Loap #3", Some("loap-loap-2-loap-3"));
195        assert_eq!(e["AGENTMUX_AGENT_ID"], "loap-loap-2-loap-3");
196        assert_eq!(e["MUXBUS_AGENT_ID"], "loap-loap-2-loap-3");
197    }
198
199    /// A pane with no row (quick launch) falls back to its display name, as
200    /// a valid id: "Loap #3" used to fail every registration.
201    #[test]
202    fn a_rowless_panes_agent_id_is_its_route_name() {
203        let mut e = env(&[]);
204        carry_agent_id_env(&mut e, "Loap #3", None);
205        assert_eq!(e["AGENTMUX_AGENT_ID"], "Loap-3");
206        let mut plain = env(&[]);
207        carry_agent_id_env(&mut plain, "AgentY", None);
208        assert_eq!(plain["AGENTMUX_AGENT_ID"], "AgentY", "a valid name keeps its casing");
209        let mut none = env(&[]);
210        carry_agent_id_env(&mut none, "  ", None);
211        assert!(!none.contains_key("AGENTMUX_AGENT_ID"));
212    }
213
214    /// With no row slug, a launch's own value wins, and its mirror is kept.
215    #[test]
216    fn without_a_slug_a_carried_agent_id_is_kept() {
217        let mut e = env(&[("AGENTMUX_AGENT_ID", "agenty-2"), ("MUXBUS_AGENT_ID", "bus-y")]);
218        assert_eq!(carry_agent_id_env(&mut e, "AgentY", None), None);
219        assert_eq!(e["AGENTMUX_AGENT_ID"], "agenty-2");
220        assert_eq!(e["MUXBUS_AGENT_ID"], "bus-y");
221        let mut blank = env(&[("AGENTMUX_AGENT_ID", "agenty-2")]);
222        carry_agent_id_env(&mut blank, "AgentY", Some("  "));
223        assert_eq!(blank["AGENTMUX_AGENT_ID"], "agenty-2", "a blank slug is no slug");
224    }
225
226    /// P0.3: a persisted `cmd:env` from before a rename loses to the
227    /// definition's slug: the id, its mirror, and the git identity the launch
228    /// derived from the old id. A git identity of the user's own is kept.
229    #[test]
230    fn a_persisted_identity_loses_to_the_definition() {
231        let mut e = env(&[
232            ("AGENTMUX_AGENT_ID", "loap-loap-2-loap-3"),
233            ("MUXBUS_AGENT_ID", "loap-loap-2-loap-3"),
234            ("GIT_AUTHOR_NAME", "Loap #3"),
235            ("GIT_AUTHOR_EMAIL", "loap-loap-2-loap-3@agents.local"),
236            ("GIT_COMMITTER_NAME", "loap-loap-2-loap-3"),
237            ("GIT_COMMITTER_EMAIL", "Loap-Loap-2-Loap-3@agents.local"),
238        ]);
239        carry_agent_identity_env(&mut e, "Loap #3", Some("loap-3"));
240        assert_eq!(e["AGENTMUX_AGENT_ID"], "loap-3");
241        assert_eq!(e["MUXBUS_AGENT_ID"], "loap-3");
242        assert_eq!(e["GIT_AUTHOR_NAME"], "Loap #3", "the display name is not the id");
243        assert_eq!(e["GIT_AUTHOR_EMAIL"], "loap-3@agents.local");
244        assert_eq!(e["GIT_COMMITTER_NAME"], "loap-3");
245        assert_eq!(e["GIT_COMMITTER_EMAIL"], "loap-3@agents.local");
246
247        let mut own = env(&[
248            ("AGENTMUX_AGENT_ID", "old-id"),
249            ("GIT_AUTHOR_NAME", "Jane Doe"),
250            ("GIT_AUTHOR_EMAIL", "jane@example.com"),
251        ]);
252        carry_agent_identity_env(&mut own, "Jane", Some("new-id"));
253        assert_eq!(own["GIT_AUTHOR_NAME"], "Jane Doe");
254        assert_eq!(own["GIT_AUTHOR_EMAIL"], "jane@example.com");
255        assert_eq!(own["GIT_COMMITTER_EMAIL"], "new-id@agentmux.local", "a missing one is filled");
256    }
257
258    /// No row: everything `cmd:env` carries stays, and the gaps are filled
259    /// from its own id, as before.
260    #[test]
261    fn an_agent_with_no_slug_keeps_its_identity() {
262        let mut e = env(&[("AGENTMUX_AGENT_ID", "Korp"), ("GIT_AUTHOR_EMAIL", "korp@agents.local")]);
263        carry_agent_identity_env(&mut e, "Korp", None);
264        assert_eq!(e["AGENTMUX_AGENT_ID"], "Korp");
265        assert_eq!(e["MUXBUS_AGENT_ID"], "Korp");
266        assert_eq!(e["GIT_AUTHOR_EMAIL"], "korp@agents.local");
267        assert_eq!(e["GIT_COMMITTER_EMAIL"], "korp@agentmux.local");
268        assert_eq!(e["GIT_AUTHOR_NAME"], "Korp");
269    }
270
271    /// P0.3 through the store, as a spawn and the agent's Shell build their
272    /// env: the agent's shared definition moved on to `loap-3` while this
273    /// channel's row and the block's persisted `cmd:env` still say the old
274    /// slug. The id, slug, MuxBus id, git email and `GH_CONFIG_DIR` all follow
275    /// the definition. A block with no row keeps its `cmd:env`.
276    #[test]
277    fn a_block_takes_the_definitions_identity_over_its_persisted_env() {
278        use crate::backend::storage::store::Store;
279        let store = Store::open_in_memory().unwrap();
280        let tmp = tempfile::tempdir().unwrap();
281        let defs = std::sync::Arc::new(crate::registry::DefinitionStore::open(tmp.path().join("definitions")).unwrap());
282        store.set_def_registry(defs.clone());
283        let mut def = crate::backend::storage::agents::test_agent_def("uid-p03", "Loap #3", "claude", "host", 1, "");
284        def.slug = "loap-loap-2-loap-3".to_string();
285        store.agent_def_insert(&mut def).unwrap();
286        let mut rec = defs.get("uid-p03").unwrap().unwrap();
287        rec.data.slug = "loap-3".to_string();
288        std::fs::write(defs.root().join("uid-p03.json"), serde_json::to_vec(&rec).unwrap()).unwrap();
289        for (block_id, agent_id) in [("block-p03", "uid-p03"), ("block-p03-none", "claude")] {
290            let mut meta = crate::backend::obj::MetaMapType::new();
291            meta.insert("view".to_string(), serde_json::json!("agent"));
292            meta.insert("agentId".to_string(), serde_json::json!(agent_id));
293            let mut block = crate::backend::obj::Block { oid: block_id.to_string(), meta, ..Default::default() };
294            store.insert(&mut block).unwrap();
295        }
296        let old = "loap-loap-2-loap-3";
297        let stale = env(&[
298            ("AGENTMUX_AGENT_ID", old),
299            ("AGENTMUX_AGENT_SLUG", old),
300            ("MUXBUS_AGENT_ID", old),
301            ("GIT_AUTHOR_EMAIL", "loap-loap-2-loap-3@agents.local"),
302            ("GH_CONFIG_DIR", "/somewhere/gh-loap-loap-2-loap-3"),
303        ]);
304        let home = tempfile::tempdir().unwrap();
305
306        let mut spawn = stale.clone();
307        crate::backend::spawn_env::block_identity::carry_block_identity_env(&store, "block-p03", &mut spawn);
308        let mut shell = stale.clone();
309        super::carry_block_slug_identity_env(&store, "block-p03", &mut shell);
310        for e in [&mut spawn, &mut shell] {
311            crate::backend::gh_guard::apply_gh_guard_in(e, home.path());
312            for key in ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID"] {
313                assert_eq!(e[key], "loap-3", "{key}");
314            }
315            assert_eq!(e["GIT_AUTHOR_EMAIL"], "loap-3@agents.local");
316            assert_eq!(std::path::PathBuf::from(&e["GH_CONFIG_DIR"]), home.path().join("gh-loap-3"));
317        }
318
319        let mut rowless = stale.clone();
320        super::carry_block_slug_identity_env(&store, "block-p03-none", &mut rowless);
321        assert_eq!(rowless, stale, "no row, no slug: cmd:env stays");
322    }
323
324    /// The PtyShell child's `cmd:env` carries the definition's slug and git
325    /// identity, never the stale ones, and not the agent's address.
326    #[test]
327    fn a_pty_child_carries_the_canonical_identity_but_not_the_address() {
328        let mut e = env(&[
329            ("AGENTMUX_AGENT_ID", "loap-loap-2-loap-3"),
330            ("AGENTMUX_AGENT_SLUG", "loap-loap-2-loap-3"),
331            ("GIT_AUTHOR_EMAIL", "loap-loap-2-loap-3@agents.local"),
332        ]);
333        super::carry_slug_identity_env(&mut e, "loap-3");
334        let child = super::pty_child_identity_env(&e);
335        assert_eq!(child["AGENTMUX_AGENT_SLUG"], "loap-3");
336        assert_eq!(child["GIT_AUTHOR_EMAIL"], "loap-3@agents.local");
337        assert_eq!(child["GIT_COMMITTER_EMAIL"], "loap-3@agentmux.local");
338        assert!(!child.contains_key("AGENTMUX_AGENT_ID") && !child.contains_key("MUXBUS_AGENT_ID"));
339    }
340
341    #[test]
342    fn maps_agent_id_to_name_and_placeholder_email() {
343        let vars = git_identity_env_vars("korp");
344        let map: HashMap<&str, String> = vars.into_iter().collect();
345        assert_eq!(map["GIT_AUTHOR_NAME"], "korp");
346        assert_eq!(map["GIT_COMMITTER_NAME"], "korp");
347        assert_eq!(map["GIT_AUTHOR_EMAIL"], "korp@agentmux.local");
348        assert_eq!(map["GIT_COMMITTER_EMAIL"], "korp@agentmux.local");
349    }
350
351    #[test]
352    fn lowercases_email_but_preserves_display_name_casing() {
353        // AGENTMUX_AGENT_ID is natural display casing (e.g. "Korp", per
354        // SPEC_PR_TITLE_AGENT_HOST_PREFIX_2026_08_22.md's distinction
355        // between the tag's lowercase machine-key and the title's natural
356        // casing) -- the git *name* field should read naturally too, but
357        // the email's local-part must stay lowercase so it can never
358        // collide with a differently-cased but same agent (git/GitHub
359        // treat email local-parts as effectively case-sensitive strings
360        // for linking purposes; we want exactly one canonical email per
361        // agent regardless of what casing happened to be in the block's
362        // agentName metadata at spawn time).
363        let vars = git_identity_env_vars("Korp");
364        let map: HashMap<&str, String> = vars.into_iter().collect();
365        assert_eq!(map["GIT_AUTHOR_NAME"], "Korp");
366        assert_eq!(map["GIT_AUTHOR_EMAIL"], "korp@agentmux.local");
367    }
368
369    #[test]
370    fn distinct_agents_get_distinct_non_colliding_identities() {
371        let a = git_identity_env_vars("agenty");
372        let b = git_identity_env_vars("smike");
373        let a_map: HashMap<&str, String> = a.into_iter().collect();
374        let b_map: HashMap<&str, String> = b.into_iter().collect();
375        assert_ne!(a_map["GIT_AUTHOR_EMAIL"], b_map["GIT_AUTHOR_EMAIL"]);
376        assert_ne!(a_map["GIT_AUTHOR_NAME"], b_map["GIT_AUTHOR_NAME"]);
377    }
378
379    #[test]
380    fn email_domain_is_not_a_real_github_verifiable_domain() {
381        // Load-bearing for the fix's safety property: this must NOT be a
382        // domain GitHub could ever link to a real account (see the
383        // git_identity_env_vars doc comment) -- asserting the exact
384        // domain here so a future edit can't accidentally change it to
385        // something real (e.g. "users.noreply.github.com") without this
386        // test catching it.
387        let vars = git_identity_env_vars("camper");
388        let map: HashMap<&str, String> = vars.into_iter().collect();
389        assert!(map["GIT_AUTHOR_EMAIL"].ends_with("@agentmux.local"));
390        assert!(map["GIT_COMMITTER_EMAIL"].ends_with("@agentmux.local"));
391    }
392}