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    // A model alias's `default_effort`. Mars before 0.35.0 refuses `none` and `minimal`.
152    Gated {
153        key: "default_effort",
154        surfaces: &[ModelAlias],
155        since: Release(0, 35, 0),
156        gate: Gate::Value(new_default_effort),
157    },
158];
159
160/// A key a file uses, as [`floor`] reads it.
161pub struct Used {
162    pub surface: Surface,
163    pub key: String,
164    /// The rule's action, for a key whose gate depends on it.
165    pub value: Option<String>,
166    /// Where the file uses it, for the message: "`[package.tools]` `bash` = \"deny\"".
167    pub at: String,
168}
169
170impl Used {
171    /// A portable hook in a `hook.toml`, which an older Mars rejects.
172    pub fn hook(name: &str) -> Self {
173        Self {
174            surface: HookToml,
175            key: "hooks".into(),
176            value: None,
177            at: format!("hook `{name}` using `[hooks]`"),
178        }
179    }
180
181    /// An effort an Agent's frontmatter writes, as written, named by `label` (`effort`, or a
182    /// model policy's override): `null` is YAML null, anything else the text of a string.
183    pub fn profile_effort(agent: &str, label: &str, written: Option<&str>) -> Self {
184        let (value, shown) = match written {
185            Some(text) => (text, format!("\"{text}\"")),
186            None => ("null", "null".to_string()),
187        };
188        Self {
189            surface: AgentProfile,
190            key: "effort".into(),
191            value: Some(value.into()),
192            at: format!("agent `{agent}` {label} = {shown}"),
193        }
194    }
195
196    /// A tool rule in an agent's frontmatter `tools`.
197    pub fn profile_rule(agent: &str, rule: &str, action: &str) -> Self {
198        Self {
199            surface: AgentProfile,
200            key: "tools".into(),
201            value: Some(action.into()),
202            at: format!("agent `{agent}` `tools` `{rule}` = \"{action}\""),
203        }
204    }
205}
206
207/// Which file [`used`] reads.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Document {
210    /// A package's `mars.toml`.
211    Package,
212    /// `mars.toml` or the user `config.toml` as a project's configuration.
213    Consumer,
214    /// `mars.local.toml`: a consumer file with the keys only it gates.
215    Local,
216}
217
218/// The gated keys `document` uses: every key of a table that has a gated row on that table's
219/// surface, and for a key that holds rules, each rule.
220pub fn used(document: &toml::Table, kind: Document) -> Vec<Used> {
221    let mut used = Vec::new();
222    let mut scan = |surface: Surface, label: String, table: &toml::Table| {
223        for row in GATED.iter().filter(|row| on(row.surfaces, surface)) {
224            let Some(value) = table.get(row.key) else {
225                continue;
226            };
227            match (row.gate, value) {
228                (Gate::Rules(_), toml::Value::Table(rules)) => {
229                    let table = if label.is_empty() {
230                        row.key.to_string()
231                    } else {
232                        format!("{label}.{}", row.key)
233                    };
234                    for (name, action) in rules {
235                        let Some(action) = action.as_str() else {
236                            continue;
237                        };
238                        used.push(Used {
239                            surface,
240                            key: row.key.into(),
241                            value: Some(action.into()),
242                            at: format!("`[{table}]` `{name}` = \"{action}\""),
243                        });
244                    }
245                }
246                (Gate::Rules(_), _) => {}
247                (Gate::Value(_), toml::Value::String(text)) => used.push(Used {
248                    surface,
249                    key: row.key.into(),
250                    value: Some(text.clone()),
251                    at: if label.is_empty() {
252                        format!("`{} = \"{text}\"`", row.key)
253                    } else {
254                        format!("`[{label}]` `{} = \"{text}\"`", row.key)
255                    },
256                }),
257                (Gate::Value(_), _) => {}
258                (Gate::Present, value) => used.push(Used {
259                    surface,
260                    key: row.key.into(),
261                    value: None,
262                    at: match value {
263                        toml::Value::Table(_) => format!("`[{}]`", row.key),
264                        toml::Value::Integer(_) | toml::Value::Boolean(_) => {
265                            format!("`{} = {value}`", row.key)
266                        }
267                        _ => format!("`{}`", row.key),
268                    },
269                }),
270            }
271        }
272    };
273    match kind {
274        Document::Package => {
275            scan(Manifest, String::new(), document);
276            if let Some(package) = document.get("package").and_then(toml::Value::as_table) {
277                scan(Package, "package".into(), package);
278            }
279            scan_aliases(document, &mut scan);
280        }
281        Document::Consumer | Document::Local => {
282            if let Some(settings) = document.get("settings").and_then(toml::Value::as_table) {
283                scan(Settings, "settings".into(), settings);
284                if kind == Document::Local {
285                    scan(LocalSettings, "settings".into(), settings);
286                }
287            }
288            let agents = document.get("agents").and_then(toml::Value::as_table);
289            for (name, agent) in agents.into_iter().flatten() {
290                if let Some(agent) = agent.as_table() {
291                    scan(AgentOverlay, format!("agents.{name}"), agent);
292                    scan_policies(AgentOverlay, &format!("agents.{name}"), agent, &mut scan);
293                }
294            }
295            if let Some(settings) = document.get("settings").and_then(toml::Value::as_table) {
296                scan_policies(Settings, "settings", settings, &mut scan);
297            }
298            scan_aliases(document, &mut scan);
299        }
300    }
301    used
302}
303
304/// The Mars a file needs, and what in it asks for that.
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct Floor {
307    pub since: Release,
308    pub at: String,
309}
310
311impl Floor {
312    /// The requirement that states it: `>=0.30.0`.
313    pub fn requirement(&self) -> String {
314        format!(">={}", self.since)
315    }
316}
317
318/// The highest `since` among the keys used whose row says an older Mars would misread them.
319/// The first of equal ones names the floor.
320pub fn floor(used: impl IntoIterator<Item = Used>) -> Option<Floor> {
321    let mut floor: Option<Floor> = None;
322    for used in used {
323        let Some(row) = GATED
324            .iter()
325            .find(|row| row.key == used.key && on(row.surfaces, used.surface))
326        else {
327            continue;
328        };
329        let holds = match row.gate {
330            Gate::Present => true,
331            Gate::Rules(holds) | Gate::Value(holds) => used.value.as_deref().is_some_and(holds),
332        };
333        if holds && floor.as_ref().is_none_or(|floor| row.since > floor.since) {
334            floor = Some(Floor {
335                since: row.since,
336                at: used.at,
337            });
338        }
339    }
340    floor
341}
342
343/// Each `[models.<alias>]` table.
344fn scan_aliases(document: &toml::Table, scan: &mut impl FnMut(Surface, String, &toml::Table)) {
345    let aliases = document.get("models").and_then(toml::Value::as_table);
346    for (name, alias) in aliases.into_iter().flatten() {
347        if let Some(alias) = alias.as_table() {
348            scan(ModelAlias, format!("models.{name}"), alias);
349        }
350    }
351}
352
353/// The `override` table of each `model-policies` rule in `table`.
354fn scan_policies(
355    surface: Surface,
356    label: &str,
357    table: &toml::Table,
358    scan: &mut impl FnMut(Surface, String, &toml::Table),
359) {
360    let rules = table.get("model-policies").and_then(toml::Value::as_array);
361    for (index, rule) in rules.into_iter().flatten().enumerate() {
362        if let Some(overrides) = rule.get("override").and_then(toml::Value::as_table) {
363            scan(
364                surface,
365                format!("{label}.model-policies[{index}].override"),
366                overrides,
367            );
368        }
369    }
370}
371
372fn on(surfaces: &[Surface], surface: Surface) -> bool {
373    surfaces.contains(&surface)
374}