Skip to main content

mars_schema/
inspect.rs

1//! `inspect`: what is in a repository, before anything is selected or converted.
2//!
3//! Pure over a file tree. Reads manifests, listings and the first lines of definitions, never
4//! payload bytes. A marketplace lists its plugins; a plugin it points at in another
5//! repository is fetched by the caller and inspected on its own, with the entry as the hint.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11use crate::claude::manifest::{MarketplaceEntry, PluginSource};
12use crate::diagnostic::SchemaDiagnostic;
13use crate::dialect::{Dialect, DialectChoice};
14use crate::discover::{enclosing_generated_dir, payload_paths};
15use crate::dispatch::{AsPlugin, Dispatched, Layout, dispatch};
16pub use crate::dispatch::{Kind, Mirror};
17use crate::item::DefinitionKind;
18use crate::prepare::{Classification, PrepareContext};
19use crate::tree::{SubTree, TreeSource};
20
21/// What the caller declares about a root; everything is optional.
22#[derive(Debug, Clone, Default, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct Hint {
25    /// Overrides prediction, never a Mars manifest.
26    #[serde(default)]
27    pub dialect: Option<Dialect>,
28    /// The package root inside the tree.
29    #[serde(default)]
30    pub subpath: Option<String>,
31    /// Read the root as this plugin of a marketplace (a fetched remote plugin tree).
32    #[serde(default)]
33    pub plugin: Option<PluginHint>,
34}
35
36#[derive(Debug, Clone, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct PluginHint {
39    pub entry: MarketplaceEntry,
40    /// Whether the entry's source is the marketplace root, which narrows the default skills.
41    #[serde(default)]
42    pub at_marketplace_root: bool,
43}
44
45#[derive(Debug, Clone, Serialize)]
46pub struct Inspection {
47    pub kind: Kind,
48    /// The dialect read, with how it was chosen and the files that decided it.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub dialect: Option<DialectChoice>,
51    /// Other harnesses' copies of the package, found and not read.
52    pub also_found: Vec<Mirror>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub name: Option<String>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub version: Option<String>,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub description: Option<String>,
59    /// A marketplace's plugins.
60    pub plugins: Vec<InspectedPlugin>,
61    /// The items of a plugin or skill tree.
62    pub items: Vec<InspectedItem>,
63    pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
64}
65
66#[derive(Debug, Clone, Serialize)]
67pub struct InspectedPlugin {
68    pub entry: MarketplaceEntry,
69    pub at_marketplace_root: bool,
70    /// The items of a plugin in the marketplace's own tree. A remote plugin has none until the
71    /// caller fetches it and inspects the tree.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub items: Option<Vec<InspectedItem>>,
74    /// Why the plugin cannot be imported at all.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub refused: Option<String>,
77    pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
81#[serde(rename_all = "lowercase")]
82pub enum InspectedKind {
83    Skill,
84    Agent,
85    /// Reported and not imported.
86    Command,
87}
88
89impl From<DefinitionKind> for InspectedKind {
90    fn from(kind: DefinitionKind) -> Self {
91        match kind {
92            DefinitionKind::Skill => Self::Skill,
93            DefinitionKind::Agent => Self::Agent,
94        }
95    }
96}
97
98#[derive(Debug, Clone, Serialize)]
99pub struct InspectedItem {
100    pub kind: InspectedKind,
101    pub slug: String,
102    /// The definition file (`…/SKILL.md`, `agents/x.md`, `commands/x.md`).
103    pub source_path: String,
104    /// The skill's directory, whose files travel with it.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub skill_root: Option<String>,
107    /// Where the definition lands in schema v1; commands have none.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub output_path: Option<String>,
110    /// A skill's payload files, by source path.
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub payload: Vec<String>,
113}
114
115pub fn inspect(source: &impl TreeSource, hint: &Hint) -> Inspection {
116    match hint.subpath.as_deref().filter(|path| !path.is_empty()) {
117        Some(subpath) => inspect_root(&SubTree::new(source, subpath), hint),
118        None => inspect_root(source, hint),
119    }
120}
121
122/// What a root is and the plugins it lists, with no plugin's files read: the resolver reads a
123/// marketplace this way, then [`inspect_listed_plugin`] for the one it chose, so importing one
124/// plugin of a large marketplace costs that plugin.
125pub struct Listing {
126    pub kind: Kind,
127    pub entries: Vec<MarketplaceEntry>,
128}
129
130pub fn list_marketplace(source: &impl TreeSource) -> Listing {
131    let dispatched = dispatch(source, PrepareContext::Package, None, None, None);
132    let kind = dispatched.kind();
133    let entries = match dispatched.layout {
134        Layout::Marketplace(marketplace) => marketplace.plugins,
135        _ => Vec::new(),
136    };
137    Listing { kind, entries }
138}
139
140/// One listed plugin, as [`inspect`] reports it.
141pub fn inspect_listed_plugin(
142    source: &impl TreeSource,
143    entry: &MarketplaceEntry,
144) -> InspectedPlugin {
145    inspect_plugin(source, None, entry)
146}
147
148fn inspect_root(source: &impl TreeSource, hint: &Hint) -> Inspection {
149    let dispatched = dispatch(
150        source,
151        PrepareContext::Package,
152        hint.dialect,
153        hint.plugin.as_ref().map(as_plugin),
154        None,
155    );
156    describe(source, hint.dialect, dispatched)
157}
158
159fn as_plugin(hint: &PluginHint) -> AsPlugin<'_> {
160    AsPlugin {
161        entry: &hint.entry,
162        at_marketplace_root: hint.at_marketplace_root,
163    }
164}
165
166fn describe(
167    source: &impl TreeSource,
168    declared: Option<Dialect>,
169    dispatched: Dispatched,
170) -> Inspection {
171    let mut diagnostics = dispatched.discovery.diagnostics.clone();
172    // An invalid root is invalid because of its manifest; say how.
173    if dispatched.kind() == Kind::Invalid
174        && let Some(bytes) = &dispatched.manifest
175    {
176        let found = crate::prepare::prepare_manifest(bytes)
177            .reading
178            .package
179            .diagnostics;
180        diagnostics
181            .entry("mars.toml".to_string())
182            .or_default()
183            .extend(found);
184    }
185    let items = list_items(source, &dispatched, &mut diagnostics);
186    let (name, version, description) = match &dispatched.layout {
187        Layout::Claude(spec) => (
188            spec.name.clone(),
189            spec.version.clone(),
190            spec.description.clone(),
191        ),
192        _ => (None, None, None),
193    };
194    let plugins = match &dispatched.layout {
195        Layout::Marketplace(marketplace) => marketplace
196            .plugins
197            .iter()
198            .map(|entry| inspect_plugin(source, declared, entry))
199            .collect(),
200        _ => Vec::new(),
201    };
202    Inspection {
203        kind: dispatched.kind(),
204        dialect: dispatched.dialect().cloned(),
205        also_found: dispatched.also_found,
206        name,
207        version,
208        description,
209        plugins,
210        items,
211        diagnostics,
212    }
213}
214
215/// A marketplace plugin: refused when its source cannot be imported, listed with its items
216/// when it lives in the marketplace's own tree.
217fn inspect_plugin(
218    source: &impl TreeSource,
219    declared: Option<Dialect>,
220    entry: &MarketplaceEntry,
221) -> InspectedPlugin {
222    let mut plugin = InspectedPlugin {
223        entry: entry.clone(),
224        at_marketplace_root: false,
225        items: None,
226        refused: None,
227        diagnostics: BTreeMap::new(),
228    };
229    match &entry.source {
230        PluginSource::Unsupported { reason } => {
231            plugin.refused = Some(format!("can't import from this source: {reason}"));
232        }
233        PluginSource::Remote { .. } => {}
234        PluginSource::Local { path } => {
235            plugin.at_marketplace_root = path.is_empty();
236            let root = SubTree::new(source, path.clone());
237            if let Some(generated) = enclosing_generated_dir(source, path) {
238                plugin.refused = Some(format!(
239                    "`{path}` is inside `{}`, plugin output Mars built, which is never input",
240                    if generated.is_empty() {
241                        "."
242                    } else {
243                        &generated
244                    }
245                ));
246                return plugin;
247            }
248            if !path.is_empty() && !source.is_dir(path) {
249                plugin.refused = Some(format!("`{path}` does not exist in the marketplace"));
250                return plugin;
251            }
252            let dispatched = dispatch(
253                &root,
254                PrepareContext::Package,
255                declared,
256                Some(AsPlugin {
257                    entry,
258                    at_marketplace_root: plugin.at_marketplace_root,
259                }),
260                Some(&entry.name),
261            );
262            if dispatched.kind() == Kind::Invalid {
263                plugin.refused = dispatched
264                    .discovery
265                    .diagnostics
266                    .values()
267                    .flatten()
268                    .find(|diagnostic| diagnostic.is_error())
269                    .map(|diagnostic| diagnostic.message.clone())
270                    .or_else(|| Some("the plugin's manifest cannot be read".to_owned()));
271            }
272            plugin.items = Some(list_items(&root, &dispatched, &mut plugin.diagnostics));
273            for (path, found) in dispatched.discovery.diagnostics {
274                plugin.diagnostics.entry(path).or_default().extend(found);
275            }
276        }
277    }
278    plugin
279}
280
281pub(crate) fn list_items(
282    source: &impl TreeSource,
283    dispatched: &Dispatched,
284    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
285) -> Vec<InspectedItem> {
286    let discovery = &dispatched.discovery;
287    let mut payload = BTreeMap::<String, Vec<String>>::new();
288    let foreign = matches!(dispatched.classification, Classification::Foreign(_));
289    let by_owner = payload_paths(
290        source,
291        discovery,
292        foreign,
293        discovery.definitions.iter(),
294        diagnostics,
295    );
296    for (path, _) in by_owner {
297        // The owner is the deepest skill root containing the file.
298        if let Some(owner) = discovery
299            .definitions
300            .iter()
301            .filter_map(|definition| definition.skill_root.as_deref())
302            .filter(|root| root.is_empty() || path.starts_with(&format!("{root}/")))
303            .max_by_key(|root| root.len())
304        {
305            payload.entry(owner.to_owned()).or_default().push(path);
306        }
307    }
308    let mut items = discovery
309        .definitions
310        .iter()
311        .map(|definition| InspectedItem {
312            kind: definition.kind.into(),
313            slug: definition.slug.clone(),
314            source_path: definition.source_path.clone(),
315            skill_root: definition.skill_root.clone(),
316            output_path: Some(definition.output_path.clone()),
317            payload: definition
318                .skill_root
319                .as_ref()
320                .and_then(|root| payload.remove(root))
321                .unwrap_or_default(),
322        })
323        .collect::<Vec<_>>();
324    items.extend(discovery.dropped.iter().map(|command| InspectedItem {
325        kind: InspectedKind::Command,
326        slug: command.slug.clone(),
327        source_path: command.source_path.clone(),
328        skill_root: None,
329        output_path: None,
330        payload: Vec::new(),
331    }));
332    items
333}