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    crate::upgrade::PRE_V1
63        .skill_tool_keys
64        .iter()
65        .copied()
66        .chain(crate::tool_policy::DISALLOWED_SPELLINGS)
67}
68
69pub(crate) fn read_fields(
70    fm: &Frontmatter,
71    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
72) -> SkillProfile {
73    use crate::diagnostic::{SchemaDiagnostic, Severity, child_path, key_path};
74
75    let mut profile = SkillProfile {
76        name: None,
77        description: None,
78        skill_type: None,
79        model_invocable: true,
80        user_invocable: true,
81        license: None,
82        compatibility: None,
83        metadata: None,
84        had_model_invocable_field: false,
85        has_frontmatter: fm.has_frontmatter(),
86        harness_overrides: Default::default(),
87    };
88    let mut classification_diagnostics = Vec::new();
89    let mut field_diagnostics = Vec::new();
90
91    for key in fm.keys() {
92        let value = fm.get(&key).expect("frontmatter key came from mapping");
93        match key.as_str() {
94            "name" | "description" | "license" | "compatibility" => {
95                let parsed = if let Some(text) = value.as_str() {
96                    Some(if key == "name" {
97                        text.trim().to_owned()
98                    } else {
99                        text.to_owned()
100                    })
101                } else {
102                    field_diagnostics.push(SchemaDiagnostic::new(
103                        "field.type",
104                        Severity::Error,
105                        key_path(&key),
106                        format!("`{key}` must be a string"),
107                    ));
108                    None
109                };
110                match key.as_str() {
111                    "name" => profile.name = parsed,
112                    "description" => profile.description = parsed,
113                    "license" => profile.license = parsed,
114                    "compatibility" => profile.compatibility = parsed,
115                    _ => unreachable!(),
116                }
117            }
118            "metadata" => {
119                profile.metadata = Some(value.clone());
120                if let Some(mapping) = value.as_mapping() {
121                    if let Some(skill_type) = mapping.get(Value::String("type".to_string())) {
122                        if let Some(skill_type) = skill_type.as_str() {
123                            profile.skill_type = Some(skill_type.to_owned());
124                        } else {
125                            field_diagnostics.push(SchemaDiagnostic::new(
126                                "field.type",
127                                Severity::Error,
128                                child_path("metadata", "type"),
129                                "`metadata.type` must be a string",
130                            ));
131                        }
132                    }
133                } else {
134                    field_diagnostics.push(SchemaDiagnostic::new(
135                        "field.type",
136                        Severity::Error,
137                        key_path("metadata"),
138                        "`metadata` must be a map",
139                    ));
140                }
141            }
142            "model-invocable" => {
143                let (value, had_field, invalid) = parse_invocability_axis(Some(value));
144                profile.model_invocable = value;
145                profile.had_model_invocable_field = had_field;
146                if invalid.is_some() {
147                    field_diagnostics.push(SchemaDiagnostic::new(
148                        "field.type",
149                        Severity::Error,
150                        key_path("model-invocable"),
151                        "`model-invocable` must be true or false",
152                    ));
153                }
154            }
155            "user-invocable" => {
156                let (value, _, invalid) = parse_invocability_axis(Some(value));
157                profile.user_invocable = value;
158                if invalid.is_some() {
159                    field_diagnostics.push(SchemaDiagnostic::new(
160                        "field.type",
161                        Severity::Error,
162                        key_path("user-invocable"),
163                        "`user-invocable` must be true or false",
164                    ));
165                }
166            }
167            "harness-overrides" => {
168                profile.harness_overrides = crate::harness_overrides::parse_harness_overrides(
169                    "skill",
170                    value,
171                    &mut field_diagnostics,
172                );
173            }
174            _ => classification_diagnostics.push(unrecognized_field(DefinitionKind::Skill, &key)),
175        }
176    }
177
178    diags.append(&mut classification_diagnostics);
179
180    if !fm.has_frontmatter() {
181        diags.push(SchemaDiagnostic::new(
182            "skill.no-frontmatter",
183            Severity::Warning,
184            Vec::new(),
185            "body-only skill has no frontmatter",
186        ));
187    } else {
188        for (key, value) in [
189            ("name", profile.name.as_deref()),
190            ("description", profile.description.as_deref()),
191        ] {
192            if value.is_none_or(|value| value.trim().is_empty()) {
193                diags.push(SchemaDiagnostic::new(
194                    "field.required",
195                    Severity::Error,
196                    key_path(key),
197                    format!("`{key}` must be a non-empty string"),
198                ));
199            }
200        }
201    }
202    diags.append(&mut field_diagnostics);
203
204    profile
205}
206
207/// Read a skill definition through the versioned schema contract.
208pub fn read(content: &str) -> crate::read::DefinitionRead<SkillProfile> {
209    crate::read::read_with(content, read_fields)
210}