Skip to main content

mars_schema/
skill.rs

1//! Skill definition reading.
2
3use crate::diagnostic::unrecognized_field;
4use crate::frontmatter::Frontmatter;
5use crate::invocability::parse_invocability_axis;
6use crate::item::DefinitionKind;
7use serde_yaml::Value;
8
9#[derive(Debug, Clone, serde::Serialize)]
10#[serde(rename_all = "kebab-case")]
11pub struct SkillProfile {
12    pub name: Option<String>,
13    pub description: Option<String>,
14    /// `metadata.type`, kept apart for callers; the reading carries it under `metadata`.
15    #[serde(skip)]
16    pub skill_type: Option<String>,
17    pub model_invocable: bool,
18    pub user_invocable: bool,
19    pub license: Option<String>,
20    pub compatibility: Option<String>,
21    #[serde(serialize_with = "serialize_metadata")]
22    pub metadata: Option<Value>,
23    /// true when the source frontmatter explicitly set `model-invocable`
24    #[serde(skip)]
25    pub had_model_invocable_field: bool,
26    #[serde(skip)]
27    pub has_frontmatter: bool,
28    /// Per-harness native keys (`harness-overrides:`), written only to that harness's file.
29    #[serde(skip)]
30    pub harness_overrides: crate::harness_overrides::HarnessOverrides,
31}
32
33/// Non-JSON YAML (tags, non-string keys) is left out, as in the reading's `frontmatter`,
34/// where it carries a `yaml.non-json-value` diagnostic.
35fn serialize_metadata<S: serde::Serializer>(
36    value: &Option<Value>,
37    serializer: S,
38) -> Result<S::Ok, S::Error> {
39    use serde::Serialize;
40    value
41        .as_ref()
42        .and_then(|value| crate::ordered::OrderedValue::from_yaml(value).ok())
43        .serialize(serializer)
44}
45
46/// The frontmatter keys Mars writes into a harness's native skill file itself. A
47/// `harness-overrides` entry never replaces one (native lowering keeps Mars's value and reports
48/// the override as dropped), so the translation's set-aside never moves one there either. The
49/// Agent counterpart is [`crate::agent::LoweredField`].
50pub const LOWERED_KEYS: &[&str] = &[
51    "name",
52    "description",
53    "license",
54    "metadata",
55    "disable-model-invocation",
56    "user-invocable",
57    "alwaysApply",
58];
59
60/// The keys that carry a skill's tool policy.
61pub(crate) fn tool_keys() -> impl Iterator<Item = &'static str> {
62    ["tools", "allowed-tools", "allowed_tools"]
63        .into_iter()
64        .chain(crate::tool_policy::DISALLOWED_SPELLINGS)
65}
66
67pub(crate) fn read_fields(
68    fm: &Frontmatter,
69    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
70) -> SkillProfile {
71    use crate::diagnostic::{SchemaDiagnostic, Severity, child_path, key_path};
72
73    let mut profile = SkillProfile {
74        name: None,
75        description: None,
76        skill_type: None,
77        model_invocable: true,
78        user_invocable: true,
79        license: None,
80        compatibility: None,
81        metadata: None,
82        had_model_invocable_field: false,
83        has_frontmatter: fm.has_frontmatter(),
84        harness_overrides: Default::default(),
85    };
86    let mut classification_diagnostics = Vec::new();
87    let mut field_diagnostics = Vec::new();
88
89    for key in fm.keys() {
90        let value = fm.get(&key).expect("frontmatter key came from mapping");
91        match key.as_str() {
92            "name" | "description" | "license" | "compatibility" => {
93                let parsed = if let Some(text) = value.as_str() {
94                    Some(if key == "name" {
95                        text.trim().to_owned()
96                    } else {
97                        text.to_owned()
98                    })
99                } else {
100                    field_diagnostics.push(SchemaDiagnostic::new(
101                        "field.type",
102                        Severity::Error,
103                        key_path(&key),
104                        format!("`{key}` must be a string"),
105                    ));
106                    None
107                };
108                match key.as_str() {
109                    "name" => profile.name = parsed,
110                    "description" => profile.description = parsed,
111                    "license" => profile.license = parsed,
112                    "compatibility" => profile.compatibility = parsed,
113                    _ => unreachable!(),
114                }
115            }
116            "metadata" => {
117                profile.metadata = Some(value.clone());
118                if let Some(mapping) = value.as_mapping() {
119                    if let Some(skill_type) = mapping.get(Value::String("type".to_string())) {
120                        if let Some(skill_type) = skill_type.as_str() {
121                            profile.skill_type = Some(skill_type.to_owned());
122                        } else {
123                            field_diagnostics.push(SchemaDiagnostic::new(
124                                "field.type",
125                                Severity::Error,
126                                child_path("metadata", "type"),
127                                "`metadata.type` must be a string",
128                            ));
129                        }
130                    }
131                } else {
132                    field_diagnostics.push(SchemaDiagnostic::new(
133                        "field.type",
134                        Severity::Error,
135                        key_path("metadata"),
136                        "`metadata` must be a map",
137                    ));
138                }
139            }
140            "model-invocable" => {
141                let (value, had_field, invalid) = parse_invocability_axis(Some(value));
142                profile.model_invocable = value;
143                profile.had_model_invocable_field = had_field;
144                if invalid.is_some() {
145                    field_diagnostics.push(SchemaDiagnostic::new(
146                        "field.type",
147                        Severity::Error,
148                        key_path("model-invocable"),
149                        "`model-invocable` must be true or false",
150                    ));
151                }
152            }
153            "user-invocable" => {
154                let (value, _, invalid) = parse_invocability_axis(Some(value));
155                profile.user_invocable = value;
156                if invalid.is_some() {
157                    field_diagnostics.push(SchemaDiagnostic::new(
158                        "field.type",
159                        Severity::Error,
160                        key_path("user-invocable"),
161                        "`user-invocable` must be true or false",
162                    ));
163                }
164            }
165            "harness-overrides" => {
166                profile.harness_overrides = crate::harness_overrides::parse_harness_overrides(
167                    "skill",
168                    value,
169                    &mut field_diagnostics,
170                );
171            }
172            _ => classification_diagnostics.push(unrecognized_field(DefinitionKind::Skill, &key)),
173        }
174    }
175
176    diags.append(&mut classification_diagnostics);
177
178    if !fm.has_frontmatter() {
179        diags.push(SchemaDiagnostic::new(
180            "skill.no-frontmatter",
181            Severity::Warning,
182            Vec::new(),
183            "body-only skill has no frontmatter",
184        ));
185    } else {
186        for (key, value) in [
187            ("name", profile.name.as_deref()),
188            ("description", profile.description.as_deref()),
189        ] {
190            if value.is_none_or(|value| value.trim().is_empty()) {
191                diags.push(SchemaDiagnostic::new(
192                    "field.required",
193                    Severity::Error,
194                    key_path(key),
195                    format!("`{key}` must be a non-empty string"),
196                ));
197            }
198        }
199    }
200    diags.append(&mut field_diagnostics);
201
202    profile
203}
204
205/// Read a skill definition through the versioned schema contract.
206pub fn read(content: &str) -> crate::read::DefinitionRead<SkillProfile> {
207    crate::read::read_with(content, read_fields)
208}