agentmux_srv_core/backend/
agent_seat.rs1use 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
22pub const ROLES: [&str; 6] = ["leader", "worker", "specialist", "platform_tester", "analyst", SUPER_ROLE];
24pub const SUPER_ROLE: &str = "super";
28pub const WORKER_OF_CONTENT: &str = "agent:worker_of";
34
35pub 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;
44pub const MAX_LANE_CHARS: usize = 40;
46const MAX_LEAD_ID_CHARS: usize = 128;
49const MAX_CHAIN: usize = 256;
51pub const SPAWNED_QUALIFIER: &str = "spawned";
53
54pub fn is_remote_lead(lead: &str) -> bool {
57 lead.contains('@')
58}
59
60pub 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
66pub fn is_role(role: &str) -> bool {
68 ROLES.contains(&role)
69}
70
71fn 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
91pub 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
128pub 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 break;
141 }
142 next = lead_of(&id);
143 }
144 Ok(())
145}
146
147pub 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
162fn 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
172pub 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
180pub 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
188pub 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
198pub 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 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
209pub 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
218pub 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
227pub const SEAT_META_KEY: &str = "agent:seat";
231
232pub 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
238pub 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
246pub 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
275pub 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;