Skip to main content

mars_schema/
prepare.rs

1//! One-pass package classification, normalization, selection, and strict reading.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6
7use crate::diagnostic::{SchemaDiagnostic, Severity};
8use crate::dialect::{Dialect, DialectChoice};
9use crate::discover::{SelectedDefinition, payload_paths};
10use crate::dispatch::{AsPlugin, Dispatched, Layout, dispatch};
11use crate::frontmatter::{Frontmatter, FrontmatterError};
12use crate::item::DefinitionKind;
13use crate::read::{DefinitionRead, Reading, read_authored, read_definition};
14use crate::selection::{Definition, Request, SelectionFacts};
15use crate::tool_policy::{RuleOrigin, ToolRule};
16use crate::tree::TreeSource;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum PrepareContext {
21    /// A package root (a dependency, or the package being published): its `mars.toml` must
22    /// declare `[package]`, and a root with no manifest is read as the dialect it looks like.
23    Package,
24    /// A consumer's own authored directory (`.mars-src`): content without a manifest is Mars
25    /// convention, and a `mars.toml` without `[package]` is consumer configuration, not read.
26    AuthoredLocal,
27    /// A directory that is either: `Package` unless its `mars.toml` has no `[package]`, which
28    /// makes it a consumer project whose tree is read as `AuthoredLocal` content.
29    Project,
30}
31
32/// The directory below a consumer project that holds its own authored content.
33pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
34
35/// What a package root is, once its manifest, declared dialect and contents have been weighed.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
37#[serde(tag = "kind", rename_all = "kebab-case")]
38pub enum Classification {
39    #[serde(rename = "schema-1")]
40    Schema1,
41    SchemaNewer {
42        schema: u64,
43    },
44    Invalid,
45    /// Another harness's layout, read as the dialect chosen.
46    Foreign(DialectChoice),
47    /// A Claude marketplace: it lists plugins and holds no definitions of its own.
48    Marketplace,
49    Empty,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53#[serde(tag = "kind", rename_all = "kebab-case")]
54pub enum ChangeRecord {
55    None,
56    /// The file has no source: `normalize` wrote it (a package's generated `mars.toml`).
57    Generated,
58    FullyRewritten,
59}
60
61#[derive(Debug, Clone, Serialize)]
62pub struct PreparedManifest {
63    /// `None` for a generated manifest.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub source_path: Option<String>,
66    pub output_path: String,
67    /// The normalized file; crosses to JavaScript as a `Uint8Array`.
68    #[serde(with = "serde_bytes")]
69    pub normalized_bytes: Vec<u8>,
70    pub reading: crate::manifest::ManifestRead,
71    pub change: ChangeRecord,
72}
73
74#[derive(Debug, Clone, Serialize)]
75pub struct PreparedDefinition {
76    pub kind: DefinitionKind,
77    pub slug: String,
78    pub source_path: String,
79    pub output_path: String,
80    /// A skill's folder in the package tree (empty for a root skill); `None` for an agent.
81    #[serde(skip)]
82    pub skill_root: Option<String>,
83    /// The normalized file; crosses to JavaScript as a `Uint8Array`.
84    #[serde(with = "serde_bytes")]
85    pub normalized_bytes: Vec<u8>,
86    /// The Agent or skill reading `kind` names.
87    pub reading: Reading,
88    pub change: ChangeRecord,
89}
90
91/// An MCP server translated from another dialect's declaration, as the `mcp/<name>/mcp.toml` it
92/// is written to. The same shape as a definition's output so a caller writes it the same way.
93#[derive(Debug, Clone, Serialize)]
94pub struct PreparedMcpServer {
95    pub name: String,
96    /// The file that declared the server (`.mcp.json`, `plugin.json`).
97    pub source_path: String,
98    pub output_path: String,
99    /// The rendered `mcp.toml`; crosses to JavaScript as a `Uint8Array`.
100    #[serde(with = "serde_bytes")]
101    pub normalized_bytes: Vec<u8>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105pub struct PayloadEntry {
106    pub source_path: String,
107    pub output_path: String,
108}
109
110#[derive(Debug, Clone, Serialize)]
111pub struct Prepared {
112    pub classification: Classification,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub manifest: Option<PreparedManifest>,
115    pub definitions: Vec<PreparedDefinition>,
116    /// The MCP servers a foreign plugin declares, translated. Selection does not apply to them.
117    #[serde(skip_serializing_if = "Vec::is_empty")]
118    pub mcp_servers: Vec<PreparedMcpServer>,
119    pub payload: Vec<PayloadEntry>,
120    /// What item selection reads of this package (see [`selection_facts`]).
121    pub selection: SelectionFacts,
122    /// Package-level findings by source path: what discovery and translation met and could not
123    /// convert. A definition's own reading diagnostics live on its `reading` only; see
124    /// [`Prepared::all_diagnostics`].
125    pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
126    /// What translating a foreign package changed in each file, by source path: the keys it
127    /// dropped, moved or repaired. A caller reports [`Prepared::changed_files`].
128    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
129    pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
130}
131
132/// What item selection reads of a prepared package: its Agents' and skills' skill refs, and the
133/// `[dependencies]` entries and `uses-providers` its manifest reads.
134pub(crate) fn selection_facts(
135    classification: &Classification,
136    manifest: Option<&PreparedManifest>,
137    definitions: &[PreparedDefinition],
138) -> SelectionFacts {
139    let reading = manifest.map(|manifest| &manifest.reading);
140    SelectionFacts {
141        definitions: definitions
142            .iter()
143            .map(|definition| Definition {
144                kind: definition.kind,
145                slug: definition.slug.clone(),
146                output_path: definition.output_path.clone(),
147                skills: match &definition.reading {
148                    Reading::Agent(read) => read
149                        .fields
150                        .as_ref()
151                        .map(|profile| profile.skills.all())
152                        .unwrap_or_default(),
153                    _ => Vec::new(),
154                },
155            })
156            .collect(),
157        edges: reading
158            .map(|reading| {
159                reading
160                    .dependencies
161                    .dependencies
162                    .iter()
163                    .map(|(name, entry)| Request {
164                        name: name.clone(),
165                        filter: entry.filter.to_mode(),
166                    })
167                    .collect()
168            })
169            .unwrap_or_default(),
170        uses_providers: reading
171            .and_then(|reading| reading.package.fields.as_ref())
172            .map(|package| package.uses_providers.clone())
173            .unwrap_or_default(),
174        unreadable: matches!(
175            classification,
176            Classification::Invalid | Classification::SchemaNewer { .. }
177        ),
178    }
179}
180
181impl Prepared {
182    /// The changes that lost a restriction (a `deny` or `ask` tool entry, `permission`,
183    /// `sandbox`, `approval`), by source path. Unlike the rest of `changes`, a caller reports
184    /// these on every run: each leaves an agent less restricted than its file says.
185    pub fn lost_restrictions(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
186        self.changes.iter().flat_map(|(path, changes)| {
187            changes
188                .iter()
189                .filter(|change| change.code == crate::set_aside::RESTRICTION_LOST)
190                .map(move |change| (path.as_str(), change))
191        })
192    }
193
194    /// The changes that ignored a non-string `effort`, `mode` or `harness`, by source path. A
195    /// sync leaves these in the count of changed files; `mars check` prints them, because the
196    /// author of the file can fix them.
197    pub fn ignored_execution_fields(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
198        self.changes.iter().flat_map(|(path, changes)| {
199            changes
200                .iter()
201                .filter(|change| change.code == crate::set_aside::EXECUTION_IGNORED)
202                .map(move |change| (path.as_str(), change))
203        })
204    }
205
206    /// The changes that quoted a value YAML could not read as plain text, by source path. Like
207    /// [`Self::ignored_execution_fields`], `mars check` prints them for the author to fix and a
208    /// sync only counts the file.
209    pub fn repaired_values(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
210        self.changes.iter().flat_map(|(path, changes)| {
211            changes
212                .iter()
213                .filter(|change| change.code == crate::claude::translate::REPAIRED)
214                .map(move |change| (path.as_str(), change))
215        })
216    }
217
218    /// How many authored files translation changed: the prepared bytes differ from the file. A
219    /// generated `mars.toml` has no file to change and is not counted.
220    pub fn changed_files(&self) -> usize {
221        self.manifest
222            .iter()
223            .map(|manifest| &manifest.change)
224            .chain(self.definitions.iter().map(|definition| &definition.change))
225            .filter(|change| !matches!(change, ChangeRecord::None | ChangeRecord::Generated))
226            .count()
227    }
228
229    /// Every diagnostic by source path: package-level first, then the file's reading.
230    pub fn all_diagnostics(&self) -> BTreeMap<&str, Vec<&SchemaDiagnostic>> {
231        let mut all: BTreeMap<&str, Vec<&SchemaDiagnostic>> = BTreeMap::new();
232        for (path, diagnostics) in &self.diagnostics {
233            all.entry(path).or_default().extend(diagnostics);
234        }
235        if let Some(manifest) = &self.manifest
236            && let Some(path) = &manifest.source_path
237        {
238            all.entry(path)
239                .or_default()
240                .extend(&manifest.reading.package.diagnostics);
241        }
242        for definition in &self.definitions {
243            all.entry(&definition.source_path)
244                .or_default()
245                .extend(definition.reading.diagnostics());
246        }
247        all.retain(|_, diagnostics| !diagnostics.is_empty());
248        all
249    }
250}
251
252/// What a caller adds when it reads a root as one plugin of a marketplace, or imports only some
253/// of the items.
254#[derive(Default, Clone, Copy)]
255pub(crate) struct RootOptions<'a> {
256    pub as_plugin: Option<AsPlugin<'a>>,
257    /// Source paths of the definitions to import; `None` imports every one found.
258    pub selection: Option<&'a BTreeSet<String>>,
259    /// Names a root `SKILL.md` when its own `name` cannot.
260    pub fallback_name: Option<&'a str>,
261}
262
263/// `prepare` plus what was discovered, for `inspect` and `normalize`.
264pub(crate) struct Rooted {
265    pub prepared: Prepared,
266    pub dispatched: Dispatched,
267}
268
269/// Prepare one rooted package without reading payload bytes.
270pub fn prepare(
271    source: &impl TreeSource,
272    context: PrepareContext,
273    declared_dialect: Option<Dialect>,
274) -> Prepared {
275    prepare_root(source, context, declared_dialect, RootOptions::default()).prepared
276}
277
278pub(crate) fn prepare_root(
279    source: &impl TreeSource,
280    context: PrepareContext,
281    declared_dialect: Option<Dialect>,
282    options: RootOptions<'_>,
283) -> Rooted {
284    let mut dispatched = dispatch(
285        source,
286        context,
287        declared_dialect,
288        options.as_plugin,
289        options.fallback_name,
290    );
291    let classification = dispatched.classification.clone();
292    let manifest_bytes = dispatched.manifest.take();
293    let mut diagnostics = std::mem::take(&mut dispatched.discovery.diagnostics);
294    let mut changes = BTreeMap::new();
295
296    let mut manifest = manifest_bytes.as_deref().map(prepare_manifest);
297
298    let can_read_definitions = !matches!(
299        classification,
300        Classification::Invalid
301            | Classification::SchemaNewer { .. }
302            | Classification::Empty
303            | Classification::Marketplace
304    );
305    let all = &dispatched.discovery.definitions;
306    let selected = all
307        .iter()
308        .filter(|definition| {
309            options
310                .selection
311                .is_none_or(|selection| selection.contains(&definition.source_path))
312        })
313        .collect::<Vec<_>>();
314    let authored = matches!(classification, Classification::Schema1);
315    let definitions = if can_read_definitions {
316        selected
317            .iter()
318            .map(|definition| {
319                let mut prepared = prepare_definition(
320                    source,
321                    definition,
322                    &classification,
323                    authored,
324                    &mut diagnostics,
325                    &mut changes,
326                );
327                if let Some(manifest) = &manifest {
328                    add_package_tools(&mut prepared, &manifest.reading);
329                }
330                prepared
331            })
332            .collect::<Vec<_>>()
333    } else {
334        Vec::new()
335    };
336    let payload = if can_read_definitions {
337        payload_paths(
338            source,
339            &dispatched.discovery,
340            matches!(classification, Classification::Foreign(_)),
341            selected.iter().copied(),
342            &mut diagnostics,
343        )
344        .into_iter()
345        .map(|(source_path, output_path)| PayloadEntry {
346            source_path,
347            output_path,
348        })
349        .collect()
350    } else {
351        Vec::new()
352    };
353
354    let mut mcp_servers = Vec::new();
355    if can_read_definitions {
356        report_unconverted(source, &dispatched, &mut diagnostics);
357        // A bare skill tree's `.mcp.json` is usually its contributors' own, not a plugin's.
358        if let Layout::Claude(spec) = &dispatched.layout
359            && !spec.is_bare_tree()
360        {
361            let imported = crate::claude::mcp::import(source, spec);
362            for (path, diagnostic) in imported.diagnostics {
363                push(&mut diagnostics, &path, diagnostic);
364            }
365            mcp_servers = imported
366                .servers
367                .into_iter()
368                .map(|server| PreparedMcpServer {
369                    output_path: format!("mcp/{}/mcp.toml", server.name),
370                    normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
371                    name: server.name,
372                    source_path: server.source_path,
373                })
374                .collect();
375        }
376    }
377    diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
378    changes.retain(|_, diagnostics| !diagnostics.is_empty());
379    let manifest = manifest.take();
380    let prepared = Prepared {
381        selection: selection_facts(&classification, manifest.as_ref(), &definitions),
382        classification,
383        manifest,
384        definitions,
385        mcp_servers,
386        payload,
387        diagnostics,
388        changes,
389    };
390    Rooted {
391        prepared,
392        dispatched,
393    }
394}
395
396/// Add the package's `[package.tools]` rules to an Agent's reading, as `mars sync` writes them
397/// into the installed file (`package_tools::missing`). `normalized_bytes` stay the file's: the
398/// rules belong to the package, not to the authored profile.
399fn add_package_tools(
400    definition: &mut PreparedDefinition,
401    manifest: &crate::manifest::ManifestRead,
402) {
403    let Reading::Agent(read) = &mut definition.reading else {
404        return;
405    };
406    // `mars sync` refuses a manifest with any error and installs none of its Agents, so an
407    // Agent read beside one carries the failure instead of reading clean without the rules.
408    if let Some(error) = manifest.first_error() {
409        read.diagnostics.push(SchemaDiagnostic::new(
410            "package-tools.unreadable",
411            Severity::Error,
412            Vec::new(),
413            format!(
414                "the package's mars.toml has an error, so its `[package.tools]` rules cannot be added and `mars sync` refuses the package: {}",
415                error.message
416            ),
417        ));
418        return;
419    }
420    let (Some(package), Some(fields)) = (
421        manifest
422            .package
423            .fields
424            .as_ref()
425            .map(|package| &package.tools),
426        read.fields.as_mut(),
427    ) else {
428        return;
429    };
430    // The reading's own `frontmatter` is ordered JSON; the shared rule reads the YAML mapping.
431    let Some(profile) = std::str::from_utf8(&definition.normalized_bytes)
432        .ok()
433        .and_then(|text| Frontmatter::parse(text).ok())
434    else {
435        return;
436    };
437    for (name, action) in crate::package_tools::missing(&profile, package) {
438        fields.tools.push_unique(
439            ToolRule::from_parsed(name.parsed().clone(), action).with_origin(RuleOrigin::Package),
440        );
441    }
442}
443
444/// Commands are dropped and hooks are not converted yet. MCP servers are translated, not
445/// reported here (`claude::mcp`).
446fn report_unconverted(
447    source: &impl TreeSource,
448    dispatched: &Dispatched,
449    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
450) {
451    let Layout::Claude(spec) = &dispatched.layout else {
452        return;
453    };
454    let mut warn = |path: &str, code: &str, message: String| {
455        diagnostics
456            .entry(path.to_owned())
457            .or_default()
458            .push(SchemaDiagnostic::new(
459                code,
460                Severity::Warning,
461                Vec::new(),
462                message,
463            ));
464    };
465    if !dispatched.discovery.dropped.is_empty() {
466        warn(
467            "commands",
468            "import.commands-dropped",
469            format!(
470                "commands are not imported (convert one to a skill): {}",
471                dispatched
472                    .discovery
473                    .dropped
474                    .iter()
475                    .map(|command| command.source_path.as_str())
476                    .collect::<Vec<_>>()
477                    .join(", ")
478            ),
479        );
480    }
481    if spec.is_bare_tree() && source.is_file(".mcp.json") {
482        warn(
483            ".mcp.json",
484            "import.mcp-not-imported",
485            "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
486        );
487    }
488    if source.is_file("hooks/hooks.json") || spec.hooks {
489        let path = if source.is_file("hooks/hooks.json") {
490            "hooks/hooks.json"
491        } else {
492            crate::claude::manifest::PLUGIN_MANIFEST
493        };
494        warn(
495            path,
496            "import.hooks-not-converted",
497            "hooks are not converted yet".into(),
498        );
499    }
500}
501
502pub(crate) fn prepare_manifest(bytes: &[u8]) -> PreparedManifest {
503    let reading = match std::str::from_utf8(bytes) {
504        Ok(text) => crate::manifest::read(text),
505        Err(error) => crate::manifest::ManifestRead::unread(vec![SchemaDiagnostic::new(
506            "text.invalid-utf8",
507            Severity::Error,
508            Vec::new(),
509            format!("mars.toml is not UTF-8: {error}"),
510        )]),
511    };
512    PreparedManifest {
513        source_path: Some("mars.toml".to_string()),
514        output_path: "mars.toml".to_string(),
515        normalized_bytes: bytes.to_vec(),
516        reading,
517        change: ChangeRecord::None,
518    }
519}
520
521fn prepare_definition(
522    source: &impl TreeSource,
523    selected: &SelectedDefinition,
524    classification: &Classification,
525    authored: bool,
526    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
527    changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
528) -> PreparedDefinition {
529    let Some(bytes) = source.read(&selected.source_path) else {
530        return PreparedDefinition {
531            kind: selected.kind,
532            slug: selected.slug.clone(),
533            source_path: selected.source_path.clone(),
534            output_path: selected.output_path.clone(),
535            skill_root: selected.skill_root.clone(),
536            normalized_bytes: Vec::new(),
537            reading: unreadable(
538                selected.kind,
539                SchemaDiagnostic::new(
540                    "definition.read-missing",
541                    Severity::Error,
542                    Vec::new(),
543                    "selected definition could not be read",
544                ),
545            ),
546            change: ChangeRecord::None,
547        };
548    };
549    let (mut notes, mut findings) = (Vec::new(), Vec::new());
550    let (normalized_bytes, change) = match (std::str::from_utf8(&bytes), classification) {
551        (Ok(text), Classification::Foreign(choice)) => {
552            let translated = translate_foreign(text, choice.dialect, selected, &bytes);
553            notes = translated.changes;
554            findings = translated.findings;
555            (translated.bytes, translated.change)
556        }
557        _ => (bytes.clone(), ChangeRecord::None),
558    };
559    changes
560        .entry(selected.source_path.clone())
561        .or_default()
562        .extend(notes);
563    diagnostics
564        .entry(selected.source_path.clone())
565        .or_default()
566        .extend(findings);
567
568    // Only text is translated, so these bytes are the file's when they are not text.
569    let reading = match std::str::from_utf8(&normalized_bytes) {
570        Ok(text) if authored => read_authored(selected.kind, text),
571        Ok(text) => read_definition(selected.kind, text),
572        Err(error) => unreadable(
573            selected.kind,
574            SchemaDiagnostic::new(
575                "text.invalid-utf8",
576                Severity::Error,
577                Vec::new(),
578                format!("definition is not UTF-8: {error}"),
579            ),
580        ),
581    };
582
583    PreparedDefinition {
584        kind: selected.kind,
585        slug: selected.slug.clone(),
586        source_path: selected.source_path.clone(),
587        output_path: selected.output_path.clone(),
588        skill_root: selected.skill_root.clone(),
589        normalized_bytes,
590        reading,
591        change,
592    }
593}
594
595/// What translating one foreign definition produced.
596struct Translated {
597    bytes: Vec<u8>,
598    change: ChangeRecord,
599    /// What the translation dropped, moved or repaired.
600    changes: Vec<SchemaDiagnostic>,
601    /// What it met and could not convert.
602    findings: Vec<SchemaDiagnostic>,
603}
604
605impl Translated {
606    fn untouched(bytes: &[u8]) -> Self {
607        Self {
608            bytes: bytes.to_vec(),
609            change: ChangeRecord::None,
610            changes: Vec::new(),
611            findings: Vec::new(),
612        }
613    }
614}
615
616/// Lift a foreign definition's frontmatter into schema v1. Frontmatter that cannot be read
617/// stays as written, with the reader's error; a Claude definition's unquoted values that YAML
618/// cannot read are quoted first.
619fn translate_foreign(
620    text: &str,
621    dialect: Dialect,
622    selected: &SelectedDefinition,
623    bytes: &[u8],
624) -> Translated {
625    let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
626    let mut changes = Vec::new();
627    let mut repaired = false;
628    let frontmatter = match Frontmatter::parse(text) {
629        Ok(frontmatter) => frontmatter,
630        Err(FrontmatterError::MalformedYaml(_)) if claude => {
631            match crate::claude::translate::repair_plain_values(text)
632                .and_then(|(fixed, keys)| Some((Frontmatter::parse(&fixed).ok()?, keys)))
633            {
634                Some((frontmatter, keys)) => {
635                    repaired = true;
636                    changes.push(crate::claude::translate::repaired_diagnostic(&keys));
637                    frontmatter
638                }
639                None => return Translated::untouched(bytes),
640            }
641        }
642        Err(_) => return Translated::untouched(bytes),
643    };
644    let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
645    changes.extend(lifted.changes);
646    let mut findings = lifted.findings;
647    if claude && selected.kind == DefinitionKind::Skill {
648        findings.extend(crate::claude::checks::skill_checks(&lifted.frontmatter));
649    }
650    let (bytes, change) = if lifted.changed || repaired {
651        (
652            lifted.frontmatter.render().into_bytes(),
653            ChangeRecord::FullyRewritten,
654        )
655    } else {
656        (bytes.to_vec(), ChangeRecord::None)
657    };
658    Translated {
659        bytes,
660        change,
661        changes,
662        findings,
663    }
664}
665
666/// A definition with no fields to read, only why.
667fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
668    match kind {
669        DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
670        DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
671    }
672}
673
674fn push(
675    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
676    path: &str,
677    diagnostic: SchemaDiagnostic,
678) {
679    diagnostics
680        .entry(path.to_owned())
681        .or_default()
682        .push(diagnostic);
683}