Skip to main content

mars_schema/
dispatch.rs

1//! Classify one package root: the ordered dispatch of `mars-normalize`, shared by `prepare`
2//! (which reads the root as one package) and `inspect` (which reports it).
3//!
4//! 1. A directory holding a valid `.mars-plugin.json` is generated output, never input.
5//! 2. A Mars manifest decides; no declaration overrides it.
6//! 3. A declared dialect (`mars-native` on a root with no manifest is schema 1), else
7//! 4. the dialect predicted from evidence in the root, strongest first.
8//! 5. No items at all is `empty`.
9
10use std::collections::{BTreeMap, BTreeSet};
11
12use serde::Serialize;
13
14use crate::claude::discover::discover_claude;
15use crate::claude::manifest::{
16    MARKETPLACE_MANIFEST, Marketplace, MarketplaceEntry, PLUGIN_MANIFEST, PLUGIN_NAME_RULE,
17    PluginManifest, PluginSpec, is_plugin_name, resolve_spec,
18};
19use crate::diagnostic::{SchemaDiagnostic, Severity};
20use crate::dialect::{Dialect, DialectChoice};
21use crate::discover::{Discovery, discover};
22use crate::item::DefinitionKind;
23use crate::package::{ManifestClassification, classify_manifest};
24use crate::plugin_metadata::{SENTINEL_FILE, is_valid_sentinel};
25use crate::prepare::{Classification, PrepareContext};
26use crate::tree::TreeSource;
27
28/// What a root is, as `inspect` reports it: derived from the classification and layout.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum Kind {
32    #[serde(rename = "schema-1")]
33    Schema1,
34    SchemaNewer,
35    Marketplace,
36    Plugin,
37    SkillTree,
38    Invalid,
39    Empty,
40}
41
42/// How the root's items are found.
43#[derive(Debug, Clone)]
44pub(crate) enum Layout {
45    /// Nothing is read (invalid, newer, empty, generated).
46    None,
47    /// Mars's convention walk, output equal to source.
48    Convention,
49    /// Claude plugin rules, relocating into schema v1.
50    Claude(PluginSpec),
51    Marketplace(Marketplace),
52}
53
54/// A harness's copy of the package, found beside the one that is read.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56pub struct Mirror {
57    pub dialect: Dialect,
58    pub paths: Vec<String>,
59    /// A weak signal (a Codex sidecar many Claude-shaped repositories also ship) is reported
60    /// and never decides.
61    pub weak: bool,
62}
63
64pub(crate) struct Dispatched {
65    /// The package manifest to prepare. Consumer configuration is not one, so it is `None`
66    /// there; the root's `mars.toml` stays the consumer's to read.
67    pub manifest: Option<Vec<u8>>,
68    pub classification: Classification,
69    pub layout: Layout,
70    pub discovery: Discovery,
71    pub also_found: Vec<Mirror>,
72}
73
74impl Dispatched {
75    /// What the root is, as `inspect` reports it: the classification, with a foreign root's
76    /// layout telling a plugin from a bare skill tree.
77    pub(crate) fn kind(&self) -> Kind {
78        match (&self.classification, &self.layout) {
79            (Classification::Schema1, _) => Kind::Schema1,
80            (Classification::SchemaNewer { .. }, _) => Kind::SchemaNewer,
81            (Classification::Invalid, _) => Kind::Invalid,
82            (Classification::Marketplace, _) => Kind::Marketplace,
83            (Classification::Empty, _) => Kind::Empty,
84            (Classification::Foreign(_), Layout::Claude(spec)) if !spec.is_bare_tree() => {
85                Kind::Plugin
86            }
87            (Classification::Foreign(_), _) => Kind::SkillTree,
88        }
89    }
90
91    /// The foreign dialect read and why; `None` for Mars packages and unreadable roots.
92    pub(crate) fn dialect(&self) -> Option<&DialectChoice> {
93        match &self.classification {
94            Classification::Foreign(choice) => Some(choice),
95            _ => None,
96        }
97    }
98}
99
100/// A marketplace entry the root is being read as, with whether the entry's source is the
101/// marketplace root itself.
102#[derive(Clone, Copy)]
103pub(crate) struct AsPlugin<'a> {
104    pub entry: &'a MarketplaceEntry,
105    pub at_marketplace_root: bool,
106}
107
108/// What the Agent Skills specification (agentskills.io/specification) defines for `SKILL.md`,
109/// `allowed-tools` included, which it marks experimental. A skill using only these says nothing
110/// about the harness it was written for.
111const STANDARD_SKILL_KEYS: &[&str] = &[
112    "name",
113    "description",
114    "license",
115    "compatibility",
116    "metadata",
117    "allowed-tools",
118];
119
120pub(crate) fn dispatch(
121    source: &impl TreeSource,
122    context: PrepareContext,
123    declared: Option<Dialect>,
124    as_plugin: Option<AsPlugin<'_>>,
125    fallback_name: Option<&str>,
126) -> Dispatched {
127    let manifest = source.read("mars.toml");
128    let manifest_class = classify_manifest(manifest.as_deref());
129    let consumer_tree = consumer_content(context, &manifest_class);
130    let mut dispatched = classify(
131        source,
132        &manifest_class,
133        consumer_tree,
134        declared,
135        as_plugin,
136        fallback_name,
137    );
138    dispatched.manifest = manifest.filter(|_| !consumer_tree);
139    dispatched
140}
141
142/// Whether the root's items are the consumer's own authored content, read as Mars convention
143/// with no manifest.
144fn consumer_content(context: PrepareContext, manifest: &ManifestClassification) -> bool {
145    matches!(
146        (context, manifest),
147        (
148            PrepareContext::AuthoredLocal,
149            ManifestClassification::NoManifest
150        ) | (
151            PrepareContext::AuthoredLocal | PrepareContext::Project,
152            ManifestClassification::ConsumerConfig
153        )
154    )
155}
156
157fn classify(
158    source: &impl TreeSource,
159    manifest: &ManifestClassification,
160    consumer_tree: bool,
161    declared: Option<Dialect>,
162    as_plugin: Option<AsPlugin<'_>>,
163    fallback_name: Option<&str>,
164) -> Dispatched {
165    let done = |classification, layout, discovery, also_found| Dispatched {
166        manifest: None,
167        classification,
168        layout,
169        discovery,
170        also_found,
171    };
172    if source
173        .read(SENTINEL_FILE)
174        .is_some_and(|bytes| is_valid_sentinel(&bytes))
175    {
176        return done(
177            Classification::Empty,
178            Layout::None,
179            Discovery::generated_root(),
180            Vec::new(),
181        );
182    }
183
184    match manifest {
185        _ if consumer_tree => {
186            return done(
187                Classification::Schema1,
188                Layout::Convention,
189                discover(source, fallback_name),
190                Vec::new(),
191            );
192        }
193        ManifestClassification::Schema1 => {
194            return done(
195                Classification::Schema1,
196                Layout::Convention,
197                discover(source, fallback_name),
198                Vec::new(),
199            );
200        }
201        ManifestClassification::SchemaNewer { schema } => {
202            return done(
203                Classification::SchemaNewer { schema: *schema },
204                Layout::None,
205                Discovery::empty(),
206                Vec::new(),
207            );
208        }
209        ManifestClassification::Invalid { .. }
210        | ManifestClassification::NoSchema
211        | ManifestClassification::ConsumerConfig => {
212            return done(
213                Classification::Invalid,
214                Layout::None,
215                Discovery::empty(),
216                Vec::new(),
217            );
218        }
219        ManifestClassification::NoManifest => {}
220    }
221
222    if declared == Some(Dialect::MarsNative) {
223        return done(
224            Classification::Schema1,
225            Layout::Convention,
226            discover(source, fallback_name),
227            Vec::new(),
228        );
229    }
230
231    let evidence = collect_evidence(source);
232    // Hidden containers and harness manifests decide before any item is read; frontmatter
233    // evidence needs the items, which Claude's rules find for both of its dialects.
234    let decided = declared.map(DialectChoice::declared).or_else(|| {
235        evidence
236            .strongest()
237            .map(|(dialect, paths)| DialectChoice::predicted(dialect, paths))
238    });
239    let also_found = |chosen: Dialect| evidence.mirrors(chosen, source);
240
241    if decided
242        .as_ref()
243        .is_none_or(|choice| matches!(choice.dialect, Dialect::Claude | Dialect::AgentSkills))
244    {
245        let (layout, manifest_diagnostics) = claude_layout(source, as_plugin);
246        let mut discovery = match &layout {
247            Layout::Claude(spec) => discover_claude(source, spec, fallback_name),
248            _ => Discovery::empty(),
249        };
250        for (path, diagnostic) in manifest_diagnostics {
251            discovery
252                .diagnostics
253                .entry(path)
254                .or_default()
255                .push(diagnostic);
256        }
257        if matches!(layout, Layout::None) {
258            return done(Classification::Invalid, layout, discovery, Vec::new());
259        }
260        let choice = match decided {
261            Some(choice) => choice,
262            // A Claude marketplace named this root as a plugin.
263            None if as_plugin.is_some() => DialectChoice::predicted(Dialect::Claude, Vec::new()),
264            None => predict_from_items(source, &discovery),
265        };
266        let mirrors = also_found(choice.dialect);
267        let has_items = !discovery.definitions.is_empty()
268            || !discovery.dropped.is_empty()
269            || matches!(layout, Layout::Marketplace(_));
270        let bare_tree = matches!(&layout, Layout::Claude(spec) if spec.is_bare_tree());
271        if !has_items && choice.evidence.paths.is_empty() && bare_tree {
272            return done(Classification::Empty, Layout::None, discovery, mirrors);
273        }
274        let classification = if matches!(layout, Layout::Marketplace(_)) {
275            Classification::Marketplace
276        } else {
277            Classification::Foreign(choice)
278        };
279        return done(classification, layout, discovery, mirrors);
280    }
281
282    let choice = decided.expect("a non-Claude dialect was decided");
283    let discovery = discover(source, fallback_name);
284    let mirrors = also_found(choice.dialect);
285    if discovery.definitions.is_empty() && choice.evidence.paths.is_empty() {
286        return done(Classification::Empty, Layout::None, discovery, mirrors);
287    }
288    done(
289        Classification::Foreign(choice),
290        Layout::Convention,
291        discovery,
292        mirrors,
293    )
294}
295
296/// Marketplace, plugin or bare tree, from the manifests in the root. A manifest that does not
297/// parse makes the root invalid.
298fn claude_layout(
299    source: &impl TreeSource,
300    as_plugin: Option<AsPlugin<'_>>,
301) -> (Layout, Vec<(String, SchemaDiagnostic)>) {
302    let mut diagnostics = Vec::new();
303    let invalid = |diagnostic: SchemaDiagnostic, path: &str| {
304        (Layout::None, vec![(path.to_owned(), diagnostic)])
305    };
306    if let Some(plugin) = as_plugin
307        && !is_plugin_name(&plugin.entry.name)
308    {
309        return invalid(
310            SchemaDiagnostic::new(
311                "marketplace.plugin-name-invalid",
312                Severity::Error,
313                Vec::new(),
314                format!(
315                    "plugin name `{}` is not usable ({PLUGIN_NAME_RULE})",
316                    plugin.entry.name
317                ),
318            ),
319            MARKETPLACE_MANIFEST,
320        );
321    }
322    if as_plugin.is_none()
323        && let Some(bytes) = source.read(MARKETPLACE_MANIFEST)
324    {
325        return match Marketplace::parse(&bytes, &mut diagnostics) {
326            Ok(marketplace) => (Layout::Marketplace(marketplace), diagnostics),
327            Err(diagnostic) => invalid(diagnostic, MARKETPLACE_MANIFEST),
328        };
329    }
330    let manifest = match source.read(PLUGIN_MANIFEST) {
331        Some(bytes) => match PluginManifest::parse(&bytes, &mut diagnostics) {
332            Ok(manifest) => Some(manifest),
333            Err(diagnostic) => return invalid(diagnostic, PLUGIN_MANIFEST),
334        },
335        None => None,
336    };
337    if manifest.is_none() && as_plugin.is_none() {
338        return (Layout::Claude(PluginSpec::walk()), diagnostics);
339    }
340    match resolve_spec(
341        manifest.as_ref(),
342        as_plugin.map(|plugin| plugin.entry),
343        as_plugin.is_some_and(|plugin| plugin.at_marketplace_root),
344    ) {
345        Ok(spec) => (Layout::Claude(spec), diagnostics),
346        Err(message) => invalid(
347            SchemaDiagnostic::new(
348                "plugin.conflicting-manifests",
349                Severity::Error,
350                Vec::new(),
351                message,
352            ),
353            PLUGIN_MANIFEST,
354        ),
355    }
356}
357
358/// No manifest or container decided: the discovered files do, strongest first. A Claude-only key
359/// on an Agent predicts Claude; an Agent written the way only OpenCode writes one predicts
360/// OpenCode; a Claude-only key on a skill predicts Claude; skills with only the standard's keys
361/// are `agent-skills`; anything else is Claude, Mars's default.
362fn predict_from_items(source: &impl TreeSource, discovery: &Discovery) -> DialectChoice {
363    let (mut claude_agents, mut claude_skills) = (Vec::new(), Vec::new());
364    let mut opencode_paths = Vec::new();
365    let mut standard_only = true;
366    let mut skills = 0;
367    for definition in &discovery.definitions {
368        if definition.kind == DefinitionKind::Agent {
369            standard_only = false;
370        } else {
371            skills += 1;
372        }
373        let Some(frontmatter) = source
374            .read(&definition.source_path)
375            .and_then(|bytes| String::from_utf8(bytes).ok())
376            .and_then(|text| crate::frontmatter::Frontmatter::parse(&text).ok())
377        else {
378            continue;
379        };
380        let keys = frontmatter.keys();
381        if keys
382            .iter()
383            .any(|key| crate::claude::translate::EVIDENCE_KEYS.contains(&key.as_str()))
384        {
385            match definition.kind {
386                DefinitionKind::Agent => claude_agents.push(definition.source_path.clone()),
387                DefinitionKind::Skill => claude_skills.push(definition.source_path.clone()),
388            }
389        }
390        if definition.kind == DefinitionKind::Agent && crate::lift::is_opencode_agent(&frontmatter)
391        {
392            opencode_paths.push(definition.source_path.clone());
393        }
394        if definition.kind == DefinitionKind::Skill
395            && keys
396                .iter()
397                .any(|key| !STANDARD_SKILL_KEYS.contains(&key.as_str()))
398        {
399            standard_only = false;
400        }
401    }
402    // An Agent decides what a skill cannot: Claude skills are everywhere, so a Claude-only
403    // skill key does not outweigh an Agent written the way only OpenCode writes one.
404    if !claude_agents.is_empty() {
405        claude_agents.extend(claude_skills);
406        claude_agents.truncate(5);
407        DialectChoice::predicted(Dialect::Claude, claude_agents)
408    } else if !opencode_paths.is_empty() {
409        opencode_paths.truncate(5);
410        DialectChoice::predicted(Dialect::OpenCode, opencode_paths)
411    } else if !claude_skills.is_empty() {
412        claude_skills.truncate(5);
413        DialectChoice::predicted(Dialect::Claude, claude_skills)
414    } else if skills > 0 && standard_only {
415        DialectChoice::predicted(Dialect::AgentSkills, Vec::new())
416    } else {
417        DialectChoice::predicted(Dialect::Claude, Vec::new())
418    }
419}
420
421/// Files that vouch for a dialect, found in the root only.
422#[derive(Default)]
423struct Evidence(BTreeMap<Dialect, Vec<String>>);
424
425/// Strongest first. A Claude plugin root outranks a Cursor or Codex mirror of it.
426const STRENGTH: &[Dialect] = &[
427    Dialect::Claude,
428    Dialect::Cursor,
429    Dialect::Codex,
430    Dialect::OpenCode,
431];
432
433fn collect_evidence(source: &impl TreeSource) -> Evidence {
434    let mut evidence = Evidence::default();
435    let mut add = |dialect, path: String| evidence.0.entry(dialect).or_default().push(path);
436    for path in [PLUGIN_MANIFEST, MARKETPLACE_MANIFEST] {
437        if source.is_file(path) {
438            add(Dialect::Claude, path.to_owned());
439        }
440    }
441    for (container, dialect) in [
442        (".claude", Dialect::Claude),
443        (".cursor", Dialect::Cursor),
444        (".codex", Dialect::Codex),
445        (".opencode", Dialect::OpenCode),
446    ] {
447        for kind in ["skills", "agents"] {
448            let path = format!("{container}/{kind}");
449            if source.is_dir(&path) && !source.children(&path).is_empty() {
450                add(dialect, path);
451                break;
452            }
453        }
454    }
455    if source.is_dir(".cursor-plugin") {
456        add(Dialect::Cursor, ".cursor-plugin".to_owned());
457    }
458    for rules in [".cursor/rules", "rules"] {
459        if let Some(rule) = source
460            .children(rules)
461            .into_iter()
462            .find(|path| path.ends_with(".mdc"))
463        {
464            add(Dialect::Cursor, rule);
465        }
466    }
467    if source.is_dir(".codex-plugin") {
468        add(Dialect::Codex, ".codex-plugin".to_owned());
469    }
470    evidence
471}
472
473impl Evidence {
474    fn strongest(&self) -> Option<(Dialect, Vec<String>)> {
475        STRENGTH
476            .iter()
477            .find_map(|dialect| Some((*dialect, self.0.get(dialect)?.clone())))
478    }
479
480    /// Everything found for a dialect other than the one read, plus the weak Codex sidecar.
481    fn mirrors(&self, chosen: Dialect, source: &impl TreeSource) -> Vec<Mirror> {
482        let mut mirrors = STRENGTH
483            .iter()
484            .filter(|dialect| **dialect != chosen)
485            .filter_map(|dialect| {
486                Some(Mirror {
487                    dialect: *dialect,
488                    paths: self.0.get(dialect)?.clone(),
489                    weak: false,
490                })
491            })
492            .collect::<Vec<_>>();
493        if chosen != Dialect::Codex {
494            let sidecars = openai_sidecars(source);
495            if !sidecars.is_empty() {
496                mirrors.push(Mirror {
497                    dialect: Dialect::Codex,
498                    paths: sidecars,
499                    weak: true,
500                });
501            }
502        }
503        mirrors
504    }
505}
506
507/// `agents/openai.yaml` beside a `SKILL.md`: a Codex sidecar, found one skill level down.
508fn openai_sidecars(source: &impl TreeSource) -> Vec<String> {
509    let mut found = BTreeSet::new();
510    let mut check = |dir: &str| {
511        let path = format!("{dir}/agents/openai.yaml");
512        if source.is_dir(dir) && source.is_file(&format!("{dir}/SKILL.md")) && source.is_file(&path)
513        {
514            found.insert(path);
515        }
516    };
517    for group in source.children("skills") {
518        check(&group);
519        for child in source.children(&group) {
520            check(&child);
521        }
522    }
523    found.into_iter().take(5).collect()
524}