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