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}
24
25/// A Mars release.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
27pub struct Release(pub u64, pub u64, pub u64);
28
29impl fmt::Display for Release {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        write!(f, "{}.{}.{}", self.0, self.1, self.2)
32    }
33}
34
35impl Release {
36    pub fn version(self) -> semver::Version {
37        semver::Version::new(self.0, self.1, self.2)
38    }
39}
40
41/// When a file that writes a gated key needs the row's `since`.
42#[derive(Debug, Clone, Copy)]
43pub enum Gate {
44    /// The key's presence: an older Mars misreads how the package reads (`schema`, `plugin`).
45    Present,
46    /// The key holds tool rules, and the rule's action decides: an older Mars drops the rule,
47    /// so a restricting one (`deny`, `ask`) must not meet one, and an `allow` loses only a grant.
48    Rules(fn(&str) -> bool),
49}
50
51/// A key a Mars release gates: a file that uses it needs a floor at or above `since`.
52#[derive(Debug, Clone, Copy)]
53pub struct Gated {
54    pub key: &'static str,
55    pub surfaces: &'static [Surface],
56    /// The first Mars release that reads the key. Mars before it ignores the key or misreads
57    /// it; the row's comment says which.
58    pub since: Release,
59    pub gate: Gate,
60}
61
62use Surface::*;
63
64fn denies_or_asks(action: &str) -> bool {
65    matches!(action, "deny" | "ask")
66}
67
68/// The first Mars that honours `min_mars_version`. A floor at or below it protects nothing a
69/// `min_mars_version` line could: Mars before it ignores the line.
70pub const MIN_MARS_VERSION_SINCE: Release = Release(0, 30, 0);
71
72/// Keys a Mars release gates; the comment on each says what an older Mars does with it.
73pub static GATED: &[Gated] = &[
74    // Mars before 0.20.0 reads a `schema = 1` package as pre-v1 and drops what it cannot place.
75    Gated {
76        key: "schema",
77        surfaces: &[Package],
78        since: Release(0, 20, 0),
79        gate: Gate::Present,
80    },
81    // Mars before 0.20.0 fails `skill__provider` refs with `skill not found`.
82    Gated {
83        key: "uses-providers",
84        surfaces: &[Package],
85        since: Release(0, 20, 0),
86        gate: Gate::Present,
87    },
88    // Mars before 0.19.0 drops `[plugin]` when `mars version` rewrites the manifest.
89    Gated {
90        key: "plugin",
91        surfaces: &[Manifest],
92        since: Release(0, 19, 0),
93        gate: Gate::Present,
94    },
95    // Mars before 0.25.0 rejects `[hooks]` and fails the whole sync.
96    Gated {
97        key: "hooks",
98        surfaces: &[HookToml],
99        since: Release(0, 25, 0),
100        gate: Gate::Present,
101    },
102    // Tool rule tables. Mars before 0.29.0 ignores them without a word; 0.29.x reads `deny`
103    // under the older precedence, where a narrower allow can beat it, and fails on `allow` or
104    // `ask`; 0.30.0 is the first where the strictest rule wins. `allow` is not a restriction:
105    // a Mars that drops one loses a grant only.
106    Gated {
107        key: "tools",
108        surfaces: &[Package, Settings, AgentOverlay, AgentProfile],
109        since: Release(0, 30, 0),
110        gate: Gate::Rules(denies_or_asks),
111    },
112];
113
114/// A key a file uses, as [`floor`] reads it.
115pub struct Used {
116    pub surface: Surface,
117    pub key: String,
118    /// The rule's action, for a key whose gate depends on it.
119    pub value: Option<String>,
120    /// Where the file uses it, for the message: "`[package.tools]` `bash` = \"deny\"".
121    pub at: String,
122}
123
124impl Used {
125    /// A portable hook in a `hook.toml`, which an older Mars rejects.
126    pub fn hook(name: &str) -> Self {
127        Self {
128            surface: HookToml,
129            key: "hooks".into(),
130            value: None,
131            at: format!("hook `{name}` using `[hooks]`"),
132        }
133    }
134
135    /// A tool rule in an agent's frontmatter `tools`.
136    pub fn profile_rule(agent: &str, rule: &str, action: &str) -> Self {
137        Self {
138            surface: AgentProfile,
139            key: "tools".into(),
140            value: Some(action.into()),
141            at: format!("agent `{agent}` `tools` `{rule}` = \"{action}\""),
142        }
143    }
144}
145
146/// Which file [`used`] reads.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum Document {
149    /// A package's `mars.toml`.
150    Package,
151    /// `mars.toml`, `mars.local.toml` or the user `config.toml` as a project's configuration.
152    Consumer,
153}
154
155/// The gated keys `document` uses: every key of a table that has a gated row on that table's
156/// surface, and for a key that holds rules, each rule.
157pub fn used(document: &toml::Table, kind: Document) -> Vec<Used> {
158    let mut used = Vec::new();
159    let mut scan = |surface: Surface, label: String, table: &toml::Table| {
160        for row in GATED.iter().filter(|row| on(row.surfaces, surface)) {
161            let Some(value) = table.get(row.key) else {
162                continue;
163            };
164            match (row.gate, value) {
165                (Gate::Rules(_), toml::Value::Table(rules)) => {
166                    let table = if label.is_empty() {
167                        row.key.to_string()
168                    } else {
169                        format!("{label}.{}", row.key)
170                    };
171                    for (name, action) in rules {
172                        let Some(action) = action.as_str() else {
173                            continue;
174                        };
175                        used.push(Used {
176                            surface,
177                            key: row.key.into(),
178                            value: Some(action.into()),
179                            at: format!("`[{table}]` `{name}` = \"{action}\""),
180                        });
181                    }
182                }
183                (Gate::Rules(_), _) => {}
184                (Gate::Present, value) => used.push(Used {
185                    surface,
186                    key: row.key.into(),
187                    value: None,
188                    at: match value {
189                        toml::Value::Table(_) => format!("`[{}]`", row.key),
190                        toml::Value::Integer(_) | toml::Value::Boolean(_) => {
191                            format!("`{} = {value}`", row.key)
192                        }
193                        _ => format!("`{}`", row.key),
194                    },
195                }),
196            }
197        }
198    };
199    match kind {
200        Document::Package => {
201            scan(Manifest, String::new(), document);
202            if let Some(package) = document.get("package").and_then(toml::Value::as_table) {
203                scan(Package, "package".into(), package);
204            }
205        }
206        Document::Consumer => {
207            if let Some(settings) = document.get("settings").and_then(toml::Value::as_table) {
208                scan(Settings, "settings".into(), settings);
209            }
210            let agents = document.get("agents").and_then(toml::Value::as_table);
211            for (name, agent) in agents.into_iter().flatten() {
212                if let Some(agent) = agent.as_table() {
213                    scan(AgentOverlay, format!("agents.{name}"), agent);
214                }
215            }
216        }
217    }
218    used
219}
220
221/// The Mars a file needs, and what in it asks for that.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct Floor {
224    pub since: Release,
225    pub at: String,
226}
227
228impl Floor {
229    /// The requirement that states it: `>=0.30.0`.
230    pub fn requirement(&self) -> String {
231        format!(">={}", self.since)
232    }
233}
234
235/// The highest `since` among the keys used whose row says an older Mars would misread them.
236/// The first of equal ones names the floor.
237pub fn floor(used: impl IntoIterator<Item = Used>) -> Option<Floor> {
238    let mut floor: Option<Floor> = None;
239    for used in used {
240        let Some(row) = GATED
241            .iter()
242            .find(|row| row.key == used.key && on(row.surfaces, used.surface))
243        else {
244            continue;
245        };
246        let holds = match row.gate {
247            Gate::Present => true,
248            Gate::Rules(restricts) => used.value.as_deref().is_some_and(restricts),
249        };
250        if holds && floor.as_ref().is_none_or(|floor| row.since > floor.since) {
251            floor = Some(Floor {
252                since: row.since,
253                at: used.at,
254            });
255        }
256    }
257    floor
258}
259
260fn on(surfaces: &[Surface], surface: Surface) -> bool {
261    surfaces.contains(&surface)
262}