Skip to main content

agentmux_srv_core/registry/
def_schema.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Global **agent-definition** registry file format + per-row validation.
5//!
6//! Sibling of `schema.rs` (which describes the named *instance* record).
7//! This record carries a full agent **definition** so the roster can be
8//! reconstructed from any channel/version without joining the local
9//! channel's SQLite — the foundation of cross-channel agent persistence
10//! (`docs/specs/SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md`, P0.2).
11//!
12//! Layering: the `registry` module must NOT depend on `backend::storage`
13//! (which already depends on `registry` — that would cycle). So the fields
14//! of `AgentDefinition` are mirrored here as a self-contained struct; the
15//! `AgentDefinition <-> DefinitionRecordV1` conversion lives in
16//! `backend::storage` (the dependent side). Bumping
17//! `DEF_MAX_SUPPORTED_SCHEMA` is the additive-evolution path, exactly like
18//! the instance record.
19
20use serde::{Deserialize, Serialize};
21use thiserror::Error;
22
23/// Lowest envelope schema this binary will load. A definition below it is
24/// skipped, not migrated: raise the repo's `UPGRADE_FLOOR` with it, as for
25/// `MIN_SUPPORTED_SCHEMA`.
26pub const DEF_MIN_SUPPORTED_SCHEMA: u32 = 1;
27/// Highest envelope schema this binary will write or read. Bumped per
28/// release that adds fields to the definition payload.
29pub const DEF_MAX_SUPPORTED_SCHEMA: u32 = 1;
30
31/// Serde default for `container_volumes` — preserves the db invariant that
32/// an omitted value is the empty JSON array `"[]"`, not `""` (which would
33/// surface via the read-path overlay). (reagent P2 on #1385.)
34fn default_container_volumes() -> String {
35    "[]".to_string()
36}
37
38/// On-disk envelope for a global agent-definition record. Stored at
39/// `<shared>/agents/definitions/<id>.json`.
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
41pub struct DefinitionRecord {
42    pub schema_version: u32,
43    pub data: DefinitionRecordV1,
44}
45
46/// A content blob (system prompt / mcp / env / soul / startup) attached to
47/// a definition — mirrors a `db_agent_content` row. Carried in the global
48/// record so a cross-channel agent launches with its instructions even
49/// though `db_agent_content` is per-version. (codex P1 on #1384.)
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
51pub struct DefContentBlob {
52    pub content_type: String,
53    pub content: String,
54}
55
56/// A skill attached to a definition — mirrors a `db_agent_skills` row.
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
58pub struct DefSkillBlob {
59    pub id: String,
60    pub name: String,
61    #[serde(default)]
62    pub trigger: String,
63    #[serde(default)]
64    pub skill_type: String,
65    #[serde(default)]
66    pub description: String,
67    #[serde(default)]
68    pub content: String,
69}
70
71/// A slug a definition answered to before a rename. Only the shared record
72/// carries these (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` §4); `retired_at`
73/// is epoch ms, like the record's other timestamps.
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
75pub struct FormerSlug {
76    pub slug: String,
77    #[serde(default)]
78    pub retired_at: i64,
79}
80
81/// An agent's seat: its role, whom it reports to and what it owns
82/// (`SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md` §2). Set by the operator
83/// (`agent.setSeat`) or by an agent (`Agents set_seat`); `backend::agent_seat` validates it. Every field but
84/// `role` is optional, and `role` is kept as text, so a seat written by a
85/// newer build with a role this one doesn't know still loads.
86#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ts_rs::TS)]
87#[ts(export, export_to = "../../../frontend/types/rpc/")]
88pub struct AgentSeat {
89    #[serde(default)]
90    #[ts(type = r#""leader" | "worker" | "specialist" | "platform_tester" | "analyst" | "super""#)]
91    pub role: String,
92    /// Shown after the role, e.g. "product".
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    #[ts(optional)]
95    pub qualifier: Option<String>,
96    /// The lead's agent uid; absent means the agent reports to the operator.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    #[ts(optional)]
99    pub lead: Option<String>,
100    /// One line: what the agent owns.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    #[ts(optional)]
103    pub area: Option<String>,
104    /// Reserved for the organization's lanes; not shown yet.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    #[ts(optional)]
107    pub lane: Option<String>,
108    /// The role this agent had before it became the super agent: what it goes
109    /// back to when another agent takes the seat. Absent otherwise.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    #[ts(optional)]
112    pub prior_role: Option<String>,
113    /// When the operator last set it (epoch ms). `0` on an effective seat,
114    /// one computed for a spawned worker and never stored.
115    #[serde(default)]
116    #[ts(type = "number")]
117    pub set_at_ms: i64,
118}
119
120/// `DefinitionRecordV1::seat`'s reader: a seat this build can't read is
121/// dropped (logged) rather than failing the whole record, which would take
122/// the agent off the roster.
123fn lenient_seat<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<AgentSeat>, D::Error> {
124    let raw = Option::<serde_json::Value>::deserialize(d)?;
125    Ok(raw.and_then(|v| match serde_json::from_value::<AgentSeat>(v) {
126        Ok(seat) => Some(seat),
127        Err(e) => {
128            tracing::warn!(error = %e, "def registry: unreadable seat ignored");
129            None
130        }
131    }))
132}
133
134/// That an agent was handed to another computer (spec `SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER_2026_11_24.md` section 5).
135/// While it is set, no start path on any instance sharing this record launches the agent: the one admission gate every
136/// start passes through refuses and says where the agent went.
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
138pub struct Handover {
139    /// [`Handover::HANDED_OVER`] (stopped here, on its way) or [`Handover::MOVED`] (final: it lives there now). Kept as text
140    /// so a state a newer build writes still loads, and still refuses a start.
141    #[serde(default)]
142    pub state: String,
143    /// Where it went: a computer's name, or `a file` when it was saved to one.
144    #[serde(default)]
145    pub to: String,
146    /// When it was marked (epoch ms).
147    #[serde(default)]
148    pub at_ms: i64,
149    /// The hash of the archive's manifest that was handed over, so a later `bring_back` or `resume` can tell which one.
150    #[serde(default)]
151    pub manifest_hash: String,
152}
153
154impl Handover {
155    pub const HANDED_OVER: &'static str = "handed_over";
156    pub const MOVED: &'static str = "moved";
157}
158
159/// `DefinitionRecordV1::handover`'s reader: a mark this build can't read is still a mark, so it is kept as a
160/// `handed_over` to nowhere rather than dropped: an unreadable mark must never become permission to start the agent.
161fn lenient_handover<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Handover>, D::Error> {
162    let raw = Option::<serde_json::Value>::deserialize(d)?;
163    Ok(raw.map(|v| match serde_json::from_value::<Handover>(v) {
164        Ok(h) if !h.state.is_empty() => h,
165        _ => {
166            tracing::warn!("def registry: unreadable hand-over mark kept as a refusal to start");
167            Handover { state: Handover::HANDED_OVER.to_string(), ..Handover::default() }
168        }
169    }))
170}
171
172/// v1 definition payload — a faithful mirror of `AgentDefinition`'s
173/// columns, PLUS the per-definition content + skills blobs (which live in
174/// separate per-version tables and must travel with the definition for a
175/// cross-channel agent to launch with its instructions). New fields go
176/// here under `#[serde(default)]` (so older files still deserialize)
177/// paired with a `DEF_MAX_SUPPORTED_SCHEMA` bump.
178#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
179pub struct DefinitionRecordV1 {
180    pub id: String,
181    #[serde(default)]
182    pub slug: String,
183    pub name: String,
184    #[serde(default)]
185    pub icon: String,
186    pub provider: String,
187    #[serde(default)]
188    pub description: String,
189    #[serde(default)]
190    pub working_directory: String,
191    #[serde(default)]
192    pub shell: String,
193    #[serde(default)]
194    pub provider_flags: String,
195    #[serde(default)]
196    pub auto_start: i64,
197    #[serde(default)]
198    pub restart_on_crash: i64,
199    #[serde(default)]
200    pub idle_timeout_minutes: i64,
201    #[serde(default)]
202    pub created_at: i64,
203    #[serde(default)]
204    pub agent_type: String,
205    #[serde(default)]
206    pub environment: String,
207    #[serde(default)]
208    pub agent_bus_id: String,
209    #[serde(default)]
210    pub is_seeded: i64,
211    #[serde(default)]
212    pub accounts: String,
213    #[serde(default)]
214    pub parent_id: String,
215    #[serde(default)]
216    pub branch_label: String,
217    #[serde(default)]
218    pub updated_at: i64,
219    #[serde(default)]
220    pub user_hidden: i64,
221    #[serde(default)]
222    pub container_image: String,
223    #[serde(default = "default_container_volumes")]
224    pub container_volumes: String,
225    #[serde(default)]
226    pub container_name: String,
227    /// Explicit per-agent opt-in to the CLI's global (ambient) login when
228    /// no oauth-class account resolves at spawn (mirrors the SQLite v12
229    /// column — SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md §2.3).
230    /// Additive under `#[serde(default)]` (older files read as 0 =
231    /// fail-by-default; older binaries ignore the extra field), same as
232    /// the container_* fields — no envelope bump.
233    #[serde(default)]
234    pub use_ambient_login: i64,
235    /// The slugs this agent had before its current one, oldest first. Never
236    /// shortened: `DefinitionStore::upsert` keeps every entry already on disk,
237    /// and a mirror write can't put one of them back as `slug` (see
238    /// `merge_for_write`). Omitted when empty, so a writer that doesn't know
239    /// the field leaves the file's copy alone (`merge_known`); additive like
240    /// `use_ambient_login`, no envelope bump.
241    #[serde(default, skip_serializing_if = "Vec::is_empty")]
242    pub former_slugs: Vec<FormerSlug>,
243    /// The agent's seat (`SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md` §2).
244    /// Only `DefinitionStore::set_seat` writes or removes it: the mirror
245    /// writes leave it out, so `merge_for_write` keeps the file's copy, as it
246    /// does for a writer that doesn't know the field. Additive like
247    /// `former_slugs`, no envelope bump.
248    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "lenient_seat")]
249    pub seat: Option<AgentSeat>,
250    /// Set while the agent is handed over to another computer. Only `DefinitionStore::set_handover` writes or removes it:
251    /// the mirror writes leave it out, so `merge_for_write` keeps the file's copy, as it does for the seat.
252    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "lenient_handover")]
253    pub handover: Option<Handover>,
254    /// System-prompt / mcp / env / soul / startup blobs (db_agent_content),
255    /// embedded so a cross-channel agent launches with its instructions.
256    #[serde(default)]
257    pub content: Vec<DefContentBlob>,
258    /// Skills (db_agent_skills) attached to this definition.
259    #[serde(default)]
260    pub skills: Vec<DefSkillBlob>,
261}
262
263#[derive(Debug, Error)]
264pub enum DefValidationError {
265    #[error("schema_version {version} outside supported [{min}, {max}]")]
266    UnsupportedSchema { version: u32, min: u32, max: u32 },
267    #[error("filename {filename:?} does not match data.id {id:?}")]
268    IdMismatch { filename: String, id: String },
269    #[error("required field missing: {0}")]
270    MissingField(&'static str),
271}
272
273/// Per-row validation. Mirrors `schema::validate`: reject anything that
274/// would surface a malformed definition to the roster. Failures are
275/// skipped (not auto-fixed), logged, and the file stays on disk for ops
276/// triage.
277pub fn validate(filename_stem: &str, rec: &DefinitionRecord) -> Result<(), DefValidationError> {
278    if rec.schema_version < DEF_MIN_SUPPORTED_SCHEMA || rec.schema_version > DEF_MAX_SUPPORTED_SCHEMA
279    {
280        return Err(DefValidationError::UnsupportedSchema {
281            version: rec.schema_version,
282            min: DEF_MIN_SUPPORTED_SCHEMA,
283            max: DEF_MAX_SUPPORTED_SCHEMA,
284        });
285    }
286    let d = &rec.data;
287    if d.id.is_empty() {
288        return Err(DefValidationError::MissingField("id"));
289    }
290    if d.id != filename_stem {
291        return Err(DefValidationError::IdMismatch {
292            filename: filename_stem.to_string(),
293            id: d.id.clone(),
294        });
295    }
296    if d.name.is_empty() {
297        return Err(DefValidationError::MissingField("name"));
298    }
299    if d.provider.is_empty() {
300        return Err(DefValidationError::MissingField("provider"));
301    }
302    Ok(())
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    fn rec(id: &str) -> DefinitionRecord {
310        DefinitionRecord {
311            schema_version: 1,
312            data: DefinitionRecordV1 {
313                id: id.to_string(),
314                slug: id.to_string(),
315                name: "Demo".to_string(),
316                icon: "✦".to_string(),
317                provider: "claude".to_string(),
318                description: String::new(),
319                working_directory: String::new(),
320                shell: String::new(),
321                provider_flags: String::new(),
322                auto_start: 0,
323                restart_on_crash: 0,
324                idle_timeout_minutes: 0,
325                created_at: 1,
326                agent_type: "host".to_string(),
327                environment: String::new(),
328                agent_bus_id: String::new(),
329                is_seeded: 0,
330                accounts: String::new(),
331                parent_id: String::new(),
332                branch_label: String::new(),
333                updated_at: 1,
334                user_hidden: 0,
335                container_image: String::new(),
336                container_volumes: "[]".to_string(),
337                container_name: String::new(),
338                use_ambient_login: 0,
339                former_slugs: Vec::new(),
340                seat: None,
341                handover: None,
342                content: Vec::new(),
343                skills: Vec::new(),
344            },
345        }
346    }
347
348    /// `former_slugs` is optional both ways: a file without it reads as
349    /// empty, and an empty list isn't written, so an older reader sees the
350    /// same file it always did.
351    #[test]
352    fn former_slugs_default_empty_and_round_trip() {
353        let raw = serde_json::json!({
354            "schema_version": 1,
355            "data": { "id": "abc", "name": "Demo", "provider": "claude" }
356        });
357        let parsed: DefinitionRecord = serde_json::from_value(raw).unwrap();
358        assert!(parsed.data.former_slugs.is_empty());
359        let written = serde_json::to_value(&parsed).unwrap();
360        assert!(written.pointer("/data/former_slugs").is_none(), "an empty list is not written");
361
362        let mut r = rec("abc");
363        r.data.former_slugs = vec![FormerSlug { slug: "loap-loap-2".into(), retired_at: 7 }];
364        let back: DefinitionRecord = serde_json::from_value(serde_json::to_value(&r).unwrap()).unwrap();
365        assert_eq!(back, r);
366    }
367
368    /// A seat round-trips; a record from before seats reads as none and is
369    /// written without the key; a seat this build can't read is dropped
370    /// without losing the record.
371    #[test]
372    fn seat_round_trips_and_defaults_to_none() {
373        let raw = serde_json::json!({
374            "schema_version": 1,
375            "data": { "id": "abc", "name": "Demo", "provider": "claude" }
376        });
377        let parsed: DefinitionRecord = serde_json::from_value(raw).unwrap();
378        assert!(parsed.data.seat.is_none());
379        assert!(serde_json::to_value(&parsed).unwrap().pointer("/data/seat").is_none());
380
381        let mut r = rec("abc");
382        r.data.seat = Some(AgentSeat {
383            role: "leader".into(),
384            qualifier: Some("product".into()),
385            lead: None,
386            area: Some("agent pane".into()),
387            lane: None,
388            prior_role: None,
389            set_at_ms: 7,
390        });
391        let written = serde_json::to_value(&r).unwrap();
392        assert_eq!(written.pointer("/data/seat/role"), Some(&serde_json::json!("leader")));
393        assert!(written.pointer("/data/seat/lead").is_none(), "an absent lead is not written");
394        let back: DefinitionRecord = serde_json::from_value(written).unwrap();
395        assert_eq!(back, r);
396
397        // A role this build doesn't know still loads (seats inform, a newer
398        // build may add roles); a seat of the wrong shape is dropped.
399        let newer = serde_json::json!({
400            "schema_version": 1,
401            "data": { "id": "abc", "name": "Demo", "provider": "claude", "seat": { "role": "reviewer", "set_at_ms": 1 } }
402        });
403        let parsed: DefinitionRecord = serde_json::from_value(newer).unwrap();
404        assert_eq!(parsed.data.seat.map(|s| s.role).as_deref(), Some("reviewer"));
405        let broken = serde_json::json!({
406            "schema_version": 1,
407            "data": { "id": "abc", "name": "Demo", "provider": "claude", "seat": "leader" }
408        });
409        let parsed: DefinitionRecord = serde_json::from_value(broken).unwrap();
410        assert!(parsed.data.seat.is_none());
411        assert_eq!(parsed.data.name, "Demo");
412    }
413
414    #[test]
415    fn happy_path() {
416        validate("abc", &rec("abc")).unwrap();
417    }
418
419    #[test]
420    fn unsupported_schema_is_rejected() {
421        let mut r = rec("abc");
422        r.schema_version = 999;
423        assert!(matches!(
424            validate("abc", &r).unwrap_err(),
425            DefValidationError::UnsupportedSchema { .. }
426        ));
427    }
428
429    #[test]
430    fn filename_mismatch_is_rejected() {
431        assert!(matches!(
432            validate("xyz", &rec("abc")).unwrap_err(),
433            DefValidationError::IdMismatch { .. }
434        ));
435    }
436
437    #[test]
438    fn missing_name_is_rejected() {
439        let mut r = rec("abc");
440        r.data.name = String::new();
441        assert!(matches!(
442            validate("abc", &r).unwrap_err(),
443            DefValidationError::MissingField("name")
444        ));
445    }
446
447    #[test]
448    fn missing_provider_is_rejected() {
449        let mut r = rec("abc");
450        r.data.provider = String::new();
451        assert!(matches!(
452            validate("abc", &r).unwrap_err(),
453            DefValidationError::MissingField("provider")
454        ));
455    }
456
457    #[test]
458    fn unknown_fields_survive_round_trip() {
459        // A future field this binary doesn't know must deserialize cleanly
460        // (serde ignores unknown keys) so a newer writer's record still loads.
461        let raw = serde_json::json!({
462            "schema_version": 1,
463            "data": {
464                "id": "abc", "name": "Demo", "provider": "claude",
465                "future_field": "ignored"
466            }
467        });
468        let parsed: DefinitionRecord = serde_json::from_value(raw).unwrap();
469        assert_eq!(parsed.data.id, "abc");
470        assert_eq!(parsed.data.provider, "claude");
471        // Defaulted field absent from JSON now uses the "[]" db invariant.
472        assert_eq!(parsed.data.container_volumes, "[]");
473    }
474}