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