Skip to main content

agentmux_srv_core/backend/
agent_seat.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent seats: an agent's role, the agent it reports to (its lead) and what
5//! it owns (its area), `SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md`.
6//!
7//! A seat is stored on the agent's shared definition record
8//! (`DefinitionRecordV1::seat`), set by the operator through `agent.setSeat`
9//! or by an agent through `Agents set_seat` (`app_api/agent_seats.rs`). This module holds what reads and writes have in common:
10//! the validation of a new seat (§2), the effective seat of a spawned worker
11//! that has none of its own, and the summary shown in MuxAPI's `Agents list`,
12//! a LAN peer's agent list and My Agents (§4, §5). Seats inform; nothing is
13//! refused because of one.
14
15use std::collections::HashSet;
16
17use crate::backend::rpc_types::{SeatInput, SeatLead, SeatSummary};
18use crate::backend::storage::store::Store;
19use crate::backend::storage::AgentDefinition;
20use crate::registry::AgentSeat;
21
22/// The roles a seat may name, as stored.
23pub const ROLES: [&str; 6] = ["leader", "worker", "specialist", "platform_tester", "analyst", SUPER_ROLE];
24/// The role of the one agent that reviews sensitive operations
25/// (`SPEC_SUPER_AGENT_2026_10_25.md`): at most one in the shared agent roster,
26/// since a seat is stored on the shared definition.
27pub const SUPER_ROLE: &str = "super";
28/// The worker's leader, `{agent, id}`, kept on the worker's definition (agent
29/// content) as well as on its pane, so a worker reopened from My Agents, whose
30/// new pane has no `agent:coached_by`, is still a worker: it can't spawn and
31/// still counts toward its leader's limit. srv writes it; `setagentcontent`
32/// refuses it from a client, and a fork of a worker doesn't inherit it.
33pub const WORKER_OF_CONTENT: &str = "agent:worker_of";
34
35/// The leader definition `def_id` is a worker of, if any.
36pub fn worker_of(mstore: &Store, def_id: &str) -> Option<String> {
37    let content = mstore.agent_content_get(def_id, WORKER_OF_CONTENT).ok()??;
38    let value: serde_json::Value = serde_json::from_str(&content.content).ok()?;
39    value.get("id")?.as_str().map(str::to_string)
40}
41
42pub const MAX_QUALIFIER_CHARS: usize = 40;
43pub const MAX_AREA_CHARS: usize = 120;
44/// The spec gives `lane` no limit; it's a short name, like the qualifier.
45pub const MAX_LANE_CHARS: usize = 40;
46/// A lead uid longer than this can't be one srv minted; it's cut, not kept,
47/// when it arrives from a LAN peer.
48const MAX_LEAD_ID_CHARS: usize = 128;
49/// How far [`validate`] follows a chain of leads before calling it a cycle.
50const MAX_CHAIN: usize = 256;
51/// The qualifier of a spawned worker's effective seat.
52pub const SPAWNED_QUALIFIER: &str = "spawned";
53
54/// A lead that is an agent on another machine, `Name@host` as `Agents list` shows it. A uid srv minted
55/// holds no `@`.
56pub fn is_remote_lead(lead: &str) -> bool {
57    lead.contains('@')
58}
59
60/// Whether a seat names its agent this computer's steward: in its qualifier or the line about what it owns.
61/// There is no steward role; the steward is who the machine's own notes go to (a low disk, a flag of the record).
62pub fn is_steward(seat: &AgentSeat) -> bool {
63    [seat.qualifier.as_deref(), seat.area.as_deref()].into_iter().flatten().any(|t| t.to_ascii_lowercase().contains("steward"))
64}
65
66/// Whether `role` is one a seat may name.
67pub fn is_role(role: &str) -> bool {
68    ROLES.contains(&role)
69}
70
71/// `text` on one line: trimmed, every run of whitespace (newlines included)
72/// one space, control characters dropped. `None` when nothing is left.
73fn one_line(text: Option<&str>) -> Option<String> {
74    let cleaned: String = text?
75        .split_whitespace()
76        .collect::<Vec<_>>()
77        .join(" ")
78        .chars()
79        .filter(|c| !c.is_control())
80        .collect();
81    (!cleaned.is_empty()).then_some(cleaned)
82}
83
84fn within(field: &str, value: Option<String>, max: usize) -> Result<Option<String>, String> {
85    match value {
86        Some(v) if v.chars().count() > max => Err(format!("INVALID_ARG: {field} is at most {max} characters (got {})", v.chars().count())),
87        v => Ok(v),
88    }
89}
90
91/// Validate the seat the operator asks for on agent `agent_id`, and stamp it
92/// with `now_ms` (§2). `is_agent` says whether a uid is an agent on this
93/// machine; `lead_of` gives an agent's current lead (its effective seat's),
94/// which is how a cycle is found: following leads from the new lead must not
95/// come back to `agent_id`.
96///
97/// A lead is an agent this machine has a definition for, or one on another machine
98/// (`Name@host`, [`is_remote_lead`]), which the caller has already checked against the LAN
99/// directory and says so through `is_agent`: a peer lists agents by name, so there is no uid here
100/// to check it against.
101pub fn validate(
102    agent_id: &str,
103    input: &SeatInput,
104    now_ms: i64,
105    is_agent: impl Fn(&str) -> bool,
106    lead_of: impl Fn(&str) -> Option<String>,
107) -> Result<AgentSeat, String> {
108    let role = input.role.trim();
109    if !is_role(role) {
110        return Err(format!("INVALID_ARG: unknown role '{role}'; one of: {}", ROLES.join(", ")));
111    }
112    let qualifier = within("qualifier", one_line(input.qualifier.as_deref()), MAX_QUALIFIER_CHARS)?;
113    let area = within("area", one_line(input.area.as_deref()), MAX_AREA_CHARS)?;
114    let lane = within("lane", one_line(input.lane.as_deref()), MAX_LANE_CHARS)?;
115    let lead = input.lead.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(str::to_string);
116    if let Some(lead) = &lead {
117        if lead == agent_id {
118            return Err("INVALID_ARG: an agent can't be its own lead".to_string());
119        }
120        if !is_agent(lead) {
121            return Err(format!("INVALID_ARG: lead {lead} is not an agent on this machine"));
122        }
123        no_cycle(agent_id, lead, lead_of)?;
124    }
125    Ok(AgentSeat { role: role.to_string(), qualifier, lead, area, lane, prior_role: None, set_at_ms: now_ms })
126}
127
128/// Refuse `lead` as `agent_id`'s lead when following leads from it comes
129/// back to `agent_id`. Also checked when a spawned worker's seat is cleared:
130/// its leader becomes its lead again.
131pub fn no_cycle(agent_id: &str, lead: &str, lead_of: impl Fn(&str) -> Option<String>) -> Result<(), String> {
132    let mut seen = HashSet::new();
133    let mut next = Some(lead.to_string());
134    while let Some(id) = next {
135        if id == agent_id {
136            return Err(format!("INVALID_ARG: {lead} already reports to this agent, so it can't be its lead (a cycle)"));
137        }
138        if !seen.insert(id.clone()) || seen.len() > MAX_CHAIN {
139            // A cycle above this agent, already stored: not this seat's.
140            break;
141        }
142        next = lead_of(&id);
143    }
144    Ok(())
145}
146
147/// The seat a definition is shown with: its stored seat, or, for a spawned
148/// worker (`agent:worker_of`) with none, role worker, qualifier "spawned"
149/// and its leader as lead (§2). Computed when read, never stored; a seat the
150/// operator sets wins. `def.seat` must be the stored one, as
151/// `agent_def_list` reads it.
152pub fn effective_seat(mstore: &Store, def: &AgentDefinition) -> Option<AgentSeat> {
153    if def.seat.is_some() {
154        return def.seat.clone();
155    }
156    if def.is_seeded != 0 {
157        return None;
158    }
159    spawned_seat(worker_of(mstore, &def.id))
160}
161
162/// The effective seat of a worker of `leader`, if any.
163fn spawned_seat(leader: Option<String>) -> Option<AgentSeat> {
164    leader.map(|leader| AgentSeat {
165        role: "worker".to_string(),
166        qualifier: Some(SPAWNED_QUALIFIER.to_string()),
167        lead: Some(leader),
168        ..Default::default()
169    })
170}
171
172/// [`effective_seat`] by uid, for a reader that has no definition list: the
173/// stored seat from the shared record, else the spawned one.
174pub fn effective_seat_by_id(mstore: &Store, id: &str) -> Option<AgentSeat> {
175    mstore
176        .agent_seat_get(id)
177        .or_else(|| spawned_seat(worker_of(mstore, id)))
178}
179
180/// The uid of the agent whose stored seat is the super agent's, if any.
181pub fn super_holder(mstore: &Store, defs: &[AgentDefinition]) -> Option<String> {
182    defs.iter()
183        .filter(|d| d.is_seeded == 0)
184        .find(|d| mstore.agent_seat_get(&d.id).is_some_and(|s| s.role == SUPER_ROLE))
185        .map(|d| d.id.clone())
186}
187
188/// Give every definition in `defs` (as `agent_def_list` returns them) its
189/// effective seat.
190pub fn apply_effective_seats(mstore: &Store, defs: &mut [AgentDefinition]) {
191    for def in defs.iter_mut() {
192        if def.seat.is_none() {
193            def.seat = effective_seat(mstore, def);
194        }
195    }
196}
197
198/// A seat as shown, with its lead's name from `name_of` (§4).
199pub fn summarize(seat: &AgentSeat, name_of: impl Fn(&str) -> Option<String>) -> SeatSummary {
200    SeatSummary {
201        role: seat.role.clone(),
202        qualifier: seat.qualifier.clone(),
203        // A lead on another machine is named as it was set: "AgentY@narko".
204        lead: seat.lead.as_ref().map(|id| SeatLead { id: id.clone(), name: name_of(id).or_else(|| is_remote_lead(id).then(|| id.clone())) }),
205        area: seat.area.clone(),
206    }
207}
208
209/// The summary of the seat definition `def_id` is shown with (its effective
210/// seat), its lead named from `defs`. `defs` is `agent_def_list`'s, so each
211/// carries its stored seat. `None` when it has no seat.
212pub fn summary_in(mstore: &Store, defs: &[AgentDefinition], def_id: &str) -> Option<SeatSummary> {
213    let def = defs.iter().find(|d| d.id == def_id)?;
214    let seat = effective_seat(mstore, def)?;
215    Some(summarize(&seat, |id| defs.iter().find(|d| d.id == id).map(|d| d.name.clone())))
216}
217
218/// [`summary_in`] by uid, for a reader that has no definition list. The
219/// list is `agent_def_list`'s, which lays each shared record over the local
220/// row, so a lead renamed in another channel is named as My Agents names it
221/// (`agent_def_get` returns the local row as it is).
222pub fn summary_by_id(mstore: &Store, id: &str) -> Option<SeatSummary> {
223    let defs = mstore.agent_def_list().ok()?;
224    summary_in(mstore, &defs, id)
225}
226
227/// The block meta key an agent pane keeps its agent's seat summary under,
228/// for the pane header's tooltip (§4). Seeded at `agent.open`, as `ui:color`
229/// is, and refreshed by `agent.setSeat` ([`stale_seat_meta`]).
230pub const SEAT_META_KEY: &str = "agent:seat";
231
232/// `agent:seat` as a meta value: the summary, or `null` for none, which a
233/// meta patch reads as "remove the key".
234pub fn seat_meta(summary: Option<&SeatSummary>) -> serde_json::Value {
235    summary.and_then(|s| serde_json::to_value(s).ok()).unwrap_or(serde_json::Value::Null)
236}
237
238/// Put agent `id`'s seat into the meta of a pane being opened for it, when
239/// it has one.
240pub fn seed_meta(mstore: &Store, id: &str, meta: &mut crate::backend::obj::MetaMapType) {
241    if let Some(seat) = summary_by_id(mstore, id) {
242        meta.insert(SEAT_META_KEY.to_string(), seat_meta(Some(&seat)));
243    }
244}
245
246/// The agent panes among `blocks` whose `agent:seat` no longer matches the
247/// seat `summary_of` gives their agent now, each with the value to patch in.
248/// `summary_of` is asked once per agent.
249pub fn stale_seat_meta(
250    blocks: &[crate::backend::obj::Block],
251    mut summary_of: impl FnMut(&str) -> Option<SeatSummary>,
252) -> Vec<(String, serde_json::Value)> {
253    let mut by_agent: std::collections::HashMap<String, serde_json::Value> = std::collections::HashMap::new();
254    let mut stale = Vec::new();
255    for block in blocks {
256        if crate::backend::obj::meta_get_string(&block.meta, "view", "") != "agent" || crate::backend::obj::is_history_reader(&block.meta) {
257            continue;
258        }
259        let agent_id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
260        if agent_id.is_empty() {
261            continue;
262        }
263        let want = by_agent
264            .entry(agent_id.clone())
265            .or_insert_with(|| seat_meta(summary_of(&agent_id).as_ref()))
266            .clone();
267        let have = block.meta.get(SEAT_META_KEY).cloned().unwrap_or(serde_json::Value::Null);
268        if have != want {
269            stale.push((block.oid.clone(), want));
270        }
271    }
272    stale
273}
274
275/// A seat summary a LAN peer sent, made safe to show (§5): a known role
276/// only, each text on one line and within its limit (cut, not refused: the
277/// peer validated it, this only bounds it). `None` when it can't be read.
278pub fn sanitize_peer_summary(value: &serde_json::Value, max_name_chars: usize) -> Option<SeatSummary> {
279    let summary: SeatSummary = serde_json::from_value(value.clone()).ok()?;
280    if !is_role(&summary.role) {
281        return None;
282    }
283    let cut = |text: Option<&str>, max: usize| one_line(text).map(|t| t.chars().take(max).collect::<String>());
284    Some(SeatSummary {
285        role: summary.role,
286        qualifier: cut(summary.qualifier.as_deref(), MAX_QUALIFIER_CHARS),
287        lead: summary.lead.and_then(|l| {
288            let id = cut(Some(&l.id), MAX_LEAD_ID_CHARS)?;
289            Some(SeatLead { id, name: cut(l.name.as_deref(), max_name_chars) })
290        }),
291        area: cut(summary.area.as_deref(), MAX_AREA_CHARS),
292    })
293}
294
295#[cfg(test)]
296#[path = "agent_seat_tests.rs"]
297mod tests;