mars-schema 0.42.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
//! Model-policy definition and validation shared by profiles and consumer config.

use crate::agent::{ApprovalMode, EffortRequest, SandboxMode};
use crate::network::NetworkPolicy;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub enum ModelPolicyMatchType {
    Model,
    Alias,
    ModelGlob,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ModelPolicyOverride {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effort: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approval: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<String>,
}

impl ModelPolicyOverride {
    pub fn is_empty(&self) -> bool {
        self.effort.is_none()
            && self.sandbox.is_none()
            && self.approval.is_none()
            && self.network.is_none()
    }

    pub fn get(&self, key: &str) -> Option<&str> {
        match key {
            "effort" => self.effort.as_deref(),
            "sandbox" => self.sandbox.as_deref(),
            "approval" => self.approval.as_deref(),
            "network" => self.network.as_deref(),
            _ => None,
        }
    }
}

/// Shared model-policy rule type used by profile frontmatter, agent overlays,
/// and settings-level model policies.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelPolicyRule {
    pub match_type: ModelPolicyMatchType,
    pub match_value: String,
    pub no_fallback: bool,
    pub overrides: ModelPolicyOverride,
    /// A compact, authored guide explaining when this model is a good choice.
    pub when: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelPolicyRuleParseError {
    RuleMustBeMapping {
        found: String,
    },
    MatchMissing,
    MatchMustBeMapping {
        found: String,
    },
    MatchMustContainExactlyOne {
        found: String,
    },
    MatchKeyMustBeString {
        found: String,
    },
    UnknownMatchKey {
        key: String,
    },
    MatchValueMustBeString {
        key: String,
        found: String,
    },
    MatchValueEmpty {
        key: String,
    },
    OverrideMustBeMapping {
        found: String,
    },
    UnknownOverrideKey {
        key: String,
    },
    /// A host set is layered by settings, profile, overlay and CLI, never by a model rule.
    NetworkHostsNotAllowed {
        key: String,
    },
    OverrideValueInvalid {
        key: String,
        found: String,
        allowed: &'static str,
    },
    NoFallbackMustBeBoolean {
        found: String,
    },
    WhenInvalid {
        found: String,
    },
    /// An entry of a `models` list is neither a model name nor a mapping.
    EntryMustBeNameOrMapping {
        found: String,
    },
    EntryModelMissing,
    EntryModelInvalid {
        found: String,
    },
}

impl ModelPolicyRuleParseError {
    fn deserialize_message(&self) -> String {
        match self {
            Self::MatchMustContainExactlyOne { .. }
            | Self::MatchMissing
            | Self::MatchMustBeMapping { .. } => {
                "model policy `match` must contain exactly one of model, alias, model-glob"
                    .to_string()
            }
            Self::MatchKeyMustBeString { .. } => {
                "model policy `match` key must be a string".to_string()
            }
            Self::MatchValueMustBeString { .. } => {
                "model policy `match` value must be a string".to_string()
            }
            Self::MatchValueEmpty { .. } => {
                "model policy `match` value must be a non-empty string".to_string()
            }
            Self::UnknownMatchKey { key } => format!(
                "unknown model policy match key `{key}`; expected model, alias, or model-glob"
            ),
            Self::OverrideMustBeMapping { .. } => {
                "model policy `override` must be a mapping".to_string()
            }
            Self::UnknownOverrideKey { key } => format!(
                "unknown model policy override `{key}`; expected effort, sandbox, approval, or network"
            ),
            Self::NetworkHostsNotAllowed { key } => format!(
                "model policy override `{key}` is not supported; set it on settings, the profile, an agent overlay, or the CLI"
            ),
            Self::OverrideValueInvalid {
                key,
                found,
                allowed,
            } => format!(
                "model policy override `{key}` has invalid value `{found}`; allowed: {allowed}"
            ),
            Self::NoFallbackMustBeBoolean { .. } => {
                "model policy `no-fallback` must be a boolean".to_string()
            }
            Self::WhenInvalid { .. } => {
                "model policy `when` must be a non-empty one-line string".to_string()
            }
            Self::RuleMustBeMapping { .. } => "model policy rule must be a mapping".to_string(),
            Self::EntryMustBeNameOrMapping { .. } => {
                "a `models` entry must be a model name or a mapping".to_string()
            }
            Self::EntryModelMissing | Self::EntryModelInvalid { .. } => {
                "a `models` entry needs `model`, a non-empty string".to_string()
            }
        }
    }
}

/// The keys of a rule that Mars reads. A key beside them is unknown. An `override` takes only
/// the fields below, every one of them an execution or restriction setting, so an unknown key
/// there is an error rather than a note.
const RULE_KEYS: &[&str] = &["match", "override", "no-fallback", "when"];
const OVERRIDE_KEYS: &[&str] = &[
    "effort",
    "sandbox",
    "approval",
    "network",
    "network-allow",
    "network-deny",
];

/// What reading one rule found, all in one pass: the rule when nothing in it is rejected, every
/// rejection when something is, and the unknown keys either way.
pub(crate) struct RuleReading {
    pub rule: Result<ModelPolicyRule, Vec<ModelPolicyRuleParseError>>,
    pub unknown: Vec<String>,
}

pub(crate) fn read_model_policy_rule(value: &serde_yaml::Value) -> RuleReading {
    use ModelPolicyRuleParseError as Error;
    let Some(rule) = value.as_mapping() else {
        return RuleReading {
            rule: Err(vec![Error::RuleMustBeMapping {
                found: crate::ordered::plain(value),
            }]),
            unknown: Vec::new(),
        };
    };
    let mut errors = Vec::new();
    let unknown = unknown_keys(rule, RULE_KEYS);

    let matched = read_match(rule).map_err(|error| errors.push(error)).ok();

    let overrides = match rule.get(serde_yaml::Value::String("override".to_string())) {
        Some(value) if !value.is_null() => match value.as_mapping() {
            Some(mapping) => read_overrides(mapping, &mut errors),
            None => {
                errors.push(Error::OverrideMustBeMapping {
                    found: crate::ordered::plain(value),
                });
                ModelPolicyOverride::default()
            }
        },
        _ => ModelPolicyOverride::default(),
    };

    let no_fallback = read_no_fallback(rule, &mut errors).unwrap_or(false);
    let when = read_when(rule, &mut errors);

    let rule = match matched {
        Some((match_type, match_value)) if errors.is_empty() => Ok(ModelPolicyRule {
            match_type,
            match_value,
            no_fallback,
            overrides,
            when,
        }),
        _ => Err(errors),
    };
    RuleReading { rule, unknown }
}

fn read_no_fallback(
    mapping: &serde_yaml::Mapping,
    errors: &mut Vec<ModelPolicyRuleParseError>,
) -> Option<bool> {
    match mapping.get(serde_yaml::Value::String("no-fallback".to_string())) {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::Bool(value)) => Some(*value),
        Some(value) => {
            errors.push(ModelPolicyRuleParseError::NoFallbackMustBeBoolean {
                found: crate::ordered::plain(value),
            });
            None
        }
    }
}

fn read_when(
    mapping: &serde_yaml::Mapping,
    errors: &mut Vec<ModelPolicyRuleParseError>,
) -> Option<String> {
    match mapping.get(serde_yaml::Value::String("when".to_string())) {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::String(value))
            if !value.is_empty() && !value.contains(['\n', '\r']) =>
        {
            Some(value.clone())
        }
        Some(value) => {
            errors.push(ModelPolicyRuleParseError::WhenInvalid {
                found: crate::ordered::plain(value),
            });
            None
        }
    }
}

fn unknown_keys(mapping: &serde_yaml::Mapping, known: &[&str]) -> Vec<String> {
    mapping
        .keys()
        .filter(|key| !key.as_str().is_some_and(|key| known.contains(&key)))
        .map(|key| {
            key.as_str()
                .map_or_else(|| crate::ordered::plain(key), str::to_owned)
        })
        .collect()
}

fn read_match(
    rule: &serde_yaml::Mapping,
) -> Result<(ModelPolicyMatchType, String), ModelPolicyRuleParseError> {
    use ModelPolicyRuleParseError as Error;
    let match_mapping = match rule.get(serde_yaml::Value::String("match".to_string())) {
        Some(value) => value
            .as_mapping()
            .ok_or_else(|| Error::MatchMustBeMapping {
                found: crate::ordered::plain(value),
            })?,
        None => return Err(Error::MatchMissing),
    };
    let exactly_one = || Error::MatchMustContainExactlyOne {
        found: crate::ordered::plain(&serde_yaml::Value::Mapping(match_mapping.clone())),
    };
    let mut entries = match_mapping.iter();
    let Some((match_key, match_value)) = entries.next() else {
        return Err(exactly_one());
    };
    if entries.next().is_some() {
        return Err(exactly_one());
    }

    let key = match_key
        .as_str()
        .ok_or_else(|| Error::MatchKeyMustBeString {
            found: crate::ordered::plain(match_key),
        })?;
    let value = match_value
        .as_str()
        .ok_or_else(|| Error::MatchValueMustBeString {
            key: key.to_string(),
            found: crate::ordered::plain(match_value),
        })?;
    if value.is_empty() {
        return Err(Error::MatchValueEmpty {
            key: key.to_string(),
        });
    }
    let match_type = match key {
        "model" => ModelPolicyMatchType::Model,
        "alias" => ModelPolicyMatchType::Alias,
        "model-glob" => ModelPolicyMatchType::ModelGlob,
        _ => {
            return Err(Error::UnknownMatchKey {
                key: key.to_string(),
            });
        }
    };
    Ok((match_type, value.to_string()))
}

/// The override keys Mars reads; each rejected one adds its own error.
fn read_overrides(
    mapping: &serde_yaml::Mapping,
    errors: &mut Vec<ModelPolicyRuleParseError>,
) -> ModelPolicyOverride {
    let mut overrides = ModelPolicyOverride::default();
    for (key, value) in mapping {
        let Some(key) = key.as_str().filter(|key| OVERRIDE_KEYS.contains(key)) else {
            errors.push(ModelPolicyRuleParseError::UnknownOverrideKey {
                key: key
                    .as_str()
                    .map_or_else(|| crate::ordered::plain(key), str::to_owned),
            });
            continue;
        };
        if matches!(key, "network-allow" | "network-deny") {
            errors.push(ModelPolicyRuleParseError::NetworkHostsNotAllowed {
                key: key.to_string(),
            });
            continue;
        }
        let invalid = |found: String| ModelPolicyRuleParseError::OverrideValueInvalid {
            key: key.to_string(),
            found,
            allowed: allowed_override_values(key),
        };
        // YAML `effort: null` is `auto`: the harness's own default, overriding lower layers.
        let raw = if key == "effort" && value.is_null() {
            Some("auto")
        } else {
            value.as_str()
        };
        let Some(raw) = raw else {
            errors.push(invalid(crate::ordered::plain(value)));
            continue;
        };
        let parsed = match key {
            "effort" => EffortRequest::parse(raw).map(|value| value.as_str().to_string()),
            "sandbox" => SandboxMode::parse(raw).map(|value| value.as_str().to_string()),
            "approval" => ApprovalMode::parse(raw).map(|value| value.as_str().to_string()),
            _ => NetworkPolicy::parse(raw).map(|value| value.as_str().to_string()),
        };
        let Some(parsed) = parsed else {
            errors.push(invalid(raw.to_string()));
            continue;
        };
        match key {
            "effort" => overrides.effort = Some(parsed),
            "sandbox" => overrides.sandbox = Some(parsed),
            "approval" => overrides.approval = Some(parsed),
            _ => overrides.network = Some(parsed),
        }
    }
    overrides
}

fn allowed_override_values(key: &str) -> &'static str {
    match key {
        "effort" => EffortRequest::ALLOWED,
        "sandbox" => SandboxMode::ALLOWED,
        "approval" => ApprovalMode::ALLOWED,
        "network" => NetworkPolicy::ALLOWED,
        _ => "effort, sandbox, approval, network",
    }
}

/// One entry of an agent's `models` list: a model the agent can run, with what to say about it
/// and the settings that apply when it runs. The first entry of a list is the agent's default.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ModelEntry {
    /// An alias or a model ID, as `-m` takes it.
    pub model: String,
    pub when: Option<String>,
    /// Shown with its `when`, and used only when a caller asks for it. Unset, it is what the
    /// same model has in the layer below, else false.
    pub no_fallback: Option<bool>,
    pub overrides: ModelPolicyOverride,
}

/// The line of a config layer's `models` that stands for the list the layer below produced.
pub const MODELS_SPLICE: &str = "...";

/// One item of a config layer's `models`: an entry, or [`MODELS_SPLICE`].
#[derive(Debug, Clone, PartialEq)]
pub enum ModelsItem {
    Rest,
    Entry(ModelEntry),
}

impl ModelsItem {
    /// The entry; `None` for [`MODELS_SPLICE`].
    pub fn entry(&self) -> Option<&ModelEntry> {
        match self {
            Self::Rest => None,
            Self::Entry(entry) => Some(entry),
        }
    }
}

/// Something a `models` list may not hold, in a profile or in a config file's line.
#[derive(Debug, Clone, PartialEq)]
pub struct ListProblem {
    pub code: &'static str,
    /// The item at fault; `None` for the list as a whole.
    pub index: Option<usize>,
    pub message: String,
}

/// What every reader of a `models` list refuses: an empty list, a model listed twice,
/// [`MODELS_SPLICE`] more than once, and `no-fallback` on the first entry, which is the
/// default. `items` are the list's entries in order, `None` standing for `...`.
pub fn list_problems<'a>(
    items: impl IntoIterator<Item = Option<&'a ModelEntry>>,
) -> Vec<ListProblem> {
    let mut problems = Vec::new();
    let mut problem = |code, index, message| {
        problems.push(ListProblem {
            code,
            index,
            message,
        })
    };
    let mut seen = std::collections::HashSet::new();
    let (mut splices, mut len) = (0, 0);
    for (index, item) in items.into_iter().enumerate() {
        len += 1;
        let Some(entry) = item else {
            splices += 1;
            if splices == 2 {
                let message = format!("`{MODELS_SPLICE}` may appear once in `models`");
                problem("models.splice-twice", Some(index), message);
            }
            continue;
        };
        if !seen.insert(entry.model.as_str()) {
            let message = format!("`models` lists `{}` twice", entry.model);
            problem("models.duplicate", Some(index), message);
        }
        if index == 0 && entry.no_fallback == Some(true) {
            let message = format!(
                "`models[0]` (`{}`) is the default, and `no-fallback` marks a model used only when asked for",
                entry.model
            );
            problem("models.default-no-fallback", Some(index), message);
        }
    }
    if len == 0 {
        let message = "`models` is empty: remove the line, or name a model".to_string();
        problem("models.empty", None, message);
    }
    problems
}

const ENTRY_KEYS: &[&str] = &[
    "model",
    "when",
    "no-fallback",
    "effort",
    "sandbox",
    "approval",
    "network",
];

pub(crate) struct EntryReading {
    pub entry: Result<ModelEntry, Vec<ModelPolicyRuleParseError>>,
    pub unknown: Vec<String>,
}

/// Reads an entry written as a name or as a mapping with flat settings.
pub(crate) fn read_model_entry(value: &serde_yaml::Value) -> EntryReading {
    use ModelPolicyRuleParseError as Error;
    let fail = |error| EntryReading {
        entry: Err(vec![error]),
        unknown: Vec::new(),
    };
    let named = |name: &str| {
        let name = name.trim();
        (!name.is_empty()).then(|| ModelEntry {
            model: name.to_string(),
            ..ModelEntry::default()
        })
    };
    let mapping = match value {
        serde_yaml::Value::String(name) => {
            return match named(name) {
                Some(entry) => EntryReading {
                    entry: Ok(entry),
                    unknown: Vec::new(),
                },
                None => fail(Error::EntryModelInvalid {
                    found: crate::ordered::plain(value),
                }),
            };
        }
        serde_yaml::Value::Mapping(mapping) => mapping,
        other => {
            return fail(Error::EntryMustBeNameOrMapping {
                found: crate::ordered::plain(other),
            });
        }
    };
    let mut errors = Vec::new();
    let unknown = unknown_keys(mapping, ENTRY_KEYS);
    let model = match mapping.get(serde_yaml::Value::String("model".to_string())) {
        None => {
            errors.push(Error::EntryModelMissing);
            None
        }
        Some(serde_yaml::Value::String(name)) if !name.trim().is_empty() => {
            Some(name.trim().to_string())
        }
        Some(other) => {
            errors.push(Error::EntryModelInvalid {
                found: crate::ordered::plain(other),
            });
            None
        }
    };
    let settings: serde_yaml::Mapping = mapping
        .iter()
        .filter(|(key, _)| {
            key.as_str()
                .is_some_and(|key| matches!(key, "effort" | "sandbox" | "approval" | "network"))
        })
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect();
    let overrides = read_overrides(&settings, &mut errors);
    let no_fallback = read_no_fallback(mapping, &mut errors);
    let when = read_when(mapping, &mut errors);
    let entry = match model {
        Some(model) if errors.is_empty() => Ok(ModelEntry {
            model,
            when,
            no_fallback,
            overrides,
        }),
        _ => Err(errors),
    };
    EntryReading { entry, unknown }
}

fn entry_error(errors: &[ModelPolicyRuleParseError]) -> String {
    errors
        .iter()
        .map(ModelPolicyRuleParseError::deserialize_message)
        .collect::<Vec<_>>()
        .join("; ")
}

/// Collects the keys an entry reads and hands every other value to serde as ignored, so a
/// reader that reports ignored keys sees an unknown field of an entry.
struct EntryVisitor;

impl<'de> serde::de::Visitor<'de> for EntryVisitor {
    type Value = ModelsItem;

    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("a model name, `...`, or a mapping with `model`")
    }

    fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<Self::Value, E> {
        if name == MODELS_SPLICE {
            return Ok(ModelsItem::Rest);
        }
        read_model_entry(&serde_yaml::Value::String(name.to_string()))
            .entry
            .map(ModelsItem::Entry)
            .map_err(|errors| E::custom(entry_error(&errors)))
    }

    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        let mut entry = serde_yaml::Mapping::new();
        while let Some(key) = map.next_key::<String>()? {
            if ENTRY_KEYS.contains(&key.as_str()) {
                entry.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
            } else {
                map.next_value::<serde::de::IgnoredAny>()?;
            }
        }
        read_model_entry(&serde_yaml::Value::Mapping(entry))
            .entry
            .map(ModelsItem::Entry)
            .map_err(|errors| serde::de::Error::custom(entry_error(&errors)))
    }
}

impl<'de> Deserialize<'de> for ModelsItem {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(EntryVisitor)
    }
}

impl Serialize for ModelEntry {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.when.is_none() && self.no_fallback.is_none() && self.overrides.is_empty() {
            return serializer.serialize_str(&self.model);
        }
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("model", &self.model)?;
        if let Some(when) = &self.when {
            map.serialize_entry("when", when)?;
        }
        if let Some(no_fallback) = self.no_fallback {
            map.serialize_entry("no-fallback", &no_fallback)?;
        }
        for key in ["effort", "sandbox", "approval", "network"] {
            if let Some(value) = self.overrides.get(key) {
                map.serialize_entry(key, value)?;
            }
        }
        map.end()
    }
}

impl Serialize for ModelsItem {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Rest => serializer.serialize_str(MODELS_SPLICE),
            Self::Entry(entry) => entry.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ModelPolicyRule {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// Takes the keys a rule reads and hands every other value to serde as ignored, so a
        /// reader that reports ignored keys sees an unknown field of a rule or of its `override`.
        struct RuleVisitor;

        impl<'de> serde::de::Visitor<'de> for RuleVisitor {
            type Value = ModelPolicyRule;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a model policy rule mapping")
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut map: A,
            ) -> Result<Self::Value, A::Error> {
                let mut rule = serde_yaml::Mapping::new();
                while let Some(key) = map.next_key::<String>()? {
                    if RULE_KEYS.contains(&key.as_str()) {
                        rule.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
                    } else {
                        map.next_value::<serde::de::IgnoredAny>()?;
                    }
                }
                read_model_policy_rule(&serde_yaml::Value::Mapping(rule))
                    .rule
                    .map_err(|errors| {
                        serde::de::Error::custom(
                            errors
                                .iter()
                                .map(ModelPolicyRuleParseError::deserialize_message)
                                .collect::<Vec<_>>()
                                .join("; "),
                        )
                    })
            }
        }

        deserializer.deserialize_map(RuleVisitor)
    }
}

impl Serialize for ModelPolicyRule {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        let match_key = match self.match_type {
            ModelPolicyMatchType::Model => "model",
            ModelPolicyMatchType::Alias => "alias",
            ModelPolicyMatchType::ModelGlob => "model-glob",
        };

        let mut match_clause = serde_yaml::Mapping::new();
        match_clause.insert(
            serde_yaml::Value::String(match_key.to_string()),
            serde_yaml::Value::String(self.match_value.clone()),
        );
        map.serialize_entry("match", &match_clause)?;
        if !self.overrides.is_empty() {
            map.serialize_entry("override", &self.overrides)?;
        }
        if self.no_fallback {
            map.serialize_entry("no-fallback", &self.no_fallback)?;
        }
        if let Some(when) = &self.when {
            map.serialize_entry("when", when)?;
        }
        map.end()
    }
}