agentmux_srv_core/backend/spawn_env/block_identity.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the spawn environment carries about the agent on a block: the display name and slug, the uid, the workdir.
5
6
7/// Identity M0 — `SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
8/// §9.1: make the display name and the slug two explicit variables, present
9/// on every launch path.
10///
11/// **Why.** `AGENTMUX_AGENT_ID` means two different things depending on who
12/// spawned the agent (spec §0.2): the frontend's `launchAgentDefinition`
13/// writes the definition *slug* into it (`agent-model.ts`), while this
14/// server path's fallback wrote the *display name*
15/// (`block.meta["agentName"]`) until `carry_agent_id_env` (2026-10-12), which
16/// writes the slug too when the row has one. Nothing downstream could tell
17/// which it got. The frontend path already sets
18/// `AGENTMUX_AGENT_DISPLAY` and `AGENTMUX_AGENT_SLUG` alongside it; this
19/// path set neither, so a reader that wanted the unambiguous form had
20/// nothing to read. After this, both are always present when the server
21/// knows them, and later phases can migrate readers off `AGENTMUX_AGENT_ID`
22/// one at a time.
23///
24/// **Precedence.** The server's own knowledge wins, `cmd:env` is the
25/// fallback — the reverse of the "user-provided values take precedence"
26/// rule the surrounding identity variables follow, deliberately:
27///
28/// - `display_name` is `block.meta["agentName"]`, the value the primary
29/// reactive registration is keyed on (see the Register-tail of
30/// `run_agent_turn`) and the name the pane header shows. A `cmd:env` copy
31/// is a launch-time snapshot that a rename (`setViewName`) leaves stale.
32/// - `persisted_slug` is `db_agents.slug` for this block's agent — the
33/// collision-resolved value `agent_def_insert` minted. A `cmd:env` copy is
34/// whatever the frontend computed before that row existed.
35///
36/// When the two disagree it is logged, not silently resolved: a disagreement
37/// is exactly the kind of signal spec §9.2 says a phase must be able to
38/// observe.
39///
40/// **What this does not do.** `AGENTMUX_AGENT_ID` is never read or written
41/// here: `identity_env` sets it, from the same slug when there is one; the
42/// git identity, `MUXBUS_AGENT_ID`, the PR-body tag and the OSC prompt hook
43/// all still derive from it.
44pub fn split_agent_identity_env(
45 env_vars: &mut std::collections::HashMap<String, String>,
46 display_name: &str,
47 persisted_slug: Option<&str>,
48) {
49 let set_authoritative = |env_vars: &mut std::collections::HashMap<String, String>,
50 key: &str,
51 value: &str| {
52 let value = value.trim();
53 if value.is_empty() {
54 return;
55 }
56 if let Some(existing) = env_vars
57 .get(key)
58 .map(|v| v.trim())
59 .filter(|v| !v.is_empty())
60 {
61 if existing != value {
62 tracing::info!(
63 key,
64 cmd_env = %existing,
65 authoritative = %value,
66 "spawn env: cmd:env disagrees with the server's value — server wins (identity M0)"
67 );
68 }
69 }
70 env_vars.insert(key.to_string(), value.to_string());
71 };
72 set_authoritative(env_vars, "AGENTMUX_AGENT_DISPLAY", display_name);
73 if let Some(slug) = persisted_slug {
74 set_authoritative(env_vars, "AGENTMUX_AGENT_SLUG", slug);
75 }
76}
77
78/// `AGENTMUX_AGENT_WORKDIR`: the agent's own workspace, which the host-only
79/// "Your workspace" Operator Config entry tells it to clone and work in
80/// (SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md §3.4).
81/// Server-set, like `AGENTMUX_AUTH_KEY`: it is the launch cwd (`cmd:cwd`),
82/// not user configuration, so a `cmd:env` copy never wins. Host agents only —
83/// a container's cwd is a host path that means nothing inside the image (the
84/// key is host-only in `agent_env_scope`).
85///
86/// Exported as the absolute path the process actually starts in: `~` is
87/// expanded and a relative `cmd:cwd` is resolved against srv's own cwd, as
88/// `core::apply_working_dir` does, so `cd "$AGENTMUX_AGENT_WORKDIR"` works
89/// from anywhere (Codex on #4113).
90pub fn carry_agent_workdir_env(
91 env_vars: &mut std::collections::HashMap<String, String>,
92 block_meta: &crate::backend::obj::MetaMapType,
93) {
94 const KEY: &str = "AGENTMUX_AGENT_WORKDIR";
95 // The MCP config to diagnose, resolved here where srv knows the data root and the cwd. A
96 // pane strips the instance variables the doctor would otherwise need (#47385).
97 const CONFIG_KEY: &str = "AGENTMUX_MCP_CONFIG";
98 let agent_mode = crate::backend::obj::meta_get_string(block_meta, "agentMode", "host");
99 let work_dir = crate::backend::obj::meta_get_string(block_meta, "cmd:cwd", "");
100 if crate::backend::operator_config_seed::agent_kind(&agent_mode) == "host" && !work_dir.trim().is_empty() {
101 let expanded = crate::backend::blockcontroller::core::expand_home_dir(&work_dir);
102 let absolute = std::path::absolute(&expanded).map_or(expanded, |p| p.to_string_lossy().into_owned());
103 env_vars.insert(
104 CONFIG_KEY.to_string(),
105 crate::backend::mcp_config_file::host_config_path(&absolute).to_string_lossy().into_owned(),
106 );
107 env_vars.insert(KEY.to_string(), absolute);
108 } else {
109 env_vars.remove(KEY);
110 // A container's doctor uses the bind-mounted path (`container_config_path`), not a host path.
111 env_vars.remove(CONFIG_KEY);
112 }
113}
114
115/// What the server knows about the agent on a block, read from its
116/// `db_agents` row: the identity that will be carried into the process.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct PersistedAgentIdentity {
119 /// `db_agents.id` — the UID (spec §3). A UUID for every non-template row.
120 pub uid: String,
121 /// `db_agents.slug`, the collision-resolved value `agent_def_insert`
122 /// minted. `None` if the row's slug is empty.
123 pub slug: Option<String>,
124 /// The agent's local identity token (`storage/agent_tokens.rs`), minted
125 /// on first spawn. `None` only if minting failed — logged, and the
126 /// spawn proceeds without it, because M1 has no reader for it yet.
127 pub token: Option<String>,
128 /// The names it had before its renames (`former_names`).
129 pub former: super::former_names::FormerNames,
130}
131
132/// The `db_agents` row for the agent shown on `block_id`, if it has one,
133/// plus that agent's token.
134///
135/// Resolves the block → row the same way the identity injector does
136/// (`identity/resolver/inject.rs`): `block.meta.agentId` first, then the
137/// latest active launch on this block. A quick-launch pane (`launchAgent`
138/// in `agent-model.ts`, whose `agentId` is a provider key like `"claude"`)
139/// has no row and gets `None` — it has no slug or UID in the identity
140/// sense, and deriving either from its display name would recreate the
141/// lossy path spec §1.1 measured as the root defect.
142///
143/// The token is minted here, at spawn, rather than at row creation: every
144/// row that exists today predates the table, so "mint at creation" would
145/// leave them all without one. `agent_token_ensure` is idempotent, so a
146/// row created in the future gets the same token on every spawn.
147///
148/// A store error is logged and treated as "unknown", never as a spawn
149/// failure: this is disambiguation, not a gate, and spec §10 constraint 1
150/// forbids a store read from making a healthy agent unreachable.
151pub fn persisted_agent_identity(
152 mstore: &crate::backend::storage::store::Store,
153 block_id: &str,
154) -> Option<PersistedAgentIdentity> {
155 let instance = match mstore.instance_get_active_for_block(block_id) {
156 Ok(Some(instance)) if !instance.id.trim().is_empty() => instance,
157 Ok(_) => return None,
158 Err(e) => {
159 tracing::warn!(block_id, error = %e, "spawn env: instance lookup failed — no persisted identity from store");
160 return None;
161 }
162 };
163 let slug = match mstore.agent_def_get(&instance.definition_id) {
164 Ok(Some(def)) if !def.slug.trim().is_empty() => Some(def.slug),
165 Ok(_) => None,
166 Err(e) => {
167 tracing::warn!(block_id, error = %e, "spawn env: definition lookup failed — no AGENTMUX_AGENT_SLUG from store");
168 None
169 }
170 };
171 let token = match mstore.agent_token_ensure(&instance.id) {
172 Ok(token) => Some(token),
173 Err(e) => {
174 tracing::warn!(block_id, uid = %instance.id, error = %e, "spawn env: token mint failed — spawning without AGENTMUX_AGENT_TOKEN");
175 None
176 }
177 };
178 // Identity M4d-2: the UID's own signing keys, copied from its name's on
179 // ownership evidence or minted. Only token-carrying spawns get them (the
180 // ones that will sign v2, M4d-6); nothing reads them yet. Like the token,
181 // a store error is logged, never a spawn failure.
182 if token.is_some() {
183 if let Err(e) = mstore.agent_uid_keys_ensure(&instance.id) {
184 tracing::warn!(block_id, uid = %instance.id, error = %e, "spawn env: UID key ensure failed");
185 }
186 }
187 let former = super::former_names::read(mstore, block_id, &instance.id);
188 Some(PersistedAgentIdentity { uid: instance.id, slug, token, former })
189}
190
191/// Identity M1 — spec §9.1: carry the UID and the token into the process.
192///
193/// `AGENTMUX_AGENT_UID` and `AGENTMUX_AGENT_TOKEN` are RESERVED,
194/// server-controlled values in exactly the sense `AGENTMUX_AUTH_KEY` and
195/// `AGENTMUX_BLOCKID` are at the top of `build_persistent_spawn_env`:
196/// unconditional `insert`, never `entry().or_insert()`. A persisted
197/// `cmd:env` carrying a stale value for either — a pane reused for a
198/// different agent, a copied block — must not survive into this spawn, and
199/// for the token specifically a stale value would be *another agent's*
200/// credential. So when the server knows the identity it overwrites, and
201/// when it does not (no row: quick-launch pane, or a lookup failure) it
202/// **removes** both rather than leaving whatever was there.
203///
204/// Spec §4.1: identity is asserted by whoever minted it. The frontend is
205/// not consulted (its `agentInstanceId` is documented as going stale on
206/// pane reuse), and the agent is not asked. The row is the source.
207///
208/// Descendant inheritance is real and not claimed otherwise (spec §6.4):
209/// the agent's own subprocesses — its shell tool, its MCP servers, build
210/// scripts — inherit the token. That is a smaller blast radius than the
211/// instance-wide `AGENTMUX_AUTH_KEY` they already inherit, not zero. The
212/// `.mcp.json` `agent_config.rs` writes into the working directory carries
213/// neither variable (it copies only `AGENTMUX_AGENT_ID`/`_BUS_ID`), so the
214/// token never lands in a file a human may commit.
215pub fn carry_agent_uid_env(
216 env_vars: &mut std::collections::HashMap<String, String>,
217 identity: Option<&PersistedAgentIdentity>,
218) {
219 const UID: &str = "AGENTMUX_AGENT_UID";
220 const TOKEN: &str = "AGENTMUX_AGENT_TOKEN";
221 super::former_names::carry(env_vars, identity.map(|i| &i.former));
222 match identity {
223 Some(id) => {
224 env_vars.insert(UID.to_string(), id.uid.clone());
225 match &id.token {
226 Some(token) => {
227 env_vars.insert(TOKEN.to_string(), token.clone());
228 }
229 None => {
230 env_vars.remove(TOKEN);
231 }
232 }
233 }
234 None => {
235 env_vars.remove(UID);
236 env_vars.remove(TOKEN);
237 }
238 }
239}
240
241/// #3577: the id of the deleted agent `block_id` names, when the block
242/// resolved to no row (`identity` is `None`) and its agent was deleted —
243/// the builder's last-read re-check of the gate's refusal (Codex P1 on
244/// #3591). `None` whenever a row resolved, or the block names nothing
245/// deleted.
246pub fn deleted_agent_of_rowless_block(
247 mstore: &crate::backend::storage::store::Store,
248 block_id: &str,
249 identity: Option<&PersistedAgentIdentity>,
250) -> Option<String> {
251 if identity.is_some() {
252 return None;
253 }
254 crate::identity::resolver::block_agent_id(mstore, block_id)
255 .filter(|agent_id| mstore.agent_was_deleted(agent_id))
256}
257
258/// Identity M4b-2 (spec §6.5.8): carry `block_id`'s row UID and token, and
259/// its slug's identity, into the env of a controller that builds its own (App Server, ACP) instead of
260/// going through `build_persistent_spawn_env`. Same resolution and the
261/// same reserved-value rules as that builder (stale values are overwritten,
262/// or removed when the block has no row). A synchronous store read and an
263/// idempotent token mint, so on a multi-thread runtime worker it runs under
264/// `block_in_place`, as eager resume does (incident #1782).
265pub fn carry_block_identity_env(
266 mstore: &crate::backend::storage::store::Store,
267 block_id: &str,
268 env_vars: &mut std::collections::HashMap<String, String>,
269) {
270 let lookup = || persisted_agent_identity(mstore, block_id);
271 let identity = match tokio::runtime::Handle::try_current() {
272 Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
273 tokio::task::block_in_place(lookup)
274 }
275 _ => lookup(),
276 };
277 carry_agent_uid_env(env_vars, identity.as_ref());
278 // And the row slug's identity over `cmd:env`'s, as on that builder.
279 if let Some(slug) = identity.as_ref().and_then(|i| i.slug.as_deref()) {
280 super::identity::carry_slug_identity_env(env_vars, slug);
281 }
282}