Skip to main content

mars_schema/
tool_project.rs

1//! Lowering a tool policy onto one host: the native names each rule becomes, the gaps Mars
2//! cannot name, and which stricter rule wins a shared name.
3//!
4//! Canonical Mars profiles express tool gating with a `tools:` action map (`rule: allow`,
5//! `deny` or `ask`), whole-server or per-tool MCP grants being `mcp(...)` keys in it.
6//! [`project`] spells a policy for one [`Host`]: a harness the binary writes files for, or
7//! Meridian Flow, which only consumes the result. Native agent lowering, skill lowering, the
8//! launch bundle and the WASM export all read that projection; nothing else turns a rule into
9//! native permission names or unscoped harness tool names.
10
11use crate::mcp::{McpRef, McpSegment};
12use crate::tool_cover::covered;
13use crate::tool_names::{Capability, is_mcp_wire_token, render_scoped};
14use crate::tool_natives::{self, Native};
15use crate::tool_policy::{EffectiveToolPolicy, ToolAction, ToolRule};
16use crate::{HarnessId, Host};
17use serde::Serialize;
18use serde::ser::{SerializeStruct, Serializer};
19
20/// What a host does with a tool name, which only this module's lowering needs.
21impl Host {
22    /// Whether a tool name can be narrowed to a pattern. A harness spells the scope in the
23    /// permission name (`Bash(git push *)`); Flow's tools take no scope.
24    fn scopes_patterns(self) -> bool {
25        !matches!(self, Self::MeridianFlow)
26    }
27
28    /// An MCP ref as this host names it. Server and tool segments are kept verbatim, never
29    /// re-cased.
30    fn mcp_token(self, r: &McpRef) -> Result<String, &'static str> {
31        let segment = |segment: &McpSegment| match segment {
32            McpSegment::Any => "*".to_owned(),
33            McpSegment::Named(name) => name.clone(),
34        };
35        let (server, tool) = (segment(&r.server), segment(&r.tool));
36        match self {
37            Self::Harness(HarnessId::Claude) => match (&r.server, &r.tool) {
38                (McpSegment::Any, McpSegment::Named(_)) => {
39                    Err("Claude cannot scope a single MCP tool across all servers")
40                }
41                (McpSegment::Any, McpSegment::Any) => Ok("mcp__*".to_owned()),
42                _ => Ok(format!("mcp__{server}__{tool}")),
43            },
44            Self::Harness(HarnessId::Cursor) => Ok(format!("Mcp({server}:{tool})")),
45            Self::Harness(HarnessId::OpenCode) => Ok(format!("{server}_{tool}")),
46            Self::Harness(HarnessId::Codex) => {
47                Err("Codex per-tool MCP gating lives in server config, not the tool list")
48            }
49            Self::Harness(HarnessId::Pi) => Err("Harness has no MCP tool surface"),
50            Self::MeridianFlow => unreachable!("Flow's MCP refs are absent in `project_rule`"),
51        }
52    }
53}
54
55/// Whether Mars can name a rule's tools on a harness.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum NativeStatus {
58    /// Mars knows the native name(s). A stricter rule on the same native name can leave this
59    /// rule no surviving name.
60    Known,
61    /// The harness has no such tool, so there is nothing to allow or deny.
62    Absent,
63    /// Mars cannot name it on this harness, for the reason given: the harness has no switch
64    /// for it, Mars has no row for it, or the name is not one Mars recognizes (a typo). The
65    /// launch bundle reports the reason in `note` and nowhere else.
66    Unknown(&'static str),
67    /// The rule has a pattern and the host's tools take no scope, so it cannot be applied as
68    /// written. Only a host that does not scope patterns reports it.
69    Unscopable,
70}
71
72impl NativeStatus {
73    /// The bundle's `native_status`.
74    pub fn as_str(self) -> &'static str {
75        match self {
76            Self::Known => "known",
77            Self::Absent => "absent",
78            Self::Unknown(_) => "unknown",
79            Self::Unscopable => "unscopable",
80        }
81    }
82
83    /// Why Mars could not name the rule, for `unknown` and `unscopable`.
84    pub fn note(self) -> Option<&'static str> {
85        match self {
86            Self::Unknown(note) => Some(note),
87            Self::Unscopable => Some(UNSCOPABLE_NOTE),
88            Self::Known | Self::Absent => None,
89        }
90    }
91}
92
93const UNSCOPABLE_NOTE: &str = "this host's tool takes no pattern, so the rule cannot be scoped";
94const NO_NATIVE_NAME: &str = "no native name known for this tool on this harness; left out";
95
96/// The stricter rule that wins a covered rule's calls, as its author wrote it.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
98pub struct CoveredBy {
99    pub action: ToolAction,
100    pub key: String,
101}
102
103impl CoveredBy {
104    fn new(rule: &ToolRule) -> Self {
105        Self {
106            action: rule.action,
107            key: rule.render(),
108        }
109    }
110}
111
112impl std::fmt::Display for CoveredBy {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        write!(f, "{} {}", self.action.as_str(), self.key)
115    }
116}
117
118/// One permission spelling and the unscoped harness tool names the canonical rule concerns.
119///
120/// Keeping the relationship intact lets conflict resolution remove availability tools with
121/// the permission they belong to. Claude scoped rules are the non-trivial case: one
122/// `Edit(path)` permission can concern `Edit`, `Write` and `NotebookEdit`.
123///
124/// A binding is never removed. `beaten_by` marks one a stricter rule wins, so it is still
125/// something the rule makes available but no longer something it tells the permission engine.
126#[derive(Debug, Clone, PartialEq, Eq)]
127struct NativeBinding {
128    native: String,
129    native_tools: Vec<String>,
130    /// The stricter rule (`deny bash`) that wins this name.
131    beaten_by: Option<CoveredBy>,
132}
133
134impl NativeBinding {
135    fn direct(name: &str, pattern: Option<&str>) -> Self {
136        Self {
137            native: render_scoped(name, pattern),
138            native_tools: vec![name.to_string()],
139            beaten_by: None,
140        }
141    }
142
143    fn scoped(name: &str, pattern: &str, native_tools: &[&str]) -> Self {
144        Self {
145            native: render_scoped(name, Some(pattern)),
146            native_tools: native_tools
147                .iter()
148                .map(|name| (*name).to_string())
149                .collect(),
150            beaten_by: None,
151        }
152    }
153}
154
155/// A rule as one harness spells it.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct ProjectedRule {
158    /// Every name the rule makes available. The ones not `beaten_by` are what it tells the
159    /// permission engine ([`Self::native`]); a covered rule tells it nothing, so a reader that
160    /// ignores `covered_by` cannot let through a call the covering rule refuses.
161    bindings: Vec<NativeBinding>,
162    /// `None` for `*`, which names no tool.
163    pub status: Option<NativeStatus>,
164    /// A harness-specific consequence of this projection that callers must surface even when
165    /// the native name is known.
166    note: Option<&'static str>,
167    /// The stricter rule (`deny bash`) that covers this one, so that it never applies: another
168    /// rule wins every call it would match, or every name it has on this harness.
169    pub covered_by: Option<CoveredBy>,
170}
171
172impl ProjectedRule {
173    fn known(bindings: Vec<NativeBinding>, note: Option<&'static str>) -> Self {
174        Self {
175            bindings,
176            status: Some(NativeStatus::Known),
177            note,
178            covered_by: None,
179        }
180    }
181
182    fn with_status(status: NativeStatus) -> Self {
183        Self {
184            bindings: Vec::new(),
185            status: Some(status),
186            note: None,
187            covered_by: None,
188        }
189    }
190
191    fn winning(&self) -> impl Iterator<Item = &NativeBinding> {
192        self.bindings
193            .iter()
194            .filter(|binding| binding.beaten_by.is_none())
195    }
196
197    /// Permission-rule spellings after conflict resolution.
198    pub fn native(&self) -> Vec<String> {
199        self.native_names().cloned().collect()
200    }
201
202    /// Unscoped harness tool names concerned by the surviving permission rules, each once.
203    pub fn native_tools(&self) -> Vec<String> {
204        let mut tools = Vec::new();
205        for binding in self.winning() {
206            for tool in &binding.native_tools {
207                if !tools.contains(tool) {
208                    tools.push(tool.clone());
209                }
210            }
211        }
212        tools
213    }
214
215    fn native_names(&self) -> impl Iterator<Item = &String> {
216        self.winning().map(|binding| &binding.native)
217    }
218
219    /// Every name the rule makes available, whether or not a stricter rule wins it.
220    fn available_names(&self) -> impl Iterator<Item = &String> {
221        self.bindings.iter().map(|binding| &binding.native)
222    }
223
224    fn beat(&mut self, by: CoveredBy) {
225        for binding in &mut self.bindings {
226            binding.beaten_by.get_or_insert_with(|| by.clone());
227        }
228        self.covered_by = Some(by);
229    }
230
231    /// Why Mars could not name this rule on the harness, when it could not.
232    pub fn gap(&self) -> Option<&'static str> {
233        self.status.and_then(NativeStatus::note)
234    }
235
236    /// A known projection's semantic note, or an unknown projection's gap reason.
237    pub fn note(&self) -> Option<&'static str> {
238        self.note.or_else(|| self.gap())
239    }
240}
241
242/// Project `rule` onto `harness`. The one place a capability becomes native permission names
243/// and unscoped harness tool names.
244fn project_rule(rule: &ToolRule, host: Host) -> ProjectedRule {
245    match &rule.capability {
246        Capability::Any => ProjectedRule {
247            bindings: Vec::new(),
248            status: None,
249            note: None,
250            covered_by: None,
251        },
252        // Flow's tool set is closed: it has no MCP tools, whatever the ref or wire token.
253        Capability::Mcp(_) if host == Host::MeridianFlow => {
254            ProjectedRule::with_status(NativeStatus::Absent)
255        }
256        Capability::Unknown(name) if is_mcp_wire_token(name) && host == Host::MeridianFlow => {
257            ProjectedRule::with_status(NativeStatus::Absent)
258        }
259        Capability::Mcp(mcp_ref) => match host.mcp_token(mcp_ref) {
260            Ok(token) => ProjectedRule::known(vec![NativeBinding::direct(&token, None)], None),
261            Err(reason) => ProjectedRule::with_status(NativeStatus::Unknown(reason)),
262        },
263        Capability::Unknown(name) if is_mcp_wire_token(name) => ProjectedRule::known(
264            vec![NativeBinding::direct(name, rule.pattern.as_deref())],
265            None,
266        ),
267        Capability::Unknown(_) => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
268        Capability::Builtin(name) => {
269            project_builtin_capability(name, rule.pattern.as_deref(), host)
270        }
271    }
272}
273
274/// Project one canonical builtin capability through the same table and status semantics as a
275/// profile rule. Launch-bundle platform rules use this without inventing a second native-name
276/// projection path.
277pub fn project_platform_capability(capability: &'static str, host: Host) -> ProjectedRule {
278    project_builtin_capability(capability, None, host)
279}
280
281fn project_builtin_capability(
282    capability: &str,
283    pattern: Option<&str>,
284    host: Host,
285) -> ProjectedRule {
286    let row = tool_natives::lookup(capability, host);
287    if pattern.is_some()
288        && !host.scopes_patterns()
289        && matches!(row, Some(Native::Tools(_) | Native::ScopedTools { .. }))
290    {
291        return ProjectedRule::with_status(NativeStatus::Unscopable);
292    }
293    match row {
294        Some(Native::Tools(names)) => ProjectedRule::known(
295            names
296                .iter()
297                .map(|name| NativeBinding::direct(name, pattern))
298                .collect(),
299            None,
300        ),
301        Some(
302            native @ Native::ScopedTools {
303                unscoped,
304                scoped: scoped_names,
305                note,
306            },
307        ) => {
308            let (bindings, note) = match pattern {
309                Some(pattern) => (
310                    scoped_names
311                        .iter()
312                        .map(|name| NativeBinding::scoped(name, pattern, native.native_tools()))
313                        .collect(),
314                    Some(note),
315                ),
316                None => (
317                    unscoped
318                        .iter()
319                        .map(|name| NativeBinding::direct(name, None))
320                        .collect(),
321                    None,
322                ),
323            };
324            ProjectedRule::known(bindings, note)
325        }
326        Some(Native::Absent) => ProjectedRule::with_status(NativeStatus::Absent),
327        Some(Native::NoSwitch(note)) => ProjectedRule::with_status(NativeStatus::Unknown(note)),
328        None => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
329    }
330}
331
332/// Lower `policy` onto `host`. The one place a rule list becomes native names, gaps and
333/// coverage; pure over the rules, the host and the published native tables.
334pub fn project(policy: &EffectiveToolPolicy, host: impl Into<Host>) -> PolicyProjection<'_> {
335    let host = host.into();
336    let mut rules: Vec<(&ToolRule, ProjectedRule)> = policy
337        .rules
338        .iter()
339        .map(|rule| (rule, project_rule(rule, host)))
340        .collect();
341    keep_strictest_per_native(&mut rules);
342    for (index, by) in covered(policy) {
343        rules[index].1.beat(CoveredBy::new(by));
344    }
345    PolicyProjection { host, rules }
346}
347
348/// Which rules that name tools a query covers. `*` names none, so no kind covers it.
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350pub enum RuleKind {
351    /// Built-in tools: everything but MCP refs.
352    Builtin,
353    Mcp,
354    All,
355}
356
357impl RuleKind {
358    fn covers(self, rule: &ToolRule) -> bool {
359        match self {
360            Self::Builtin => !rule.is_mcp() && !rule.is_wildcard(),
361            Self::Mcp => rule.is_mcp(),
362            Self::All => !rule.is_wildcard(),
363        }
364    }
365}
366
367/// The `note` on a rule that lost a native name to a stricter rule on the same name.
368const STRICTER_RULE_NOTE: &str = "a stricter rule controls the same native tool and wins (deny, then ask, then allow); this rule is left out";
369
370/// A policy's rules spelled for one harness, in profile order.
371pub struct PolicyProjection<'a> {
372    host: Host,
373    rules: Vec<(&'a ToolRule, ProjectedRule)>,
374}
375
376impl<'a> PolicyProjection<'a> {
377    pub fn rules(&self) -> &[(&'a ToolRule, ProjectedRule)] {
378        &self.rules
379    }
380
381    /// What a tool no rule names gets: the strictest `*` rule's action, or `None` without one.
382    pub fn default_action(&self) -> Option<ToolAction> {
383        self.rules
384            .iter()
385            .filter(|(rule, _)| rule.is_wildcard())
386            .map(|(rule, _)| rule.action)
387            .max_by_key(|action| action.strictness())
388    }
389
390    /// The projected `kind` rules with `action`: built-in tools first, then MCP refs.
391    fn select(&self, action: ToolAction, kind: RuleKind) -> Vec<&ProjectedRule> {
392        let mut picked: Vec<_> = self
393            .rules
394            .iter()
395            .filter(|(rule, _)| rule.action == action && kind.covers(rule))
396            .collect();
397        picked.sort_by_key(|(rule, _)| rule.is_mcp());
398        picked.into_iter().map(|(_, projected)| projected).collect()
399    }
400
401    /// Native names of the `kind` rules with `action`, built-in tools first, each name once.
402    pub fn natives(&self, action: ToolAction, kind: RuleKind) -> Vec<String> {
403        let mut names: Vec<String> = Vec::new();
404        for projected in self.select(action, kind) {
405            for native in projected.native_names() {
406                if !names.contains(native) {
407                    names.push(native.clone());
408                }
409            }
410        }
411        names
412    }
413
414    /// Names of every allow and ask rule, taken before coverage and conflict resolution cleared
415    /// any: the tools an allowlist must keep available. A deny that beats one of them is
416    /// written beside the list, never by emptying it.
417    pub fn available(&self) -> Vec<String> {
418        let mut names: Vec<String> = Vec::new();
419        let mut rules: Vec<_> = self
420            .rules
421            .iter()
422            .filter(|(rule, _)| rule.action != ToolAction::Deny && !rule.is_wildcard())
423            .collect();
424        rules.sort_by_key(|(rule, _)| rule.is_mcp());
425        for (_, projected) in rules {
426            for name in projected.available_names() {
427                if !names.contains(name) {
428                    names.push(name.clone());
429                }
430            }
431        }
432        names
433    }
434
435    /// Why Mars could not name each `kind` rule with `action`.
436    pub fn gaps(&self, action: ToolAction, kind: RuleKind) -> Vec<&'static str> {
437        self.select(action, kind)
438            .into_iter()
439            .filter_map(ProjectedRule::gap)
440            .collect()
441    }
442}
443
444/// The published shape of a projection (`project` in the WASM package): per rule, then the
445/// native names each action ends with. A consumer decides from these what to warn about: a
446/// `status` other than `known`, a `covered_by` or a `note` is something the author may not
447/// have meant.
448impl Serialize for PolicyProjection<'_> {
449    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
450        struct Rule<'r>(&'r ToolRule, &'r ProjectedRule);
451        impl Serialize for Rule<'_> {
452            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
453                let Rule(rule, projected) = self;
454                let mut out = serializer.serialize_struct("ProjectedRule", 6)?;
455                out.serialize_field("rule", rule)?;
456                out.serialize_field("status", &projected.status.map(NativeStatus::as_str))?;
457                out.serialize_field("native", &projected.native())?;
458                out.serialize_field("native_tools", &projected.native_tools())?;
459                out.serialize_field("note", &projected.note())?;
460                out.serialize_field("covered_by", &projected.covered_by)?;
461                out.end()
462            }
463        }
464        let rules: Vec<Rule> = self.rules.iter().map(|(r, p)| Rule(r, p)).collect();
465        let mut out = serializer.serialize_struct("ToolProjection", 7)?;
466        out.serialize_field("host", &self.host)?;
467        out.serialize_field("default", &self.default_action().map(ToolAction::as_str))?;
468        out.serialize_field("rules", &rules)?;
469        out.serialize_field("allow", &self.natives(ToolAction::Allow, RuleKind::All))?;
470        out.serialize_field("deny", &self.natives(ToolAction::Deny, RuleKind::All))?;
471        out.serialize_field("ask", &self.natives(ToolAction::Ask, RuleKind::All))?;
472        out.serialize_field("available", &self.available())?;
473        out.end()
474    }
475}
476
477/// Of the rules that name one native permission, the strictest action keeps it (deny, then ask,
478/// then allow), as Claude's own lists do. `edit: deny` beside `write: allow` leaves the allow
479/// no `Write` on Claude and no `write` on Pi; capabilities a harness cannot tell apart
480/// (`write` and `edit` on Codex) resolve the same way. A rule that loses a name gets a note.
481fn keep_strictest_per_native(rules: &mut [(&ToolRule, ProjectedRule)]) {
482    let named: Vec<(&ToolRule, Vec<String>)> = rules
483        .iter()
484        .map(|(rule, projected)| (*rule, projected.native()))
485        .collect();
486    for (rule, projected) in rules.iter_mut() {
487        let mut beaten = 0;
488        for binding in &mut projected.bindings {
489            let by = named.iter().find(|(stricter, names)| {
490                stricter.action.strictness() > rule.action.strictness()
491                    && names.contains(&binding.native)
492            });
493            if let Some((stricter, _)) = by {
494                binding.beaten_by = Some(CoveredBy::new(stricter));
495                beaten += 1;
496            }
497        }
498        if beaten > 0 {
499            projected.note = Some(STRICTER_RULE_NOTE);
500        }
501        if beaten > 0 && beaten == projected.bindings.len() {
502            projected.covered_by = projected.bindings[0].beaten_by.clone();
503        }
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510    use crate::frontmatter::Frontmatter;
511    use crate::tool_names::parse_mars_tool_name;
512    use crate::tool_policy::append_mcp_server_entries_to_tools;
513    use serde_yaml::Value;
514
515    fn agent_policy(yaml: &str) -> EffectiveToolPolicy {
516        let reading = crate::agent::read(yaml);
517        assert!(
518            reading.diagnostics.is_empty(),
519            "agent diags: {:?}",
520            reading.diagnostics
521        );
522        reading.fields.unwrap().tools
523    }
524
525    /// Native names and status of a raw tool entry on a harness, via parse then table.
526    fn natives(raw: &str, harness: &str) -> (Vec<String>, &'static str) {
527        let kind = Host::parse(harness).expect("test host exists");
528        let parsed = parse_mars_tool_name(raw).unwrap();
529        let projected = project_rule(&ToolRule::from_parsed(parsed, ToolAction::Deny), kind);
530        (
531            projected.native(),
532            projected.status.map_or("none", NativeStatus::as_str),
533        )
534    }
535
536    fn known(names: &[&str]) -> (Vec<String>, &'static str) {
537        (names.iter().map(|n| n.to_string()).collect(), "known")
538    }
539
540    #[test]
541    fn covered_allows_stay_available() {
542        // `deny` covers the allow, so the allow names no permission; the tool it opens stays
543        // on Claude's `tools:` list, and the deny is what takes it back.
544        let policy = agent_policy(
545            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  write: allow\n  edit: deny\n  'bash(git status *)': allow\n  bash: ask\n---\n",
546        );
547        let projection = project(&policy, HarnessId::Claude);
548        assert_eq!(
549            projection.natives(ToolAction::Allow, RuleKind::All),
550            Vec::<String>::new()
551        );
552        assert_eq!(
553            projection.available(),
554            ["Write", "Bash(git status *)", "Bash"]
555        );
556    }
557
558    #[test]
559    fn append_mcp_server_entries_to_tools_preserves_map_form() {
560        let mut fm = Frontmatter::parse("---\ntools:\n  Bash: allow\n  Read: deny\n---\n").unwrap();
561        assert!(append_mcp_server_entries_to_tools(
562            &mut fm,
563            &["context7".to_string(), "github".to_string()]
564        ));
565        let tools = fm.get("tools").unwrap();
566        let Value::Mapping(mapping) = tools else {
567            panic!("expected map-form tools, got {tools:?}");
568        };
569        assert_eq!(
570            mapping.get(Value::String("Bash".into())),
571            Some(&Value::String("allow".into()))
572        );
573        assert_eq!(
574            mapping.get(Value::String("Read".into())),
575            Some(&Value::String("deny".into()))
576        );
577        assert_eq!(
578            mapping.get(Value::String("mcp(context7)".into())),
579            Some(&Value::String("allow".into()))
580        );
581        assert_eq!(
582            mapping.get(Value::String("mcp(github)".into())),
583            Some(&Value::String("allow".into()))
584        );
585    }
586
587    #[test]
588    fn map_form_allows_are_grants_not_an_allowlist() {
589        let policy = agent_policy(
590            "---\nname: a\ndescription: d\ntools:\n  read: allow\n  edit: deny\n---\n",
591        );
592        assert_eq!(policy.describe(), vec!["allow:read", "deny:edit"]);
593        assert!(!policy.is_allowlist());
594    }
595
596    #[test]
597    fn explicit_wildcard_deny_makes_a_map_an_allowlist() {
598        let policy = agent_policy(
599            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  'bash(rg *)': allow\n---\n",
600        );
601        assert_eq!(policy.describe(), vec!["deny:*", "allow:bash(rg *)"]);
602        assert!(policy.is_allowlist());
603    }
604
605    #[test]
606    fn the_strictest_action_keeps_each_native_name_on_every_harness() {
607        // (rules, harness, the allow rule's surviving names, the deny rule's)
608        type Row = (
609            &'static str,
610            &'static str,
611            HarnessId,
612            &'static [&'static str],
613            &'static [&'static str],
614        );
615        let rows: &[Row] = &[
616            (
617                "edit",
618                "write",
619                HarnessId::Claude,
620                &[],
621                &["Edit", "Write", "NotebookEdit"],
622            ),
623            (
624                "edit",
625                "notebook",
626                HarnessId::Claude,
627                &[],
628                &["Edit", "Write", "NotebookEdit"],
629            ),
630            ("edit", "write", HarnessId::Pi, &[], &["edit", "write"]),
631            ("edit", "write", HarnessId::Codex, &[], &["apply_patch"]),
632            ("edit", "write", HarnessId::OpenCode, &[], &["edit"]),
633            (
634                "web",
635                "web_fetch",
636                HarnessId::Claude,
637                &[],
638                &["WebSearch", "WebFetch"],
639            ),
640            (
641                "web",
642                "web_search",
643                HarnessId::Claude,
644                &[],
645                &["WebSearch", "WebFetch"],
646            ),
647        ];
648        for (deny, allow, harness, allowed, denied) in rows {
649            let policy = agent_policy(&format!(
650                "---\nname: a\ndescription: d\ntools:\n  {deny}: deny\n  {allow}: allow\n---\n"
651            ));
652            let projection = project(&policy, *harness);
653            assert_eq!(
654                projection.rules()[1].1.native(),
655                *allowed,
656                "{deny}/{allow} {harness:?}"
657            );
658            assert!(projection.rules()[1].1.note().is_some());
659            assert_eq!(
660                projection.rules()[0].1.native(),
661                *denied,
662                "{deny}/{allow} {harness:?}"
663            );
664        }
665    }
666
667    #[test]
668    fn a_scoped_rule_does_not_narrow_an_unscoped_one() {
669        let policy = agent_policy(
670            "---\nname: a\ndescription: d\ntools:\n  bash: allow\n  'bash(git push *)': deny\n---\n",
671        );
672        let projection = project(&policy, HarnessId::Claude);
673        assert_eq!(projection.rules()[0].1.native(), ["Bash"]);
674        assert_eq!(projection.rules()[1].1.native(), ["Bash(git push *)"]);
675    }
676
677    #[test]
678    fn mcp_server_entries_appended_to_absent_tools_do_not_create_an_allowlist() {
679        // A Claude agent with `mcpServers` and no `tools:` inherits every tool. The
680        // synthesized `mcp(server)` grant must not turn that into "MCP only".
681        let mut fm = Frontmatter::parse("---\nname: a\n---\n").unwrap();
682        assert!(append_mcp_server_entries_to_tools(
683            &mut fm,
684            &["context7".to_string()]
685        ));
686        let policy = crate::agent::read(&fm.render()).fields.unwrap().tools;
687        assert_eq!(policy.describe(), vec!["allow:mcp(context7/*)"]);
688        assert!(!policy.is_allowlist());
689    }
690
691    #[test]
692    fn aliases_and_native_spellings_reach_the_same_native_tools() {
693        assert_eq!(natives("Bash", "codex"), known(&["exec_command"]));
694        assert_eq!(natives("shell", "claude"), known(&["Bash"]));
695        assert_eq!(natives("exec_command", "claude"), known(&["Bash"]));
696        assert_eq!(natives("WebSearch", "opencode"), known(&["websearch"]));
697        assert_eq!(
698            natives("web", "opencode"),
699            known(&["websearch", "webfetch"])
700        );
701        assert_eq!(
702            natives("AskUserQuestion", "claude"),
703            known(&["AskUserQuestion"])
704        );
705        assert_eq!(natives("askuser", "opencode"), known(&["question"]));
706        assert_eq!(
707            natives("edit", "claude"),
708            known(&["Edit", "Write", "NotebookEdit"])
709        );
710        assert_eq!(natives("todowrite", "claude").0.len(), 7);
711    }
712
713    #[test]
714    fn claude_scoped_file_rules_separate_permissions_from_callable_tools() {
715        assert_eq!(
716            natives("bash(git push *)", "codex"),
717            known(&["exec_command(git push *)"])
718        );
719        for (rule, native, native_tools) in [
720            ("read(src/**)", "Read(src/**)", &["Read"][..]),
721            ("write(src/**)", "Edit(src/**)", &["Write"][..]),
722            (
723                "edit(src/**)",
724                "Edit(src/**)",
725                &["Edit", "Write", "NotebookEdit"][..],
726            ),
727            ("notebook(src/**)", "Edit(src/**)", &["NotebookEdit"][..]),
728            ("glob(src/**)", "Read(src/**)", &["Glob"][..]),
729            ("grep(src/**)", "Read(src/**)", &["Grep"][..]),
730            (
731                "web_fetch(domain:example.com)",
732                "WebFetch(domain:example.com)",
733                &["WebFetch"][..],
734            ),
735        ] {
736            assert_eq!(natives(rule, "claude"), known(&[native]), "{rule}");
737            let parsed = parse_mars_tool_name(rule).unwrap();
738            let projected = project_rule(
739                &ToolRule::from_parsed(parsed, ToolAction::Deny),
740                Host::Harness(HarnessId::Claude),
741            );
742            assert_eq!(projected.native_tools(), native_tools, "{rule}");
743        }
744
745        let write = project_rule(
746            &ToolRule::from_parsed(
747                parse_mars_tool_name("write(src/**)").unwrap(),
748                ToolAction::Allow,
749            ),
750            Host::Harness(HarnessId::Claude),
751        );
752        assert!(
753            write
754                .note()
755                .is_some_and(|note| note.contains("deny also refuses other built-in file edits")),
756            "{:?}",
757            write.note()
758        );
759    }
760
761    #[test]
762    fn claude_strictest_action_wins_when_scoped_capabilities_share_a_permission() {
763        let policy = agent_policy(
764            "---\nname: a\ndescription: d\ntools:\n  'write(src/**)': allow\n  'edit(src/**)': ask\n  'notebook(src/**)': deny\n---\n",
765        );
766        let projection = project(&policy, HarnessId::Claude);
767        assert!(projection.rules()[0].1.native().is_empty(), "allow loses");
768        assert!(
769            projection.rules()[0].1.native_tools().is_empty(),
770            "shadowed rules name no availability tools"
771        );
772        assert!(projection.rules()[1].1.native().is_empty(), "ask loses");
773        assert!(projection.rules()[1].1.native_tools().is_empty());
774        assert_eq!(projection.rules()[2].1.native(), ["Edit(src/**)"]);
775        assert_eq!(projection.rules()[2].1.native_tools(), ["NotebookEdit"]);
776        assert_eq!(
777            projection.natives(ToolAction::Deny, RuleKind::Builtin),
778            ["Edit(src/**)"]
779        );
780        assert!(
781            projection.rules()[0]
782                .1
783                .note()
784                .is_some_and(|note| note.contains("deny, then ask, then allow"))
785        );
786    }
787
788    #[test]
789    fn a_tool_the_harness_lacks_is_absent_not_guessed() {
790        assert_eq!(natives("notebook", "codex"), (vec![], "absent"));
791        assert_eq!(natives("ask_user", "pi"), (vec![], "absent"));
792    }
793
794    #[test]
795    fn a_thing_the_harness_can_do_without_a_tool_to_switch_is_unknown_not_absent() {
796        // Codex fetches pages through `web_search` and reads, globs and greps through its shell;
797        // Codex and Pi load skills by reading files.
798        for (capability, harness) in [
799            ("web_fetch", "codex"),
800            ("skill", "codex"),
801            ("skill", "pi"),
802            ("read", "codex"),
803            ("glob", "codex"),
804            ("grep", "codex"),
805        ] {
806            assert_eq!(
807                natives(capability, harness),
808                (vec![], "unknown"),
809                "{harness} {capability}"
810            );
811        }
812    }
813
814    #[test]
815    fn a_name_without_a_table_row_is_unknown_with_no_native_name() {
816        // Known capability, no Cursor row: no convention fallback fills it in.
817        assert_eq!(natives("lsp", "cursor"), (vec![], "unknown"));
818        // Not a capability at all, including one that merely looks like the `mcp` capability.
819        for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
820            assert_eq!(
821                natives("my_custom_tool", harness),
822                (vec![], "unknown"),
823                "{harness}"
824            );
825        }
826        for raw in ["café_tool", "🚀tool"] {
827            assert_eq!(natives(raw, "claude"), (vec![], "unknown"));
828        }
829    }
830
831    #[test]
832    fn mcp_wire_tokens_are_verbatim_on_every_harness() {
833        for raw in [
834            "mcp__github__CreateIssue",
835            "MCP__Server__Tool",
836            "mcp__github__create_issue",
837        ] {
838            for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
839                assert_eq!(natives(raw, harness), known(&[raw]), "{raw} on {harness}");
840                let kind = Host::parse(harness).expect("test host exists");
841                let projected = project_rule(
842                    &ToolRule::from_parsed(parse_mars_tool_name(raw).unwrap(), ToolAction::Deny),
843                    kind,
844                );
845                assert_eq!(projected.native_tools(), [raw], "{raw} on {harness}");
846            }
847        }
848    }
849
850    #[test]
851    fn the_any_capability_names_no_tool_and_has_no_status() {
852        assert_eq!(natives("*", "claude"), (vec![], "none"));
853    }
854}