Skip to main content

mars_schema/
keys.rs

1//! The keys a Mars release gates: a file that uses one needs a floor at or above the release that
2//! first read it. This lists keys Mars reads today and when they arrived, nothing about keys it
3//! no longer reads. A file's version floor is [`floor`] over the keys [`used`] finds in it, plus
4//! the uses a caller derives from other files (a hook, a profile's tool rule).
5
6use std::fmt;
7
8/// Where a gated key appears.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Surface {
11    /// Agent frontmatter.
12    AgentProfile,
13    /// `[package]` in `mars.toml`.
14    Package,
15    /// A top-level table of a package's `mars.toml`, such as `[plugin]`.
16    Manifest,
17    /// `hook.toml`.
18    HookToml,
19    /// `[settings]` in `mars.toml`, `mars.local.toml` and the user config.
20    Settings,
21    /// `[settings]` in `mars.local.toml` alone, where a key can mean more than in `mars.toml`.
22    LocalSettings,
23    /// `[agents.<name>]` in the consumer config files.
24    AgentOverlay,
25    /// `[models.<alias>]` in `mars.toml`.
26    ModelAlias,
27}
28
29/// A Mars release.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
31pub struct Release(pub u64, pub u64, pub u64);
32
33impl fmt::Display for Release {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "{}.{}.{}", self.0, self.1, self.2)
36    }
37}
38
39impl Release {
40    pub fn version(self) -> semver::Version {
41        semver::Version::new(self.0, self.1, self.2)
42    }
43}
44
45/// When a file that writes a gated key needs the row's `since`.
46#[derive(Debug, Clone, Copy)]
47pub enum Gate {
48    /// The key's presence: an older Mars misreads how the package reads (`schema`, `plugin`).
49    Present,
50    /// The key holds tool rules, and the rule's action decides: an older Mars drops the rule,
51    /// so a restricting one (`deny`, `ask`) must not meet one, and an `allow` loses only a grant.
52    Rules(fn(&str) -> bool),
53    /// The key's value decides: an older Mars refuses a value it doesn't know and fails the
54    /// whole sync, so a file that writes a new value needs the row's `since`.
55    Value(fn(&str) -> bool),
56}
57
58/// A key a Mars release gates: a file that uses it needs a floor at or above `since`.
59#[derive(Debug, Clone, Copy)]
60pub struct Gated {
61    pub key: &'static str,
62    pub surfaces: &'static [Surface],
63    /// The first Mars release that reads the key. Mars before it ignores the key or misreads
64    /// it; the row's comment says which.
65    pub since: Release,
66    pub gate: Gate,
67}
68
69use crate::agent::EffortRequest;
70use Surface::*;
71
72fn denies_or_asks(action: &str) -> bool {
73    matches!(action, "deny" | "ask")
74}
75
76/// Effort requests Mars before 0.35.0 refuses. `null` is YAML's spelling of `auto`.
77fn new_effort_request(value: &str) -> bool {
78    matches!(
79        value.to_ascii_lowercase().as_str(),
80        "minimal" | "auto" | "null"
81    )
82}
83
84/// `default_effort` spellings Mars before 0.35.0 refuses: it matched `low`, `medium`, `high`,
85/// `xhigh`, `max` and `auto` exactly, in lowercase. Mars now reads any case and the new levels.
86fn new_default_effort(value: &str) -> bool {
87    !matches!(value, "low" | "medium" | "high" | "xhigh" | "max" | "auto")
88        && EffortRequest::parse(value).is_some()
89}
90
91/// The first Mars that honours `min_mars_version`. A floor at or below it protects nothing a
92/// `min_mars_version` line could: Mars before it ignores the line.
93pub const MIN_MARS_VERSION_SINCE: Release = Release(0, 30, 0);
94
95/// Keys a Mars release gates; the comment on each says what an older Mars does with it.
96pub static GATED: &[Gated] = &[
97    // Mars before 0.20.0 reads a `schema = 1` package as pre-v1 and drops what it cannot place.
98    Gated {
99        key: "schema",
100        surfaces: &[Package],
101        since: Release(0, 20, 0),
102        gate: Gate::Present,
103    },
104    // Mars before 0.20.0 fails `skill__provider` refs with `skill not found`.
105    Gated {
106        key: "uses-providers",
107        surfaces: &[Package],
108        since: Release(0, 20, 0),
109        gate: Gate::Present,
110    },
111    // Mars before 0.19.0 drops `[plugin]` when `mars version` rewrites the manifest.
112    Gated {
113        key: "plugin",
114        surfaces: &[Manifest],
115        since: Release(0, 19, 0),
116        gate: Gate::Present,
117    },
118    // Mars before 0.25.0 rejects `[hooks]` and fails the whole sync.
119    Gated {
120        key: "hooks",
121        surfaces: &[HookToml],
122        since: Release(0, 25, 0),
123        gate: Gate::Present,
124    },
125    // Tool rule tables. Mars before 0.29.0 ignores them without a word; 0.29.x reads `deny`
126    // under the older precedence, where a narrower allow can beat it, and fails on `allow` or
127    // `ask`; 0.30.0 is the first where the strictest rule wins. `allow` is not a restriction:
128    // a Mars that drops one loses a grant only.
129    Gated {
130        key: "tools",
131        surfaces: &[Package, Settings, AgentOverlay, AgentProfile],
132        since: Release(0, 30, 0),
133        gate: Gate::Rules(denies_or_asks),
134    },
135    // Mars before 0.39.0 reads a local `targets` as the whole list, not an addition to the
136    // project's, and under its advised `--force` rewrites the shared lock to match.
137    Gated {
138        key: "targets",
139        surfaces: &[LocalSettings],
140        since: Release(0, 39, 0),
141        gate: Gate::Present,
142    },
143    // An Agent's `effort`, an overlay's `effort` and a model policy's `override.effort`. Mars
144    // before 0.35.0 refuses `minimal`, `auto` and `null` and fails the whole sync.
145    Gated {
146        key: "effort",
147        surfaces: &[AgentProfile, AgentOverlay, Settings],
148        since: Release(0, 35, 0),
149        gate: Gate::Value(new_effort_request),
150    },
151    // An agent's `models` list, in a profile and in an overlay. Mars before 0.42.0 ignores the key
152    // and, for a profile with no `model`, runs the harness's own default.
153    Gated {
154        key: "models",
155        surfaces: &[AgentProfile, AgentOverlay],
156        since: Release(0, 42, 0),
157        gate: Gate::Present,
158    },
159    // A model alias's `default_effort`. Mars before 0.35.0 refuses `none` and `minimal`.
160    Gated {
161        key: "default_effort",
162        surfaces: &[ModelAlias],
163        since: Release(0, 35, 0),
164        gate: Gate::Value(new_default_effort),
165    },
166    // A model alias's `note`. Mars before 0.42.0 refuses the unknown key and fails the whole sync.
167    Gated {
168        key: "note",
169        surfaces: &[ModelAlias],
170        since: Release(0, 42, 0),
171        gate: Gate::Present,
172    },
173    // A `[models.<alias>]` with no routing field (it only adds to the layer below). Mars before
174    // 0.42.0 refuses it as "must have either 'model' or 'match'". `scan_aliases` reports it.
175    Gated {
176        key: ROUTING_LESS,
177        surfaces: &[ModelAlias],
178        since: Release(0, 42, 0),
179        gate: Gate::Present,
180    },
181];
182
183/// The marker `scan_aliases` reports for a `[models.<alias>]` with no routing field.
184const ROUTING_LESS: &str = "routing-less";
185
186/// A key a file uses, as [`floor`] reads it.
187pub struct Used {
188    pub surface: Surface,
189    pub key: String,
190    /// The rule's action, for a key whose gate depends on it.
191    pub value: Option<String>,
192    /// Where the file uses it, for the message: "`[package.tools]` `bash` = \"deny\"".
193    pub at: String,
194}
195
196impl Used {
197    /// A portable hook in a `hook.toml`, which an older Mars rejects.
198    pub fn hook(name: &str) -> Self {
199        Self {
200            surface: HookToml,
201            key: "hooks".into(),
202            value: None,
203            at: format!("hook `{name}` using `[hooks]`"),
204        }
205    }
206
207    /// An effort an Agent's frontmatter writes, as written, named by `label` (`effort`, or a
208    /// model policy's override): `null` is YAML null, anything else the text of a string.
209    pub fn profile_effort(agent: &str, label: &str, written: Option<&str>) -> Self {
210        let (value, shown) = match written {
211            Some(text) => (text, format!("\"{text}\"")),
212            None => ("null", "null".to_string()),
213        };
214        Self {
215            surface: AgentProfile,
216            key: "effort".into(),
217            value: Some(value.into()),
218            at: format!("agent `{agent}` {label} = {shown}"),
219        }
220    }
221
222    /// An agent's frontmatter `models` list.
223    pub fn profile_models(agent: &str) -> Self {
224        Self {
225            surface: AgentProfile,
226            key: "models".into(),
227            value: None,
228            at: format!("agent `{agent}` `models`"),
229        }
230    }
231
232    /// A tool rule in an agent's frontmatter `tools`.
233    pub fn profile_rule(agent: &str, rule: &str, action: &str) -> Self {
234        Self {
235            surface: AgentProfile,
236            key: "tools".into(),
237            value: Some(action.into()),
238            at: format!("agent `{agent}` `tools` `{rule}` = \"{action}\""),
239        }
240    }
241}
242
243/// Which file [`used`] reads.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum Document {
246    /// A package's `mars.toml`.
247    Package,
248    /// `mars.toml` or the user `config.toml` as a project's configuration.
249    Consumer,
250    /// `mars.local.toml`: a consumer file with the keys only it gates.
251    Local,
252}
253
254/// The gated keys `document` uses: every key of a table that has a gated row on that table's
255/// surface, and for a key that holds rules, each rule.
256pub fn used(document: &toml::Table, kind: Document) -> Vec<Used> {
257    let mut used = Vec::new();
258    let mut scan = |surface: Surface, label: String, table: &toml::Table| {
259        for row in GATED.iter().filter(|row| on(row.surfaces, surface)) {
260            let Some(value) = table.get(row.key) else {
261                continue;
262            };
263            match (row.gate, value) {
264                (Gate::Rules(_), toml::Value::Table(rules)) => {
265                    let table = if label.is_empty() {
266                        row.key.to_string()
267                    } else {
268                        format!("{label}.{}", row.key)
269                    };
270                    for (name, action) in rules {
271                        let Some(action) = action.as_str() else {
272                            continue;
273                        };
274                        used.push(Used {
275                            surface,
276                            key: row.key.into(),
277                            value: Some(action.into()),
278                            at: format!("`[{table}]` `{name}` = \"{action}\""),
279                        });
280                    }
281                }
282                (Gate::Rules(_), _) => {}
283                (Gate::Value(_), toml::Value::String(text)) => used.push(Used {
284                    surface,
285                    key: row.key.into(),
286                    value: Some(text.clone()),
287                    at: if label.is_empty() {
288                        format!("`{} = \"{text}\"`", row.key)
289                    } else {
290                        format!("`[{label}]` `{} = \"{text}\"`", row.key)
291                    },
292                }),
293                (Gate::Value(_), _) => {}
294                (Gate::Present, _) if row.key == ROUTING_LESS => used.push(Used {
295                    surface,
296                    key: row.key.into(),
297                    value: None,
298                    at: format!("`[{label}]` with no `model` or `match`"),
299                }),
300                (Gate::Present, value) => used.push(Used {
301                    surface,
302                    key: row.key.into(),
303                    value: None,
304                    at: match value {
305                        toml::Value::Table(_) => format!("`[{}]`", row.key),
306                        toml::Value::Integer(_) | toml::Value::Boolean(_) => {
307                            format!("`{} = {value}`", row.key)
308                        }
309                        _ => format!("`{}`", row.key),
310                    },
311                }),
312            }
313        }
314    };
315    match kind {
316        Document::Package => {
317            scan(Manifest, String::new(), document);
318            if let Some(package) = document.get("package").and_then(toml::Value::as_table) {
319                scan(Package, "package".into(), package);
320            }
321            scan_aliases(document, &mut scan);
322        }
323        Document::Consumer | Document::Local => {
324            if let Some(settings) = document.get("settings").and_then(toml::Value::as_table) {
325                scan(Settings, "settings".into(), settings);
326                if kind == Document::Local {
327                    scan(LocalSettings, "settings".into(), settings);
328                }
329            }
330            let agents = document.get("agents").and_then(toml::Value::as_table);
331            for (name, agent) in agents.into_iter().flatten() {
332                if let Some(agent) = agent.as_table() {
333                    scan(AgentOverlay, format!("agents.{name}"), agent);
334                    scan_policies(AgentOverlay, &format!("agents.{name}"), agent, &mut scan);
335                }
336            }
337            if let Some(settings) = document.get("settings").and_then(toml::Value::as_table) {
338                scan_policies(Settings, "settings", settings, &mut scan);
339            }
340            scan_aliases(document, &mut scan);
341        }
342    }
343    used
344}
345
346/// The Mars a file needs, and what in it asks for that.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct Floor {
349    pub since: Release,
350    pub at: String,
351}
352
353impl Floor {
354    /// The requirement that states it: `>=0.30.0`.
355    pub fn requirement(&self) -> String {
356        format!(">={}", self.since)
357    }
358}
359
360/// The highest `since` among the keys used whose row says an older Mars would misread them.
361/// The first of equal ones names the floor.
362pub fn floor(used: impl IntoIterator<Item = Used>) -> Option<Floor> {
363    let mut floor: Option<Floor> = None;
364    for used in used {
365        let Some(row) = GATED
366            .iter()
367            .find(|row| row.key == used.key && on(row.surfaces, used.surface))
368        else {
369            continue;
370        };
371        let holds = match row.gate {
372            Gate::Present => true,
373            Gate::Rules(holds) | Gate::Value(holds) => used.value.as_deref().is_some_and(holds),
374        };
375        if holds && floor.as_ref().is_none_or(|floor| row.since > floor.since) {
376            floor = Some(Floor {
377                since: row.since,
378                at: used.at,
379            });
380        }
381    }
382    floor
383}
384
385/// Each `[models.<alias>]` table.
386fn scan_aliases(document: &toml::Table, scan: &mut impl FnMut(Surface, String, &toml::Table)) {
387    let aliases = document.get("models").and_then(toml::Value::as_table);
388    for (name, alias) in aliases.into_iter().flatten() {
389        if let Some(alias) = alias.as_table() {
390            let label = format!("models.{name}");
391            scan(ModelAlias, label.clone(), alias);
392            let routes = ["model", "match", "exclude", "provider", "harness"]
393                .iter()
394                .any(|key| alias.contains_key(*key));
395            if !routes {
396                let mut marker = toml::Table::new();
397                marker.insert(ROUTING_LESS.into(), ROUTING_LESS.into());
398                scan(ModelAlias, label, &marker);
399            }
400        }
401    }
402}
403
404/// The `override` table of each `model-policies` rule in `table`.
405fn scan_policies(
406    surface: Surface,
407    label: &str,
408    table: &toml::Table,
409    scan: &mut impl FnMut(Surface, String, &toml::Table),
410) {
411    let rules = table.get("model-policies").and_then(toml::Value::as_array);
412    for (index, rule) in rules.into_iter().flatten().enumerate() {
413        if let Some(overrides) = rule.get("override").and_then(toml::Value::as_table) {
414            scan(
415                surface,
416                format!("{label}.model-policies[{index}].override"),
417                overrides,
418            );
419        }
420    }
421}
422
423fn on(surfaces: &[Surface], surface: Surface) -> bool {
424    surfaces.contains(&surface)
425}