mars-schema 0.33.0

Pure schema reader and editor for Mars agent packages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Lowering a tool policy onto one host: the native names each rule becomes, the gaps Mars
//! cannot name, and which stricter rule wins a shared name.
//!
//! Canonical Mars profiles express tool gating with a `tools:` action map (`rule: allow`,
//! `deny` or `ask`), whole-server or per-tool MCP grants being `mcp(...)` keys in it.
//! [`project`] spells a policy for one [`Host`]: a harness the binary writes files for, or
//! Meridian Flow, which only consumes the result. Native agent lowering, skill lowering, the
//! launch bundle and the WASM export all read that projection; nothing else turns a rule into
//! native permission names or unscoped harness tool names.

use crate::mcp::{McpRef, McpSegment};
use crate::tool_cover::covered;
use crate::tool_names::{Capability, is_mcp_wire_token, render_scoped};
use crate::tool_natives::{self, Native};
use crate::tool_policy::{EffectiveToolPolicy, ToolAction, ToolRule};
use crate::{HarnessId, Host};
use serde::Serialize;
use serde::ser::{SerializeStruct, Serializer};

/// What a host does with a tool name, which only this module's lowering needs.
impl Host {
    /// Whether a tool name can be narrowed to a pattern. A harness spells the scope in the
    /// permission name (`Bash(git push *)`); Flow's tools take no scope.
    fn scopes_patterns(self) -> bool {
        !matches!(self, Self::MeridianFlow)
    }

    /// An MCP ref as this host names it. Server and tool segments are kept verbatim, never
    /// re-cased.
    fn mcp_token(self, r: &McpRef) -> Result<String, &'static str> {
        let segment = |segment: &McpSegment| match segment {
            McpSegment::Any => "*".to_owned(),
            McpSegment::Named(name) => name.clone(),
        };
        let (server, tool) = (segment(&r.server), segment(&r.tool));
        match self {
            Self::Harness(HarnessId::Claude) => match (&r.server, &r.tool) {
                (McpSegment::Any, McpSegment::Named(_)) => {
                    Err("Claude cannot scope a single MCP tool across all servers")
                }
                (McpSegment::Any, McpSegment::Any) => Ok("mcp__*".to_owned()),
                _ => Ok(format!("mcp__{server}__{tool}")),
            },
            Self::Harness(HarnessId::Cursor) => Ok(format!("Mcp({server}:{tool})")),
            Self::Harness(HarnessId::OpenCode) => Ok(format!("{server}_{tool}")),
            Self::Harness(HarnessId::Codex) => {
                Err("Codex per-tool MCP gating lives in server config, not the tool list")
            }
            Self::Harness(HarnessId::Pi) => Err("Harness has no MCP tool surface"),
            Self::MeridianFlow => unreachable!("Flow's MCP refs are absent in `project_rule`"),
        }
    }
}

/// Whether Mars can name a rule's tools on a harness.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NativeStatus {
    /// Mars knows the native name(s). A stricter rule on the same native name can leave this
    /// rule no surviving name.
    Known,
    /// The harness has no such tool, so there is nothing to allow or deny.
    Absent,
    /// Mars cannot name it on this harness, for the reason given: the harness has no switch
    /// for it, Mars has no row for it, or the name is not one Mars recognizes (a typo). The
    /// launch bundle reports the reason in `note` and nowhere else.
    Unknown(&'static str),
    /// The rule has a pattern and the host's tools take no scope, so it cannot be applied as
    /// written. Only a host that does not scope patterns reports it.
    Unscopable,
}

impl NativeStatus {
    /// The bundle's `native_status`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Known => "known",
            Self::Absent => "absent",
            Self::Unknown(_) => "unknown",
            Self::Unscopable => "unscopable",
        }
    }

    /// Why Mars could not name the rule, for `unknown` and `unscopable`.
    pub fn note(self) -> Option<&'static str> {
        match self {
            Self::Unknown(note) => Some(note),
            Self::Unscopable => Some(UNSCOPABLE_NOTE),
            Self::Known | Self::Absent => None,
        }
    }
}

const UNSCOPABLE_NOTE: &str = "this host's tool takes no pattern, so the rule cannot be scoped";
const NO_NATIVE_NAME: &str = "no native name known for this tool on this harness; left out";

/// The stricter rule that wins a covered rule's calls, as its author wrote it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CoveredBy {
    pub action: ToolAction,
    pub key: String,
}

impl CoveredBy {
    fn new(rule: &ToolRule) -> Self {
        Self {
            action: rule.action,
            key: rule.render(),
        }
    }
}

impl std::fmt::Display for CoveredBy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.action.as_str(), self.key)
    }
}

/// One permission spelling and the unscoped harness tool names the canonical rule concerns.
///
/// Keeping the relationship intact lets conflict resolution remove availability tools with
/// the permission they belong to. Claude scoped rules are the non-trivial case: one
/// `Edit(path)` permission can concern `Edit`, `Write` and `NotebookEdit`.
///
/// A binding is never removed. `beaten_by` marks one a stricter rule wins, so it is still
/// something the rule makes available but no longer something it tells the permission engine.
#[derive(Debug, Clone, PartialEq, Eq)]
struct NativeBinding {
    native: String,
    native_tools: Vec<String>,
    /// The stricter rule (`deny bash`) that wins this name.
    beaten_by: Option<CoveredBy>,
}

impl NativeBinding {
    fn direct(name: &str, pattern: Option<&str>) -> Self {
        Self {
            native: render_scoped(name, pattern),
            native_tools: vec![name.to_string()],
            beaten_by: None,
        }
    }

    fn scoped(name: &str, pattern: &str, native_tools: &[&str]) -> Self {
        Self {
            native: render_scoped(name, Some(pattern)),
            native_tools: native_tools
                .iter()
                .map(|name| (*name).to_string())
                .collect(),
            beaten_by: None,
        }
    }
}

/// A rule as one harness spells it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectedRule {
    /// Every name the rule makes available. The ones not `beaten_by` are what it tells the
    /// permission engine ([`Self::native`]); a covered rule tells it nothing, so a reader that
    /// ignores `covered_by` cannot let through a call the covering rule refuses.
    bindings: Vec<NativeBinding>,
    /// `None` for `*`, which names no tool.
    pub status: Option<NativeStatus>,
    /// A harness-specific consequence of this projection that callers must surface even when
    /// the native name is known.
    note: Option<&'static str>,
    /// The stricter rule (`deny bash`) that covers this one, so that it never applies: another
    /// rule wins every call it would match, or every name it has on this harness.
    pub covered_by: Option<CoveredBy>,
}

impl ProjectedRule {
    fn known(bindings: Vec<NativeBinding>, note: Option<&'static str>) -> Self {
        Self {
            bindings,
            status: Some(NativeStatus::Known),
            note,
            covered_by: None,
        }
    }

    fn with_status(status: NativeStatus) -> Self {
        Self {
            bindings: Vec::new(),
            status: Some(status),
            note: None,
            covered_by: None,
        }
    }

    fn winning(&self) -> impl Iterator<Item = &NativeBinding> {
        self.bindings
            .iter()
            .filter(|binding| binding.beaten_by.is_none())
    }

    /// Permission-rule spellings after conflict resolution.
    pub fn native(&self) -> Vec<String> {
        self.native_names().cloned().collect()
    }

    /// Unscoped harness tool names concerned by the surviving permission rules, each once.
    pub fn native_tools(&self) -> Vec<String> {
        let mut tools = Vec::new();
        for binding in self.winning() {
            for tool in &binding.native_tools {
                if !tools.contains(tool) {
                    tools.push(tool.clone());
                }
            }
        }
        tools
    }

    fn native_names(&self) -> impl Iterator<Item = &String> {
        self.winning().map(|binding| &binding.native)
    }

    /// Every name the rule makes available, whether or not a stricter rule wins it.
    fn available_names(&self) -> impl Iterator<Item = &String> {
        self.bindings.iter().map(|binding| &binding.native)
    }

    fn beat(&mut self, by: CoveredBy) {
        for binding in &mut self.bindings {
            binding.beaten_by.get_or_insert_with(|| by.clone());
        }
        self.covered_by = Some(by);
    }

    /// Why Mars could not name this rule on the harness, when it could not.
    pub fn gap(&self) -> Option<&'static str> {
        self.status.and_then(NativeStatus::note)
    }

    /// A known projection's semantic note, or an unknown projection's gap reason.
    pub fn note(&self) -> Option<&'static str> {
        self.note.or_else(|| self.gap())
    }
}

/// Project `rule` onto `harness`. The one place a capability becomes native permission names
/// and unscoped harness tool names.
fn project_rule(rule: &ToolRule, host: Host) -> ProjectedRule {
    match &rule.capability {
        Capability::Any => ProjectedRule {
            bindings: Vec::new(),
            status: None,
            note: None,
            covered_by: None,
        },
        // Flow's tool set is closed: it has no MCP tools, whatever the ref or wire token.
        Capability::Mcp(_) if host == Host::MeridianFlow => {
            ProjectedRule::with_status(NativeStatus::Absent)
        }
        Capability::Unknown(name) if is_mcp_wire_token(name) && host == Host::MeridianFlow => {
            ProjectedRule::with_status(NativeStatus::Absent)
        }
        Capability::Mcp(mcp_ref) => match host.mcp_token(mcp_ref) {
            Ok(token) => ProjectedRule::known(vec![NativeBinding::direct(&token, None)], None),
            Err(reason) => ProjectedRule::with_status(NativeStatus::Unknown(reason)),
        },
        Capability::Unknown(name) if is_mcp_wire_token(name) => ProjectedRule::known(
            vec![NativeBinding::direct(name, rule.pattern.as_deref())],
            None,
        ),
        Capability::Unknown(_) => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
        Capability::Builtin(name) => {
            project_builtin_capability(name, rule.pattern.as_deref(), host)
        }
    }
}

/// Project one canonical builtin capability through the same table and status semantics as a
/// profile rule. Launch-bundle platform rules use this without inventing a second native-name
/// projection path.
pub fn project_platform_capability(capability: &'static str, host: Host) -> ProjectedRule {
    project_builtin_capability(capability, None, host)
}

fn project_builtin_capability(
    capability: &str,
    pattern: Option<&str>,
    host: Host,
) -> ProjectedRule {
    let row = tool_natives::lookup(capability, host);
    if pattern.is_some()
        && !host.scopes_patterns()
        && matches!(row, Some(Native::Tools(_) | Native::ScopedTools { .. }))
    {
        return ProjectedRule::with_status(NativeStatus::Unscopable);
    }
    match row {
        Some(Native::Tools(names)) => ProjectedRule::known(
            names
                .iter()
                .map(|name| NativeBinding::direct(name, pattern))
                .collect(),
            None,
        ),
        Some(
            native @ Native::ScopedTools {
                unscoped,
                scoped: scoped_names,
                note,
            },
        ) => {
            let (bindings, note) = match pattern {
                Some(pattern) => (
                    scoped_names
                        .iter()
                        .map(|name| NativeBinding::scoped(name, pattern, native.native_tools()))
                        .collect(),
                    Some(note),
                ),
                None => (
                    unscoped
                        .iter()
                        .map(|name| NativeBinding::direct(name, None))
                        .collect(),
                    None,
                ),
            };
            ProjectedRule::known(bindings, note)
        }
        Some(Native::Absent) => ProjectedRule::with_status(NativeStatus::Absent),
        Some(Native::NoSwitch(note)) => ProjectedRule::with_status(NativeStatus::Unknown(note)),
        None => ProjectedRule::with_status(NativeStatus::Unknown(NO_NATIVE_NAME)),
    }
}

/// Lower `policy` onto `host`. The one place a rule list becomes native names, gaps and
/// coverage; pure over the rules, the host and the published native tables.
pub fn project(policy: &EffectiveToolPolicy, host: impl Into<Host>) -> PolicyProjection<'_> {
    let host = host.into();
    let mut rules: Vec<(&ToolRule, ProjectedRule)> = policy
        .rules
        .iter()
        .map(|rule| (rule, project_rule(rule, host)))
        .collect();
    keep_strictest_per_native(&mut rules);
    for (index, by) in covered(policy) {
        rules[index].1.beat(CoveredBy::new(by));
    }
    PolicyProjection { host, rules }
}

/// Which rules that name tools a query covers. `*` names none, so no kind covers it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleKind {
    /// Built-in tools: everything but MCP refs.
    Builtin,
    Mcp,
    All,
}

impl RuleKind {
    fn covers(self, rule: &ToolRule) -> bool {
        match self {
            Self::Builtin => !rule.is_mcp() && !rule.is_wildcard(),
            Self::Mcp => rule.is_mcp(),
            Self::All => !rule.is_wildcard(),
        }
    }
}

/// The `note` on a rule that lost a native name to a stricter rule on the same name.
const STRICTER_RULE_NOTE: &str = "a stricter rule controls the same native tool and wins (deny, then ask, then allow); this rule is left out";

/// A policy's rules spelled for one harness, in profile order.
pub struct PolicyProjection<'a> {
    host: Host,
    rules: Vec<(&'a ToolRule, ProjectedRule)>,
}

impl<'a> PolicyProjection<'a> {
    pub fn rules(&self) -> &[(&'a ToolRule, ProjectedRule)] {
        &self.rules
    }

    /// What a tool no rule names gets: the strictest `*` rule's action, or `None` without one.
    pub fn default_action(&self) -> Option<ToolAction> {
        self.rules
            .iter()
            .filter(|(rule, _)| rule.is_wildcard())
            .map(|(rule, _)| rule.action)
            .max_by_key(|action| action.strictness())
    }

    /// The projected `kind` rules with `action`: built-in tools first, then MCP refs.
    fn select(&self, action: ToolAction, kind: RuleKind) -> Vec<&ProjectedRule> {
        let mut picked: Vec<_> = self
            .rules
            .iter()
            .filter(|(rule, _)| rule.action == action && kind.covers(rule))
            .collect();
        picked.sort_by_key(|(rule, _)| rule.is_mcp());
        picked.into_iter().map(|(_, projected)| projected).collect()
    }

    /// Native names of the `kind` rules with `action`, built-in tools first, each name once.
    pub fn natives(&self, action: ToolAction, kind: RuleKind) -> Vec<String> {
        let mut names: Vec<String> = Vec::new();
        for projected in self.select(action, kind) {
            for native in projected.native_names() {
                if !names.contains(native) {
                    names.push(native.clone());
                }
            }
        }
        names
    }

    /// Names of every allow and ask rule, taken before coverage and conflict resolution cleared
    /// any: the tools an allowlist must keep available. A deny that beats one of them is
    /// written beside the list, never by emptying it.
    pub fn available(&self) -> Vec<String> {
        let mut names: Vec<String> = Vec::new();
        let mut rules: Vec<_> = self
            .rules
            .iter()
            .filter(|(rule, _)| rule.action != ToolAction::Deny && !rule.is_wildcard())
            .collect();
        rules.sort_by_key(|(rule, _)| rule.is_mcp());
        for (_, projected) in rules {
            for name in projected.available_names() {
                if !names.contains(name) {
                    names.push(name.clone());
                }
            }
        }
        names
    }

    /// Why Mars could not name each `kind` rule with `action`.
    pub fn gaps(&self, action: ToolAction, kind: RuleKind) -> Vec<&'static str> {
        self.select(action, kind)
            .into_iter()
            .filter_map(ProjectedRule::gap)
            .collect()
    }
}

/// The published shape of a projection (`project` in the WASM package): per rule, then the
/// native names each action ends with. A consumer decides from these what to warn about: a
/// `status` other than `known`, a `covered_by` or a `note` is something the author may not
/// have meant.
impl Serialize for PolicyProjection<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        struct Rule<'r>(&'r ToolRule, &'r ProjectedRule);
        impl Serialize for Rule<'_> {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let Rule(rule, projected) = self;
                let mut out = serializer.serialize_struct("ProjectedRule", 6)?;
                out.serialize_field("rule", rule)?;
                out.serialize_field("status", &projected.status.map(NativeStatus::as_str))?;
                out.serialize_field("native", &projected.native())?;
                out.serialize_field("native_tools", &projected.native_tools())?;
                out.serialize_field("note", &projected.note())?;
                out.serialize_field("covered_by", &projected.covered_by)?;
                out.end()
            }
        }
        let rules: Vec<Rule> = self.rules.iter().map(|(r, p)| Rule(r, p)).collect();
        let mut out = serializer.serialize_struct("ToolProjection", 7)?;
        out.serialize_field("host", &self.host)?;
        out.serialize_field("default", &self.default_action().map(ToolAction::as_str))?;
        out.serialize_field("rules", &rules)?;
        out.serialize_field("allow", &self.natives(ToolAction::Allow, RuleKind::All))?;
        out.serialize_field("deny", &self.natives(ToolAction::Deny, RuleKind::All))?;
        out.serialize_field("ask", &self.natives(ToolAction::Ask, RuleKind::All))?;
        out.serialize_field("available", &self.available())?;
        out.end()
    }
}

/// Of the rules that name one native permission, the strictest action keeps it (deny, then ask,
/// then allow), as Claude's own lists do. `edit: deny` beside `write: allow` leaves the allow
/// no `Write` on Claude and no `write` on Pi; capabilities a harness cannot tell apart
/// (`write` and `edit` on Codex) resolve the same way. A rule that loses a name gets a note.
fn keep_strictest_per_native(rules: &mut [(&ToolRule, ProjectedRule)]) {
    let named: Vec<(&ToolRule, Vec<String>)> = rules
        .iter()
        .map(|(rule, projected)| (*rule, projected.native()))
        .collect();
    for (rule, projected) in rules.iter_mut() {
        let mut beaten = 0;
        for binding in &mut projected.bindings {
            let by = named.iter().find(|(stricter, names)| {
                stricter.action.strictness() > rule.action.strictness()
                    && names.contains(&binding.native)
            });
            if let Some((stricter, _)) = by {
                binding.beaten_by = Some(CoveredBy::new(stricter));
                beaten += 1;
            }
        }
        if beaten > 0 {
            projected.note = Some(STRICTER_RULE_NOTE);
        }
        if beaten > 0 && beaten == projected.bindings.len() {
            projected.covered_by = projected.bindings[0].beaten_by.clone();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frontmatter::Frontmatter;
    use crate::tool_names::parse_mars_tool_name;
    use crate::tool_policy::append_mcp_server_entries_to_tools;
    use serde_yaml::Value;

    fn agent_policy(yaml: &str) -> EffectiveToolPolicy {
        let reading = crate::agent::read(yaml);
        assert!(
            reading.diagnostics.is_empty(),
            "agent diags: {:?}",
            reading.diagnostics
        );
        reading.fields.unwrap().tools
    }

    /// Native names and status of a raw tool entry on a harness, via parse then table.
    fn natives(raw: &str, harness: &str) -> (Vec<String>, &'static str) {
        let kind = Host::parse(harness).expect("test host exists");
        let parsed = parse_mars_tool_name(raw).unwrap();
        let projected = project_rule(&ToolRule::from_parsed(parsed, ToolAction::Deny), kind);
        (
            projected.native(),
            projected.status.map_or("none", NativeStatus::as_str),
        )
    }

    fn known(names: &[&str]) -> (Vec<String>, &'static str) {
        (names.iter().map(|n| n.to_string()).collect(), "known")
    }

    #[test]
    fn covered_allows_stay_available() {
        // `deny` covers the allow, so the allow names no permission; the tool it opens stays
        // on Claude's `tools:` list, and the deny is what takes it back.
        let policy = agent_policy(
            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  write: allow\n  edit: deny\n  'bash(git status *)': allow\n  bash: ask\n---\n",
        );
        let projection = project(&policy, HarnessId::Claude);
        assert_eq!(
            projection.natives(ToolAction::Allow, RuleKind::All),
            Vec::<String>::new()
        );
        assert_eq!(
            projection.available(),
            ["Write", "Bash(git status *)", "Bash"]
        );
    }

    #[test]
    fn append_mcp_server_entries_to_tools_preserves_map_form() {
        let mut fm = Frontmatter::parse("---\ntools:\n  Bash: allow\n  Read: deny\n---\n").unwrap();
        assert!(append_mcp_server_entries_to_tools(
            &mut fm,
            &["context7".to_string(), "github".to_string()]
        ));
        let tools = fm.get("tools").unwrap();
        let Value::Mapping(mapping) = tools else {
            panic!("expected map-form tools, got {tools:?}");
        };
        assert_eq!(
            mapping.get(Value::String("Bash".into())),
            Some(&Value::String("allow".into()))
        );
        assert_eq!(
            mapping.get(Value::String("Read".into())),
            Some(&Value::String("deny".into()))
        );
        assert_eq!(
            mapping.get(Value::String("mcp(context7)".into())),
            Some(&Value::String("allow".into()))
        );
        assert_eq!(
            mapping.get(Value::String("mcp(github)".into())),
            Some(&Value::String("allow".into()))
        );
    }

    #[test]
    fn map_form_allows_are_grants_not_an_allowlist() {
        let policy = agent_policy(
            "---\nname: a\ndescription: d\ntools:\n  read: allow\n  edit: deny\n---\n",
        );
        assert_eq!(policy.describe(), vec!["allow:read", "deny:edit"]);
        assert!(!policy.is_allowlist());
    }

    #[test]
    fn explicit_wildcard_deny_makes_a_map_an_allowlist() {
        let policy = agent_policy(
            "---\nname: a\ndescription: d\ntools:\n  '*': deny\n  'bash(rg *)': allow\n---\n",
        );
        assert_eq!(policy.describe(), vec!["deny:*", "allow:bash(rg *)"]);
        assert!(policy.is_allowlist());
    }

    #[test]
    fn the_strictest_action_keeps_each_native_name_on_every_harness() {
        // (rules, harness, the allow rule's surviving names, the deny rule's)
        type Row = (
            &'static str,
            &'static str,
            HarnessId,
            &'static [&'static str],
            &'static [&'static str],
        );
        let rows: &[Row] = &[
            (
                "edit",
                "write",
                HarnessId::Claude,
                &[],
                &["Edit", "Write", "NotebookEdit"],
            ),
            (
                "edit",
                "notebook",
                HarnessId::Claude,
                &[],
                &["Edit", "Write", "NotebookEdit"],
            ),
            ("edit", "write", HarnessId::Pi, &[], &["edit", "write"]),
            ("edit", "write", HarnessId::Codex, &[], &["apply_patch"]),
            ("edit", "write", HarnessId::OpenCode, &[], &["edit"]),
            (
                "web",
                "web_fetch",
                HarnessId::Claude,
                &[],
                &["WebSearch", "WebFetch"],
            ),
            (
                "web",
                "web_search",
                HarnessId::Claude,
                &[],
                &["WebSearch", "WebFetch"],
            ),
        ];
        for (deny, allow, harness, allowed, denied) in rows {
            let policy = agent_policy(&format!(
                "---\nname: a\ndescription: d\ntools:\n  {deny}: deny\n  {allow}: allow\n---\n"
            ));
            let projection = project(&policy, *harness);
            assert_eq!(
                projection.rules()[1].1.native(),
                *allowed,
                "{deny}/{allow} {harness:?}"
            );
            assert!(projection.rules()[1].1.note().is_some());
            assert_eq!(
                projection.rules()[0].1.native(),
                *denied,
                "{deny}/{allow} {harness:?}"
            );
        }
    }

    #[test]
    fn a_scoped_rule_does_not_narrow_an_unscoped_one() {
        let policy = agent_policy(
            "---\nname: a\ndescription: d\ntools:\n  bash: allow\n  'bash(git push *)': deny\n---\n",
        );
        let projection = project(&policy, HarnessId::Claude);
        assert_eq!(projection.rules()[0].1.native(), ["Bash"]);
        assert_eq!(projection.rules()[1].1.native(), ["Bash(git push *)"]);
    }

    #[test]
    fn mcp_server_entries_appended_to_absent_tools_do_not_create_an_allowlist() {
        // A Claude agent with `mcpServers` and no `tools:` inherits every tool. The
        // synthesized `mcp(server)` grant must not turn that into "MCP only".
        let mut fm = Frontmatter::parse("---\nname: a\n---\n").unwrap();
        assert!(append_mcp_server_entries_to_tools(
            &mut fm,
            &["context7".to_string()]
        ));
        let policy = crate::agent::read(&fm.render()).fields.unwrap().tools;
        assert_eq!(policy.describe(), vec!["allow:mcp(context7/*)"]);
        assert!(!policy.is_allowlist());
    }

    #[test]
    fn aliases_and_native_spellings_reach_the_same_native_tools() {
        assert_eq!(natives("Bash", "codex"), known(&["exec_command"]));
        assert_eq!(natives("shell", "claude"), known(&["Bash"]));
        assert_eq!(natives("exec_command", "claude"), known(&["Bash"]));
        assert_eq!(natives("WebSearch", "opencode"), known(&["websearch"]));
        assert_eq!(
            natives("web", "opencode"),
            known(&["websearch", "webfetch"])
        );
        assert_eq!(
            natives("AskUserQuestion", "claude"),
            known(&["AskUserQuestion"])
        );
        assert_eq!(natives("askuser", "opencode"), known(&["question"]));
        assert_eq!(
            natives("edit", "claude"),
            known(&["Edit", "Write", "NotebookEdit"])
        );
        assert_eq!(natives("todowrite", "claude").0.len(), 7);
    }

    #[test]
    fn claude_scoped_file_rules_separate_permissions_from_callable_tools() {
        assert_eq!(
            natives("bash(git push *)", "codex"),
            known(&["exec_command(git push *)"])
        );
        for (rule, native, native_tools) in [
            ("read(src/**)", "Read(src/**)", &["Read"][..]),
            ("write(src/**)", "Edit(src/**)", &["Write"][..]),
            (
                "edit(src/**)",
                "Edit(src/**)",
                &["Edit", "Write", "NotebookEdit"][..],
            ),
            ("notebook(src/**)", "Edit(src/**)", &["NotebookEdit"][..]),
            ("glob(src/**)", "Read(src/**)", &["Glob"][..]),
            ("grep(src/**)", "Read(src/**)", &["Grep"][..]),
            (
                "web_fetch(domain:example.com)",
                "WebFetch(domain:example.com)",
                &["WebFetch"][..],
            ),
        ] {
            assert_eq!(natives(rule, "claude"), known(&[native]), "{rule}");
            let parsed = parse_mars_tool_name(rule).unwrap();
            let projected = project_rule(
                &ToolRule::from_parsed(parsed, ToolAction::Deny),
                Host::Harness(HarnessId::Claude),
            );
            assert_eq!(projected.native_tools(), native_tools, "{rule}");
        }

        let write = project_rule(
            &ToolRule::from_parsed(
                parse_mars_tool_name("write(src/**)").unwrap(),
                ToolAction::Allow,
            ),
            Host::Harness(HarnessId::Claude),
        );
        assert!(
            write
                .note()
                .is_some_and(|note| note.contains("deny also refuses other built-in file edits")),
            "{:?}",
            write.note()
        );
    }

    #[test]
    fn claude_strictest_action_wins_when_scoped_capabilities_share_a_permission() {
        let policy = agent_policy(
            "---\nname: a\ndescription: d\ntools:\n  'write(src/**)': allow\n  'edit(src/**)': ask\n  'notebook(src/**)': deny\n---\n",
        );
        let projection = project(&policy, HarnessId::Claude);
        assert!(projection.rules()[0].1.native().is_empty(), "allow loses");
        assert!(
            projection.rules()[0].1.native_tools().is_empty(),
            "shadowed rules name no availability tools"
        );
        assert!(projection.rules()[1].1.native().is_empty(), "ask loses");
        assert!(projection.rules()[1].1.native_tools().is_empty());
        assert_eq!(projection.rules()[2].1.native(), ["Edit(src/**)"]);
        assert_eq!(projection.rules()[2].1.native_tools(), ["NotebookEdit"]);
        assert_eq!(
            projection.natives(ToolAction::Deny, RuleKind::Builtin),
            ["Edit(src/**)"]
        );
        assert!(
            projection.rules()[0]
                .1
                .note()
                .is_some_and(|note| note.contains("deny, then ask, then allow"))
        );
    }

    #[test]
    fn a_tool_the_harness_lacks_is_absent_not_guessed() {
        assert_eq!(natives("notebook", "codex"), (vec![], "absent"));
        assert_eq!(natives("ask_user", "pi"), (vec![], "absent"));
    }

    #[test]
    fn a_thing_the_harness_can_do_without_a_tool_to_switch_is_unknown_not_absent() {
        // Codex fetches pages through `web_search` and reads, globs and greps through its shell;
        // Codex and Pi load skills by reading files.
        for (capability, harness) in [
            ("web_fetch", "codex"),
            ("skill", "codex"),
            ("skill", "pi"),
            ("read", "codex"),
            ("glob", "codex"),
            ("grep", "codex"),
        ] {
            assert_eq!(
                natives(capability, harness),
                (vec![], "unknown"),
                "{harness} {capability}"
            );
        }
    }

    #[test]
    fn a_name_without_a_table_row_is_unknown_with_no_native_name() {
        // Known capability, no Cursor row: no convention fallback fills it in.
        assert_eq!(natives("lsp", "cursor"), (vec![], "unknown"));
        // Not a capability at all, including one that merely looks like the `mcp` capability.
        for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
            assert_eq!(
                natives("my_custom_tool", harness),
                (vec![], "unknown"),
                "{harness}"
            );
        }
        for raw in ["café_tool", "🚀tool"] {
            assert_eq!(natives(raw, "claude"), (vec![], "unknown"));
        }
    }

    #[test]
    fn mcp_wire_tokens_are_verbatim_on_every_harness() {
        for raw in [
            "mcp__github__CreateIssue",
            "MCP__Server__Tool",
            "mcp__github__create_issue",
        ] {
            for harness in ["claude", "codex", "opencode", "pi", "cursor"] {
                assert_eq!(natives(raw, harness), known(&[raw]), "{raw} on {harness}");
                let kind = Host::parse(harness).expect("test host exists");
                let projected = project_rule(
                    &ToolRule::from_parsed(parse_mars_tool_name(raw).unwrap(), ToolAction::Deny),
                    kind,
                );
                assert_eq!(projected.native_tools(), [raw], "{raw} on {harness}");
            }
        }
    }

    #[test]
    fn the_any_capability_names_no_tool_and_has_no_status() {
        assert_eq!(natives("*", "claude"), (vec![], "none"));
    }
}