1use 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
31const CHANGE_CODES: [&str; 3] = [RESTRICTION_LOST, EXECUTION_IGNORED, REPAIRED];
33
34const MANIFEST: &str = "mars.toml";
35
36#[derive(Debug, Clone, Serialize)]
38pub struct Check {
39 pub diagnostics: IndexMap<String, Vec<SchemaDiagnostic>>,
43 pub dependency_diagnostics: BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>>,
46 pub missing_dependencies: Vec<MissingDependency>,
49 pub unreadable_dependencies: Vec<MissingDependency>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56pub struct MissingDependency {
57 pub name: String,
58 pub declared_in: Option<String>,
60}
61
62pub 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#[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 found.sort_by_key(|diagnostic| diagnostic.severity as u8);
134 }
135 merged
136 }
137
138 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 fn requirement(&mut self, prepared: &Prepared) {
155 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 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 let mut by_slug: BTreeMap<(DefinitionKind, &str), Vec<&Named>> = BTreeMap::new();
282 for item in &items {
283 by_slug
284 .entry((item.definition.kind, item.definition.slug.as_str()))
285 .or_default()
286 .push(item);
287 }
288 for items in by_slug.values() {
289 let [first, second, ..] = items.as_slice() else {
290 continue;
291 };
292 if !shared(first) {
293 self.rule(
294 &first.definition.source_path,
295 SchemaDiagnostic::new(
296 "definition.duplicate-slug",
297 Severity::Error,
298 Vec::new(),
299 format!(
300 "{} slug `{}` is also selected by `{}`",
301 first.definition.kind,
302 first.definition.slug,
303 second.definition.source_path
304 ),
305 ),
306 );
307 }
308 }
309 }
310
311 fn selection_duplicates(&mut self, prepared: &Prepared, selection: &SelectionResult) {
314 for duplicate in duplicate_slugs(&selection.items) {
315 if duplicate.packages.iter().flatten().next().is_none() {
317 continue;
318 }
319 let names = duplicate
320 .packages
321 .iter()
322 .flatten()
323 .map(|name| format!("`{name}`"))
324 .collect::<Vec<_>>();
325 let dependencies = names.join(", ");
326 if duplicate.packages.contains(&None) {
327 let Some(root) = prepared.definitions.iter().find(|definition| {
328 ItemKind::from(definition.kind) == duplicate.kind
329 && definition.slug == duplicate.slug
330 }) else {
331 continue;
332 };
333 self.rule(
334 &root.source_path,
335 SchemaDiagnostic::new(
336 "selection.duplicate-slug",
337 Severity::Info,
338 Vec::new(),
339 format!(
340 "{} `{}` is also shipped by {dependencies}; this package's is the one installed",
341 duplicate.kind, duplicate.slug
342 ),
343 ),
344 );
345 } else {
346 self.rule(
347 MANIFEST,
348 SchemaDiagnostic::new(
349 "selection.duplicate-slug",
350 Severity::Warning,
351 key_path("dependencies"),
352 format!(
353 "{} `{}` is shipped by {}; one is installed",
354 duplicate.kind,
355 duplicate.slug,
356 both(&names)
357 ),
358 ),
359 );
360 }
361 }
362 }
363
364 fn skill_refs(&mut self, prepared: &Prepared, graph: &Graph) {
366 for missing in graph
367 .selection
368 .missing_skills
369 .iter()
370 .filter(|missing| missing.package.is_none())
371 {
372 let Some(agent) = prepared.definitions.iter().find(|definition| {
373 definition.kind == DefinitionKind::Agent && definition.slug == missing.agent
374 }) else {
375 continue;
376 };
377 let (code, severity) = match &missing.hint {
378 Some(_) if graph.has_package => ("skill-ref.provider", Severity::Error),
379 _ if graph.has_dependencies => ("skill-ref.missing", Severity::Error),
380 _ => ("skill-ref.external", Severity::Warning),
381 };
382 let message = if code == "skill-ref.external" {
383 format!(
384 "agent `{}` references skill `{}`, which this package does not ship; a consumer must hold a package that does",
385 missing.agent, missing.skill
386 )
387 } else {
388 missing_message(missing)
389 };
390 self.rule(
391 &agent.source_path,
392 SchemaDiagnostic::new(code, severity, key_path("skills"), message),
393 );
394 }
395 }
396
397 fn skill_folders(&mut self, source: &impl TreeSource, prepared: &Prepared) {
400 let boundary = Boundary::of(source);
401 let containers = kept_skill_containers(
402 source,
403 prepared
404 .definitions
405 .iter()
406 .map(|definition| definition.source_path.as_str()),
407 );
408 for container in containers {
409 for dir in source.children(&container) {
410 if basename(&dir).starts_with('.')
411 || !source.is_dir(&dir)
412 || source.is_file(&join(&dir, "SKILL.md"))
413 || !boundary.admits(source, &dir, &mut Vec::new())
414 || !holds_file(source, &boundary, &dir)
415 {
416 continue;
417 }
418 self.rule(
419 &dir,
420 SchemaDiagnostic::new(
421 "skill.no-definition",
422 Severity::Warning,
423 Vec::new(),
424 format!("`{dir}` has files and no `SKILL.md`, so none of it is installed"),
425 ),
426 );
427 }
428 }
429 }
430}
431
432struct Named<'a> {
434 definition: &'a PreparedDefinition,
435 agent: bool,
436 declared: Option<&'a str>,
438 described: bool,
439 unfenced: bool,
441}
442
443impl<'a> Named<'a> {
444 fn of(definition: &'a PreparedDefinition) -> Option<Self> {
445 let (declared, described, unfenced) = match &definition.reading {
446 Reading::Agent(reading) => {
447 let profile = reading.fields.as_ref()?;
448 (
449 profile.name.as_deref(),
450 profile.description.is_some(),
451 reading
452 .diagnostics
453 .iter()
454 .any(|diagnostic| diagnostic.code == "frontmatter.missing"),
455 )
456 }
457 Reading::Skill(reading) => {
458 let profile = reading.fields.as_ref()?;
459 (
460 profile.name.as_deref(),
461 profile.description.is_some(),
462 false,
463 )
464 }
465 Reading::Manifest(_) => return None,
466 };
467 Some(Self {
468 agent: definition.kind == DefinitionKind::Agent,
469 definition,
470 declared,
471 described,
472 unfenced,
473 })
474 }
475
476 fn name(&self) -> &str {
478 self.declared.unwrap_or(&self.definition.slug)
479 }
480}
481
482struct Graph {
484 selection: SelectionResult,
485 has_package: bool,
487 has_dependencies: bool,
490 missing: Vec<MissingDependency>,
492 unreadable: Vec<MissingDependency>,
495}
496
497impl Graph {
498 fn of(prepared: &Prepared, dependencies: &BTreeMap<String, SelectionFacts>) -> Self {
499 let has_package = prepared
500 .manifest
501 .as_ref()
502 .is_some_and(|manifest| manifest.reading.package.fields.is_some());
503 let has_dependencies = has_package && !prepared.selection.edges.is_empty();
504 let mut root = prepared.selection.clone();
505 let mut packages = BTreeMap::new();
506 if has_dependencies {
507 packages = dependencies.clone();
508 } else {
509 root.edges.clear();
510 }
511
512 let mut missing = Vec::new();
513 let mut unreadable = Vec::new();
514 let mut seen = BTreeSet::new();
515 let mut queue: VecDeque<(Option<&str>, &SelectionFacts)> = VecDeque::from([(None, &root)]);
516 while let Some((declared_in, facts)) = queue.pop_front() {
517 for edge in &facts.edges {
518 if !seen.insert(edge.name.as_str()) {
519 continue;
520 }
521 match packages.get(&edge.name) {
522 Some(package) => {
523 if package.unreadable {
524 unreadable.push(MissingDependency {
525 name: edge.name.clone(),
526 declared_in: declared_in.map(str::to_owned),
527 });
528 }
529 queue.push_back((Some(edge.name.as_str()), package));
530 }
531 None => missing.push(MissingDependency {
532 name: edge.name.clone(),
533 declared_in: declared_in.map(str::to_owned),
534 }),
535 }
536 }
537 }
538
539 let view = |facts| PackageView {
540 facts,
541 extra_items: Vec::new(),
542 };
543 let selection = select(&GraphView {
544 requests: Vec::new(),
545 packages: packages
546 .into_iter()
547 .map(|(name, facts)| (name, view(facts)))
548 .collect(),
549 root: Some(view(root)),
550 });
551 Self {
552 selection,
553 has_package,
554 has_dependencies,
555 missing,
556 unreadable,
557 }
558 }
559
560 fn dependency_findings(
562 &self,
563 dependencies: &BTreeMap<String, SelectionFacts>,
564 ) -> BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>> {
565 let mut found: BTreeMap<String, BTreeMap<String, Vec<SchemaDiagnostic>>> = BTreeMap::new();
566 for missing in &self.selection.missing_skills {
567 let Some(package) = missing.package.as_deref() else {
568 continue;
569 };
570 let Some(agent) = dependencies.get(package).and_then(|facts| {
571 facts.definitions.iter().find(|definition| {
572 definition.kind == DefinitionKind::Agent && definition.slug == missing.agent
573 })
574 }) else {
575 continue;
576 };
577 found
578 .entry(package.to_owned())
579 .or_default()
580 .entry(agent.output_path.clone())
581 .or_default()
582 .push(SchemaDiagnostic::new(
583 "skill-ref.dependency",
584 Severity::Error,
585 key_path("skills"),
586 missing_message(missing),
587 ));
588 }
589 found
590 }
591}
592
593fn missing_message(missing: &MissingSkill) -> String {
595 let skill = &missing.skill;
596 let agent = match &missing.package {
598 Some(package) => format!("agent `{}` of dependency `{package}`", missing.agent),
599 None => format!("agent `{}`", missing.agent),
600 };
601 if let Some(hint) = &missing.hint {
602 return format!(
603 "{agent} references skill `{skill}`, which is not in this package or its dependencies; {hint}"
604 );
605 }
606 let remedy = match &missing.package {
607 Some(package) => {
608 format!("use a version of `{package}` that ships it, or add a dependency that does")
609 }
610 None => "add the skill's source package as a dependency, or remove the skill reference"
611 .to_string(),
612 };
613 let own = match &missing.package {
614 Some(package) => package.as_str(),
615 None => "(this package)",
616 };
617 let searched = std::iter::once(own)
618 .chain(
619 missing
620 .searched
621 .iter()
622 .map(String::as_str)
623 .filter(|name| *name != own),
624 )
625 .collect::<Vec<_>>()
626 .join(", ");
627 format!(
628 "{agent} references skill `{skill}` not found in local package or dependencies\n searched: {searched}\n hint: {remedy}"
629 )
630}
631
632fn both(names: &[String]) -> String {
634 match names {
635 [first, second] => format!("both {first} and {second}"),
636 [init @ .., last] => format!("{} and {last}", init.join(", ")),
637 [] => String::new(),
638 }
639}