Skip to main content

mars_schema/
tool_rule_map.rs

1//! An ordered map from tool key to action: `[settings.tools]` and the rule entries of
2//! `[agents.<name>.tools]` in `mars.toml`.
3
4use std::fmt;
5
6use serde::de::{Error as _, MapAccess, Visitor};
7use serde::ser::SerializeMap;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::tool_names::{OverlayToolName, ParsedToolName};
11use crate::tool_policy::ToolAction;
12
13/// Tool rules keyed by tool name, in the order the author wrote them.
14///
15/// Two spellings of one key (`Bash` beside `bash`, or `bash(git push:*)` beside
16/// `bash(git push *)`) are one key: a table that holds both fails to load, since file order
17/// would otherwise pick the winner.
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct ToolRuleMap {
20    entries: Vec<(OverlayToolName, ToolAction)>,
21}
22
23impl ToolRuleMap {
24    pub fn is_empty(&self) -> bool {
25        self.entries.is_empty()
26    }
27
28    pub fn len(&self) -> usize {
29        self.entries.len()
30    }
31
32    pub fn iter(&self) -> impl Iterator<Item = (&OverlayToolName, ToolAction)> {
33        self.entries.iter().map(|(name, action)| (name, *action))
34    }
35
36    pub fn contains_key(&self, key: &ParsedToolName) -> bool {
37        self.entries.iter().any(|(name, _)| name.parsed() == key)
38    }
39
40    /// `lower` with every key that `higher` names replaced by `higher`'s entry, then the rest
41    /// of `higher`. Keys compare by their parsed form, and `higher`'s spelling is the one kept.
42    pub fn merge_by_key(lower: &Self, higher: &Self) -> Self {
43        let mut entries: Vec<_> = lower
44            .entries
45            .iter()
46            .filter(|(name, _)| !higher.contains_key(name.parsed()))
47            .cloned()
48            .collect();
49        entries.extend(higher.entries.iter().cloned());
50        Self { entries }
51    }
52}
53
54impl Serialize for ToolRuleMap {
55    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
56        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
57        for (name, action) in &self.entries {
58            map.serialize_entry(&String::from(name.clone()), action)?;
59        }
60        map.end()
61    }
62}
63
64impl<'de> Deserialize<'de> for ToolRuleMap {
65    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
66        struct MapVisitor;
67
68        impl<'de> Visitor<'de> for MapVisitor {
69            type Value = ToolRuleMap;
70
71            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72                f.write_str("a table of tool name to allow, deny or ask")
73            }
74
75            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
76                let mut entries: Vec<(OverlayToolName, ToolAction)> = Vec::new();
77                while let Some(raw) = map.next_key::<String>()? {
78                    let action = map
79                        .next_value::<ToolAction>()
80                        .map_err(|error| A::Error::custom(format!("`{raw}`: {error}")))?;
81                    let name = OverlayToolName::try_from(raw).map_err(A::Error::custom)?;
82                    if let Some((earlier, _)) = entries
83                        .iter()
84                        .find(|(earlier, _)| earlier.parsed() == name.parsed())
85                    {
86                        return Err(A::Error::custom(format!(
87                            "`{}` and `{}` name the same tool",
88                            String::from(earlier.clone()),
89                            String::from(name)
90                        )));
91                    }
92                    entries.push((name, action));
93                }
94                Ok(ToolRuleMap { entries })
95            }
96        }
97
98        deserializer.deserialize_map(MapVisitor)
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn parse(toml: &str) -> Result<ToolRuleMap, toml::de::Error> {
107        toml::from_str(toml)
108    }
109
110    fn keys(map: &ToolRuleMap) -> Vec<(String, &'static str)> {
111        map.iter()
112            .map(|(name, action)| (String::from(name.clone()), action.as_str()))
113            .collect()
114    }
115
116    #[test]
117    fn reads_in_file_order_and_keeps_the_authored_spelling() {
118        let map =
119            parse("zeta = \"deny\"\n\"Bash(git push:*)\" = \"ask\"\nalpha = \"allow\"\n").unwrap();
120        assert_eq!(
121            keys(&map),
122            [
123                ("zeta".into(), "deny"),
124                ("Bash(git push:*)".into(), "ask"),
125                ("alpha".into(), "allow"),
126            ]
127        );
128        let saved = toml::to_string(&map).unwrap();
129        assert_eq!(parse(&saved).unwrap(), map);
130        assert!(saved.contains("\"Bash(git push:*)\""));
131    }
132
133    #[test]
134    fn two_spellings_of_one_key_fail_naming_both() {
135        for (a, b) in [
136            ("Bash", "bash"),
137            ("shell", "bash"),
138            ("bash(git push:*)", "bash(git push *)"),
139        ] {
140            let err = parse(&format!("\"{a}\" = \"deny\"\n\"{b}\" = \"allow\"\n"))
141                .unwrap_err()
142                .to_string();
143            assert!(err.contains(&format!("`{a}`")), "{err}");
144            assert!(err.contains(&format!("`{b}`")), "{err}");
145        }
146    }
147
148    #[test]
149    fn rejects_a_malformed_name_and_an_unknown_action() {
150        assert!(parse("\"bash(\" = \"deny\"\n").is_err());
151        assert!(parse("mcp = \"deny\"\n").is_err());
152        assert!(parse("bash = \"block\"\n").is_err());
153        assert!(parse("bash = 1\n").is_err());
154    }
155
156    #[test]
157    fn merge_replaces_by_parsed_key() {
158        let lower =
159            parse("Bash = \"allow\"\nread = \"deny\"\n\"bash(git push:*)\" = \"allow\"\n").unwrap();
160        let higher =
161            parse("shell = \"deny\"\n\"bash(git push *)\" = \"deny\"\nedit = \"ask\"\n").unwrap();
162        let merged = ToolRuleMap::merge_by_key(&lower, &higher);
163        assert_eq!(
164            keys(&merged),
165            [
166                ("read".into(), "deny"),
167                ("shell".into(), "deny"),
168                ("bash(git push *)".into(), "deny"),
169                ("edit".into(), "ask"),
170            ]
171        );
172        assert_eq!(
173            ToolRuleMap::merge_by_key(&lower, &ToolRuleMap::default()),
174            lower
175        );
176    }
177}