Skip to main content

mars_schema/
normalize.rs

1//! `normalize`: turn a selection of a repository into schema v1 packages.
2//!
3//! Each package is the [`Prepared`] value that `prepare` returns for one root, with the root
4//! read under Claude's rules (relocated, translated), a generated `mars.toml`, and provenance.
5//! A Mars package is the identity case: its own manifest, its own paths.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10
11use crate::claude::manifest::{
12    MARKETPLACE_MANIFEST, MarketplaceEntry, PLUGIN_MANIFEST, PluginSource,
13};
14use crate::diagnostic::{SchemaDiagnostic, Severity};
15use crate::dialect::Dialect;
16use crate::discover::enclosing_generated_dir;
17use crate::dispatch::{AsPlugin, Layout};
18use crate::inspect::{Hint, Kind};
19use crate::prepare::{
20    ChangeRecord, Classification, PrepareContext, Prepared, PreparedManifest, RootOptions, Rooted,
21    prepare_root,
22};
23use crate::tree::{SubTree, TreeSource};
24
25/// Where a tree came from; names and provenance are derived from it.
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct SourceInfo {
29    /// The repository's name, used when nothing in the package names it.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub name: Option<String>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub url: Option<String>,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub requested_ref: Option<String>,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub resolved_commit: Option<String>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub subpath: Option<String>,
40}
41
42/// What the caller chose from an inspection. An absent choice takes everything found.
43#[derive(Debug, Clone, Default, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct Selection {
46    /// Marketplace plugin names.
47    #[serde(default)]
48    pub plugins: Option<Vec<String>>,
49    /// Definition source paths by plugin name; the key `""` is a root that is not a
50    /// marketplace plugin.
51    #[serde(default)]
52    pub items: BTreeMap<String, Vec<String>>,
53}
54
55pub struct NormalizeRequest<'a, T: TreeSource> {
56    pub tree: &'a T,
57    pub source: SourceInfo,
58    pub hint: Hint,
59    pub selection: Selection,
60}
61
62#[derive(Debug, Clone, Serialize)]
63pub struct Normalized {
64    pub kind: Kind,
65    pub packages: Vec<NormalizedPackage>,
66    /// Marketplace-level findings and the reasons a package was left out, by path.
67    pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
68}
69
70impl Normalized {
71    /// Add each package's link verdict ([`crate::links::package`]). Normalizing leaves it out
72    /// because the binary judges a dependency's links against what the consumer installs; the
73    /// WASM export, which has no consumer, adds it.
74    pub fn report_links(&mut self) {
75        for package in &mut self.packages {
76            crate::links::package(&mut package.prepared);
77        }
78    }
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct NormalizedPackage {
83    /// The plugin name for a marketplace plugin, else the package name.
84    pub id: String,
85    pub provenance: Provenance,
86    pub prepared: Prepared,
87}
88
89#[derive(Debug, Clone, Serialize)]
90pub struct Provenance {
91    /// The version of the rules that produced these files.
92    pub translator: &'static str,
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub dialect: Option<Dialect>,
95    pub source: SourceInfo,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub marketplace: Option<MarketplaceProvenance>,
98    /// The definition source paths imported.
99    pub selected_items: Vec<String>,
100}
101
102#[derive(Debug, Clone, Serialize)]
103pub struct MarketplaceProvenance {
104    pub plugin: String,
105    pub plugin_source: PluginSource,
106}
107
108pub fn normalize<T: TreeSource>(request: &NormalizeRequest<'_, T>) -> Normalized {
109    match request
110        .hint
111        .subpath
112        .as_deref()
113        .filter(|path| !path.is_empty())
114    {
115        Some(subpath) => normalize_root(&SubTree::new(request.tree, subpath), request),
116        None => normalize_root(request.tree, request),
117    }
118}
119
120fn item_set(selection: &Selection, plugin: &str) -> Option<BTreeSet<String>> {
121    selection
122        .items
123        .get(plugin)
124        .map(|paths| paths.iter().cloned().collect())
125}
126
127/// Where a package sits in a marketplace, when it does.
128struct Origin<'a> {
129    entry: &'a MarketplaceEntry,
130}
131
132/// A repository that names plugins but is no plugin itself. A remote plugin source must not be
133/// one: its plugins would be a second marketplace the dependency never chose from.
134fn is_nested_marketplace(tree: &impl TreeSource) -> bool {
135    tree.is_file(MARKETPLACE_MANIFEST) && !tree.is_file(PLUGIN_MANIFEST)
136}
137
138const NESTED_MARKETPLACE: &str = "is itself a marketplace, which cannot be imported as a plugin";
139
140fn normalize_root<T: TreeSource>(
141    root: &impl TreeSource,
142    request: &NormalizeRequest<'_, T>,
143) -> Normalized {
144    let hint_plugin = request.hint.plugin.as_ref();
145    if let Some(plugin) = hint_plugin
146        && matches!(plugin.entry.source, PluginSource::Remote { .. })
147        && is_nested_marketplace(root)
148    {
149        return Normalized {
150            kind: Kind::Marketplace,
151            packages: Vec::new(),
152            diagnostics: BTreeMap::from([(
153                MARKETPLACE_MANIFEST.to_owned(),
154                vec![SchemaDiagnostic::new(
155                    "marketplace.nested-marketplace",
156                    Severity::Error,
157                    Vec::new(),
158                    format!("plugin `{}` {NESTED_MARKETPLACE}", plugin.entry.name),
159                )],
160            )]),
161        };
162    }
163    let items = item_set(&request.selection, "");
164    let rooted = prepare_root(
165        root,
166        PrepareContext::Package,
167        request.hint.dialect,
168        RootOptions {
169            as_plugin: hint_plugin.map(|plugin| AsPlugin {
170                entry: &plugin.entry,
171                at_marketplace_root: plugin.at_marketplace_root,
172            }),
173            selection: items.as_ref(),
174            fallback_name: request.source.name.as_deref(),
175        },
176    );
177    let mut normalized = Normalized {
178        kind: rooted.dispatched.kind(),
179        packages: Vec::new(),
180        diagnostics: BTreeMap::new(),
181    };
182    if let Layout::Marketplace(marketplace) = &rooted.dispatched.layout {
183        normalized.diagnostics = rooted.prepared.diagnostics.clone();
184        for entry in &marketplace.plugins {
185            let named = request
186                .selection
187                .plugins
188                .as_ref()
189                .map(|names| names.contains(&entry.name));
190            if named != Some(false) {
191                normalize_plugin(root, request, entry, named == Some(true), &mut normalized);
192            }
193        }
194        return normalized;
195    }
196    let origin = hint_plugin.map(|plugin| Origin {
197        entry: &plugin.entry,
198    });
199    finish_package(rooted, request, origin, &mut normalized);
200    normalized
201}
202
203fn normalize_plugin<T: TreeSource>(
204    marketplace_root: &impl TreeSource,
205    request: &NormalizeRequest<'_, T>,
206    entry: &MarketplaceEntry,
207    named: bool,
208    normalized: &mut Normalized,
209) {
210    // A plugin the caller asked for by name must work; one taken along with all of them need not.
211    let severity = if named {
212        Severity::Error
213    } else {
214        Severity::Warning
215    };
216    let mut report = |severity, code: &str, message: String| {
217        normalized
218            .diagnostics
219            .entry(MARKETPLACE_MANIFEST.to_owned())
220            .or_default()
221            .push(SchemaDiagnostic::new(
222                code,
223                severity,
224                Vec::new(),
225                format!("plugin `{}`: {message}", entry.name),
226            ));
227    };
228    let items = item_set(&request.selection, &entry.name);
229    let options = |at_marketplace_root| RootOptions {
230        as_plugin: Some(AsPlugin {
231            entry,
232            at_marketplace_root,
233        }),
234        selection: items.as_ref(),
235        fallback_name: Some(&entry.name),
236    };
237    let rooted = match &entry.source {
238        PluginSource::Unsupported { reason } => {
239            report(
240                severity,
241                "marketplace.plugin-unsupported",
242                format!("can't import from this source: {reason}"),
243            );
244            return;
245        }
246        PluginSource::Local { path } => {
247            if let Some(generated) = enclosing_generated_dir(marketplace_root, path) {
248                report(
249                    Severity::Warning,
250                    "marketplace.plugin-generated",
251                    format!(
252                        "`{path}` is inside `{}`, plugin output Mars built, which is never input",
253                        if generated.is_empty() {
254                            "."
255                        } else {
256                            &generated
257                        }
258                    ),
259                );
260                return;
261            }
262            if !path.is_empty() && !marketplace_root.is_dir(path) {
263                report(
264                    Severity::Error,
265                    "marketplace.plugin-missing",
266                    format!("`{path}` does not exist in the marketplace"),
267                );
268                return;
269            }
270            let root = SubTree::new(marketplace_root, path.clone());
271            prepare_root(
272                &root,
273                PrepareContext::Package,
274                request.hint.dialect,
275                options(path.is_empty()),
276            )
277        }
278        // The caller fetches it and normalizes the fetched tree with `hint.plugin` set to the
279        // entry: the one protocol for a plugin whose files are not in this tree.
280        PluginSource::Remote { .. } => {
281            report(
282                severity,
283                "marketplace.remote-not-fetched",
284                "lives in another repository: fetch it and normalize that tree with `hint.plugin`"
285                    .into(),
286            );
287            return;
288        }
289    };
290    finish_package(rooted, request, Some(Origin { entry }), normalized);
291}
292
293/// Add the package. A package-level error (two skills with one slug, conflicting manifests,
294/// an unreadable manifest) is reported on the package, which then holds nothing to write; a
295/// definition that cannot be read does not do that, because it imports unavailable with its
296/// error.
297fn finish_package<T: TreeSource>(
298    rooted: Rooted,
299    request: &NormalizeRequest<'_, T>,
300    origin: Option<Origin<'_>>,
301    normalized: &mut Normalized,
302) {
303    let Rooted {
304        mut prepared,
305        dispatched,
306    } = rooted;
307    let refused = prepared
308        .diagnostics
309        .values()
310        .flatten()
311        .any(SchemaDiagnostic::is_error);
312    if refused {
313        prepared.definitions.clear();
314        prepared.mcp_servers.clear();
315        prepared.payload.clear();
316    }
317
318    let spec = match &dispatched.layout {
319        Layout::Claude(spec) => Some(spec),
320        _ => None,
321    };
322    if prepared.manifest.is_none()
323        && !refused
324        && matches!(
325            prepared.classification,
326            Classification::Foreign(_) | Classification::Schema1
327        )
328    {
329        let name = spec
330            .and_then(|spec| spec.name.clone())
331            .or_else(|| origin.as_ref().map(|origin| origin.entry.name.clone()))
332            .unwrap_or_else(|| repository_name(request));
333        prepared.manifest = Some(generated_manifest(
334            &name,
335            spec.and_then(|spec| spec.version.as_deref()),
336            spec.and_then(|spec| spec.description.as_deref()),
337        ));
338    }
339    let manifest_name = prepared
340        .manifest
341        .as_ref()
342        .and_then(|manifest| manifest.reading.package.fields.as_ref())
343        .map(|package| package.name.clone())
344        .unwrap_or_else(|| repository_name(request));
345    let selected_items = prepared
346        .definitions
347        .iter()
348        .map(|definition| definition.source_path.clone())
349        .collect();
350    normalized.packages.push(NormalizedPackage {
351        id: origin
352            .as_ref()
353            .map_or(manifest_name, |origin| origin.entry.name.clone()),
354        provenance: Provenance {
355            translator: crate::VERSION,
356            dialect: dispatched.dialect().map(|choice| choice.dialect),
357            source: request.source.clone(),
358            marketplace: origin.as_ref().map(|origin| MarketplaceProvenance {
359                plugin: origin.entry.name.clone(),
360                plugin_source: origin.entry.source.clone(),
361            }),
362            selected_items,
363        },
364        prepared,
365    });
366}
367
368/// The repository's name, plus `/<path>` for a subpath import.
369fn repository_name<T: TreeSource>(request: &NormalizeRequest<'_, T>) -> String {
370    let base = request.source.name.as_deref().unwrap_or("package");
371    match request
372        .source
373        .subpath
374        .as_deref()
375        .or(request.hint.subpath.as_deref())
376        .filter(|path| !path.is_empty())
377    {
378        Some(subpath) => format!("{base}/{subpath}"),
379        None => base.to_owned(),
380    }
381}
382
383/// The `mars.toml` a manifest-free package is stored with.
384fn generated_manifest(
385    name: &str,
386    version: Option<&str>,
387    description: Option<&str>,
388) -> PreparedManifest {
389    use toml_edit::{DocumentMut, Item, Table, value};
390    let mut package = Table::new();
391    package.insert("schema", value(1));
392    package.insert("name", value(name));
393    if let Some(version) = version {
394        package.insert("version", value(version));
395    }
396    if let Some(description) = description {
397        package.insert("description", value(description));
398    }
399    let mut document = DocumentMut::new();
400    document.insert("package", Item::Table(package));
401    let text = document.to_string();
402    let mut reading = crate::manifest::read(&text);
403    // A package with no declared version is not a defect of the generated file.
404    reading
405        .package
406        .diagnostics
407        .retain(|diagnostic| diagnostic.code != "manifest.version-missing");
408    PreparedManifest {
409        source_path: None,
410        output_path: "mars.toml".to_owned(),
411        normalized_bytes: text.into_bytes(),
412        reading,
413        change: ChangeRecord::Generated,
414    }
415}