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