Skip to main content

agentmux_srv_core/registry/
schema.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Registry file format + per-row validation.
5//!
6//! Bumping `MAX_SUPPORTED_SCHEMA` is the additive-evolution path:
7//! readers of the previous bound still skip-and-log new files; old
8//! disk files keep validating because the v1 reader stays intact.
9
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13/// Lowest envelope schema this binary will load. Bumped only with a
14/// deprecation cycle (see SPEC §6). A record below it is skipped, not
15/// migrated, so raising it hides the agents of an install that skipped the
16/// versions in between: raise the repo's `UPGRADE_FLOOR` with it.
17pub const MIN_SUPPORTED_SCHEMA: u32 = 1;
18/// Highest envelope schema this binary will write or read. Bumped
19/// per release that adds fields.
20pub const MAX_SUPPORTED_SCHEMA: u32 = 3;
21
22/// On-disk envelope. The `data` field's shape is gated by
23/// `schema_version`; readers should match on the version before
24/// projecting.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26pub struct NamedAgentRecord {
27    pub schema_version: u32,
28    pub data: NamedAgentRecordV1,
29}
30
31/// v1 payload. Add new optional fields here under `#[serde(default)]`
32/// and bump `MAX_SUPPORTED_SCHEMA` — old readers will skip the new
33/// version, new readers fill defaults for old files.
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35pub struct NamedAgentRecordV1 {
36    pub instance_id: String,
37    pub instance_name: String,
38    pub definition_id: String,
39    /// Legacy Identity-bundle id — `db_identity_bundles` was dropped in
40    /// Phase 4c of SPEC_PRESET_TO_BUNDLE_REFACTOR_2026_07_02.md, so this
41    /// field is now vestigial (opaque pass-through only; credential
42    /// resolution is `db_agent_identity_links`-only). None = unbound
43    /// (no account).
44    pub identity_id: Option<String>,
45    /// FK to `db_bundles.id`. None = unbound (= vanilla CLI).
46    pub memory_id: Option<String>,
47    /// Provider CLI session id for `--resume` (e.g. a Claude Code session
48    /// uuid). `None` = no session wired yet (fresh stub / legacy record).
49    /// Added in schema v2 so a global/migrated record can resume the
50    /// agent's conversation across channels without a current-channel
51    /// SQLite join. Old (v1) files deserialize this as `None`.
52    #[serde(default)]
53    pub session_id: Option<String>,
54    /// Path **relative to [`source_agents_base`]** (or, for legacy records
55    /// without one, the reader's current channel agents dir) — never
56    /// absolute. Keeps the record portable across machines where the home
57    /// dir differs.
58    pub working_dir: String,
59    /// Absolute path of the agents dir that [`working_dir`] is relative to —
60    /// i.e. the channel/dev instance the agent actually lives in
61    /// (`channels/<ch>/agents` or `<dev-instance>/agents`). Added in schema
62    /// v3 (cross-channel persistence P0.4): the registry is global, so a row
63    /// surfaced in a DIFFERENT channel must reconstruct its absolute
64    /// `working_directory` against the SOURCE base, not the reader's current
65    /// channel. `None` for legacy (v1/v2) records — the reader then falls
66    /// back to its current channel agents dir, matching pre-P0.4 behavior.
67    /// Old binaries deserialize this as `None`.
68    #[serde(default)]
69    pub source_agents_base: Option<String>,
70    pub created_at_ms: i64,
71    pub last_launched_at_ms: i64,
72    pub created_by_version: String,
73    pub last_launched_by_version: String,
74}
75
76impl NamedAgentRecordV1 {
77    /// Lowest envelope schema that can faithfully represent this payload.
78    /// Climbs only when a higher-version-only field is populated, so an
79    /// older binary keeps reading records that don't use any newer feature —
80    /// only records that actually need the newer schema are hidden from it.
81    /// Writers should stamp the record with this rather than always using
82    /// `MAX_SUPPORTED_SCHEMA`.
83    ///
84    /// - v3 when `source_agents_base` is set (cross-channel reconstruction)
85    /// - v2 when `session_id` is set (cross-channel resume)
86    /// - v1 otherwise
87    pub fn min_schema_version(&self) -> u32 {
88        if self.source_agents_base.is_some() {
89            3
90        } else if self.session_id.is_some() {
91            2
92        } else {
93            1
94        }
95    }
96}
97
98#[derive(Debug, Error)]
99pub enum ValidationError {
100    #[error("schema_version {version} outside supported [{min}, {max}]")]
101    UnsupportedSchema {
102        version: u32,
103        min: u32,
104        max: u32,
105    },
106    #[error("filename UUID {filename:?} does not match data.instance_id {instance_id:?}")]
107    IdMismatch {
108        filename: String,
109        instance_id: String,
110    },
111    #[error("working_dir {0:?} is not a safe relative subpath of agents/")]
112    UnsafeWorkingDir(String),
113    #[error("required field missing: {0}")]
114    MissingField(&'static str),
115}
116
117/// Per-row validation. Fails fast on anything that would let a
118/// malformed file be returned to the frontend. Validation
119/// failures are skipped (not auto-fixed), logged, and the file stays
120/// on disk for ops triage.
121pub fn validate(filename_stem: &str, rec: &NamedAgentRecord) -> Result<(), ValidationError> {
122    if rec.schema_version < MIN_SUPPORTED_SCHEMA || rec.schema_version > MAX_SUPPORTED_SCHEMA {
123        return Err(ValidationError::UnsupportedSchema {
124            version: rec.schema_version,
125            min: MIN_SUPPORTED_SCHEMA,
126            max: MAX_SUPPORTED_SCHEMA,
127        });
128    }
129    let d = &rec.data;
130    if d.instance_id.is_empty() {
131        return Err(ValidationError::MissingField("instance_id"));
132    }
133    if d.instance_id != filename_stem {
134        return Err(ValidationError::IdMismatch {
135            filename: filename_stem.to_string(),
136            instance_id: d.instance_id.clone(),
137        });
138    }
139    if d.instance_name.is_empty() {
140        return Err(ValidationError::MissingField("instance_name"));
141    }
142    if d.definition_id.is_empty() {
143        return Err(ValidationError::MissingField("definition_id"));
144    }
145    if d.working_dir.is_empty() {
146        return Err(ValidationError::MissingField("working_dir"));
147    }
148    if !is_safe_relative_subpath(&d.working_dir) {
149        return Err(ValidationError::UnsafeWorkingDir(d.working_dir.clone()));
150    }
151    Ok(())
152}
153
154fn is_safe_relative_subpath(s: &str) -> bool {
155    let p = std::path::Path::new(s);
156    if p.is_absolute() {
157        return false;
158    }
159    for comp in p.components() {
160        match comp {
161            std::path::Component::ParentDir
162            | std::path::Component::RootDir
163            | std::path::Component::Prefix(_) => return false,
164            _ => {}
165        }
166    }
167    true
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    fn v1_record(id: &str) -> NamedAgentRecord {
175        NamedAgentRecord {
176            schema_version: 1,
177            data: NamedAgentRecordV1 {
178                instance_id: id.to_string(),
179                instance_name: "demo".to_string(),
180                definition_id: "claude-code".to_string(),
181                identity_id: None,
182                memory_id: None,
183                session_id: None,
184                working_dir: "demo-0512a".to_string(),
185                source_agents_base: None,
186                created_at_ms: 1,
187                last_launched_at_ms: 1,
188                created_by_version: "0.33.822".to_string(),
189                last_launched_by_version: "0.33.822".to_string(),
190            },
191        }
192    }
193
194    #[test]
195    fn happy_path() {
196        let r = v1_record("abc");
197        validate("abc", &r).unwrap();
198    }
199
200    #[test]
201    fn unsupported_schema_is_rejected() {
202        let mut r = v1_record("abc");
203        r.schema_version = 999;
204        let err = validate("abc", &r).unwrap_err();
205        assert!(matches!(err, ValidationError::UnsupportedSchema { .. }));
206    }
207
208    #[test]
209    fn filename_mismatch_is_rejected() {
210        let r = v1_record("abc");
211        assert!(matches!(
212            validate("xyz", &r).unwrap_err(),
213            ValidationError::IdMismatch { .. }
214        ));
215    }
216
217    #[test]
218    fn absolute_workdir_is_rejected() {
219        let mut r = v1_record("abc");
220        r.data.working_dir = if cfg!(windows) {
221            "C:\\tmp\\evil".to_string()
222        } else {
223            "/tmp/evil".to_string()
224        };
225        assert!(matches!(
226            validate("abc", &r).unwrap_err(),
227            ValidationError::UnsafeWorkingDir(_)
228        ));
229    }
230
231    #[test]
232    fn dotdot_workdir_is_rejected() {
233        let mut r = v1_record("abc");
234        r.data.working_dir = "../../sneaky".to_string();
235        assert!(matches!(
236            validate("abc", &r).unwrap_err(),
237            ValidationError::UnsafeWorkingDir(_)
238        ));
239    }
240
241    #[test]
242    fn missing_required_field_is_rejected() {
243        let mut r = v1_record("abc");
244        r.data.instance_name = String::new();
245        assert!(matches!(
246            validate("abc", &r).unwrap_err(),
247            ValidationError::MissingField("instance_name")
248        ));
249    }
250
251    #[test]
252    fn session_id_drives_min_schema_version() {
253        let mut r = v1_record("abc");
254        assert_eq!(r.data.min_schema_version(), 1, "session-less record is v1");
255        r.data.session_id = Some("sess-xyz".to_string());
256        assert_eq!(r.data.min_schema_version(), 2, "session-wired record is v2");
257        // A v2 record validates under the bumped MAX_SUPPORTED_SCHEMA.
258        r.schema_version = 2;
259        validate("abc", &r).unwrap();
260    }
261
262    #[test]
263    fn source_agents_base_drives_min_schema_version_v3() {
264        let mut r = v1_record("abc");
265        assert_eq!(r.data.min_schema_version(), 1);
266        r.data.source_agents_base = Some("/home/u/.agentmux/channels/stable/agents".to_string());
267        assert_eq!(
268            r.data.min_schema_version(),
269            3,
270            "a source-anchored record needs v3"
271        );
272        // v3 takes precedence even with session_id also set.
273        r.data.session_id = Some("sess-1".to_string());
274        assert_eq!(r.data.min_schema_version(), 3);
275        // Validates under the bumped MAX_SUPPORTED_SCHEMA.
276        r.schema_version = 3;
277        validate("abc", &r).unwrap();
278    }
279
280    #[test]
281    fn unknown_future_field_round_trips() {
282        // A v3 record written by a newer binary with an unknown field must
283        // still deserialize (serde ignores unknowns) so this reader can load
284        // it — the additive-evolution contract.
285        let raw = serde_json::json!({
286            "schema_version": 3,
287            "data": {
288                "instance_id": "abc", "instance_name": "demo",
289                "definition_id": "claude-code", "identity_id": null,
290                "memory_id": null, "working_dir": "demo-0",
291                "source_agents_base": "/h/.agentmux/channels/x/agents",
292                "created_at_ms": 1, "last_launched_at_ms": 1,
293                "created_by_version": "0.45.0", "last_launched_by_version": "0.45.0",
294                "future_field": "ignored"
295            }
296        });
297        let parsed: NamedAgentRecord = serde_json::from_value(raw).unwrap();
298        assert_eq!(parsed.data.instance_id, "abc");
299        assert_eq!(
300            parsed.data.source_agents_base.as_deref(),
301            Some("/h/.agentmux/channels/x/agents")
302        );
303    }
304}