Skip to main content

fallow_core/plugins/
manifest_entries.rs

1//! Evaluation of external-plugin `manifestEntries` rules.
2//!
3//! A [`ManifestEntryRule`] seeds entry points DERIVED from framework manifest
4//! files: it finds manifests by a recursive glob (a bounded, `.gitignore`-aware
5//! second walk, because manifests are config files and are NOT in the
6//! source-discovery set), parses each one, and for every manifest that passes
7//! the rule-level `when` gate resolves each `entries[].path` relative to that
8//! manifest's directory (with `${dotted.field}` and `[*]` interpolation) into a
9//! root-relative entry pattern.
10//!
11//! The dominant failure mode is silent-none across a large manifest set (a typo
12//! in a field path seeds nothing), so evaluation emits loud `tracing::warn!`
13//! diagnostics: a `manifests` glob that matches nothing, a `when` that excludes
14//! every matched manifest, a referenced field path that resolves in zero
15//! matched manifests, an empty `entries` list, and unparseable manifests.
16
17use std::collections::BTreeMap;
18use std::path::{Path, PathBuf};
19
20use fallow_config::{
21    ExternalPluginDef, ManifestCondition, ManifestEntryRule, ManifestFieldPath,
22    ManifestFieldSegment, ManifestFormat, ManifestPathPart, ManifestPathTemplate,
23};
24use serde_json::Value;
25
26use super::PathRule;
27use super::config_parser::normalize_config_path;
28
29/// Maximum number of values one field traversal may retain at any step.
30/// This bounds large manifest arrays before scalar conversion or cartesian
31/// expansion begins.
32const MAX_MANIFEST_FIELD_VALUES: usize = 1_024;
33
34/// Maximum number of concrete paths one entry template may produce per manifest.
35const MAX_MANIFEST_ENTRY_EXPANSIONS: usize = 4_096;
36
37/// A kind of `manifestEntries` diagnostic, kebab-serialized for agents that
38/// branch on it. Centralizes the vocabulary shared by the production warn path
39/// (`evaluate_manifest_entries`) and the agent-facing check path
40/// (`check_manifest_entries` / `fallow plugin-check`).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum WarningKind {
43    /// The `manifests` glob matched zero files.
44    ManifestsMatchedNone,
45    /// The `when` gate excluded every matched manifest.
46    WhenExcludedAll,
47    /// A referenced field path resolved in none of the gated manifests (typo).
48    FieldPathUnresolved,
49    /// The rule's `entries` list is empty; it seeds nothing.
50    EntriesEmpty,
51    /// One or more matched manifests could not be read or parsed.
52    ManifestParseFailed,
53    /// A field path yielded more values than the evaluator permits.
54    FieldValuesLimitExceeded,
55    /// An entry template's interpolation product exceeded the evaluator limit.
56    EntryExpansionLimitExceeded,
57    /// An entry resolved outside the project root and was skipped.
58    EntryOutsideRoot,
59    /// A rule seeded entries but none of the seeded paths exist on disk.
60    /// Check-only (production seeds the pattern regardless of existence).
61    SeededPathsMissing,
62}
63
64impl WarningKind {
65    /// The kebab-case token agents branch on.
66    #[must_use]
67    pub fn as_kebab(self) -> &'static str {
68        match self {
69            Self::ManifestsMatchedNone => "manifests-matched-none",
70            Self::WhenExcludedAll => "when-excluded-all",
71            Self::FieldPathUnresolved => "field-path-unresolved",
72            Self::EntriesEmpty => "entries-empty",
73            Self::ManifestParseFailed => "manifest-parse-failed",
74            Self::FieldValuesLimitExceeded => "field-values-limit-exceeded",
75            Self::EntryExpansionLimitExceeded => "entry-expansion-limit-exceeded",
76            Self::EntryOutsideRoot => "entry-outside-root",
77            Self::SeededPathsMissing => "seeded-paths-missing",
78        }
79    }
80
81    /// The enforced ceiling for warnings caused by bounded expansion.
82    #[must_use]
83    pub fn expansion_limit(self) -> Option<usize> {
84        match self {
85            Self::FieldValuesLimitExceeded => Some(MAX_MANIFEST_FIELD_VALUES),
86            Self::EntryExpansionLimitExceeded => Some(MAX_MANIFEST_ENTRY_EXPANSIONS),
87            _ => None,
88        }
89    }
90}
91
92/// A single `manifestEntries` diagnostic with typed payload slots (agents read
93/// the slot their `kind` implies rather than parsing prose).
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CheckWarning {
96    pub kind: WarningKind,
97    /// The offending `manifests` glob (for `manifests-matched-none`).
98    pub glob: Option<String>,
99    /// The offending field path (for unresolved or value-limit warnings).
100    pub field_path: Option<String>,
101    /// The manifest a per-manifest warning relates to (root-relative).
102    pub manifest: Option<String>,
103    /// The offending entry or template (for entry-path warnings).
104    pub entry: Option<String>,
105}
106
107impl CheckWarning {
108    /// A warning carrying only the offending `manifests` glob.
109    fn glob(kind: WarningKind, glob: &str) -> Self {
110        Self {
111            kind,
112            glob: Some(glob.to_string()),
113            field_path: None,
114            manifest: None,
115            entry: None,
116        }
117    }
118
119    /// A warning carrying only the offending dotted field path.
120    fn field(kind: WarningKind, field_path: String) -> Self {
121        Self {
122            kind,
123            glob: None,
124            field_path: Some(field_path),
125            manifest: None,
126            entry: None,
127        }
128    }
129
130    /// A warning carrying only the offending manifest (root-relative).
131    fn manifest(kind: WarningKind, manifest: String) -> Self {
132        Self {
133            kind,
134            glob: None,
135            field_path: None,
136            manifest: Some(manifest),
137            entry: None,
138        }
139    }
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
143enum ExpansionError {
144    FieldValues { field_path: String },
145    EntryPaths { template: String },
146}
147
148impl ExpansionError {
149    fn into_warning(self, manifest: Option<String>) -> CheckWarning {
150        match self {
151            Self::FieldValues { field_path } => CheckWarning {
152                kind: WarningKind::FieldValuesLimitExceeded,
153                glob: None,
154                field_path: Some(field_path),
155                manifest,
156                entry: None,
157            },
158            Self::EntryPaths { template } => CheckWarning {
159                kind: WarningKind::EntryExpansionLimitExceeded,
160                glob: None,
161                field_path: None,
162                manifest,
163                entry: Some(template),
164            },
165        }
166    }
167}
168
169/// What one matched-and-parsed manifest yielded under a rule.
170#[derive(Debug, Clone)]
171pub struct ManifestResult {
172    /// Root-relative manifest path.
173    pub path: String,
174    /// Whether the rule-level `when` gate passed for this manifest.
175    pub when_passed: bool,
176    /// Root-relative entry globs seeded from this manifest (empty unless
177    /// `when_passed`). Each still encodes its own extension (e.g. `{ts,tsx}`).
178    pub seeded: Vec<String>,
179}
180
181/// The result of evaluating one `manifestEntries` rule: the shared source of
182/// truth for BOTH production seeding and the agent-facing check output, so the
183/// two can never drift.
184#[derive(Debug, Clone)]
185pub struct RuleReport {
186    /// The rule's `manifests` glob.
187    pub manifests: String,
188    /// Root-relative paths of the manifests the glob matched (sorted, stable).
189    pub manifests_matched: Vec<String>,
190    /// Per-matched-manifest results (sorted by path).
191    pub matched: Vec<ManifestResult>,
192    /// Diagnostics for this rule, sorted by `(kind, manifest, entry, field_path)`
193    /// so the JSON is byte-identical across machines and CI runs.
194    pub warnings: Vec<CheckWarning>,
195}
196
197/// Evaluate every `manifestEntries` rule on an active external plugin, returning
198/// the root-relative entry patterns to seed. Delegates to the shared
199/// `build_rule_report` so the seeded set and the `fallow plugin-check` report
200/// are computed by identical logic, then re-emits each report warning as a
201/// `tracing::warn!` (the loud stderr behavior is preserved).
202///
203/// Manifest files are config files, not source files, so they are not in the
204/// source-discovery set; this does a bounded `.gitignore`-respecting walk (like
205/// plugin detection's file-existence fallback) to find them. Manifests under
206/// gitignored / `node_modules` directories are intentionally invisible.
207#[must_use]
208pub(crate) fn evaluate_manifest_entries(ext: &ExternalPluginDef, root: &Path) -> Vec<PathRule> {
209    let mut out = Vec::new();
210    for rule in &ext.manifest_entries {
211        let report = build_rule_report(rule, root);
212        for manifest in &report.matched {
213            for seed in &manifest.seeded {
214                out.push(PathRule::new(seed.clone()));
215            }
216        }
217        emit_report_warnings(&ext.name, &report);
218    }
219    out
220}
221
222/// Evaluate every `manifestEntries` rule and return the STRUCTURED report per
223/// rule, without seeding or warning. This is the read-only dry-run the
224/// `fallow plugin-check` command surfaces to agents.
225#[must_use]
226pub fn check_manifest_entries(ext: &ExternalPluginDef, root: &Path) -> Vec<RuleReport> {
227    ext.manifest_entries
228        .iter()
229        .map(|rule| build_rule_report(rule, root))
230        .collect()
231}
232
233/// The shared core: walk manifests, gate on `when`, seed entries, and collect
234/// diagnostics into a [`RuleReport`]. Deterministically ordered.
235fn build_rule_report(rule: &ManifestEntryRule, root: &Path) -> RuleReport {
236    let mut report = RuleReport {
237        manifests: rule.manifests.clone(),
238        manifests_matched: Vec::new(),
239        matched: Vec::new(),
240        warnings: Vec::new(),
241    };
242
243    if rule.entries.is_empty() {
244        report.warnings.push(CheckWarning::glob(
245            WarningKind::EntriesEmpty,
246            &rule.manifests,
247        ));
248        return report;
249    }
250
251    let Ok(glob) = fallow_config::compile_path_glob(&rule.manifests) else {
252        // Glob validity is enforced at config load; a compile failure here is
253        // defensive and, like a non-matching glob, seeds nothing.
254        report.warnings.push(CheckWarning::glob(
255            WarningKind::ManifestsMatchedNone,
256            &rule.manifests,
257        ));
258        return report;
259    };
260    let matcher = glob.compile_matcher();
261
262    let referenced = referenced_field_paths(rule);
263    let mut resolved: BTreeMap<&str, bool> =
264        referenced.iter().map(|p| (p.as_str(), false)).collect();
265    let mut passed = 0usize;
266    let mut parsed = 0usize;
267    let mut gate_errors = 0usize;
268
269    for file in discover_manifest_paths(root, &matcher) {
270        let rel_manifest = root_relative_forward_slash(&file, root)
271            .unwrap_or_else(|| file.to_string_lossy().replace('\\', "/"));
272        report.manifests_matched.push(rel_manifest.clone());
273
274        let manifest: Value = match crate::discover::project_read::read_project_file(root, &file)
275            .and_then(|source| parse_manifest(&source, rule.format))
276        {
277            Some(value) => value,
278            None => {
279                // Per-file diagnostic (with the offending manifest) so an agent
280                // does not have to set-difference manifests_matched vs matched.
281                report.warnings.push(CheckWarning::manifest(
282                    WarningKind::ManifestParseFailed,
283                    rel_manifest,
284                ));
285                continue;
286            }
287        };
288        parsed += 1;
289
290        let when_passed = match when_matches(&manifest, &rule.when) {
291            Ok(passed) => passed,
292            Err(error) => {
293                gate_errors += 1;
294                report
295                    .warnings
296                    .push(error.into_warning(Some(rel_manifest.clone())));
297                false
298            }
299        };
300        let mut seeded = Vec::new();
301        if when_passed {
302            passed += 1;
303            for path in &referenced {
304                let path_resolved = match field_values(&manifest, path) {
305                    Ok(values) => !values.is_empty(),
306                    // The path resolved; its fan-out is the problem. Evaluation
307                    // emits the more precise limit warning below.
308                    Err(_) => true,
309                };
310                if path_resolved && let Some(flag) = resolved.get_mut(path.as_str()) {
311                    *flag = true;
312                }
313            }
314            let (entries, mut entry_warnings) = seed_rule_entries(rule, &manifest, &file, root);
315            seeded = entries;
316            report.warnings.append(&mut entry_warnings);
317        }
318        report.matched.push(ManifestResult {
319            path: rel_manifest,
320            when_passed,
321            seeded,
322        });
323    }
324
325    report.warnings.extend(rule_level_warnings(
326        &rule.manifests,
327        report.manifests_matched.len(),
328        parsed,
329        passed,
330        gate_errors,
331        &resolved,
332    ));
333
334    // manifests_matched inherits discover_manifest_paths' sorted order; matched
335    // and warnings are sorted here so the JSON is byte-identical across runs and
336    // filesystems (warnings tie-break on manifest then entry, since a rule can
337    // emit multiple parse-failed / entry-outside-root warnings).
338    report.matched.sort_by(|a, b| a.path.cmp(&b.path));
339    report.warnings.sort_by(|a, b| {
340        a.kind
341            .as_kebab()
342            .cmp(b.kind.as_kebab())
343            .then_with(|| a.manifest.cmp(&b.manifest))
344            .then_with(|| a.entry.cmp(&b.entry))
345            .then_with(|| a.field_path.cmp(&b.field_path))
346    });
347    report.warnings.dedup();
348    report
349}
350
351/// Seed the entries of one manifest that a built-in plugin already found and
352/// parsed. The rule's `manifests` glob is not used: the caller owns discovery.
353/// The gates, the `${...}` interpolation and the root containment are the same
354/// as for an external plugin rule. A gate or template that exceeds an
355/// evaluator limit seeds nothing, as on the external path.
356#[must_use]
357pub(crate) fn seed_parsed_manifest(
358    rule: &ManifestEntryRule,
359    manifest: &Value,
360    manifest_path: &Path,
361    root: &Path,
362) -> Vec<String> {
363    if !matches!(when_matches(manifest, &rule.when), Ok(true)) {
364        return Vec::new();
365    }
366    seed_rule_entries(rule, manifest, manifest_path, root).0
367}
368
369/// Parse manifest source text in the rule's declared format.
370#[must_use]
371pub(crate) fn parse_manifest(source: &str, format: ManifestFormat) -> Option<Value> {
372    match format {
373        ManifestFormat::Jsonc => fallow_config::jsonc::parse_to_value(source).ok(),
374        ManifestFormat::Json => serde_json::from_str(source).ok(),
375    }
376}
377
378/// Assemble the RULE-LEVEL diagnostics (matched-none / when-excluded-all /
379/// field-path-unresolved) from the walk tallies. Per-manifest diagnostics
380/// (parse-failed, entry-outside-root) are pushed during the walk. `parsed` is
381/// the count of manifests that read + parsed; `passed` cleared the `when` gate;
382/// `gate_errors` could not be evaluated because their traversal exceeded a
383/// declared bound.
384fn rule_level_warnings(
385    manifests: &str,
386    matched: usize,
387    parsed: usize,
388    passed: usize,
389    gate_errors: usize,
390    resolved: &BTreeMap<&str, bool>,
391) -> Vec<CheckWarning> {
392    let mut out = Vec::new();
393    if matched == 0 {
394        out.push(CheckWarning::glob(
395            WarningKind::ManifestsMatchedNone,
396            manifests,
397        ));
398        return out;
399    }
400    // Only claim the `when` gate excluded everything when there WERE parseable
401    // manifests for it to gate; if all failed to parse, the per-file
402    // parse-failed warnings already explain the zero seed.
403    if parsed > 0 && passed == 0 && gate_errors == 0 {
404        out.push(CheckWarning::glob(WarningKind::WhenExcludedAll, manifests));
405        return out;
406    }
407    if passed == 0 {
408        return out;
409    }
410    for (path, was_resolved) in resolved {
411        if !was_resolved {
412            out.push(CheckWarning::field(
413                WarningKind::FieldPathUnresolved,
414                (*path).to_string(),
415            ));
416        }
417    }
418    out
419}
420
421/// Seed one manifest's entries: returns the root-relative entry globs plus any
422/// `entry-outside-root` diagnostics.
423fn seed_rule_entries(
424    rule: &ManifestEntryRule,
425    manifest: &Value,
426    manifest_path: &Path,
427    root: &Path,
428) -> (Vec<String>, Vec<CheckWarning>) {
429    let rel_manifest = root_relative_forward_slash(manifest_path, root);
430    let mut seeded = Vec::new();
431    let mut warnings = Vec::new();
432    for seed in &rule.entries {
433        match when_matches(manifest, &seed.when) {
434            Ok(true) => {}
435            Ok(false) => continue,
436            Err(error) => {
437                warnings.push(error.into_warning(rel_manifest.clone()));
438                continue;
439            }
440        }
441        let concretes = match expand_interpolations(&seed.path, manifest) {
442            Ok(concretes) => concretes,
443            Err(error) => {
444                warnings.push(error.into_warning(rel_manifest.clone()));
445                continue;
446            }
447        };
448        for concrete in concretes {
449            match normalize_config_path(&concrete, manifest_path, root) {
450                Some(rel) => seeded.push(rel),
451                None => warnings.push(CheckWarning {
452                    kind: WarningKind::EntryOutsideRoot,
453                    glob: None,
454                    field_path: None,
455                    manifest: rel_manifest.clone(),
456                    entry: Some(concrete),
457                }),
458            }
459        }
460    }
461    (seeded, warnings)
462}
463
464/// Re-emit a rule report's warnings as `tracing::warn!` on the production path.
465fn emit_report_warnings(plugin_name: &str, report: &RuleReport) {
466    for warning in &report.warnings {
467        match warning.kind {
468            WarningKind::EntriesEmpty => tracing::warn!(
469                "Plugin '{plugin_name}': manifestEntries rule for '{}' has an empty 'entries' \
470                 list; it seeds nothing.",
471                report.manifests
472            ),
473            WarningKind::ManifestsMatchedNone => tracing::warn!(
474                "Plugin '{plugin_name}': manifestEntries 'manifests' glob '{}' matched no files. \
475                 Check the glob and whether the manifests live under an ignored directory.",
476                report.manifests
477            ),
478            WarningKind::ManifestParseFailed => tracing::warn!(
479                "Plugin '{plugin_name}': manifestEntries skipped manifest '{}' (glob '{}') because \
480                 it could not be read or parsed using the rule's declared format.",
481                warning.manifest.as_deref().unwrap_or(""),
482                report.manifests
483            ),
484            WarningKind::FieldValuesLimitExceeded => tracing::warn!(
485                "Plugin '{plugin_name}': manifestEntries field path '{}' in manifest '{}' exceeded \
486                 the traversal value limit of {}. The affected gate or template was skipped without \
487                 partial seeding.",
488                warning.field_path.as_deref().unwrap_or(""),
489                warning.manifest.as_deref().unwrap_or(""),
490                warning
491                    .kind
492                    .expansion_limit()
493                    .unwrap_or(MAX_MANIFEST_FIELD_VALUES)
494            ),
495            WarningKind::EntryExpansionLimitExceeded => tracing::warn!(
496                "Plugin '{plugin_name}': manifestEntries template '{}' in manifest '{}' exceeded \
497                 the concrete entry limit of {}. No entries were seeded from that template.",
498                warning.entry.as_deref().unwrap_or(""),
499                warning.manifest.as_deref().unwrap_or(""),
500                warning
501                    .kind
502                    .expansion_limit()
503                    .unwrap_or(MAX_MANIFEST_ENTRY_EXPANSIONS)
504            ),
505            WarningKind::WhenExcludedAll => tracing::warn!(
506                "Plugin '{plugin_name}': manifestEntries 'when' gate excluded all matched \
507                 manifest(s) for glob '{}'. No entries were seeded.",
508                report.manifests
509            ),
510            WarningKind::FieldPathUnresolved => tracing::warn!(
511                "Plugin '{plugin_name}': manifestEntries field path '{}' resolved in none of the \
512                 gated manifest(s). Likely a typo in a 'when' key or a ${{...}} interpolation.",
513                warning.field_path.as_deref().unwrap_or("")
514            ),
515            WarningKind::EntryOutsideRoot => tracing::warn!(
516                "Plugin '{plugin_name}': manifestEntries entry '{}' (from manifest '{}') resolved \
517                 outside the project root and was skipped.",
518                warning.entry.as_deref().unwrap_or(""),
519                warning.manifest.as_deref().unwrap_or("")
520            ),
521            // Check-only; never produced by build_rule_report.
522            WarningKind::SeededPathsMissing => {}
523        }
524    }
525}
526
527/// Collect every field path a rule references (rule-level `when` keys, per-seed
528/// `when` keys, and `${...}` interpolations in seed paths) for typo diagnostics.
529fn referenced_field_paths(rule: &ManifestEntryRule) -> Vec<ManifestFieldPath> {
530    let mut paths: Vec<ManifestFieldPath> = rule
531        .when
532        .iter()
533        .filter(|(_, condition)| condition_requires_present_value(condition))
534        .map(|(path, _)| path.clone())
535        .collect();
536    for seed in &rule.entries {
537        paths.extend(
538            seed.when
539                .iter()
540                .filter(|(_, condition)| condition_requires_present_value(condition))
541                .map(|(path, _)| path.clone()),
542        );
543        paths.extend(seed.path.parts().iter().filter_map(|part| match part {
544            ManifestPathPart::Field(path) => Some(path.clone()),
545            ManifestPathPart::Literal(_) => None,
546        }));
547    }
548    paths.sort();
549    paths.dedup();
550    paths
551}
552
553/// Expand `${dotted.field}` interpolations in a path against a manifest, fanning
554/// out over string / array field values. Returns an empty vec when any
555/// interpolation resolves to nothing (a missing field seeds nothing).
556fn expand_interpolations(
557    path: &ManifestPathTemplate,
558    manifest: &Value,
559) -> Result<Vec<String>, ExpansionError> {
560    let mut expanded = vec![String::new()];
561    for part in path.parts() {
562        match part {
563            ManifestPathPart::Literal(literal) => {
564                for value in &mut expanded {
565                    value.push_str(literal);
566                }
567            }
568            ManifestPathPart::Field(field) => {
569                let values = field_segment_values(manifest, field)?;
570                if values.is_empty() {
571                    return Ok(Vec::new());
572                }
573
574                let Some(next_len) = expanded.len().checked_mul(values.len()) else {
575                    return Err(ExpansionError::EntryPaths {
576                        template: path.as_str().to_string(),
577                    });
578                };
579                if next_len > MAX_MANIFEST_ENTRY_EXPANSIONS {
580                    return Err(ExpansionError::EntryPaths {
581                        template: path.as_str().to_string(),
582                    });
583                }
584
585                let mut next = Vec::with_capacity(next_len);
586                for prefix in &expanded {
587                    for value in &values {
588                        let mut concrete = String::with_capacity(prefix.len() + value.len());
589                        concrete.push_str(prefix);
590                        concrete.push_str(value);
591                        next.push(concrete);
592                    }
593                }
594                expanded = next;
595            }
596        }
597    }
598    Ok(expanded)
599}
600
601/// The path-segment string values a field yields: a string or number yields
602/// one; a final array yields one per scalar element; anything else yields none.
603fn field_segment_values(
604    manifest: &Value,
605    field: &ManifestFieldPath,
606) -> Result<Vec<String>, ExpansionError> {
607    let mut values = Vec::new();
608    for value in field_values(manifest, field)? {
609        match value {
610            Value::Array(items) => {
611                for item in items.iter().filter_map(scalar_segment) {
612                    push_field_segment(&mut values, item, field)?;
613                }
614            }
615            value => {
616                if let Some(segment) = scalar_segment(value) {
617                    push_field_segment(&mut values, segment, field)?;
618                }
619            }
620        }
621    }
622    Ok(values)
623}
624
625fn push_field_segment(
626    values: &mut Vec<String>,
627    value: String,
628    field: &ManifestFieldPath,
629) -> Result<(), ExpansionError> {
630    if values.len() == MAX_MANIFEST_FIELD_VALUES {
631        return Err(ExpansionError::FieldValues {
632            field_path: field.as_str().to_string(),
633        });
634    }
635    values.push(value);
636    Ok(())
637}
638
639fn scalar_segment(value: &Value) -> Option<String> {
640    match value {
641        Value::String(s) if !s.is_empty() => Some(s.clone()),
642        Value::Number(n) => Some(n.to_string()),
643        _ => None,
644    }
645}
646
647/// Whether every `(dotted-path, expected)` pair in `when` matches the manifest
648/// by strict equality. An empty map always matches.
649fn when_matches(
650    manifest: &Value,
651    when: &BTreeMap<ManifestFieldPath, ManifestCondition>,
652) -> Result<bool, ExpansionError> {
653    for (path, condition) in when {
654        let values = field_values(manifest, path)?;
655        let matches = match condition {
656            ManifestCondition::Equals(expected) => values.contains(&expected),
657            ManifestCondition::Exists(predicate) => values.is_empty() != predicate.exists,
658        };
659        if !matches {
660            return Ok(false);
661        }
662    }
663    Ok(true)
664}
665
666fn condition_requires_present_value(condition: &ManifestCondition) -> bool {
667    match condition {
668        ManifestCondition::Equals(_) => true,
669        ManifestCondition::Exists(predicate) => predicate.exists,
670    }
671}
672
673/// Evaluate a typed manifest field path, including explicit `[*]` traversal.
674fn field_values<'a>(
675    value: &'a Value,
676    path: &ManifestFieldPath,
677) -> Result<Vec<&'a Value>, ExpansionError> {
678    let mut current = vec![value];
679    for segment in path.segments() {
680        let mut next = Vec::new();
681        for value in current {
682            match segment {
683                ManifestFieldSegment::Key(key) => {
684                    if let Some(child) = value.get(key) {
685                        push_field_value(&mut next, child, path)?;
686                    }
687                }
688                ManifestFieldSegment::Each => {
689                    if let Value::Array(items) = value {
690                        for item in items {
691                            push_field_value(&mut next, item, path)?;
692                        }
693                    }
694                }
695            }
696        }
697        current = next;
698    }
699    Ok(current)
700}
701
702fn push_field_value<'a>(
703    values: &mut Vec<&'a Value>,
704    value: &'a Value,
705    path: &ManifestFieldPath,
706) -> Result<(), ExpansionError> {
707    if values.len() == MAX_MANIFEST_FIELD_VALUES {
708        return Err(ExpansionError::FieldValues {
709            field_path: path.as_str().to_string(),
710        });
711    }
712    values.push(value);
713    Ok(())
714}
715
716/// Walk `root` (respecting `.gitignore`, skipping `node_modules`) and return the
717/// absolute paths of files whose root-relative path matches `matcher`. Bounded
718/// to the manifest glob; runs only when an active plugin declares manifestEntries.
719fn discover_manifest_paths(root: &Path, matcher: &globset::GlobMatcher) -> Vec<PathBuf> {
720    let mut out = Vec::new();
721    let canonical_root = root.canonicalize().ok();
722    let walker = fallow_config::source_walk_builder(root)
723        .filter_entry(|entry| entry.file_name() != "node_modules")
724        .build();
725    for entry in walker.flatten() {
726        let Some(file_type) = entry.file_type() else {
727            continue;
728        };
729        if file_type.is_dir() {
730            continue;
731        }
732        let path = entry.path();
733        if file_type.is_symlink()
734            && !is_contained_regular_file_symlink(path, canonical_root.as_deref())
735        {
736            tracing::debug!(
737                path = %path.display(),
738                "skipping manifest symlink with a broken, non-file, or outside-root target"
739            );
740            continue;
741        }
742        if let Some(rel) = root_relative_forward_slash(path, root)
743            && matcher.is_match(Path::new(&rel))
744        {
745            out.push(path.to_path_buf());
746        }
747    }
748    // `ignore::WalkBuilder` yields raw filesystem order; sort so seeding and the
749    // check report (manifests_matched, per-manifest warnings) are deterministic
750    // across machines and CI runners.
751    out.sort();
752    out
753}
754
755fn is_contained_regular_file_symlink(path: &Path, canonical_root: Option<&Path>) -> bool {
756    let Some(root) = canonical_root else {
757        return false;
758    };
759    let Ok(target) = path.canonicalize() else {
760        return false;
761    };
762    target.starts_with(root) && target.metadata().is_ok_and(|metadata| metadata.is_file())
763}
764
765/// Root-relative forward-slash string for a discovered (absolute) path, or
766/// `None` if it is not under `root`.
767fn root_relative_forward_slash(file: &Path, root: &Path) -> Option<String> {
768    let rel = file.strip_prefix(root).ok()?;
769    Some(rel.to_string_lossy().replace('\\', "/"))
770}
771
772#[cfg(test)]
773mod tests {
774    use super::*;
775    use fallow_config::{
776        EntryPointRole, ManifestExistsPredicate, ManifestFormat, ManifestSeedRule,
777    };
778
779    fn json(text: &str) -> Value {
780        serde_json::from_str(text).unwrap()
781    }
782
783    fn seed(path: &str, when: &[(&str, Value)]) -> ManifestSeedRule {
784        ManifestSeedRule {
785            path: path.parse().unwrap(),
786            when: conditions(when),
787        }
788    }
789
790    fn field(path: &str) -> ManifestFieldPath {
791        path.parse().unwrap()
792    }
793
794    fn template(path: &str) -> ManifestPathTemplate {
795        path.parse().unwrap()
796    }
797
798    fn conditions(when: &[(&str, Value)]) -> BTreeMap<ManifestFieldPath, ManifestCondition> {
799        when.iter()
800            .map(|(path, expected)| (field(path), ManifestCondition::Equals(expected.clone())))
801            .collect()
802    }
803
804    fn exists(path: &str, expected: bool) -> (ManifestFieldPath, ManifestCondition) {
805        (
806            field(path),
807            ManifestCondition::Exists(ManifestExistsPredicate { exists: expected }),
808        )
809    }
810
811    #[test]
812    fn field_values_traverse_nested_fields_and_object_arrays() {
813        let m = json(r#"{"plugin": {"browser": true, "id": "actions"}}"#);
814        assert_eq!(
815            field_values(&m, &field("plugin.browser")).unwrap(),
816            vec![&Value::Bool(true)]
817        );
818        assert_eq!(
819            field_values(&m, &field("plugin.id")).unwrap(),
820            vec![&Value::String("actions".into())]
821        );
822        assert!(
823            field_values(&m, &field("plugin.missing"))
824                .unwrap()
825                .is_empty()
826        );
827        assert!(field_values(&m, &field("absent.field")).unwrap().is_empty());
828
829        let m = json(
830            r#"{"content_scripts":[{"js":["a.js","b.js"]},null,{"js":["c.js"]},"invalid",{"css":[]}]}"#,
831        );
832        assert_eq!(
833            field_segment_values(&m, &field("content_scripts[*].js")).unwrap(),
834            vec!["a.js", "b.js", "c.js"]
835        );
836
837        let nested = json(
838            r#"{"groups":[{"entries":[{"path":"a.js"},{"path":"b.js"}]},{"entries":[{"path":"c.js"}]}]}"#,
839        );
840        assert_eq!(
841            field_segment_values(&nested, &field("groups[*].entries[*].path")).unwrap(),
842            vec!["a.js", "b.js", "c.js"]
843        );
844    }
845
846    #[test]
847    fn when_matches_is_strict_equality_and_presence_is_not_matched() {
848        let m = json(r#"{"type": "plugin", "plugin": {"browser": false}}"#);
849        let mut when = BTreeMap::new();
850        when.insert(
851            field("type"),
852            ManifestCondition::Equals(Value::String("plugin".into())),
853        );
854        assert!(when_matches(&m, &when).unwrap());
855
856        // browser is present but false: matching against `true` must FAIL
857        // (strict equality, no presence overload).
858        let mut when_browser = BTreeMap::new();
859        when_browser.insert(
860            field("plugin.browser"),
861            ManifestCondition::Equals(Value::Bool(true)),
862        );
863        assert!(!when_matches(&m, &when_browser).unwrap());
864
865        // empty when always matches
866        assert!(when_matches(&m, &BTreeMap::new()).unwrap());
867
868        let manifest = json(r#"{"plugins":[{"kind":"worker"},{"kind":"browser"}]}"#);
869        let wildcard = conditions(&[("plugins[*].kind", Value::String("browser".into()))]);
870        assert!(when_matches(&manifest, &wildcard).unwrap());
871
872        let structured = json(r#"{"array":["worker"],"object":{"kind":"browser"}}"#);
873        let structured_when = BTreeMap::from([
874            (
875                field("array"),
876                ManifestCondition::Equals(json(r#"["worker"]"#)),
877            ),
878            (
879                field("object"),
880                ManifestCondition::Equals(json(r#"{"kind":"browser"}"#)),
881            ),
882        ]);
883        assert!(when_matches(&structured, &structured_when).unwrap());
884    }
885
886    #[test]
887    fn exists_conditions_test_presence_without_truthiness() {
888        let manifest = json(
889            r#"{"presentFalse":false,"presentNull":null,"presentEmpty":"","presentObject":{},"items":[]}"#,
890        );
891        for path in [
892            "presentFalse",
893            "presentNull",
894            "presentEmpty",
895            "presentObject",
896            "items",
897        ] {
898            assert!(
899                when_matches(&manifest, &BTreeMap::from([exists(path, true)])).unwrap(),
900                "{path} is present regardless of its value"
901            );
902        }
903        assert!(when_matches(&manifest, &BTreeMap::from([exists("missing", false)])).unwrap());
904        assert!(!when_matches(&manifest, &BTreeMap::from([exists("missing", true)])).unwrap());
905        assert!(
906            when_matches(
907                &manifest,
908                &BTreeMap::from([exists("items[*].value", false)])
909            )
910            .unwrap()
911        );
912    }
913
914    #[test]
915    fn exists_false_can_gate_a_rule_without_an_unresolved_path_warning() {
916        let dir = tempfile::tempdir().unwrap();
917        let root = dir.path();
918        write_manifest(root, "plugins/alpha/manifest.json", r#"{"name":"alpha"}"#);
919        let mut manifest_rule = rule("**/manifest.json", &[], vec![seed("index.ts", &[])]);
920        manifest_rule.when = BTreeMap::from([exists("main", false)]);
921
922        let reports = check_manifest_entries(&plugin_with(vec![manifest_rule]), root);
923        assert!(reports[0].warnings.is_empty());
924        assert!(reports[0].matched[0].when_passed);
925        assert_eq!(reports[0].matched[0].seeded, vec!["plugins/alpha/index.ts"]);
926    }
927
928    #[test]
929    fn parse_manifest_honors_the_declared_format() {
930        let jsonc_only = r#"{
931            // JSONC comment
932            "type": "plugin",
933        }"#;
934
935        assert!(parse_manifest(jsonc_only, ManifestFormat::Jsonc).is_some());
936        assert!(parse_manifest(jsonc_only, ManifestFormat::Json).is_none());
937        assert!(parse_manifest(r#"{"type":"plugin"}"#, ManifestFormat::Json).is_some());
938    }
939
940    #[test]
941    fn expand_interpolations_string_array_and_missing() {
942        let m = json(r#"{"plugin": {"extraPublicDirs": ["common", "types"], "id": "actions"}}"#);
943        // string field -> one entry
944        assert_eq!(
945            expand_interpolations(&template("${plugin.id}/index.ts"), &m).unwrap(),
946            vec!["actions/index.ts"]
947        );
948        // array field -> one entry per element
949        assert_eq!(
950            expand_interpolations(&template("${plugin.extraPublicDirs}/index.{ts,tsx}"), &m)
951                .unwrap(),
952            vec!["common/index.{ts,tsx}", "types/index.{ts,tsx}"]
953        );
954        // missing field -> nothing seeded
955        assert!(
956            expand_interpolations(&template("${plugin.absent}/index.ts"), &m)
957                .unwrap()
958                .is_empty()
959        );
960        // no interpolation -> passthrough
961        assert_eq!(
962            expand_interpolations(&template("public/index.{ts,tsx}"), &m).unwrap(),
963            vec!["public/index.{ts,tsx}"]
964        );
965    }
966
967    #[test]
968    fn interpolation_limits_are_explicit_errors() {
969        let too_many: Vec<Value> = (0..=MAX_MANIFEST_FIELD_VALUES)
970            .map(|index| Value::String(index.to_string()))
971            .collect();
972        let manifest = serde_json::json!({ "values": too_many });
973        assert_eq!(
974            expand_interpolations(&template("${values}/index.ts"), &manifest),
975            Err(ExpansionError::FieldValues {
976                field_path: "values".to_string(),
977            })
978        );
979
980        let factors = (0..65)
981            .map(|index| Value::String(index.to_string()))
982            .collect::<Vec<_>>();
983        let manifest = serde_json::json!({ "left": factors, "right": factors });
984        assert_eq!(
985            expand_interpolations(&template("${left}/${right}/index.ts"), &manifest),
986            Err(ExpansionError::EntryPaths {
987                template: "${left}/${right}/index.ts".to_string(),
988            })
989        );
990    }
991
992    #[test]
993    fn evaluate_seeds_relative_to_manifest_dir_with_when_and_fanout() {
994        let dir = tempfile::tempdir().unwrap();
995        let root = dir.path();
996        let manifest_dir = root.join("x-pack/plugins/actions");
997        std::fs::create_dir_all(&manifest_dir).unwrap();
998        let manifest_path = manifest_dir.join("kibana.jsonc");
999        std::fs::write(
1000            &manifest_path,
1001            r#"{
1002                // a real Kibana-shaped manifest
1003                "type": "plugin",
1004                "plugin": { "browser": true, "server": false, "extraPublicDirs": ["common"] },
1005            }"#,
1006        )
1007        .unwrap();
1008
1009        let ext = ExternalPluginDef {
1010            schema: None,
1011            name: "kibana".to_string(),
1012            detection: None,
1013            enablers: vec![],
1014            entry_points: vec![],
1015            entry_point_role: Some(EntryPointRole::Runtime),
1016            manifest_entries: vec![ManifestEntryRule {
1017                manifests: "**/kibana.jsonc".to_string(),
1018                format: ManifestFormat::Jsonc,
1019                when: conditions(&[("type", Value::String("plugin".into()))]),
1020                entries: vec![
1021                    seed(
1022                        "public/index.{ts,tsx}",
1023                        &[("plugin.browser", Value::Bool(true))],
1024                    ),
1025                    seed(
1026                        "server/index.{ts,tsx}",
1027                        &[("plugin.server", Value::Bool(true))],
1028                    ),
1029                    seed("${plugin.extraPublicDirs}/index.{ts,tsx}", &[]),
1030                ],
1031            }],
1032            config_patterns: vec![],
1033            config_default_export_opt_out: vec![],
1034            always_used: vec![],
1035            tooling_dependencies: vec![],
1036            used_exports: vec![],
1037            used_class_members: vec![],
1038        };
1039
1040        let rules = evaluate_manifest_entries(&ext, root);
1041        let paths: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect();
1042
1043        // browser:true seeds public; server:false does NOT seed server; extraPublicDirs fans out.
1044        assert!(paths.contains(&"x-pack/plugins/actions/public/index.{ts,tsx}"));
1045        assert!(paths.contains(&"x-pack/plugins/actions/common/index.{ts,tsx}"));
1046        assert!(
1047            !paths.iter().any(|p| p.contains("server/index")),
1048            "server:false must not seed the server entry, got {paths:?}"
1049        );
1050    }
1051
1052    #[test]
1053    fn evaluate_fans_out_over_object_array_fields() {
1054        let dir = tempfile::tempdir().unwrap();
1055        let root = dir.path();
1056        write_manifest(
1057            root,
1058            "extension/manifest.json",
1059            r#"{
1060                "manifest_version": 3,
1061                "content_scripts": [
1062                    { "matches": ["https://a.example/*"], "js": ["content/a.js", "content/b.js"] },
1063                    { "matches": ["https://b.example/*"], "js": ["content/c.js"] }
1064                ]
1065            }"#,
1066        );
1067        let ext = plugin_with(vec![rule(
1068            "**/manifest.json",
1069            &[("manifest_version", Value::Number(3.into()))],
1070            vec![seed("${content_scripts[*].js}", &[])],
1071        )]);
1072
1073        let reports = check_manifest_entries(&ext, root);
1074        assert!(reports[0].warnings.is_empty());
1075        assert_eq!(
1076            reports[0].matched[0].seeded,
1077            vec![
1078                "extension/content/a.js",
1079                "extension/content/b.js",
1080                "extension/content/c.js",
1081            ]
1082        );
1083    }
1084
1085    fn plugin_with(rules: Vec<ManifestEntryRule>) -> ExternalPluginDef {
1086        ExternalPluginDef {
1087            schema: None,
1088            name: "kibana".to_string(),
1089            detection: None,
1090            enablers: vec![],
1091            entry_points: vec![],
1092            entry_point_role: Some(EntryPointRole::Runtime),
1093            manifest_entries: rules,
1094            config_patterns: vec![],
1095            config_default_export_opt_out: vec![],
1096            always_used: vec![],
1097            tooling_dependencies: vec![],
1098            used_exports: vec![],
1099            used_class_members: vec![],
1100        }
1101    }
1102
1103    fn rule(
1104        manifests: &str,
1105        when: &[(&str, Value)],
1106        entries: Vec<ManifestSeedRule>,
1107    ) -> ManifestEntryRule {
1108        ManifestEntryRule {
1109            manifests: manifests.to_string(),
1110            format: ManifestFormat::Jsonc,
1111            when: conditions(when),
1112            entries,
1113        }
1114    }
1115
1116    fn write_manifest(root: &Path, rel: &str, body: &str) {
1117        let p = root.join(rel);
1118        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1119        std::fs::write(p, body).unwrap();
1120    }
1121
1122    #[cfg(unix)]
1123    fn symlink_file(target: &Path, link: &Path) {
1124        std::os::unix::fs::symlink(target, link).expect("create file symlink");
1125    }
1126
1127    #[cfg(windows)]
1128    fn symlink_file(target: &Path, link: &Path) {
1129        std::os::windows::fs::symlink_file(target, link).expect("create file symlink");
1130    }
1131
1132    #[test]
1133    fn manifest_symlinks_must_target_regular_files_inside_root() {
1134        let dir = tempfile::tempdir().expect("create project");
1135        let outside = tempfile::tempdir().expect("create outside dir");
1136        let root = dir.path();
1137        let targets = root.join("targets");
1138        let plugins = root.join("plugins");
1139        std::fs::create_dir_all(&targets).unwrap();
1140        std::fs::create_dir_all(&plugins).unwrap();
1141        std::fs::write(targets.join("inside.jsonc"), r#"{"type":"plugin"}"#).unwrap();
1142        std::fs::write(outside.path().join("outside.jsonc"), r#"{"type":"plugin"}"#).unwrap();
1143
1144        symlink_file(
1145            &targets.join("inside.jsonc"),
1146            &plugins.join("inside-kibana.jsonc"),
1147        );
1148        symlink_file(
1149            &outside.path().join("outside.jsonc"),
1150            &plugins.join("outside-kibana.jsonc"),
1151        );
1152        symlink_file(
1153            &targets.join("missing.jsonc"),
1154            &plugins.join("broken-kibana.jsonc"),
1155        );
1156
1157        let matcher = globset::Glob::new("**/*-kibana.jsonc")
1158            .unwrap()
1159            .compile_matcher();
1160        let paths = discover_manifest_paths(root, &matcher);
1161        let relative: Vec<String> = paths
1162            .iter()
1163            .filter_map(|path| root_relative_forward_slash(path, root))
1164            .collect();
1165
1166        assert_eq!(relative, vec!["plugins/inside-kibana.jsonc"]);
1167    }
1168
1169    fn kinds(reports: &[RuleReport]) -> Vec<WarningKind> {
1170        reports
1171            .iter()
1172            .flat_map(|r| r.warnings.iter().map(|w| w.kind))
1173            .collect()
1174    }
1175
1176    #[test]
1177    fn check_reports_matched_manifests_when_gate_and_seeded_entries() {
1178        let dir = tempfile::tempdir().unwrap();
1179        let root = dir.path();
1180        write_manifest(
1181            root,
1182            "plugins/alpha/kibana.jsonc",
1183            r#"{"type":"plugin","plugin":{"browser":true,"server":true}}"#,
1184        );
1185        write_manifest(
1186            root,
1187            "plugins/beta/kibana.jsonc",
1188            r#"{"type":"plugin","plugin":{"browser":true,"server":false}}"#,
1189        );
1190        let ext = plugin_with(vec![rule(
1191            "**/kibana.jsonc",
1192            &[("type", Value::String("plugin".into()))],
1193            vec![
1194                seed(
1195                    "public/index.{ts,tsx}",
1196                    &[("plugin.browser", Value::Bool(true))],
1197                ),
1198                seed(
1199                    "server/index.{ts,tsx}",
1200                    &[("plugin.server", Value::Bool(true))],
1201                ),
1202            ],
1203        )]);
1204
1205        let reports = check_manifest_entries(&ext, root);
1206        assert_eq!(reports.len(), 1);
1207        let report = &reports[0];
1208        assert!(
1209            report.warnings.is_empty(),
1210            "clean plugin, got {:?}",
1211            report.warnings
1212        );
1213        // manifests_matched is sorted (agents diff across runs).
1214        assert_eq!(
1215            report.manifests_matched,
1216            vec![
1217                "plugins/alpha/kibana.jsonc".to_string(),
1218                "plugins/beta/kibana.jsonc".to_string()
1219            ]
1220        );
1221
1222        let beta = report
1223            .matched
1224            .iter()
1225            .find(|m| m.path == "plugins/beta/kibana.jsonc")
1226            .expect("beta matched");
1227        assert!(beta.when_passed);
1228        assert!(beta.seeded.iter().any(|s| s.contains("beta/public/index")));
1229        assert!(
1230            !beta.seeded.iter().any(|s| s.contains("server/index")),
1231            "beta server:false must not seed the server entry, got {:?}",
1232            beta.seeded
1233        );
1234    }
1235
1236    #[test]
1237    fn manifests_glob_single_star_stays_within_one_segment() {
1238        let dir = tempfile::tempdir().unwrap();
1239        let root = dir.path();
1240        write_manifest(root, "plugins/alpha/kibana.jsonc", r#"{"type":"plugin"}"#);
1241        write_manifest(
1242            root,
1243            "plugins/group/beta/kibana.jsonc",
1244            r#"{"type":"plugin"}"#,
1245        );
1246        let ext = plugin_with(vec![rule(
1247            "plugins/*/kibana.jsonc",
1248            &[],
1249            vec![seed("public/index.ts", &[])],
1250        )]);
1251
1252        let reports = check_manifest_entries(&ext, root);
1253        assert_eq!(
1254            reports[0].manifests_matched,
1255            vec!["plugins/alpha/kibana.jsonc".to_string()]
1256        );
1257    }
1258
1259    #[test]
1260    fn check_warns_manifests_matched_none() {
1261        let dir = tempfile::tempdir().unwrap();
1262        let ext = plugin_with(vec![rule(
1263            "**/nonexistent.jsonc",
1264            &[],
1265            vec![seed("public/index.ts", &[])],
1266        )]);
1267        let reports = check_manifest_entries(&ext, dir.path());
1268        assert!(kinds(&reports).contains(&WarningKind::ManifestsMatchedNone));
1269        assert_eq!(
1270            reports[0].warnings[0].glob.as_deref(),
1271            Some("**/nonexistent.jsonc")
1272        );
1273    }
1274
1275    #[test]
1276    fn check_warns_field_path_unresolved_on_typo() {
1277        let dir = tempfile::tempdir().unwrap();
1278        let root = dir.path();
1279        write_manifest(
1280            root,
1281            "plugins/alpha/kibana.jsonc",
1282            r#"{"type":"plugin","plugin":{"browser":true}}"#,
1283        );
1284        let ext = plugin_with(vec![rule(
1285            "**/kibana.jsonc",
1286            &[("type", Value::String("plugin".into()))],
1287            // typo: plugin.extarPublicDirs does not exist
1288            vec![seed("${plugin.extarPublicDirs}/index.ts", &[])],
1289        )]);
1290        let reports = check_manifest_entries(&ext, root);
1291        let warn = reports[0]
1292            .warnings
1293            .iter()
1294            .find(|w| w.kind == WarningKind::FieldPathUnresolved)
1295            .expect("field-path-unresolved warning");
1296        assert_eq!(warn.field_path.as_deref(), Some("plugin.extarPublicDirs"));
1297    }
1298
1299    #[test]
1300    fn check_reports_interpolation_limits_without_partial_seeding() {
1301        let dir = tempfile::tempdir().unwrap();
1302        let root = dir.path();
1303        let values = (0..=MAX_MANIFEST_FIELD_VALUES)
1304            .map(|index| index.to_string())
1305            .collect::<Vec<_>>();
1306        write_manifest(
1307            root,
1308            "plugins/alpha/manifest.json",
1309            &serde_json::json!({ "entries": values }).to_string(),
1310        );
1311        let ext = plugin_with(vec![rule(
1312            "**/manifest.json",
1313            &[],
1314            vec![seed("static.ts", &[]), seed("${entries}/index.ts", &[])],
1315        )]);
1316
1317        let reports = check_manifest_entries(&ext, root);
1318        let warning = reports[0]
1319            .warnings
1320            .iter()
1321            .find(|warning| warning.kind == WarningKind::FieldValuesLimitExceeded)
1322            .expect("field-values-limit-exceeded warning");
1323        assert_eq!(warning.field_path.as_deref(), Some("entries"));
1324        assert_eq!(
1325            warning.manifest.as_deref(),
1326            Some("plugins/alpha/manifest.json")
1327        );
1328        assert_eq!(
1329            warning.kind.expansion_limit(),
1330            Some(MAX_MANIFEST_FIELD_VALUES)
1331        );
1332        assert_eq!(
1333            reports[0].matched[0].seeded,
1334            vec!["plugins/alpha/static.ts"],
1335            "a limited template must not suppress valid sibling seeds"
1336        );
1337    }
1338
1339    #[test]
1340    fn check_reports_wildcard_gate_limits_without_a_false_exclusion_warning() {
1341        let dir = tempfile::tempdir().unwrap();
1342        let root = dir.path();
1343        let items = std::iter::repeat_with(|| serde_json::json!({ "enabled": true }))
1344            .take(MAX_MANIFEST_FIELD_VALUES + 1)
1345            .collect::<Vec<_>>();
1346        write_manifest(
1347            root,
1348            "plugins/alpha/manifest.json",
1349            &serde_json::json!({ "items": items }).to_string(),
1350        );
1351        let ext = plugin_with(vec![rule(
1352            "**/manifest.json",
1353            &[("items[*].enabled", Value::Bool(true))],
1354            vec![seed("index.ts", &[])],
1355        )]);
1356
1357        let reports = check_manifest_entries(&ext, root);
1358        assert!(
1359            kinds(&reports).contains(&WarningKind::FieldValuesLimitExceeded),
1360            "wildcard fan-out must report its explicit bound"
1361        );
1362        assert!(
1363            !kinds(&reports).contains(&WarningKind::WhenExcludedAll),
1364            "an evaluation limit is not a false 'when' result"
1365        );
1366        assert!(!reports[0].matched[0].when_passed);
1367    }
1368
1369    #[test]
1370    fn check_warns_when_excluded_all() {
1371        let dir = tempfile::tempdir().unwrap();
1372        let root = dir.path();
1373        write_manifest(root, "plugins/alpha/kibana.jsonc", r#"{"type":"package"}"#);
1374        let ext = plugin_with(vec![rule(
1375            "**/kibana.jsonc",
1376            &[("type", Value::String("plugin".into()))],
1377            vec![seed("public/index.ts", &[])],
1378        )]);
1379        let reports = check_manifest_entries(&ext, root);
1380        assert!(kinds(&reports).contains(&WarningKind::WhenExcludedAll));
1381    }
1382
1383    #[test]
1384    fn check_warns_manifest_parse_failed_per_file() {
1385        let dir = tempfile::tempdir().unwrap();
1386        let root = dir.path();
1387        write_manifest(root, "plugins/good/kibana.jsonc", r#"{"type":"plugin"}"#);
1388        write_manifest(root, "plugins/bad/kibana.jsonc", "{ this is not valid json");
1389        let ext = plugin_with(vec![rule(
1390            "**/kibana.jsonc",
1391            &[("type", Value::String("plugin".into()))],
1392            vec![seed("public/index.ts", &[])],
1393        )]);
1394        let reports = check_manifest_entries(&ext, root);
1395        let warn = reports[0]
1396            .warnings
1397            .iter()
1398            .find(|w| w.kind == WarningKind::ManifestParseFailed)
1399            .expect("manifest-parse-failed warning");
1400        // carries the offending file, not just the glob (agents read the slot).
1401        assert_eq!(warn.manifest.as_deref(), Some("plugins/bad/kibana.jsonc"));
1402    }
1403
1404    #[test]
1405    fn check_output_is_deterministic_across_walk_order() {
1406        let dir = tempfile::tempdir().unwrap();
1407        let root = dir.path();
1408        // Names chosen so raw readdir order is unlikely to be sorted.
1409        for name in ["mmm", "aaa", "zzz", "ccc"] {
1410            write_manifest(
1411                root,
1412                &format!("plugins/{name}/kibana.jsonc"),
1413                r#"{"type":"plugin"}"#,
1414            );
1415        }
1416        let ext = plugin_with(vec![rule(
1417            "**/kibana.jsonc",
1418            &[("type", Value::String("plugin".into()))],
1419            // escapes root -> one entry-outside-root warning per manifest.
1420            vec![seed("../../../../escape/index.ts", &[])],
1421        )]);
1422        let reports = check_manifest_entries(&ext, root);
1423        let r = &reports[0];
1424        // manifests_matched and the per-file warnings are sorted, not walk order.
1425        let mut sorted = r.manifests_matched.clone();
1426        sorted.sort();
1427        assert_eq!(
1428            r.manifests_matched, sorted,
1429            "manifests_matched must be sorted"
1430        );
1431        let warn_manifests: Vec<&str> = r
1432            .warnings
1433            .iter()
1434            .filter_map(|w| w.manifest.as_deref())
1435            .collect();
1436        let mut sorted_w = warn_manifests.clone();
1437        sorted_w.sort_unstable();
1438        assert_eq!(
1439            warn_manifests, sorted_w,
1440            "entry-outside-root warnings must be sorted"
1441        );
1442    }
1443
1444    #[test]
1445    fn check_warns_entry_outside_root() {
1446        let dir = tempfile::tempdir().unwrap();
1447        let root = dir.path();
1448        write_manifest(root, "plugins/alpha/kibana.jsonc", r#"{"type":"plugin"}"#);
1449        let ext = plugin_with(vec![rule(
1450            "**/kibana.jsonc",
1451            &[("type", Value::String("plugin".into()))],
1452            // escapes above root from plugins/alpha
1453            vec![seed("../../../../escape/index.ts", &[])],
1454        )]);
1455        let reports = check_manifest_entries(&ext, root);
1456        let warn = reports[0]
1457            .warnings
1458            .iter()
1459            .find(|w| w.kind == WarningKind::EntryOutsideRoot)
1460            .expect("entry-outside-root warning");
1461        assert!(warn.entry.as_deref().is_some_and(|e| e.contains("escape")));
1462        assert_eq!(warn.manifest.as_deref(), Some("plugins/alpha/kibana.jsonc"));
1463    }
1464}