Skip to main content

mars_schema/
check.rs

1//! What is wrong with a package, from its files and its dependencies: `mars check` and the WASM
2//! `check` share this one function. It has no host I/O, and it reports what is true of the package
3//! wherever it runs. A finding that exists only because a harness target or an older Mars cannot
4//! take something belongs where that target or version exists (the binary).
5//!
6//! A level says what the author loses: `Error`, the file or package won't load or install;
7//! `Warning`, something written won't take effect; `Info`, nothing written is lost.
8//!
9//! Per path, a result lists `prepare`'s findings, then the three kinds of change translation made
10//! that an author should see ([`CHANGE_CODES`]), then the check's own rules in the order they run
11//! below, stably sorted by level. Dropping the codes of those rules and changes from a path's list
12//! leaves what `prepare` returns for it, so the two never disagree about a file.
13
14use std::collections::{BTreeMap, BTreeSet, VecDeque};
15
16use indexmap::IndexMap;
17use serde::Serialize;
18
19use crate::claude::translate::REPAIRED;
20use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, key_path};
21use crate::discover::{Boundary, basename, holds_file, join, kept_skill_containers};
22use crate::item::{DefinitionKind, ItemKind};
23use crate::prepare::{Classification, Prepared, PreparedDefinition};
24use crate::read::Reading;
25use crate::selection::{
26    GraphView, MissingSkill, PackageView, SelectionFacts, SelectionResult, duplicate_slugs, select,
27};
28use crate::set_aside::{EXECUTION_IGNORED, RESTRICTION_LOST};
29use crate::tree::TreeSource;
30
31/// The codes `check` takes from `Prepared::changes`.
32const CHANGE_CODES: [&str; 3] = [RESTRICTION_LOST, EXECUTION_IGNORED, REPAIRED];
33
34const MANIFEST: &str = "mars.toml";
35
36/// What is wrong with a package.
37#[derive(Debug, Clone, Serialize)]
38pub struct Check {
39    /// Findings in the root's own files, by source path: what `prepare` reported for the file,
40    /// then the check's own. `mars.toml` holds what applies to the whole package and comes first,
41    /// then the paths in lexical order.
42    pub diagnostics: IndexMap<String, Vec<SchemaDiagnostic>>,
43    /// `skill-ref.dependency` only: a dependency's own Agent names a skill no package ships. By
44    /// the dependency's source name, then the Agent's output path (`agents/<slug>.md`).
45    pub dependency_diagnostics: BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>>,
46    /// Every `[dependencies]` name reachable from the root that `dependencies` lacks. While it
47    /// is not empty the result is not a verdict: no skill ref was judged.
48    pub missing_dependencies: Vec<MissingDependency>,
49    /// Every dependency reachable from the root whose `selection.unreadable` is set: an invalid
50    /// or newer-schema manifest. It may be the one that ships a skill, so while this is not empty
51    /// the result is not a verdict either. Same shape as `missing_dependencies`.
52    pub unreadable_dependencies: Vec<MissingDependency>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56pub struct MissingDependency {
57    pub name: String,
58    /// The package whose `mars.toml` declares it; `None` for the root.
59    pub declared_in: Option<String>,
60}
61
62/// What is wrong with the package that `prepared` (with [`crate::links::package`] applied) is
63/// the result of preparing from `source`. `dependencies` is the whole closure: every package
64/// reachable from the root through any `[dependencies]` entry, filtered or not, by the name the
65/// declaring table gives its source.
66pub fn check(
67    source: &impl TreeSource,
68    prepared: &Prepared,
69    dependencies: &BTreeMap<String, SelectionFacts>,
70) -> Check {
71    let mut found = Found::default();
72    let mut dependency_diagnostics = BTreeMap::new();
73    let mut missing_dependencies = Vec::new();
74    let mut unreadable_dependencies = Vec::new();
75    if matches!(
76        prepared.classification,
77        Classification::Schema1 | Classification::Foreign(_)
78    ) {
79        found.changes(prepared);
80        found.requirement(prepared);
81        found.definition_names(prepared);
82        let graph = Graph::of(prepared, dependencies);
83        found.selection_duplicates(prepared, &graph.selection);
84        if graph.missing.is_empty() && graph.unreadable.is_empty() {
85            found.skill_refs(prepared, &graph);
86            dependency_diagnostics = graph.dependency_findings(dependencies);
87        }
88        if matches!(prepared.classification, Classification::Schema1) {
89            found.skill_folders(source, prepared);
90        }
91        missing_dependencies = graph.missing;
92        unreadable_dependencies = graph.unreadable;
93    }
94    Check {
95        diagnostics: found.merge(prepared),
96        dependency_diagnostics,
97        missing_dependencies,
98        unreadable_dependencies,
99    }
100}
101
102/// The check's own findings by source path, in the order the rules run.
103#[derive(Default)]
104struct Found {
105    changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
106    rules: BTreeMap<String, Vec<SchemaDiagnostic>>,
107}
108
109impl Found {
110    fn rule(&mut self, path: &str, diagnostic: SchemaDiagnostic) {
111        self.rules
112            .entry(path.to_owned())
113            .or_default()
114            .push(diagnostic);
115    }
116
117    fn merge(self, prepared: &Prepared) -> IndexMap<String, Vec<SchemaDiagnostic>> {
118        let mut by_path: BTreeMap<String, Vec<SchemaDiagnostic>> = prepared
119            .all_diagnostics()
120            .into_iter()
121            .map(|(path, found)| (path.to_owned(), found.into_iter().cloned().collect()))
122            .collect();
123        for (path, found) in self.changes.into_iter().chain(self.rules) {
124            by_path.entry(path).or_default().extend(found);
125        }
126        let mut merged = IndexMap::new();
127        if let Some(found) = by_path.remove(MANIFEST) {
128            merged.insert(MANIFEST.to_owned(), found);
129        }
130        merged.extend(by_path);
131        for found in merged.values_mut() {
132            // `Severity` is declared most severe first.
133            found.sort_by_key(|diagnostic| diagnostic.severity as u8);
134        }
135        merged
136    }
137
138    /// The changes translation made that the author can act on.
139    fn changes(&mut self, prepared: &Prepared) {
140        for (path, changes) in &prepared.changes {
141            for change in changes
142                .iter()
143                .filter(|change| CHANGE_CODES.contains(&change.code.as_str()))
144            {
145                self.changes
146                    .entry(path.clone())
147                    .or_default()
148                    .push(change.clone());
149            }
150        }
151    }
152
153    /// `package.requirement`.
154    fn requirement(&mut self, prepared: &Prepared) {
155        // A generated manifest has no `requires-*` to read.
156        let Some(package) = prepared
157            .manifest
158            .as_ref()
159            .filter(|manifest| manifest.source_path.is_some())
160            .and_then(|manifest| manifest.reading.package.fields.as_ref())
161        else {
162            return;
163        };
164        for (key, message) in crate::package::requirement_errors(package) {
165            self.rule(
166                MANIFEST,
167                SchemaDiagnostic::new(
168                    "package.requirement",
169                    Severity::Error,
170                    vec![
171                        PathSegment::Key("package".into()),
172                        PathSegment::Key(key.into()),
173                    ],
174                    message,
175                ),
176            );
177        }
178    }
179
180    /// `agent.description-missing`, `agent.name-missing`, `definition.name-mismatch`
181    /// and `definition.duplicate-name`.
182    fn definition_names(&mut self, prepared: &Prepared) {
183        let items = prepared
184            .definitions
185            .iter()
186            .filter_map(Named::of)
187            .collect::<Vec<_>>();
188        let agents = || items.iter().filter(|item| item.agent && !item.unfenced);
189
190        for item in agents().filter(|item| !item.described) {
191            self.rule(
192                &item.definition.source_path,
193                SchemaDiagnostic::new(
194                    "agent.description-missing",
195                    Severity::Info,
196                    key_path("description"),
197                    format!(
198                        "agent `{}` has no `description`; Claude does not load an Agent without one",
199                        item.name()
200                    ),
201                ),
202            );
203        }
204        for item in agents().filter(|item| item.declared.is_none()) {
205            self.rule(
206                &item.definition.source_path,
207                SchemaDiagnostic::new(
208                    "agent.name-missing",
209                    Severity::Info,
210                    key_path("name"),
211                    format!(
212                        "agent `{}` has no `name`; the file name is used",
213                        item.definition.slug
214                    ),
215                ),
216            );
217        }
218        for item in items.iter().filter(|item| {
219            item.declared
220                .is_some_and(|name| name != item.definition.slug)
221        }) {
222            let (noun, file) = if item.agent {
223                ("agent file", format!("{}.md", item.definition.slug))
224            } else {
225                ("skill folder", item.definition.slug.clone())
226            };
227            let consequence = if item.agent {
228                "the item loads under both".to_string()
229            } else {
230                format!(
231                    "Claude lists it as `{}`, but skill refs and install use the folder name `{file}`",
232                    item.name()
233                )
234            };
235            self.rule(
236                &item.definition.source_path,
237                SchemaDiagnostic::new(
238                    "definition.name-mismatch",
239                    Severity::Info,
240                    key_path("name"),
241                    format!(
242                        "{noun} `{file}` doesn't match its `name` `{}`; {consequence}",
243                        item.name()
244                    ),
245                ),
246            );
247        }
248
249        let mut by_name: BTreeMap<(DefinitionKind, &str), Vec<&Named>> = BTreeMap::new();
250        for item in &items {
251            by_name
252                .entry((item.definition.kind, item.name()))
253                .or_default()
254                .push(item);
255        }
256        let shared = |item: &Named| by_name[&(item.definition.kind, item.name())].len() > 1;
257        for item in items.iter().filter(|item| shared(item)) {
258            let others = by_name[&(item.definition.kind, item.name())]
259                .iter()
260                .filter(|other| other.definition.source_path != item.definition.source_path)
261                .map(|other| format!("`{}`", other.definition.source_path))
262                .collect::<Vec<_>>()
263                .join(", ");
264            self.rule(
265                &item.definition.source_path,
266                SchemaDiagnostic::new(
267                    "definition.duplicate-name",
268                    Severity::Error,
269                    key_path("name"),
270                    format!(
271                        "{} name `{}` is also the name of {others}; `mars sync` installs both, and one native file replaces the other",
272                        item.definition.kind,
273                        item.name()
274                    ),
275                ),
276            );
277        }
278    }
279
280    /// `selection.duplicate-slug`: a root item over a dependency's is only information, a slug
281    /// two dependencies ship is a dependency the author declared installing less than it ships.
282    fn selection_duplicates(&mut self, prepared: &Prepared, selection: &SelectionResult) {
283        for duplicate in duplicate_slugs(&selection.items) {
284            // Two files of the root's own are `import.duplicate-slug`, not two packages.
285            if duplicate.packages.iter().flatten().next().is_none() {
286                continue;
287            }
288            let names = duplicate
289                .packages
290                .iter()
291                .flatten()
292                .map(|name| format!("`{name}`"))
293                .collect::<Vec<_>>();
294            let dependencies = names.join(", ");
295            if duplicate.packages.contains(&None) {
296                let Some(root) = prepared.definitions.iter().find(|definition| {
297                    ItemKind::from(definition.kind) == duplicate.kind
298                        && definition.slug == duplicate.slug
299                }) else {
300                    continue;
301                };
302                self.rule(
303                    &root.source_path,
304                    SchemaDiagnostic::new(
305                        "selection.duplicate-slug",
306                        Severity::Info,
307                        Vec::new(),
308                        format!(
309                            "{} `{}` is also shipped by {dependencies}; this package's is the one installed",
310                            duplicate.kind, duplicate.slug
311                        ),
312                    ),
313                );
314            } else {
315                self.rule(
316                    MANIFEST,
317                    SchemaDiagnostic::new(
318                        "selection.duplicate-slug",
319                        Severity::Warning,
320                        key_path("dependencies"),
321                        format!(
322                            "{} `{}` is shipped by {}; one is installed",
323                            duplicate.kind,
324                            duplicate.slug,
325                            both(&names)
326                        ),
327                    ),
328                );
329            }
330        }
331    }
332
333    /// `skill-ref.missing` and `skill-ref.provider`, for the root's Agents.
334    fn skill_refs(&mut self, prepared: &Prepared, graph: &Graph) {
335        for missing in graph
336            .selection
337            .missing_skills
338            .iter()
339            .filter(|missing| missing.package.is_none())
340        {
341            let Some(agent) = prepared.definitions.iter().find(|definition| {
342                definition.kind == DefinitionKind::Agent && definition.slug == missing.agent
343            }) else {
344                continue;
345            };
346            let code = match &missing.hint {
347                Some(_) if graph.has_package => "skill-ref.provider",
348                _ => "skill-ref.missing",
349            };
350            let message = missing_message(missing);
351            self.rule(
352                &agent.source_path,
353                SchemaDiagnostic::new(code, Severity::Error, key_path("skills"), message),
354            );
355        }
356    }
357
358    /// `skill.no-definition`: a folder directly under a `skills/` that discovery read, holding
359    /// files and no `SKILL.md`.
360    fn skill_folders(&mut self, source: &impl TreeSource, prepared: &Prepared) {
361        let boundary = Boundary::of(source);
362        let containers = kept_skill_containers(
363            source,
364            prepared
365                .definitions
366                .iter()
367                .map(|definition| definition.source_path.as_str()),
368        );
369        for container in containers {
370            for dir in source.children(&container) {
371                if basename(&dir).starts_with('.')
372                    || !source.is_dir(&dir)
373                    || source.is_file(&join(&dir, "SKILL.md"))
374                    || !boundary.admits(source, &dir, &mut Vec::new())
375                    || !holds_file(source, &boundary, &dir)
376                {
377                    continue;
378                }
379                self.rule(
380                    &dir,
381                    SchemaDiagnostic::new(
382                        "skill.no-definition",
383                        Severity::Warning,
384                        Vec::new(),
385                        format!("`{dir}` has files and no `SKILL.md`, so none of it is installed"),
386                    ),
387                );
388            }
389        }
390    }
391}
392
393/// An Agent or skill of the root that was read, with what its check rules need.
394struct Named<'a> {
395    definition: &'a PreparedDefinition,
396    agent: bool,
397    /// The author's `name`.
398    declared: Option<&'a str>,
399    described: bool,
400    /// An Agent with no opening `---`: `frontmatter.missing` already says it has no fields.
401    unfenced: bool,
402}
403
404impl<'a> Named<'a> {
405    fn of(definition: &'a PreparedDefinition) -> Option<Self> {
406        let (declared, described, unfenced) = match &definition.reading {
407            Reading::Agent(reading) => {
408                let profile = reading.fields.as_ref()?;
409                (
410                    profile.name.as_deref(),
411                    profile.description.is_some(),
412                    reading
413                        .diagnostics
414                        .iter()
415                        .any(|diagnostic| diagnostic.code == "frontmatter.missing"),
416                )
417            }
418            Reading::Skill(reading) => {
419                let profile = reading.fields.as_ref()?;
420                (
421                    profile.name.as_deref(),
422                    profile.description.is_some(),
423                    false,
424                )
425            }
426            Reading::Manifest(_) => return None,
427        };
428        Some(Self {
429            agent: definition.kind == DefinitionKind::Agent,
430            definition,
431            declared,
432            described,
433            unfenced,
434        })
435    }
436
437    /// The name the item goes by: its `name`, else the file or folder name.
438    fn name(&self) -> &str {
439        self.declared.unwrap_or(&self.definition.slug)
440    }
441}
442
443/// Selection over the root and its dependencies, whole, as a sync of the package alone selects.
444struct Graph {
445    selection: SelectionResult,
446    /// The root has `[package]`.
447    has_package: bool,
448    /// Dependencies a ref could resolve through that the caller left out.
449    missing: Vec<MissingDependency>,
450    /// Dependencies a ref could resolve through that could not be read; their own errors say
451    /// so, and a ref that only they could satisfy is not the root's to report.
452    unreadable: Vec<MissingDependency>,
453}
454
455impl Graph {
456    fn of(prepared: &Prepared, dependencies: &BTreeMap<String, SelectionFacts>) -> Self {
457        let has_package = prepared
458            .manifest
459            .as_ref()
460            .is_some_and(|manifest| manifest.reading.package.fields.is_some());
461        let has_dependencies = has_package && !prepared.selection.edges.is_empty();
462        let mut root = prepared.selection.clone();
463        let mut packages = BTreeMap::new();
464        if has_dependencies {
465            packages = dependencies.clone();
466        } else {
467            root.edges.clear();
468        }
469
470        let mut missing = Vec::new();
471        let mut unreadable = Vec::new();
472        let mut seen = BTreeSet::new();
473        let mut queue: VecDeque<(Option<&str>, &SelectionFacts)> = VecDeque::from([(None, &root)]);
474        while let Some((declared_in, facts)) = queue.pop_front() {
475            for edge in &facts.edges {
476                if !seen.insert(edge.name.as_str()) {
477                    continue;
478                }
479                match packages.get(&edge.name) {
480                    Some(package) => {
481                        if package.unreadable {
482                            unreadable.push(MissingDependency {
483                                name: edge.name.clone(),
484                                declared_in: declared_in.map(str::to_owned),
485                            });
486                        }
487                        queue.push_back((Some(edge.name.as_str()), package));
488                    }
489                    None => missing.push(MissingDependency {
490                        name: edge.name.clone(),
491                        declared_in: declared_in.map(str::to_owned),
492                    }),
493                }
494            }
495        }
496
497        let view = |facts| PackageView {
498            facts,
499            extra_items: Vec::new(),
500        };
501        let selection = select(&GraphView {
502            requests: Vec::new(),
503            packages: packages
504                .into_iter()
505                .map(|(name, facts)| (name, view(facts)))
506                .collect(),
507            root: Some(view(root)),
508        });
509        Self {
510            selection,
511            has_package,
512            missing,
513            unreadable,
514        }
515    }
516
517    /// `skill-ref.dependency`: a dependency's own Agent names a skill no package ships.
518    fn dependency_findings(
519        &self,
520        dependencies: &BTreeMap<String, SelectionFacts>,
521    ) -> BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>> {
522        let mut found: BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>> = BTreeMap::new();
523        for missing in &self.selection.missing_skills {
524            let Some(package) = missing.package.as_deref() else {
525                continue;
526            };
527            let Some(agent) = dependencies.get(package).and_then(|facts| {
528                facts.definitions.iter().find(|definition| {
529                    definition.kind == DefinitionKind::Agent && definition.slug == missing.agent
530                })
531            }) else {
532                continue;
533            };
534            found
535                .entry(package.to_owned())
536                .or_default()
537                .entry(agent.output_path.clone())
538                .or_default()
539                .push(SchemaDiagnostic::new(
540                    "skill-ref.dependency",
541                    Severity::Error,
542                    key_path("skills"),
543                    missing_message(missing),
544                ));
545        }
546        found
547    }
548}
549
550/// The error for a ref no package ships, in the words `mars check` has always used.
551fn missing_message(missing: &MissingSkill) -> String {
552    let skill = &missing.skill;
553    // An Agent of a dependency is that package's to fix, and the author's to work around.
554    let agent = match &missing.package {
555        Some(package) => format!("agent `{}` of dependency `{package}`", missing.agent),
556        None => format!("agent `{}`", missing.agent),
557    };
558    if let Some(hint) = &missing.hint {
559        return format!(
560            "{agent} references skill `{skill}`, which is not in this package or its dependencies; {hint}"
561        );
562    }
563    let remedy = match &missing.package {
564        Some(package) => {
565            format!("use a version of `{package}` that ships it, or add a dependency that does")
566        }
567        None => "add the skill's source package as a dependency, or remove the skill reference"
568            .to_string(),
569    };
570    let own = match &missing.package {
571        Some(package) => package.as_str(),
572        None => "(this package)",
573    };
574    let searched = std::iter::once(own)
575        .chain(
576            missing
577                .searched
578                .iter()
579                .map(String::as_str)
580                .filter(|name| *name != own),
581        )
582        .collect::<Vec<_>>()
583        .join(", ");
584    format!(
585        "{agent} references skill `{skill}` not found in local package or dependencies\n  searched: {searched}\n  hint: {remedy}"
586    )
587}
588
589/// "both `a` and `b`", or "`a`, `b` and `c`" for more.
590fn both(names: &[String]) -> String {
591    match names {
592        [first, second] => format!("both {first} and {second}"),
593        [init @ .., last] => format!("{} and {last}", init.join(", ")),
594        [] => String::new(),
595    }
596}