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
280 fn selection_duplicates(&mut self, prepared: &Prepared, selection: &SelectionResult) {
283 for duplicate in duplicate_slugs(&selection.items) {
284 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 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 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
393struct Named<'a> {
395 definition: &'a PreparedDefinition,
396 agent: bool,
397 declared: Option<&'a str>,
399 described: bool,
400 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 fn name(&self) -> &str {
439 self.declared.unwrap_or(&self.definition.slug)
440 }
441}
442
443struct Graph {
445 selection: SelectionResult,
446 has_package: bool,
448 missing: Vec<MissingDependency>,
450 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 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
550fn missing_message(missing: &MissingSkill) -> String {
552 let skill = &missing.skill;
553 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
589fn 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}