Skip to main content

memstead_base/
source_scope.rs

1//! Source scope enumeration — the declaration-layer walk that turns a
2//! binding source's scope patterns (allow / deny globs over a medium,
3//! entity selectors over a graph) plus a binding's ingest-level deny
4//! paths into the set of artifacts the binding answers for, `S(D)`.
5//!
6//! Kernel, not loop: the anchors health axis enumerates a mem's source
7//! artifacts to report the unclaimed ones, and the facet read surface
8//! reports a scope's enumeration, so the walk lives beside the binding
9//! store it reads and never behind the maintenance loop that also
10//! consumes it. Moved here from `ingest::cursor` on 2026-09-10; the loop
11//! reaches these items through `ingest::cursor`'s re-exports.
12
13use std::path::{Component, Path, PathBuf};
14
15use globset::{Glob, GlobSet, GlobSetBuilder};
16
17use crate::Engine;
18use crate::pipeline::{MediumType, PatternMode, Source};
19
20/// Lexically normalize a path — resolve `.` and `..` without touching the
21/// filesystem (no symlink resolution), matching Node's `path.resolve` on an
22/// already-absolute path.
23pub fn normalize_lexical(path: &Path) -> PathBuf {
24    let mut out: Vec<Component> = Vec::new();
25    for comp in path.components() {
26        match comp {
27            Component::CurDir => {}
28            Component::ParentDir => match out.last() {
29                Some(Component::Normal(_)) => {
30                    out.pop();
31                }
32                Some(Component::RootDir | Component::Prefix(_)) => {}
33                _ => out.push(comp),
34            },
35            other => out.push(other),
36        }
37    }
38    out.iter().collect()
39}
40
41/// The relative path from `from` to `to` (both normalized), matching Node's
42/// `path.relative`.
43pub fn relative_path(from: &Path, to: &Path) -> PathBuf {
44    let from = normalize_lexical(from);
45    let to = normalize_lexical(to);
46    let from_comps: Vec<Component> = from.components().collect();
47    let to_comps: Vec<Component> = to.components().collect();
48    let mut common = 0;
49    while common < from_comps.len()
50        && common < to_comps.len()
51        && from_comps[common] == to_comps[common]
52    {
53        common += 1;
54    }
55    let mut result = PathBuf::new();
56    for _ in common..from_comps.len() {
57        result.push("..");
58    }
59    for comp in &to_comps[common..] {
60        result.push(comp.as_os_str());
61    }
62    result
63}
64
65/// The medium pointer resolved to an absolute base directory. Public
66/// so init-time surfaces (CLI `projection init`) can resolve a medium
67/// base exactly as the strategies do — e.g. to warn when it falls
68/// outside the workspace root.
69pub fn medium_base(pointer: &str, workspace_root: &Path) -> PathBuf {
70    if pointer.is_empty() {
71        workspace_root.to_path_buf()
72    } else {
73        normalize_lexical(&workspace_root.join(pointer))
74    }
75}
76
77/// Workspace-relative deny globs excluding the engine's own state from
78/// every strategy's input set. Unconditional and non-configurable: a
79/// binding can never legitimately model `.memstead/`,
80/// `.memstead.cache/`, or a mount's resolved storage location as
81/// source artifacts — an allow glob covering them does not admit them.
82/// The dot-directories key on their *names* (the names are the
83/// contract, and a foreign workspace's `.memstead/` is still engine
84/// state); the mount storage locations key on their *resolved* paths
85/// because their directory names are configurable. Fail-open on an
86/// unreadable mount list: the name-based excludes stay in force.
87pub fn engine_state_denies(workspace_root: &Path) -> Vec<String> {
88    use crate::workspace_store::{FileWorkspaceStore, WorkspaceStoreAdapter};
89
90    let mut denies: Vec<String> = vec![
91        ".memstead/**".to_string(),
92        ".memstead.cache/**".to_string(),
93        "**/.memstead/**".to_string(),
94        "**/.memstead.cache/**".to_string(),
95    ];
96    if let Ok(ws) = FileWorkspaceStore.load(workspace_root) {
97        for mount in &ws.mounts {
98            let dir: Option<PathBuf> = match &mount.storage {
99                crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
100                    gitdir.parent().map(Path::to_path_buf)
101                }
102                crate::workspace::MountStorage::Folder { path } => Some(path.clone()),
103                crate::workspace::MountStorage::Archive { path, .. } => {
104                    // A sealed archive is one file, not a tree.
105                    let rel = relative_path(workspace_root, &normalize_lexical(path));
106                    denies.push(rel.to_string_lossy().to_string());
107                    None
108                }
109                // No on-disk footprint to exclude.
110                crate::workspace::MountStorage::InMemory => None,
111            };
112            if let Some(dir) = dir {
113                let rel = relative_path(workspace_root, &normalize_lexical(&dir));
114                // A collapsed single-mem folder workspace stores the mem
115                // AT the workspace root — excluding `**` there would
116                // empty every denominator; skip it.
117                if !rel.as_os_str().is_empty() {
118                    denies.push(format!("{}/**", rel.to_string_lossy()));
119                }
120            }
121        }
122    }
123    denies
124}
125
126/// Build a [`GlobSet`] from glob patterns, or `None` if any pattern is
127/// malformed. The namespace the patterns are written in is the caller's
128/// business — scope patterns are source-relative, ingest denies
129/// workspace-relative.
130pub fn build_glob_set(patterns: &[&str]) -> Option<GlobSet> {
131    build_glob_set_reporting(patterns).0
132}
133
134/// [`build_glob_set`], plus the patterns that would not compile.
135///
136/// All-or-nothing was the old contract and it degraded silently in both
137/// directions: one malformed allow emptied the whole enumeration, and one
138/// malformed deny disabled every deny and inflated the set. Now the valid
139/// patterns still compile and the malformed ones come back by name, so the
140/// caller can state the partiality instead of computing over it.
141/// `validate_binding` refuses a malformed scope pattern outright; this path
142/// carries records written before that gate existed.
143pub fn build_glob_set_reporting(patterns: &[&str]) -> (Option<GlobSet>, Vec<String>) {
144    let mut builder = GlobSetBuilder::new();
145    let mut malformed = Vec::new();
146    let mut any = false;
147    for pattern in patterns {
148        match Glob::new(pattern) {
149            Ok(g) => {
150                builder.add(g);
151                any = true;
152            }
153            Err(_) => malformed.push((*pattern).to_string()),
154        }
155    }
156    let set = if any { builder.build().ok() } else { None };
157    (set, malformed)
158}
159
160/// Enumerate the workspace-relative file paths a primary source's facet scope
161/// selects — the `mtime` strategy's input set. Mirrors the plugin's
162/// `enumerateFacetFiles`: the path-shaped mediums (`codebase` / `filesystem` /
163/// `git` — a git source's artifacts are paths pinned at a commit, so the walk
164/// is identical and only the anchor namespace differs); the facet's
165/// allow globs minus its deny globs, evaluated over the medium's directory
166/// tree. Returns a sorted, de-duplicated list. An unscoped facet (no allows)
167/// yields an empty list here — but callers must not treat that as signal: the
168/// strategy layer (`compute_mtime_slice` / `current_primary_token`) refuses
169/// an unscoped facet via `facet_unscoped` *before* enumerating, so the empty
170/// list is only ever reached for a genuinely-empty scoped enumeration.
171///
172/// ## Scope patterns are SOURCE-relative
173///
174/// A facet's own `scope` patterns resolve against the source's **pointer** —
175/// the same base the walk starts from, and the same convention the anchor
176/// artifact decision already ratified for every other surface around a
177/// binding. It is also what the rendered brief teaches, printing the pointer
178/// and the allow list directly beneath it.
179///
180/// Until 2026-08-27 the walk honoured the pointer and then matched each
181/// candidate by its *workspace*-relative path, with no join. The two readings
182/// coincide only for an empty pointer (the shape the scaffolder writes, and
183/// the only shape the enumeration test covered), which is why the defect stayed
184/// invisible: under a non-empty pointer a prefix-anchored pattern or a bare
185/// literal matched nothing, a `**`-prefixed pattern matched regardless, and a
186/// scope mixing the two produced a silently truncated denominator that every
187/// coverage figure was then computed over. [`scope_migration_notes`] names the
188/// patterns a binding still has in the old dialect.
189///
190/// `deny_paths` are the ingest-level denies (`ResolvedIngest::deny_paths`),
191/// applied on top of the facet's own scope denies. These stay
192/// **workspace-relative** — deliberately, and it is not a second dialect for
193/// the same thing: an ingest deny spans every source in the binding, so it has
194/// no single pointer to be relative to, and the git strategy pushes the same
195/// entries down as workspace-rooted `:(glob,exclude)` pathspecs. Scope is
196/// per-source and source-relative; ingest denies are per-binding and
197/// workspace-relative. Passing `&[]` yields the facet-scope-only behaviour.
198pub fn enumerate_facet_files(
199    source: &Source,
200    deny_paths: &[String],
201    workspace_root: &Path,
202) -> Vec<String> {
203    enumerate_facet_files_reported(source, deny_paths, workspace_root).files
204}
205
206/// [`enumerate_facet_files`], carrying what the enumeration could not speak
207/// for: patterns that would not compile, and patterns still in the retired
208/// workspace-relative dialect. Any surface that reduces the set to a figure
209/// must consult [`ScopeEnumeration::is_partial`] first.
210pub fn enumerate_facet_files_reported(
211    source: &Source,
212    deny_paths: &[String],
213    workspace_root: &Path,
214) -> ScopeEnumeration {
215    if !matches!(
216        source.medium_type,
217        MediumType::Codebase | MediumType::Filesystem | MediumType::Git
218    ) {
219        return ScopeEnumeration::default();
220    }
221    let legacy_dialect = scope_migration_notes(source);
222    let mut allows: Vec<&str> = Vec::new();
223    let mut scope_denies: Vec<&str> = Vec::new();
224    for rule in &source.scope {
225        match rule.mode {
226            PatternMode::Allow => allows.push(&rule.path),
227            PatternMode::Deny => scope_denies.push(&rule.path),
228        }
229    }
230    // Ingest deny_paths deny on top of the facet's own denies, in the
231    // workspace-relative grammar — the same entries the git strategy resolves
232    // as exclude pathspecs, so deny enforcement is strategy-invariant. They are
233    // matched against the candidate's workspace-relative path, NOT its
234    // source-relative one: an ingest deny spans every source in the binding.
235    let mut ws_denies: Vec<&str> = deny_paths.iter().map(String::as_str).collect();
236    // Engine self-exclusion — unconditional, below configuration; the
237    // git strategy pushes the same set as exclude pathspecs so the
238    // denominator stays strategy-invariant.
239    let forced = engine_state_denies(workspace_root);
240    for f in &forced {
241        ws_denies.push(f);
242    }
243    if allows.is_empty() {
244        return ScopeEnumeration {
245            legacy_dialect,
246            ..Default::default()
247        };
248    }
249    // Malformed patterns no longer take the whole set with them: the valid
250    // ones compile, the bad ones come back by name, and the caller states the
251    // partiality. A malformed ALLOW leaves the denominator short; a malformed
252    // DENY leaves it long. Either way the figure over it is not the answer.
253    let (allow_set, mut malformed) = build_glob_set_reporting(&allows);
254    let (scope_deny_set, deny_malformed) = build_glob_set_reporting(&scope_denies);
255    malformed.extend(deny_malformed);
256    // The ingest-level denies go through the SAME resolver the path-check
257    // command answers with — glob plus the literal-base directory-prefix rule
258    // plus the malformed-entry fallback — so a path denied at the hook can
259    // never be counted in the denominator. Sharing the glob library alone left
260    // the two disagreeing on exactly those extra rules.
261    let ws_oracle = crate::check_path::DenyOracle::new(
262        &ws_denies
263            .iter()
264            .map(|d| (*d).to_string())
265            .collect::<Vec<_>>(),
266    );
267    let Some(allow_set) = allow_set else {
268        return ScopeEnumeration {
269            malformed,
270            legacy_dialect,
271            ..Default::default()
272        };
273    };
274
275    // Walk the medium's directory tree. A candidate is matched twice, in two
276    // namespaces: the facet's own scope patterns against its SOURCE-relative
277    // path (relative to the medium base below), the ingest-level denies
278    // against its workspace-relative one. The returned paths stay
279    // workspace-relative — that is the namespace every consumer of this list
280    // speaks. VCS internals are never source artifacts — they are pruned here
281    // so `.git/**` plumbing cannot enter `S(D)`, matching the git strategy
282    // (whose diffs never name `.git` files).
283    let base = medium_base(&source.pointer, workspace_root);
284    // Directory pruning by allow-prefix: a directory is entered only when
285    // some allow pattern could still match beneath it. Each pattern
286    // contributes its longest literal leading segment run (up to the first
287    // segment carrying a glob metacharacter); a directory whose segments
288    // diverge from every pattern's literal prefix can contain no match, so
289    // the walk never descends into it. A pattern that begins with a glob
290    // segment (`**/*.rs`) contributes the empty prefix and keeps the full
291    // walk — behaviour is unchanged for unanchored scopes. This is what
292    // keeps a broad-pointer facet (`..` with `dev/**/*.md`) from stat-walking
293    // every build tree and node_modules in the repository on each
294    // enumeration (status tokens, verify S(D), sync briefs all pass here).
295    let allow_prefixes: Vec<Vec<String>> = allows.iter().map(|p| glob_literal_prefix(p)).collect();
296    let mut out: Vec<String> = Vec::new();
297    let mut stack = vec![base.clone()];
298    while let Some(dir) = stack.pop() {
299        let Ok(entries) = std::fs::read_dir(&dir) else {
300            continue;
301        };
302        for entry in entries.flatten() {
303            let Ok(file_type) = entry.file_type() else {
304                continue;
305            };
306            let path = entry.path();
307            if file_type.is_dir() {
308                let skip = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
309                    // VCS internals and engine state are never source
310                    // artifacts — pruning here saves the walk; the
311                    // forced deny globs enforce the same exclusion for
312                    // anything that still slips into a candidate list.
313                    VCS_INTERNAL_DIRS.contains(&n) || n == ".memstead" || n == ".memstead.cache"
314                });
315                if !skip {
316                    let dir_src_rel = relative_path(&base, &normalize_lexical(&path))
317                        .to_string_lossy()
318                        .to_string();
319                    if allow_could_match_under(&allow_prefixes, &dir_src_rel) {
320                        stack.push(path);
321                    }
322                }
323            } else if file_type.is_file() {
324                let normalized = normalize_lexical(&path);
325                let rel = relative_path(workspace_root, &normalized)
326                    .to_string_lossy()
327                    .to_string();
328                let src_rel = relative_path(&base, &normalized)
329                    .to_string_lossy()
330                    .to_string();
331                let denied = scope_deny_set
332                    .as_ref()
333                    .is_some_and(|d| d.is_match(&src_rel))
334                    || ws_oracle.is_denied(&rel);
335                if allow_set.is_match(&src_rel) && !denied {
336                    out.push(rel);
337                }
338            }
339        }
340    }
341    out.sort();
342    out.dedup();
343    ScopeEnumeration {
344        files: out,
345        malformed,
346        legacy_dialect,
347    }
348}
349
350/// The longest run of leading path segments in a glob pattern that carry no
351/// glob metacharacter — the literal region a match must live under. `dev/**/
352/// *.md` → `["dev"]`; `VISION.md` → `["VISION.md"]`; `**/*.rs` → `[]`.
353pub fn glob_literal_prefix(pattern: &str) -> Vec<String> {
354    pattern
355        .split('/')
356        .take_while(|seg| {
357            !seg.chars()
358                .any(|c| matches!(c, '*' | '?' | '[' | ']' | '{' | '}'))
359        })
360        .map(str::to_string)
361        .collect()
362}
363
364/// Whether any allow pattern could match a file somewhere under the
365/// directory at `dir_rel` (source-relative). True when, for some pattern's
366/// literal prefix, the directory's segments and the prefix agree over their
367/// common length: the directory is either an ancestor of the literal region
368/// (the walk must pass through it) or inside the pattern's glob region. An
369/// empty prefix (pattern starts with a glob segment) matches every
370/// directory — no pruning for unanchored scopes.
371pub fn allow_could_match_under(prefixes: &[Vec<String>], dir_rel: &str) -> bool {
372    let dir_segs: Vec<&str> = dir_rel.split('/').filter(|s| !s.is_empty()).collect();
373    prefixes.iter().any(|prefix| {
374        let n = dir_segs.len().min(prefix.len());
375        dir_segs[..n]
376            .iter()
377            .zip(prefix[..n].iter())
378            .all(|(d, p)| *d == p.as_str())
379    })
380}
381
382/// What an enumeration of a source's scope selected, and what it could not
383/// speak for.
384///
385/// The rule this serves: a surface does not report a figure over
386/// state it did not examine. A coverage percentage computed over a denominator
387/// that silently lost patterns is exactly that figure, so the partiality
388/// travels with the set rather than being discarded at the seam.
389#[derive(Debug, Clone, Default, PartialEq, Eq)]
390pub struct ScopeEnumeration {
391    /// The workspace-relative artifact paths the scope selected.
392    pub files: Vec<String>,
393    /// Scope patterns that would not compile, by name. Their share of the
394    /// population is unknown, so any enumeration carrying one is partial.
395    pub malformed: Vec<String>,
396    /// Scope patterns still written in the retired workspace-relative
397    /// dialect — reported so an author is told before a pattern's meaning
398    /// changes, never after.
399    pub legacy_dialect: Vec<ScopePatternNote>,
400}
401
402impl ScopeEnumeration {
403    /// Whether this enumeration is known to be incomplete. A partial
404    /// enumeration must not be reduced to a percentage: the denominator is
405    /// not the population.
406    ///
407    /// BOTH causes count. A malformed pattern was skipped, so its share never
408    /// entered the walk; a pattern still in the retired workspace-relative
409    /// dialect selects nothing under the pointer join, so its share is
410    /// likewise absent. The second is the more dangerous of the two, because a
411    /// MIXED scope still enumerates and the surviving subset looks like a
412    /// population.
413    pub fn is_partial(&self) -> bool {
414        !self.malformed.is_empty() || !self.legacy_dialect.is_empty()
415    }
416
417    /// Why this enumeration is incomplete, naming the offending patterns, or
418    /// `None` when it is whole.
419    pub fn partiality_reason(&self) -> Option<String> {
420        let mut causes = Vec::new();
421        if !self.malformed.is_empty() {
422            causes.push(format!(
423                "scope pattern(s) that would not compile were skipped: {}",
424                self.malformed.join(", ")
425            ));
426        }
427        if !self.legacy_dialect.is_empty() {
428            causes.push(format!(
429                "scope pattern(s) are still written against the workspace root rather than the \
430                 source pointer, so they select nothing under the pointer join: {}",
431                self.legacy_dialect
432                    .iter()
433                    .map(|n| n.pattern.as_str())
434                    .collect::<Vec<_>>()
435                    .join(", ")
436            ));
437        }
438        (!causes.is_empty()).then(|| causes.join("; "))
439    }
440}
441
442/// One scope pattern still written in the retired workspace-relative dialect.
443///
444/// Emitted by [`scope_migration_notes`] so a binding author is told BEFORE a
445/// pattern's meaning changes, never after. The rule this serves is the
446/// plain one: a surface does not quietly begin covering a different set.
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct ScopePatternNote {
449    /// The pattern as written in the binding record.
450    pub pattern: String,
451    /// Whether it is an allow or a deny rule.
452    pub deny: bool,
453    /// The pattern rewritten into the source-relative dialect, when the
454    /// rewrite is mechanical (the pattern begins with the source's pointer).
455    /// `None` when it is not — the author has to decide what they meant.
456    pub suggested: Option<String>,
457}
458
459/// Name every scope pattern of `source` that reads as the retired
460/// workspace-relative dialect: one that begins with the source's own pointer,
461/// so it selected artifacts before the 2026-08-27 join and selects nothing
462/// after it.
463///
464/// A pointer-less source has no dialect to migrate (the two readings coincide
465/// — which is exactly why the defect stayed invisible on the scaffolded path),
466/// so it returns empty. A `**`-prefixed pattern is prefix-free and matched
467/// under both readings, so it is not reported.
468pub fn scope_migration_notes(source: &Source) -> Vec<ScopePatternNote> {
469    let pointer = source.pointer.trim_end_matches('/');
470    if pointer.is_empty() {
471        return Vec::new();
472    }
473    let prefix = format!("{pointer}/");
474    source
475        .scope
476        .iter()
477        .filter(|r| !r.path.starts_with("**"))
478        .filter_map(|rule| {
479            let stripped = rule.path.strip_prefix(&prefix)?;
480            Some(ScopePatternNote {
481                pattern: rule.path.clone(),
482                deny: rule.mode == PatternMode::Deny,
483                suggested: (!stripped.is_empty()).then(|| stripped.to_string()),
484            })
485        })
486        .collect()
487}
488
489/// One parsed entry of a **graph** facet's scope — the entity-namespace
490/// counterpart of a path glob. A graph source selects entities, and an entity
491/// is not a path: matching id-shaped globs against `mem--slug` invites the
492/// "looks scoped, selects nothing" failure the dead-deny lint exists to catch
493/// on paths, so the vocabulary is explicit about which axis it selects on.
494///
495/// Grammar (the whole of it):
496///
497/// - `*` — every entity in the source mem
498/// - `type:<entity_type>` — entities of exactly that type
499/// - `id:<glob>` — entities whose full `mem--slug` id matches the glob
500///
501/// Anything else is refused at binding validation
502/// ([`crate::binding::validate_binding`]) rather than silently selecting
503/// nothing: a scope nothing interprets is the defect, not a permissible form.
504#[derive(Debug, Clone, PartialEq, Eq)]
505pub enum EntitySelector {
506    /// `*` — every entity in the mem.
507    All,
508    /// `type:<entity_type>` — exact type match.
509    Type(String),
510    /// `id:<glob>` — glob over the full entity id.
511    Id(String),
512}
513
514/// Parse one graph scope pattern. `None` for an unrecognised form — the
515/// caller decides whether that is a validation refusal (declaration time) or
516/// a skipped rule (run time, already refused at declaration).
517pub fn parse_entity_selector(pattern: &str) -> Option<EntitySelector> {
518    let pattern = pattern.trim();
519    if pattern == "*" {
520        return Some(EntitySelector::All);
521    }
522    if let Some(rest) = pattern.strip_prefix("type:") {
523        let rest = rest.trim();
524        if rest.is_empty() {
525            return None;
526        }
527        return Some(EntitySelector::Type(rest.to_string()));
528    }
529    if let Some(rest) = pattern.strip_prefix("id:") {
530        let rest = rest.trim();
531        if rest.is_empty() {
532            return None;
533        }
534        // A malformed glob is a refusal, not a rule that matches nothing.
535        Glob::new(rest).ok()?;
536        return Some(EntitySelector::Id(rest.to_string()));
537    }
538    None
539}
540
541/// Does `selector` select this entity?
542pub fn selector_matches(selector: &EntitySelector, id: &str, entity_type: &str) -> bool {
543    match selector {
544        EntitySelector::All => true,
545        EntitySelector::Type(t) => entity_type == t,
546        EntitySelector::Id(g) => Glob::new(g)
547            .ok()
548            .map(|glob| glob.compile_matcher().is_match(id))
549            .unwrap_or(false),
550    }
551}
552
553/// Enumerate the entity ids a **graph** source's facet scope selects — the
554/// graph medium's `S(D)`, the exact counterpart of [`enumerate_facet_files`]
555/// for a path medium. The source's `pointer` names the source mem; the store
556/// already holds every mounted mem's entities, so this is a filter over
557/// memory rather than any kind of walk.
558///
559/// Stubs are excluded: a stub is a placeholder the engine created for an
560/// unresolved reference, not an authored source artifact. Counting them would
561/// inflate the denominator with entities the source never wrote, making
562/// coverage look worse than it is for a reason no author can act on.
563///
564/// An unscoped facet (no allow rules) yields an empty list here — callers must
565/// not read that as "nothing in scope"; the strategy layer refuses an unscoped
566/// facet before reaching this, exactly as it does for the path mediums.
567pub fn enumerate_graph_entities(engine: &Engine, source: &Source) -> Vec<String> {
568    if source.medium_type != MediumType::Graph {
569        return Vec::new();
570    }
571    let mut allows: Vec<EntitySelector> = Vec::new();
572    let mut denies: Vec<EntitySelector> = Vec::new();
573    for rule in &source.scope {
574        // An unparseable rule is already a validation refusal; at run time it
575        // selects nothing rather than everything — a scope the engine cannot
576        // read must never widen reach.
577        let Some(sel) = parse_entity_selector(&rule.path) else {
578            continue;
579        };
580        match rule.mode {
581            PatternMode::Allow => allows.push(sel),
582            PatternMode::Deny => denies.push(sel),
583        }
584    }
585    if allows.is_empty() {
586        return Vec::new();
587    }
588    let mem = source.pointer.as_str();
589    let mut out: Vec<String> = Vec::new();
590    for entity in engine.store().all_entities() {
591        if entity.mem != mem || entity.stub {
592            continue;
593        }
594        let id = entity.id.0.as_str();
595        let ty = entity.entity_type.as_str();
596        if !allows.iter().any(|s| selector_matches(s, id, ty)) {
597            continue;
598        }
599        if denies.iter().any(|s| selector_matches(s, id, ty)) {
600            continue;
601        }
602        out.push(id.to_string());
603    }
604    out.sort();
605    out.dedup();
606    out
607}
608
609/// Enumerate one primary source's in-scope artifacts, whatever its medium —
610/// the single entry point every `S(D)` consumer uses. Path-shaped mediums
611/// (codebase / filesystem / git) walk the file tree; a graph source filters
612/// the source mem's entities. A medium the matrix marks non-enumerable
613/// yields nothing, and its callers render the non-enumerable basis rather
614/// than a denominator.
615///
616/// This exists because the enumeration bail was never in one place: five call
617/// sites each repeated the same loop over `enumerate_facet_files`, so teaching
618/// only the report about a new medium left the findings store, the refinement
619/// rotation, and the exclude membership gate empty-handed.
620pub fn enumerate_source_artifacts(
621    engine: &Engine,
622    source: &Source,
623    deny_paths: &[String],
624    workspace_root: &Path,
625) -> Vec<String> {
626    enumerate_source_artifacts_reported(engine, source, deny_paths, workspace_root).files
627}
628
629/// [`enumerate_source_artifacts`], carrying what the enumeration could not
630/// speak for. Any surface reducing `S(D)` to a figure consults
631/// [`ScopeEnumeration::is_partial`] first.
632pub fn enumerate_source_artifacts_reported(
633    engine: &Engine,
634    source: &Source,
635    deny_paths: &[String],
636    workspace_root: &Path,
637) -> ScopeEnumeration {
638    match source.medium_type {
639        MediumType::Codebase | MediumType::Filesystem | MediumType::Git => {
640            enumerate_facet_files_reported(source, deny_paths, workspace_root)
641        }
642        // Entity selectors are their own grammar with their own parser — a
643        // graph scope has no glob to malform and no pointer dialect to migrate.
644        MediumType::Graph => ScopeEnumeration {
645            files: enumerate_graph_entities(engine, source),
646            ..Default::default()
647        },
648        MediumType::Web => ScopeEnumeration::default(),
649    }
650}
651
652/// VCS metadata directories — never source artifacts. Pruned from source
653/// enumeration (`S(D)`, mtime slices, advance) and from the dead-deny scan.
654pub const VCS_INTERNAL_DIRS: &[&str] = &[".git", ".svn", ".hg"];