Skip to main content

mars_schema/
selection.rs

1//! Item selection: which Agents, skills and package-level documents of a settled dependency graph
2//! a consumer installs.
3//!
4//! A pure pass over the graph the resolver settled. It seeds items from the consumer's own
5//! requests and from unfiltered manifest edges, then closes over the skills the selected Agents
6//! name. Nothing here reads the filesystem, so the answer does not depend on the order the
7//! resolver met the packages in. Items are identified by package, kind and slug; the names they
8//! install under (renames, collision suffixes) are the caller's.
9//!
10//! The rule, in three steps:
11//!
12//! 1. **Seeds.** Each of the consumer's requests seeds its package, and so does each entry of
13//!    the root package's manifest, as the consumer's own request. The root package itself is
14//!    selected whole. A request that takes everything also opens its package: every unfiltered
15//!    entry of an open package's manifest seeds its target in turn and opens it. A filtered entry
16//!    of a dependency's manifest seeds nothing, and its `exclude` blocks nothing; only the consumer's own `exclude` (or the root's) does.
17//! 2. **Items per request.** `All` takes every item; `Include` takes Agents and skills by kind and
18//!    slug, and the package's bootstrap documents; `Exclude` takes all but the items it names by
19//!    slug or path; `only_skills` and `only_agents` take one kind. Hooks are taken by `All` and
20//!    `Exclude` only.
21//! 3. **Skill refs.** Every selected Agent's `skills` resolve to a package: its own, then its
22//!    dependencies breadth first, then any other package in registry order. The skill is selected
23//!    unless the consumer excluded it, and a package it lands in also selects its bootstrap
24//!    documents. A ref `<skill>__<provider>` that no package ships is skipped when the requester
25//!    declares the provider, and is a [`MissingSkill`] otherwise.
26//!
27//! **Registry order** is computed here, not supplied: a depth-first walk from the root package
28//! (if any), then each request in order, descending each package's manifest entries in
29//! declaration order. [`GraphView::packages`] is a set. A package no request reaches is never
30//! selected from and never supplies a skill.
31
32use std::collections::{HashMap, HashSet, VecDeque};
33
34use indexmap::IndexMap;
35use serde::{Deserialize, Serialize};
36
37use crate::diagnostic::{SchemaDiagnostic, Severity};
38use crate::filter::FilterMode;
39use crate::item::{DefinitionKind, ItemKind};
40use crate::names::ItemName;
41
42/// A dependency entry as selection sees it: the package it names and the items it asks for.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Request {
45    pub name: String,
46    pub filter: FilterMode,
47}
48
49/// An item of a package, found by the caller: what the crate does not prepare (bootstrap
50/// documents, hooks). MCP servers are selected outside this pass, by the caller.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(deny_unknown_fields)]
53pub struct Item {
54    pub kind: ItemKind,
55    pub slug: String,
56    /// Package-relative location, `/`-separated.
57    pub path: String,
58}
59
60/// An Agent or skill of a package, with the skills an Agent names.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct Definition {
63    pub kind: DefinitionKind,
64    pub slug: String,
65    pub output_path: String,
66    /// The skills the Agent names; empty for a skill.
67    pub skills: Vec<String>,
68}
69
70/// What selection reads of a prepared package. `prepare` computes it (`Prepared::selection`), so
71/// a caller on the other side of the JSON boundary passes `prepare`'s result and derives nothing.
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct SelectionFacts {
74    pub definitions: Vec<Definition>,
75    /// The package's manifest entries, in declaration order: the `[dependencies]` table, never
76    /// `[local-dependencies]`.
77    pub edges: Vec<Request>,
78    pub uses_providers: Vec<String>,
79    /// The package could not be read (`Invalid` or `SchemaNewer`), so `definitions` is empty
80    /// because nothing was read, not because it ships nothing. A check does not judge skill
81    /// refs against it.
82    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
83    pub unreadable: bool,
84}
85
86#[derive(Debug, Clone)]
87pub struct PackageView {
88    pub facts: SelectionFacts,
89    /// Bootstrap documents and hooks. They never change which Agents and skills are selected:
90    /// only Agents and skills are followed, so a caller with none to give passes `[]`.
91    pub extra_items: Vec<Item>,
92}
93
94/// A package as a caller holds it across the JSON boundary: the [`crate::prepare::Prepared`] it
95/// got earlier (`prepare`'s result, as serialized) and the items preparation does not read. Only
96/// `prepared.selection` is read; the rest is ignored.
97#[derive(Debug, Deserialize)]
98#[serde(deny_unknown_fields)]
99pub struct PackageInput {
100    prepared: PreparedInput,
101    #[serde(default, deserialize_with = "extra_items")]
102    extra_items: Option<Vec<Item>>,
103}
104
105/// `extra_items` hold bootstrap documents and hooks; an MCP server in them is the caller's mistake,
106/// since selection never reads one.
107fn extra_items<'de, D: serde::Deserializer<'de>>(
108    deserializer: D,
109) -> Result<Option<Vec<Item>>, D::Error> {
110    let items = Option::<Vec<Item>>::deserialize(deserializer)?;
111    match items
112        .iter()
113        .flatten()
114        .find(|item| item.kind == ItemKind::McpServer)
115    {
116        Some(item) => Err(serde::de::Error::custom(format!(
117            "extra_items `{}`: MCP servers are not selected by selectItems",
118            item.slug
119        ))),
120        None => Ok(items),
121    }
122}
123
124#[derive(Debug, Deserialize)]
125struct PreparedInput {
126    selection: SelectionFacts,
127}
128
129impl From<PackageInput> for PackageView {
130    fn from(input: PackageInput) -> Self {
131        Self {
132            facts: input.prepared.selection,
133            extra_items: input.extra_items.unwrap_or_default(),
134        }
135    }
136}
137
138#[derive(Debug)]
139pub struct GraphView {
140    /// The consumer's own entries.
141    pub requests: Vec<Request>,
142    /// The package being selected for, such as a project's own package: it is selected whole and
143    /// its items are in the result with no package. Its manifest entries are the consumer's own
144    /// requests, so its filters and `exclude` apply as in a project's own `mars.toml`. Its Agents' skill refs resolve like any package's.
145    pub root: Option<PackageView>,
146    /// Every package of the graph, in no particular order: [`select`] orders them (see the module
147    /// documentation).
148    pub packages: HashMap<String, PackageView>,
149}
150
151/// Why an item is selected.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
153#[serde(tag = "by", rename_all = "kebab-case")]
154pub enum Requester {
155    /// An entry of the consumer, or of the root package: the root's manifest entries, its items
156    /// and its Agents' skill refs are the consumer's own.
157    Consumer,
158    /// An unfiltered entry of this dependency's manifest, reached through unfiltered entries only.
159    Package { package: String },
160    /// A skill ref of this Agent.
161    Item {
162        package: String,
163        kind: ItemKind,
164        slug: String,
165    },
166}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
169pub struct SelectedItem {
170    /// `None` for the root's own item.
171    pub package: Option<String>,
172    pub kind: ItemKind,
173    pub slug: String,
174    /// Location in the prepared package: an Agent's file, a skill's directory (`.` for a flat
175    /// skill), a document's or hook's directory.
176    pub path: String,
177    pub required_by: Vec<Requester>,
178}
179
180/// A skill ref no package ships.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182pub struct MissingSkill {
183    pub skill: String,
184    /// The Agent that names it.
185    pub agent: String,
186    /// The package of that Agent; `None` for the root.
187    pub package: Option<String>,
188    /// The packages looked in, sorted; the root is not among them.
189    pub searched: Vec<String>,
190    /// For a name shaped like a provider's, when no package declares that provider.
191    pub hint: Option<String>,
192}
193
194#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
195pub struct SelectionResult {
196    /// In package order of the graph, then the package's own item order.
197    pub items: Vec<SelectedItem>,
198    pub missing_skills: Vec<MissingSkill>,
199    /// `selection.duplicate-slug`: an Agent or skill slug that two packages both install, which
200    /// installs under one name only after a rename or a collision suffix.
201    pub diagnostics: Vec<SchemaDiagnostic>,
202}
203
204/// An item with the definition it came from, when it has one.
205struct Entry<'a> {
206    item: Item,
207    definition: Option<&'a Definition>,
208}
209
210type Key<'a> = (&'a str, ItemKind, &'a str);
211
212/// The root's key among the packages. No dependency has an empty name.
213const ROOT: &str = "";
214
215/// The packages in registry order, the root among them.
216struct Graph<'v> {
217    packages: HashMap<&'v str, &'v PackageView>,
218    order: Vec<&'v str>,
219}
220
221impl<'v> Graph<'v> {
222    fn new(view: &'v GraphView) -> Self {
223        let mut packages: HashMap<&str, &PackageView> = view
224            .packages
225            .iter()
226            .map(|(name, package)| (name.as_str(), package))
227            .collect();
228        if let Some(root) = &view.root {
229            packages.insert(ROOT, root);
230        }
231        // Depth first, a package before its entries; a stack pops the first entry first.
232        let mut order = Vec::new();
233        let mut seen: HashSet<&str> = HashSet::new();
234        let mut stack: Vec<&str> = Vec::new();
235        let starts = view
236            .root
237            .iter()
238            .map(|_| ROOT)
239            .chain(view.requests.iter().map(|request| request.name.as_str()));
240        for start in starts {
241            stack.push(start);
242            while let Some(name) = stack.pop() {
243                let Some((&name, package)) = packages.get_key_value(name) else {
244                    continue;
245                };
246                if seen.insert(name) {
247                    order.push(name);
248                    stack.extend(
249                        package
250                            .facts
251                            .edges
252                            .iter()
253                            .rev()
254                            .map(|edge| edge.name.as_str()),
255                    );
256                }
257            }
258        }
259        Self { packages, order }
260    }
261}
262
263pub fn select(view: &GraphView) -> SelectionResult {
264    let graph = Graph::new(view);
265    let entries: HashMap<&str, Vec<Entry>> = graph
266        .order
267        .iter()
268        .map(|&name| (name, package_entries(graph.packages[name])))
269        .collect();
270
271    let seeds = seeds(view, &graph);
272    let excluded: HashMap<&str, Vec<&FilterMode>> = {
273        let mut excluded: HashMap<&str, Vec<&FilterMode>> = HashMap::new();
274        for seed in &seeds {
275            if matches!(seed.filter, FilterMode::Exclude(_)) {
276                excluded.entry(seed.package).or_default().push(seed.filter);
277            }
278        }
279        excluded
280    };
281
282    let mut selected: IndexMap<Key, Vec<Requester>> = IndexMap::new();
283    let mut queue: VecDeque<Key> = VecDeque::new();
284    for seed in &seeds {
285        for entry in &entries[seed.package] {
286            if !seed_accepts(seed.filter, &entry.item)
287                || is_excluded(&excluded, seed.package, &entry.item)
288            {
289                continue;
290            }
291            let key = (seed.package, entry.item.kind, entry.item.slug.as_str());
292            let requesters = selected.entry(key).or_default();
293            if !requesters.contains(&seed.requester) {
294                requesters.push(seed.requester.clone());
295            }
296            if matches!(entry.item.kind, ItemKind::Agent | ItemKind::Skill) {
297                queue.push_back(key);
298            }
299        }
300    }
301
302    let mut missing_skills = Vec::new();
303    // A package a skill ref lands in installs its bootstrap documents, as any requested part of
304    // a package does.
305    let mut pulled: IndexMap<&str, Requester> = IndexMap::new();
306    let mut processed: HashSet<Key> = HashSet::new();
307    while let Some(key) = queue.pop_front() {
308        if !processed.insert(key) {
309            continue;
310        }
311        let (package, kind, slug) = key;
312        let Some(entry) = entries[package]
313            .iter()
314            .find(|entry| entry.item.kind == kind && entry.item.slug == slug)
315        else {
316            continue;
317        };
318        let requester = if package == ROOT {
319            Requester::Consumer
320        } else {
321            Requester::Item {
322                package: package.to_string(),
323                kind,
324                slug: slug.to_string(),
325            }
326        };
327        for skill in entry
328            .definition
329            .map_or(&[][..], |definition| definition.skills.as_slice())
330        {
331            match resolve_skill(&graph, &entries, package, skill) {
332                Resolved::Deferred => {}
333                Resolved::Missing => {
334                    missing_skills.push(missing_skill(&graph, package, slug, skill))
335                }
336                Resolved::In(target) => {
337                    let target_entry = entries[target]
338                        .iter()
339                        .find(|entry| {
340                            entry.item.kind == ItemKind::Skill && entry.item.slug == *skill
341                        })
342                        .expect("a package that has the skill lists it");
343                    if is_excluded(&excluded, target, &target_entry.item) {
344                        continue;
345                    }
346                    pulled.entry(target).or_insert_with(|| requester.clone());
347                    let key = (target, ItemKind::Skill, target_entry.item.slug.as_str());
348                    let requesters = selected.entry(key).or_default();
349                    if !requesters.contains(&requester) {
350                        requesters.push(requester.clone());
351                    }
352                    queue.push_back(key);
353                }
354            }
355        }
356    }
357    for (package, requester) in &pulled {
358        for entry in &entries[package] {
359            if entry.item.kind == ItemKind::BootstrapDoc
360                && !is_excluded(&excluded, package, &entry.item)
361            {
362                let key = (*package, entry.item.kind, entry.item.slug.as_str());
363                let requesters = selected.entry(key).or_default();
364                if !requesters.contains(requester) {
365                    requesters.push(requester.clone());
366                }
367            }
368        }
369    }
370
371    let mut items = Vec::with_capacity(selected.len());
372    for &package in &graph.order {
373        for entry in &entries[package] {
374            let key = (package, entry.item.kind, entry.item.slug.as_str());
375            if let Some(required_by) = selected.get(&key) {
376                items.push(SelectedItem {
377                    package: (package != ROOT).then(|| package.to_string()),
378                    kind: entry.item.kind,
379                    slug: entry.item.slug.clone(),
380                    path: entry.item.path.clone(),
381                    required_by: required_by.clone(),
382                });
383            }
384        }
385    }
386    let diagnostics = duplicate_slug_diagnostics(&items);
387    SelectionResult {
388        items,
389        missing_skills,
390        diagnostics,
391    }
392}
393
394/// An Agent or skill slug that more than one package installs.
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct DuplicateSlug {
397    pub kind: ItemKind,
398    pub slug: String,
399    /// The packages that ship it, in package order; `None` is the root.
400    pub packages: Vec<Option<String>>,
401}
402
403/// The slugs two or more of `items` share, in item order.
404pub fn duplicate_slugs(items: &[SelectedItem]) -> Vec<DuplicateSlug> {
405    let mut packages: IndexMap<(ItemKind, &str), Vec<Option<String>>> = IndexMap::new();
406    for item in items
407        .iter()
408        .filter(|item| matches!(item.kind, ItemKind::Agent | ItemKind::Skill))
409    {
410        packages
411            .entry((item.kind, item.slug.as_str()))
412            .or_default()
413            .push(item.package.clone());
414    }
415    packages
416        .into_iter()
417        .filter(|(_, packages)| packages.len() > 1)
418        .map(|((kind, slug), packages)| DuplicateSlug {
419            kind,
420            slug: slug.to_string(),
421            packages,
422        })
423        .collect()
424}
425
426fn duplicate_slug_diagnostics(items: &[SelectedItem]) -> Vec<SchemaDiagnostic> {
427    duplicate_slugs(items)
428        .into_iter()
429        .map(|duplicate| {
430            let packages = duplicate
431                .packages
432                .iter()
433                .map(|package| package.as_deref().unwrap_or("the root package"))
434                .collect::<Vec<_>>();
435            SchemaDiagnostic::new(
436                "selection.duplicate-slug",
437                Severity::Warning,
438                Vec::new(),
439                format!(
440                    "{} `{}` is installed from {}",
441                    duplicate.kind,
442                    duplicate.slug,
443                    packages.join(", ")
444                ),
445            )
446        })
447        .collect()
448}
449
450struct Seed<'a> {
451    package: &'a str,
452    filter: &'a FilterMode,
453    requester: Requester,
454}
455
456/// The requests that seed items: the root and its manifest entries, the consumer's own, and each
457/// unfiltered manifest entry of a package reached through unfiltered requests only. A filtered
458/// entry of a dependency's manifest seeds nothing, and its `exclude` blocks nothing. The root's
459/// entries are the consumer's own requests, filters and `exclude` included.
460fn seeds<'a>(view: &'a GraphView, graph: &Graph<'a>) -> Vec<Seed<'a>> {
461    static ALL: FilterMode = FilterMode::All;
462    let mut seeds = Vec::new();
463    let mut open: HashSet<&str> = HashSet::new();
464    let mut queue: VecDeque<&str> = VecDeque::new();
465    if view.root.is_some() {
466        seeds.push(Seed {
467            package: ROOT,
468            filter: &ALL,
469            requester: Requester::Consumer,
470        });
471    }
472    let root_edges = view.root.iter().flat_map(|root| &root.facts.edges);
473    for request in root_edges.chain(&view.requests) {
474        let Some((&package, _)) = graph.packages.get_key_value(request.name.as_str()) else {
475            continue;
476        };
477        seeds.push(Seed {
478            package,
479            filter: &request.filter,
480            requester: Requester::Consumer,
481        });
482        if request.filter == FilterMode::All && open.insert(package) {
483            queue.push_back(package);
484        }
485    }
486    while let Some(from) = queue.pop_front() {
487        for edge in &graph.packages[from].facts.edges {
488            let Some((&package, _)) = graph.packages.get_key_value(edge.name.as_str()) else {
489                continue;
490            };
491            if edge.filter != FilterMode::All {
492                continue;
493            }
494            seeds.push(Seed {
495                package,
496                filter: &edge.filter,
497                requester: Requester::Package {
498                    package: from.to_string(),
499                },
500            });
501            if open.insert(package) {
502                queue.push_back(package);
503            }
504        }
505    }
506    seeds
507}
508
509fn package_entries<'a>(package: &'a PackageView) -> Vec<Entry<'a>> {
510    let definitions = package.facts.definitions.iter().map(|definition| {
511        let (kind, path) = match definition.kind {
512            DefinitionKind::Agent => (ItemKind::Agent, definition.output_path.clone()),
513            DefinitionKind::Skill => (
514                ItemKind::Skill,
515                match definition.output_path.rsplit_once('/') {
516                    Some((parent, _)) if !parent.is_empty() => parent.to_string(),
517                    _ => ".".to_string(),
518                },
519            ),
520        };
521        Entry {
522            item: Item {
523                kind,
524                slug: definition.slug.clone(),
525                path,
526            },
527            definition: Some(definition),
528        }
529    });
530    let extras = package.extra_items.iter().map(|item| Entry {
531        item: item.clone(),
532        definition: None,
533    });
534    definitions.chain(extras).collect()
535}
536
537/// Whether a request's filter takes the item. Hooks and MCP servers are not selectable by name or
538/// category, only by taking everything.
539fn seed_accepts(filter: &FilterMode, item: &Item) -> bool {
540    match filter {
541        FilterMode::All => true,
542        FilterMode::Include { agents, skills } => match item.kind {
543            ItemKind::Agent => agents.iter().any(|name| name.as_str() == item.slug),
544            ItemKind::Skill => skills.iter().any(|name| name.as_str() == item.slug),
545            // Package-level documents travel with any requested part of the package.
546            ItemKind::BootstrapDoc => true,
547            ItemKind::Hook | ItemKind::McpServer => false,
548        },
549        FilterMode::Exclude(excluded) => !names_item(excluded, item),
550        FilterMode::OnlySkills => item.kind == ItemKind::Skill,
551        FilterMode::OnlyAgents => item.kind == ItemKind::Agent,
552    }
553}
554
555/// An exclude entry names an item by slug or by path, whatever the item's kind.
556fn names_item(excluded: &[ItemName], item: &Item) -> bool {
557    excluded
558        .iter()
559        .any(|name| name.as_str() == item.slug || name.as_str() == item.path)
560}
561
562fn is_excluded(excluded: &HashMap<&str, Vec<&FilterMode>>, package: &str, item: &Item) -> bool {
563    excluded.get(package).is_some_and(|filters| {
564        filters.iter().any(|filter| match filter {
565            FilterMode::Exclude(names) => names_item(names, item),
566            _ => false,
567        })
568    })
569}
570
571enum Resolved<'a> {
572    In(&'a str),
573    /// A ref `<skill>__<provider>` to a provider the requester declares, which no package ships.
574    Deferred,
575    Missing,
576}
577
578/// The package that supplies a skill ref: the requester's own, then its dependencies breadth
579/// first, then any other package in registry order.
580fn resolve_skill<'a>(
581    graph: &Graph<'a>,
582    entries: &HashMap<&str, Vec<Entry>>,
583    requester: &'a str,
584    skill: &str,
585) -> Resolved<'a> {
586    let has_skill = |package: &str| {
587        entries[package]
588            .iter()
589            .any(|entry| entry.item.kind == ItemKind::Skill && entry.item.slug == skill)
590    };
591    if has_skill(requester) {
592        return Resolved::In(requester);
593    }
594
595    // Breadth first keeps direct dependencies ahead of transitive ones.
596    let mut closure: Vec<&str> = Vec::new();
597    let mut seen: HashSet<&str> = HashSet::from([requester]);
598    let mut queue: VecDeque<&str> = VecDeque::from([requester]);
599    while let Some(package) = queue.pop_front() {
600        if package != requester {
601            closure.push(package);
602        }
603        for edge in &graph.packages[package].facts.edges {
604            if let Some((&name, _)) = graph.packages.get_key_value(edge.name.as_str())
605                && seen.insert(name)
606            {
607                queue.push_back(name);
608            }
609        }
610    }
611    if let Some(package) = closure.into_iter().find(|package| has_skill(package)) {
612        return Resolved::In(package);
613    }
614    for &name in &graph.order {
615        if !seen.contains(name) && has_skill(name) {
616            return Resolved::In(name);
617        }
618    }
619
620    if crate::provider::deferred_provider(
621        skill,
622        Some(&graph.packages[requester].facts.uses_providers),
623    )
624    .is_some()
625    {
626        return Resolved::Deferred;
627    }
628    Resolved::Missing
629}
630
631fn missing_skill(graph: &Graph, package: &str, agent: &str, skill: &str) -> MissingSkill {
632    let mut searched: Vec<String> = graph
633        .order
634        .iter()
635        .filter(|&&name| name != ROOT)
636        .map(|name| name.to_string())
637        .collect();
638    searched.sort();
639    MissingSkill {
640        skill: skill.to_string(),
641        agent: agent.to_string(),
642        package: (package != ROOT).then(|| package.to_string()),
643        searched,
644        hint: crate::provider::provider_of(skill).map(crate::provider::undeclared_provider_hint),
645    }
646}