Skip to main content

mars_schema/
tool_cover.rs

1//! Which tool-rule key covers which: the one place that decides whether one rule's scope
2//! holds inside another's.
3//!
4//! [`relation`] answers only what it can prove for every harness, and returns
5//! [`Relation::Unknown`] for the rest. A wrong `Covers` makes a caller drop a rule that
6//! should apply, so a case that is not listed below is `Unknown`, never a guess.
7//!
8//! What it proves, by capability:
9//! - `edit` covers `write` and `notebook`; `web` covers `web_search` and `web_fetch`
10//!   ([`capability_covers`]). Other pairs of distinct capabilities never overlap.
11//! - An unscoped key covers every key of a capability it covers.
12//! - `bash` patterns, compared as text: a literal followed by one trailing `*` covers
13//!   every pattern that starts with that literal, and covers the bare command (`git *`
14//!   covers `git`, not `gitk`). Two such patterns whose literals are not prefixes of each
15//!   other are disjoint. This is what Pi's `globMatches`, Codex's `_glob_matches` and
16//!   OpenCode's `Wildcard.match` agree on once `?` (a wildcard on OpenCode, a literal on
17//!   the others), `\` (OpenCode reads it as `/`) and any other `*` are excluded.
18//! - `skill` names with no wildcard character: two different ones are disjoint.
19//! - An MCP server key covers its tools; `*` is a whole segment.
20//!
21//! Path capabilities are always `Unknown` for two different scopes: Pi anchors and
22//! normalizes path patterns, Claude gives `/`, `//`, `./` and `~` different roots, and
23//! Claude's `*` does not cross `/`, so no text comparison proves anything there.
24
25use crate::mcp::{McpRef, McpSegment};
26use crate::tool_names::{Capability, ParsedToolName, is_mcp_wire_token};
27use crate::tool_policy::ToolRule;
28
29/// How the scope of key `a` stands to the scope of key `b`.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Relation {
32    /// The same scope.
33    Equal,
34    /// Everything `b` matches, `a` matches too.
35    Covers,
36    /// Everything `a` matches, `b` matches too.
37    CoveredBy,
38    /// No call matches both.
39    Disjoint,
40    /// Not provable here: the scopes may overlap, nest or be apart.
41    Unknown,
42}
43
44/// A rule's key: its capability and scope, without the action.
45#[derive(Debug, Clone, Copy)]
46pub struct ToolKey<'a> {
47    pub capability: &'a Capability,
48    pub pattern: Option<&'a str>,
49}
50
51impl<'a> From<&'a ToolRule> for ToolKey<'a> {
52    fn from(rule: &'a ToolRule) -> Self {
53        Self {
54            capability: &rule.capability,
55            pattern: rule.pattern.as_deref(),
56        }
57    }
58}
59
60impl<'a> From<&'a ParsedToolName> for ToolKey<'a> {
61    fn from(name: &'a ParsedToolName) -> Self {
62        Self {
63            capability: &name.capability,
64            pattern: name.pattern.as_deref(),
65        }
66    }
67}
68
69/// Whether capability `a` includes capability `b` as a part of itself.
70pub fn capability_covers(a: &str, b: &str) -> bool {
71    matches!(
72        (a, b),
73        ("edit", "write" | "notebook") | ("web", "web_search" | "web_fetch")
74    )
75}
76
77pub fn relation(a: ToolKey<'_>, b: ToolKey<'_>) -> Relation {
78    if a.capability == b.capability && a.pattern == b.pattern {
79        return Relation::Equal;
80    }
81    match (a.capability, b.capability) {
82        // `*` names the tools no other rule names, not a set a key can be measured against.
83        (Capability::Any, _) | (_, Capability::Any) => Relation::Unknown,
84        (Capability::Mcp(x), Capability::Mcp(y)) => mcp_relation(x, y),
85        // An `mcp__server__tool` wire token may name the same tool as an `mcp(...)` key.
86        (Capability::Mcp(_), Capability::Unknown(name))
87        | (Capability::Unknown(name), Capability::Mcp(_)) => {
88            if is_mcp_wire_token(name) {
89                Relation::Unknown
90            } else {
91                Relation::Disjoint
92            }
93        }
94        (Capability::Mcp(_), _) | (_, Capability::Mcp(_)) => Relation::Disjoint,
95        // Wire tokens may carry `*` (`mcp__github__*`), so two of them can overlap.
96        (Capability::Unknown(x), Capability::Unknown(y))
97            if x == y || (is_mcp_wire_token(x) && is_mcp_wire_token(y)) =>
98        {
99            Relation::Unknown
100        }
101        (Capability::Unknown(_), _) | (_, Capability::Unknown(_)) => Relation::Disjoint,
102        (Capability::Builtin(x), Capability::Builtin(y)) => builtin_relation(x, y, a, b),
103    }
104}
105
106fn builtin_relation(x: &str, y: &str, a: ToolKey<'_>, b: ToolKey<'_>) -> Relation {
107    if x == y {
108        return match (a.pattern, b.pattern) {
109            (None, Some(_)) => Relation::Covers,
110            (Some(_), None) => Relation::CoveredBy,
111            (Some(p), Some(q)) if x == "bash" => bash_relation(p, q),
112            // A skill name with no wildcard character names one skill, and every harness
113            // compares it whole.
114            (Some(p), Some(q)) if x == "skill" && is_plain(p) && is_plain(q) => Relation::Disjoint,
115            _ => Relation::Unknown,
116        };
117    }
118    if capability_covers(x, y) {
119        // `edit(src/**)` against `write` overlaps without either holding the other.
120        return if a.pattern.is_none() {
121            Relation::Covers
122        } else {
123            Relation::Unknown
124        };
125    }
126    if capability_covers(y, x) {
127        return if b.pattern.is_none() {
128            Relation::CoveredBy
129        } else {
130            Relation::Unknown
131        };
132    }
133    Relation::Disjoint
134}
135
136/// A `bash` pattern as far as the three matchers agree on its meaning.
137enum BashPattern<'a> {
138    /// Matches only this command.
139    Literal(&'a str),
140    /// Matches every command that starts with this text, and the bare command when the
141    /// text ends in a space.
142    Prefix(&'a str),
143    Other,
144}
145
146/// No character any of the matchers reads as a wildcard or an escape.
147fn is_plain(text: &str) -> bool {
148    !text.contains(['*', '?', '\\', '\n', '\r'])
149}
150
151fn bash_pattern(pattern: &str) -> BashPattern<'_> {
152    let wildcards = pattern.matches('*').count();
153    let literal = pattern.strip_suffix('*').unwrap_or(pattern);
154    let plain = is_plain(literal);
155    match (wildcards, pattern.ends_with('*'), plain) {
156        (0, _, true) => BashPattern::Literal(pattern),
157        (1, true, true) => BashPattern::Prefix(literal),
158        _ => BashPattern::Other,
159    }
160}
161
162fn prefix_matches(prefix: &str, command: &str) -> bool {
163    command.starts_with(prefix) || prefix.strip_suffix(' ') == Some(command)
164}
165
166fn bash_relation(p: &str, q: &str) -> Relation {
167    match (bash_pattern(p), bash_pattern(q)) {
168        (BashPattern::Literal(_), BashPattern::Literal(_)) => Relation::Disjoint,
169        (BashPattern::Prefix(prefix), BashPattern::Literal(command)) => {
170            if prefix_matches(prefix, command) {
171                Relation::Covers
172            } else {
173                Relation::Disjoint
174            }
175        }
176        (BashPattern::Literal(command), BashPattern::Prefix(prefix)) => {
177            if prefix_matches(prefix, command) {
178                Relation::CoveredBy
179            } else {
180                Relation::Disjoint
181            }
182        }
183        (BashPattern::Prefix(x), BashPattern::Prefix(y)) => {
184            if y.starts_with(x) {
185                Relation::Covers
186            } else if x.starts_with(y) {
187                Relation::CoveredBy
188            } else {
189                Relation::Disjoint
190            }
191        }
192        _ => Relation::Unknown,
193    }
194}
195
196fn mcp_relation(a: &McpRef, b: &McpRef) -> Relation {
197    let server = segment_relation(&a.server, &b.server);
198    let tool = segment_relation(&a.tool, &b.tool);
199    match (server, tool) {
200        (Relation::Disjoint, _) | (_, Relation::Disjoint) => Relation::Disjoint,
201        (Relation::Equal, other) | (other, Relation::Equal) => other,
202        (x, y) if x == y => x,
203        // `*/tool` against `github/*`: they meet at `github/tool` and neither holds the other.
204        _ => Relation::Unknown,
205    }
206}
207
208fn segment_relation(a: &McpSegment, b: &McpSegment) -> Relation {
209    match (a, b) {
210        (McpSegment::Any, McpSegment::Any) => Relation::Equal,
211        (McpSegment::Any, McpSegment::Named(_)) => Relation::Covers,
212        (McpSegment::Named(_), McpSegment::Any) => Relation::CoveredBy,
213        (McpSegment::Named(x), McpSegment::Named(y)) if x == y => Relation::Equal,
214        (McpSegment::Named(_), McpSegment::Named(_)) => Relation::Disjoint,
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::Relation::*;
221    use super::*;
222    use crate::tool_names::parse_mars_tool_name;
223
224    fn rel(a: &str, b: &str) -> Relation {
225        let (a, b) = (
226            parse_mars_tool_name(a).unwrap(),
227            parse_mars_tool_name(b).unwrap(),
228        );
229        relation((&a).into(), (&b).into())
230    }
231
232    fn flipped(relation: Relation) -> Relation {
233        match relation {
234            Covers => CoveredBy,
235            CoveredBy => Covers,
236            other => other,
237        }
238    }
239
240    #[test]
241    fn relations() {
242        let rows: &[(&str, &str, Relation)] = &[
243            // Same key, spelled two ways.
244            ("bash", "shell", Equal),
245            ("bash(git push:*)", "bash(git push *)", Equal),
246            ("read(src/**)", "read(src/**)", Equal),
247            ("mcp(github)", "mcp(github/*)", Equal),
248            // Capabilities.
249            ("edit", "write", Covers),
250            ("edit", "notebook", Covers),
251            ("web", "web_search", Covers),
252            ("web", "web_fetch", Covers),
253            ("write", "notebook", Disjoint),
254            ("web_search", "web_fetch", Disjoint),
255            ("edit", "web", Disjoint),
256            ("bash", "read", Disjoint),
257            ("grep", "read", Disjoint),
258            ("edit", "bash(git *)", Disjoint),
259            ("skill(init)", "agent(init)", Disjoint),
260            // Unscoped covers scoped; scoped never covers unscoped.
261            ("bash", "bash(git *)", Covers),
262            ("read", "read(src/**)", Covers),
263            ("edit", "write(src/**)", Covers),
264            ("web", "web_fetch(domain:example.com)", Covers),
265            ("write(src/**)", "edit", CoveredBy),
266            ("edit(src/**)", "write", Unknown),
267            ("edit(src/**)", "write(src/**)", Unknown),
268            ("web_fetch(domain:a.com)", "web", CoveredBy),
269            // Bash prefixes.
270            ("bash(git *)", "bash(git push *)", Covers),
271            ("bash(git *)", "bash(git push)", Covers),
272            ("bash(git *)", "bash(git)", Covers),
273            ("bash(git *)", "bash(gitk)", Disjoint),
274            ("bash(git *)", "bash(gitk *)", Disjoint),
275            ("bash(git*)", "bash(gitk *)", Covers),
276            ("bash(git*)", "bash(git *)", Covers),
277            ("bash(git*)", "bash(git)", Covers),
278            ("bash(*)", "bash(git push *)", Covers),
279            ("bash(git push *)", "bash(git pull *)", Disjoint),
280            ("bash(git push *)", "bash(git status)", Disjoint),
281            ("bash(git status)", "bash(git status -s)", Disjoint),
282            ("bash(git status)", "bash(git status)", Equal),
283            ("bash(git push *)", "bash(git push -f *)", Covers),
284            ("bash(git push -f *)", "bash(git push *)", CoveredBy),
285            ("bash(pkill -f *)", "bash(pkill -f)", Covers),
286            // Bash patterns that are not a literal plus one trailing `*`.
287            ("bash(git * main)", "bash(git push main)", Unknown),
288            ("bash(git *)", "bash(git * main)", Unknown),
289            ("bash(git **)", "bash(git push *)", Unknown),
290            ("bash(*git)", "bash(git)", Unknown),
291            ("bash(git ?*)", "bash(git a *)", Unknown),
292            ("bash(git push?)", "bash(git push1)", Unknown),
293            ("bash(git push?)", "bash(git push *)", Unknown),
294            ("bash(git *)", "bash(git\\ push)", Unknown),
295            ("bash(git\\ *)", "bash(git\\ push *)", Unknown),
296            // Paths are never compared as text.
297            ("read(src/**)", "read(src/lib/**)", Unknown),
298            ("read(./src/*)", "read(src/*)", Unknown),
299            ("read(~/x)", "read(/home/x)", Unknown),
300            ("read(src/a)", "read(src/b)", Unknown),
301            ("write(src/**)", "write(docs/**)", Unknown),
302            ("grep(src/**)", "grep(src/a/**)", Unknown),
303            ("skill(init)", "skill(review)", Disjoint),
304            ("skill(init)", "skill(re*)", Unknown),
305            (
306                "web_fetch(domain:a.com)",
307                "web_fetch(domain:b.com)",
308                Unknown,
309            ),
310            // MCP.
311            ("mcp(github)", "mcp(github/create_issue)", Covers),
312            ("mcp(github/*)", "mcp(github/create_issue)", Covers),
313            ("mcp(*/*)", "mcp(github)", Covers),
314            ("mcp(*/*)", "mcp(github/create_issue)", Covers),
315            ("mcp(*/create_issue)", "mcp(github/create_issue)", Covers),
316            (
317                "mcp(github/create_issue)",
318                "mcp(github/delete_repo)",
319                Disjoint,
320            ),
321            ("mcp(github)", "mcp(gitlab)", Disjoint),
322            ("mcp(github)", "mcp(gitlab/x)", Disjoint),
323            ("mcp(*/create_issue)", "mcp(github/*)", Unknown),
324            ("mcp(github/Create)", "mcp(github/create)", Disjoint),
325            ("mcp(github)", "bash", Disjoint),
326            ("mcp(github)", "bash(git *)", Disjoint),
327            ("mcp(*/*)", "edit", Disjoint),
328            // `*`, unknown names and wire tokens.
329            ("*", "bash", Unknown),
330            ("*", "mcp(github)", Unknown),
331            ("*", "*", Equal),
332            ("mystery", "mystery", Equal),
333            ("mystery", "mystery(x)", Unknown),
334            ("mystery", "other", Disjoint),
335            ("mystery", "bash", Disjoint),
336            ("mystery", "mcp(github)", Disjoint),
337            ("mcp__github__create_issue", "mcp(github)", Unknown),
338            (
339                "mcp__github__create_issue",
340                "mcp__github__create_issue",
341                Equal,
342            ),
343            ("mcp__github__a", "mcp__github__b", Unknown),
344        ];
345        for (a, b, expected) in rows {
346            assert_eq!(rel(a, b), *expected, "{a} against {b}");
347            assert_eq!(rel(b, a), flipped(*expected), "{b} against {a}");
348        }
349    }
350}