1use 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
20impl Host {
22 fn scopes_patterns(self) -> bool {
25 !matches!(self, Self::MeridianFlow)
26 }
27
28 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 => {
51 unreachable!("Flow's MCP refs lower in `project_flow_connection_tools`")
52 }
53 }
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum NativeStatus {
60 Known,
63 Absent,
65 Unknown(&'static str),
69 Unscopable,
72}
73
74impl NativeStatus {
75 pub fn as_str(self) -> &'static str {
77 match self {
78 Self::Known => "known",
79 Self::Absent => "absent",
80 Self::Unknown(_) => "unknown",
81 Self::Unscopable => "unscopable",
82 }
83 }
84
85 pub fn note(self) -> Option<&'static str> {
87 match self {
88 Self::Unknown(note) => Some(note),
89 Self::Unscopable => Some(UNSCOPABLE_NOTE),
90 Self::Known | Self::Absent => None,
91 }
92 }
93}
94
95const UNSCOPABLE_NOTE: &str = "this host's tool takes no pattern, so the rule cannot be scoped";
96const 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";
97const 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";
98const 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";
99const NO_NATIVE_NAME: &str = "no native name known for this tool on this harness; left out";
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct CoveredBy {
104 pub action: ToolAction,
105 pub key: String,
106}
107
108impl CoveredBy {
109 fn new(rule: &ToolRule) -> Self {
110 Self {
111 action: rule.action,
112 key: rule.render(),
113 }
114 }
115}
116
117impl std::fmt::Display for CoveredBy {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 write!(f, "{} {}", self.action.as_str(), self.key)
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
132struct NativeBinding {
133 native: String,
134 native_tools: Vec<String>,
135 beaten_by: Option<CoveredBy>,
137}
138
139impl NativeBinding {
140 fn direct(name: &str, pattern: Option<&str>) -> Self {
141 Self {
142 native: render_scoped(name, pattern),
143 native_tools: vec![name.to_string()],
144 beaten_by: None,
145 }
146 }
147
148 fn scoped(name: &str, pattern: &str, native_tools: &[&str]) -> Self {
149 Self {
150 native: render_scoped(name, Some(pattern)),
151 native_tools: native_tools
152 .iter()
153 .map(|name| (*name).to_string())
154 .collect(),
155 beaten_by: None,
156 }
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct ProjectedRule {
163 bindings: Vec<NativeBinding>,
167 pub status: Option<NativeStatus>,
169 note: Option<&'static str>,
172 pub covered_by: Option<CoveredBy>,
175}
176
177impl ProjectedRule {
178 fn known(bindings: Vec<NativeBinding>, note: Option<&'static str>) -> Self {
179 Self {
180 bindings,
181 status: Some(NativeStatus::Known),
182 note,
183 covered_by: None,
184 }
185 }
186
187 fn with_status(status: NativeStatus) -> Self {
188 Self {
189 bindings: Vec::new(),
190 status: Some(status),
191 note: None,
192 covered_by: None,
193 }
194 }
195
196 fn winning(&self) -> impl Iterator<Item = &NativeBinding> {
197 self.bindings
198 .iter()
199 .filter(|binding| binding.beaten_by.is_none())
200 }
201
202 pub fn native(&self) -> Vec<String> {
204 self.native_names().cloned().collect()
205 }
206
207 pub fn native_tools(&self) -> Vec<String> {
209 let mut tools = Vec::new();
210 for binding in self.winning() {
211 for tool in &binding.native_tools {
212 if !tools.contains(tool) {
213 tools.push(tool.clone());
214 }
215 }
216 }
217 tools
218 }
219
220 fn native_names(&self) -> impl Iterator<Item = &String> {
221 self.winning().map(|binding| &binding.native)
222 }
223
224 fn available_names(&self) -> impl Iterator<Item = &String> {
226 self.bindings.iter().map(|binding| &binding.native)
227 }
228
229 fn beat(&mut self, by: CoveredBy) {
230 for binding in &mut self.bindings {
231 binding.beaten_by.get_or_insert_with(|| by.clone());
232 }
233 self.covered_by = Some(by);
234 }
235
236 pub fn gap(&self) -> Option<&'static str> {
238 self.status.and_then(NativeStatus::note)
239 }
240
241 pub fn note(&self) -> Option<&'static str> {
243 self.note.or_else(|| self.gap())
244 }
245}
246
247fn project_rule(rule: &ToolRule, host: Host, restricted: bool) -> ProjectedRule {
253 match &rule.capability {
254 Capability::Any => ProjectedRule {
255 bindings: Vec::new(),
256 status: None,
257 note: None,
258 covered_by: None,
259 },
260 capability if host == Host::MeridianFlow && capability.names_mcp() => {
261 project_flow_connection_tools(rule.action, restricted)
262 }
263 Capability::Mcp(mcp_ref) => match host.mcp_token(mcp_ref) {
264 Ok(token) => ProjectedRule::known(vec![NativeBinding::direct(&token, None)], None),
265 Err(reason) => ProjectedRule::with_status(NativeStatus::Unknown(reason)),
266 },
267 Capability::Unknown(name) if is_mcp_wire_token(name) => ProjectedRule::known(
268 vec![NativeBinding::direct(name, rule.pattern.as_deref())],
269 None,
270 ),
271 Capability::Unknown(_) => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
272 Capability::Builtin(name) => {
273 project_builtin_capability(name, rule.pattern.as_deref(), host)
274 }
275 }
276}
277
278fn project_flow_connection_tools(action: ToolAction, restricted: bool) -> ProjectedRule {
285 if restricted && action != ToolAction::Deny {
286 return ProjectedRule::known(Vec::new(), Some(FLOW_MCP_GRANT_NOTE));
287 }
288 let note = match action {
289 ToolAction::Deny => Some(FLOW_MCP_DENY_NOTE),
290 ToolAction::Ask => Some(FLOW_MCP_ASK_NOTE),
291 ToolAction::Allow => None,
292 };
293 let bindings = tool_natives::FLOW_CONNECTION_TOOLS
294 .iter()
295 .map(|name| NativeBinding::direct(name, None))
296 .collect();
297 ProjectedRule::known(bindings, note)
298}
299
300pub fn project_platform_capability(capability: &'static str, host: Host) -> ProjectedRule {
304 project_builtin_capability(capability, None, host)
305}
306
307fn project_builtin_capability(
308 capability: &str,
309 pattern: Option<&str>,
310 host: Host,
311) -> ProjectedRule {
312 let row = tool_natives::lookup(capability, host);
313 if pattern.is_some()
314 && !host.scopes_patterns()
315 && matches!(row, Some(Native::Tools(_) | Native::ScopedTools { .. }))
316 {
317 return ProjectedRule::with_status(NativeStatus::Unscopable);
318 }
319 match row {
320 Some(Native::Tools(names)) => ProjectedRule::known(
321 names
322 .iter()
323 .map(|name| NativeBinding::direct(name, pattern))
324 .collect(),
325 None,
326 ),
327 Some(
328 native @ Native::ScopedTools {
329 unscoped,
330 scoped: scoped_names,
331 note,
332 },
333 ) => {
334 let (bindings, note) = match pattern {
335 Some(pattern) => (
336 scoped_names
337 .iter()
338 .map(|name| NativeBinding::scoped(name, pattern, native.native_tools()))
339 .collect(),
340 Some(note),
341 ),
342 None => (
343 unscoped
344 .iter()
345 .map(|name| NativeBinding::direct(name, None))
346 .collect(),
347 None,
348 ),
349 };
350 ProjectedRule::known(bindings, note)
351 }
352 Some(Native::Absent) => ProjectedRule::with_status(NativeStatus::Absent),
353 Some(Native::NoSwitch(note)) => ProjectedRule::with_status(NativeStatus::Unknown(note)),
354 None => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
355 }
356}
357
358pub fn project(policy: &EffectiveToolPolicy, host: impl Into<Host>) -> PolicyProjection<'_> {
361 let host = host.into();
362 let restricted = policy
363 .rules
364 .iter()
365 .any(|rule| rule.is_wildcard() && rule.action != ToolAction::Allow);
366 let mut rules: Vec<(&ToolRule, ProjectedRule)> = policy
367 .rules
368 .iter()
369 .map(|rule| (rule, project_rule(rule, host, restricted)))
370 .collect();
371 keep_strictest_per_native(&mut rules);
372 for (index, by) in covered(policy) {
373 rules[index].1.beat(CoveredBy::new(by));
374 }
375 PolicyProjection { host, rules }
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum RuleKind {
381 Builtin,
383 Mcp,
384 All,
385}
386
387impl RuleKind {
388 fn covers(self, rule: &ToolRule) -> bool {
389 match self {
390 Self::Builtin => !rule.is_mcp() && !rule.is_wildcard(),
391 Self::Mcp => rule.is_mcp(),
392 Self::All => !rule.is_wildcard(),
393 }
394 }
395}
396
397const STRICTER_RULE_NOTE: &str = "a stricter rule controls the same native tool and wins (deny, then ask, then allow); this rule is left out";
399
400pub struct PolicyProjection<'a> {
402 host: Host,
403 rules: Vec<(&'a ToolRule, ProjectedRule)>,
404}
405
406impl<'a> PolicyProjection<'a> {
407 pub fn rules(&self) -> &[(&'a ToolRule, ProjectedRule)] {
408 &self.rules
409 }
410
411 pub fn default_action(&self) -> Option<ToolAction> {
413 self.rules
414 .iter()
415 .filter(|(rule, _)| rule.is_wildcard())
416 .map(|(rule, _)| rule.action)
417 .max_by_key(|action| action.strictness())
418 }
419
420 fn select(&self, action: ToolAction, kind: RuleKind) -> Vec<&ProjectedRule> {
422 let mut picked: Vec<_> = self
423 .rules
424 .iter()
425 .filter(|(rule, _)| rule.action == action && kind.covers(rule))
426 .collect();
427 picked.sort_by_key(|(rule, _)| rule.is_mcp());
428 picked.into_iter().map(|(_, projected)| projected).collect()
429 }
430
431 pub fn natives(&self, action: ToolAction, kind: RuleKind) -> Vec<String> {
433 let mut names: Vec<String> = Vec::new();
434 for projected in self.select(action, kind) {
435 for native in projected.native_names() {
436 if !names.contains(native) {
437 names.push(native.clone());
438 }
439 }
440 }
441 names
442 }
443
444 pub fn available(&self) -> Vec<String> {
448 let mut names: Vec<String> = Vec::new();
449 let mut rules: Vec<_> = self
450 .rules
451 .iter()
452 .filter(|(rule, _)| rule.action != ToolAction::Deny && !rule.is_wildcard())
453 .collect();
454 rules.sort_by_key(|(rule, _)| rule.is_mcp());
455 for (_, projected) in rules {
456 for name in projected.available_names() {
457 if !names.contains(name) {
458 names.push(name.clone());
459 }
460 }
461 }
462 names
463 }
464
465 pub fn gaps(&self, action: ToolAction, kind: RuleKind) -> Vec<(String, &'static str)> {
467 self.rules
468 .iter()
469 .filter(|(rule, _)| rule.action == action && kind.covers(rule))
470 .filter_map(|(rule, projected)| Some((rule.render(), projected.gap()?)))
471 .collect()
472 }
473}
474
475impl Serialize for PolicyProjection<'_> {
480 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
481 struct Rule<'r>(&'r ToolRule, &'r ProjectedRule);
482 impl Serialize for Rule<'_> {
483 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
484 let Rule(rule, projected) = self;
485 let mut out = serializer.serialize_struct("ProjectedRule", 6)?;
486 out.serialize_field("rule", rule)?;
487 out.serialize_field("status", &projected.status.map(NativeStatus::as_str))?;
488 out.serialize_field("native", &projected.native())?;
489 out.serialize_field("native_tools", &projected.native_tools())?;
490 out.serialize_field("note", &projected.note())?;
491 out.serialize_field("covered_by", &projected.covered_by)?;
492 out.end()
493 }
494 }
495 let rules: Vec<Rule> = self.rules.iter().map(|(r, p)| Rule(r, p)).collect();
496 let mut out = serializer.serialize_struct("ToolProjection", 7)?;
497 out.serialize_field("host", &self.host)?;
498 out.serialize_field("default", &self.default_action().map(ToolAction::as_str))?;
499 out.serialize_field("rules", &rules)?;
500 out.serialize_field("allow", &self.natives(ToolAction::Allow, RuleKind::All))?;
501 out.serialize_field("deny", &self.natives(ToolAction::Deny, RuleKind::All))?;
502 out.serialize_field("ask", &self.natives(ToolAction::Ask, RuleKind::All))?;
503 out.serialize_field("available", &self.available())?;
504 out.end()
505 }
506}
507
508fn keep_strictest_per_native(rules: &mut [(&ToolRule, ProjectedRule)]) {
513 let named: Vec<(&ToolRule, Vec<String>)> = rules
514 .iter()
515 .map(|(rule, projected)| (*rule, projected.native()))
516 .collect();
517 for (rule, projected) in rules.iter_mut() {
518 let mut beaten = 0;
519 for binding in &mut projected.bindings {
520 let by = named.iter().find(|(stricter, names)| {
521 stricter.action.strictness() > rule.action.strictness()
522 && names.contains(&binding.native)
523 });
524 if let Some((stricter, _)) = by {
525 binding.beaten_by = Some(CoveredBy::new(stricter));
526 beaten += 1;
527 }
528 }
529 if beaten > 0 {
530 projected.note = Some(STRICTER_RULE_NOTE);
531 }
532 if beaten > 0 && beaten == projected.bindings.len() {
533 projected.covered_by = projected.bindings[0].beaten_by.clone();
534 }
535 }
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541 use crate::frontmatter::Frontmatter;
542 use crate::tool_names::parse_mars_tool_name;
543 use crate::tool_policy::append_mcp_server_entries_to_tools;
544 use serde_yaml::Value;
545
546 fn agent_policy(yaml: &str) -> EffectiveToolPolicy {
547 let reading = crate::agent::read(yaml);
548 assert!(
549 reading.diagnostics.is_empty(),
550 "agent diags: {:?}",
551 reading.diagnostics
552 );
553 reading.fields.unwrap().tools
554 }
555
556 fn natives(raw: &str, harness: &str) -> (Vec<String>, &'static str) {
558 let kind = Host::parse(harness).expect("test host exists");
559 let parsed = parse_mars_tool_name(raw).unwrap();
560 let projected = project_rule(
561 &ToolRule::from_parsed(parsed, ToolAction::Deny),
562 kind,
563 false,
564 );
565 (
566 projected.native(),
567 projected.status.map_or("none", NativeStatus::as_str),
568 )
569 }
570
571 fn known(names: &[&str]) -> (Vec<String>, &'static str) {
572 (names.iter().map(|n| n.to_string()).collect(), "known")
573 }
574
575 #[test]
576 fn covered_allows_stay_available() {
577 let policy = agent_policy(
580 "---\nname: a\ndescription: d\ntools:\n '*': deny\n write: allow\n edit: deny\n 'bash(git status *)': allow\n bash: ask\n---\n",
581 );
582 let projection = project(&policy, HarnessId::Claude);
583 assert_eq!(
584 projection.natives(ToolAction::Allow, RuleKind::All),
585 Vec::<String>::new()
586 );
587 assert_eq!(
588 projection.available(),
589 ["Write", "Bash(git status *)", "Bash"]
590 );
591 }
592
593 #[test]
594 fn append_mcp_server_entries_to_tools_preserves_map_form() {
595 let mut fm = Frontmatter::parse("---\ntools:\n Bash: allow\n Read: deny\n---\n").unwrap();
596 assert!(append_mcp_server_entries_to_tools(
597 &mut fm,
598 &["context7".to_string(), "github".to_string()]
599 ));
600 let tools = fm.get("tools").unwrap();
601 let Value::Mapping(mapping) = tools else {
602 panic!("expected map-form tools, got {tools:?}");
603 };
604 assert_eq!(
605 mapping.get(Value::String("Bash".into())),
606 Some(&Value::String("allow".into()))
607 );
608 assert_eq!(
609 mapping.get(Value::String("Read".into())),
610 Some(&Value::String("deny".into()))
611 );
612 assert_eq!(
613 mapping.get(Value::String("mcp(context7)".into())),
614 Some(&Value::String("allow".into()))
615 );
616 assert_eq!(
617 mapping.get(Value::String("mcp(github)".into())),
618 Some(&Value::String("allow".into()))
619 );
620 }
621
622 #[test]
623 fn map_form_allows_are_grants_not_an_allowlist() {
624 let policy = agent_policy(
625 "---\nname: a\ndescription: d\ntools:\n read: allow\n edit: deny\n---\n",
626 );
627 assert_eq!(policy.describe(), vec!["allow:read", "deny:edit"]);
628 assert!(!policy.is_allowlist());
629 }
630
631 #[test]
632 fn explicit_wildcard_deny_makes_a_map_an_allowlist() {
633 let policy = agent_policy(
634 "---\nname: a\ndescription: d\ntools:\n '*': deny\n 'bash(rg *)': allow\n---\n",
635 );
636 assert_eq!(policy.describe(), vec!["deny:*", "allow:bash(rg *)"]);
637 assert!(policy.is_allowlist());
638 }
639
640 #[test]
641 fn the_strictest_action_keeps_each_native_name_on_every_harness() {
642 type Row = (
644 &'static str,
645 &'static str,
646 HarnessId,
647 &'static [&'static str],
648 &'static [&'static str],
649 );
650 let rows: &[Row] = &[
651 (
652 "edit",
653 "write",
654 HarnessId::Claude,
655 &[],
656 &["Edit", "Write", "NotebookEdit"],
657 ),
658 (
659 "edit",
660 "notebook",
661 HarnessId::Claude,
662 &[],
663 &["Edit", "Write", "NotebookEdit"],
664 ),
665 ("edit", "write", HarnessId::Pi, &[], &["edit", "write"]),
666 ("edit", "write", HarnessId::Codex, &[], &["apply_patch"]),
667 ("edit", "write", HarnessId::OpenCode, &[], &["edit"]),
668 (
669 "web",
670 "web_fetch",
671 HarnessId::Claude,
672 &[],
673 &["WebSearch", "WebFetch"],
674 ),
675 (
676 "web",
677 "web_search",
678 HarnessId::Claude,
679 &[],
680 &["WebSearch", "WebFetch"],
681 ),
682 ];
683 for (deny, allow, harness, allowed, denied) in rows {
684 let policy = agent_policy(&format!(
685 "---\nname: a\ndescription: d\ntools:\n {deny}: deny\n {allow}: allow\n---\n"
686 ));
687 let projection = project(&policy, *harness);
688 assert_eq!(
689 projection.rules()[1].1.native(),
690 *allowed,
691 "{deny}/{allow} {harness:?}"
692 );
693 assert!(projection.rules()[1].1.note().is_some());
694 assert_eq!(
695 projection.rules()[0].1.native(),
696 *denied,
697 "{deny}/{allow} {harness:?}"
698 );
699 }
700 }
701
702 #[test]
703 fn a_scoped_rule_does_not_narrow_an_unscoped_one() {
704 let policy = agent_policy(
705 "---\nname: a\ndescription: d\ntools:\n bash: allow\n 'bash(git push *)': deny\n---\n",
706 );
707 let projection = project(&policy, HarnessId::Claude);
708 assert_eq!(projection.rules()[0].1.native(), ["Bash"]);
709 assert_eq!(projection.rules()[1].1.native(), ["Bash(git push *)"]);
710 }
711
712 #[test]
713 fn mcp_server_entries_appended_to_absent_tools_do_not_create_an_allowlist() {
714 let mut fm = Frontmatter::parse("---\nname: a\n---\n").unwrap();
717 assert!(append_mcp_server_entries_to_tools(
718 &mut fm,
719 &["context7".to_string()]
720 ));
721 let policy = crate::agent::read(&fm.render()).fields.unwrap().tools;
722 assert_eq!(policy.describe(), vec!["allow:mcp(context7/*)"]);
723 assert!(!policy.is_allowlist());
724 }
725
726 #[test]
727 fn aliases_and_native_spellings_reach_the_same_native_tools() {
728 assert_eq!(natives("Bash", "codex"), known(&["exec_command"]));
729 assert_eq!(natives("shell", "claude"), known(&["Bash"]));
730 assert_eq!(natives("exec_command", "claude"), known(&["Bash"]));
731 assert_eq!(natives("WebSearch", "opencode"), known(&["websearch"]));
732 assert_eq!(
733 natives("web", "opencode"),
734 known(&["websearch", "webfetch"])
735 );
736 assert_eq!(
737 natives("AskUserQuestion", "claude"),
738 known(&["AskUserQuestion"])
739 );
740 assert_eq!(natives("askuser", "opencode"), known(&["question"]));
741 assert_eq!(
742 natives("edit", "claude"),
743 known(&["Edit", "Write", "NotebookEdit"])
744 );
745 assert_eq!(natives("todowrite", "claude").0.len(), 7);
746 }
747
748 #[test]
749 fn claude_scoped_file_rules_separate_permissions_from_callable_tools() {
750 assert_eq!(
751 natives("bash(git push *)", "codex"),
752 known(&["exec_command(git push *)"])
753 );
754 for (rule, native, native_tools) in [
755 ("read(src/**)", "Read(src/**)", &["Read"][..]),
756 ("write(src/**)", "Edit(src/**)", &["Write"][..]),
757 (
758 "edit(src/**)",
759 "Edit(src/**)",
760 &["Edit", "Write", "NotebookEdit"][..],
761 ),
762 ("notebook(src/**)", "Edit(src/**)", &["NotebookEdit"][..]),
763 ("glob(src/**)", "Read(src/**)", &["Glob"][..]),
764 ("grep(src/**)", "Read(src/**)", &["Grep"][..]),
765 (
766 "web_fetch(domain:example.com)",
767 "WebFetch(domain:example.com)",
768 &["WebFetch"][..],
769 ),
770 ] {
771 assert_eq!(natives(rule, "claude"), known(&[native]), "{rule}");
772 let parsed = parse_mars_tool_name(rule).unwrap();
773 let projected = project_rule(
774 &ToolRule::from_parsed(parsed, ToolAction::Deny),
775 Host::Harness(HarnessId::Claude),
776 false,
777 );
778 assert_eq!(projected.native_tools(), native_tools, "{rule}");
779 }
780
781 let write = project_rule(
782 &ToolRule::from_parsed(
783 parse_mars_tool_name("write(src/**)").unwrap(),
784 ToolAction::Allow,
785 ),
786 Host::Harness(HarnessId::Claude),
787 false,
788 );
789 assert!(
790 write
791 .note()
792 .is_some_and(|note| note.contains("deny also refuses other built-in file edits")),
793 "{:?}",
794 write.note()
795 );
796 }
797
798 #[test]
799 fn claude_strictest_action_wins_when_scoped_capabilities_share_a_permission() {
800 let policy = agent_policy(
801 "---\nname: a\ndescription: d\ntools:\n 'write(src/**)': allow\n 'edit(src/**)': ask\n 'notebook(src/**)': deny\n---\n",
802 );
803 let projection = project(&policy, HarnessId::Claude);
804 assert!(projection.rules()[0].1.native().is_empty(), "allow loses");
805 assert!(
806 projection.rules()[0].1.native_tools().is_empty(),
807 "shadowed rules name no availability tools"
808 );
809 assert!(projection.rules()[1].1.native().is_empty(), "ask loses");
810 assert!(projection.rules()[1].1.native_tools().is_empty());
811 assert_eq!(projection.rules()[2].1.native(), ["Edit(src/**)"]);
812 assert_eq!(projection.rules()[2].1.native_tools(), ["NotebookEdit"]);
813 assert_eq!(
814 projection.natives(ToolAction::Deny, RuleKind::Builtin),
815 ["Edit(src/**)"]
816 );
817 assert!(
818 projection.rules()[0]
819 .1
820 .note()
821 .is_some_and(|note| note.contains("deny, then ask, then allow"))
822 );
823 }
824
825 #[test]
826 fn a_tool_the_harness_lacks_is_absent_not_guessed() {
827 assert_eq!(natives("notebook", "codex"), (vec![], "absent"));
828 assert_eq!(natives("ask_user", "pi"), (vec![], "absent"));
829 }
830
831 #[test]
832 fn a_thing_the_harness_can_do_without_a_tool_to_switch_is_unknown_not_absent() {
833 for (capability, harness) in [
836 ("web_fetch", "codex"),
837 ("skill", "codex"),
838 ("skill", "pi"),
839 ("read", "codex"),
840 ("glob", "codex"),
841 ("grep", "codex"),
842 ] {
843 assert_eq!(
844 natives(capability, harness),
845 (vec![], "unknown"),
846 "{harness} {capability}"
847 );
848 }
849 }
850
851 #[test]
852 fn a_name_without_a_table_row_is_unknown_with_no_native_name() {
853 assert_eq!(natives("lsp", "cursor"), (vec![], "unknown"));
855 for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
857 assert_eq!(
858 natives("my_custom_tool", harness),
859 (vec![], "unknown"),
860 "{harness}"
861 );
862 }
863 for raw in ["café_tool", "🚀tool"] {
864 assert_eq!(natives(raw, "claude"), (vec![], "unknown"));
865 }
866 }
867
868 #[test]
869 fn mcp_wire_tokens_are_verbatim_on_every_harness() {
870 for raw in [
871 "mcp__github__CreateIssue",
872 "MCP__Server__Tool",
873 "mcp__github__create_issue",
874 ] {
875 for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
876 assert_eq!(natives(raw, harness), known(&[raw]), "{raw} on {harness}");
877 let kind = Host::parse(harness).expect("test host exists");
878 let projected = project_rule(
879 &ToolRule::from_parsed(parse_mars_tool_name(raw).unwrap(), ToolAction::Deny),
880 kind,
881 false,
882 );
883 assert_eq!(projected.native_tools(), [raw], "{raw} on {harness}");
884 }
885 }
886 }
887
888 #[test]
889 fn the_any_capability_names_no_tool_and_has_no_status() {
890 assert_eq!(natives("*", "claude"), (vec![], "none"));
891 }
892}