Skip to main content

verum_mappa/
lib.rs

1pub mod composer;
2pub mod dockerfile;
3pub mod endpoints;
4pub mod go_lang;
5pub mod html;
6pub mod java;
7pub mod java_web;
8pub mod javascript;
9pub mod kubernetes;
10pub mod laravel;
11pub mod php;
12pub mod python;
13pub mod resolver;
14pub mod rust_lang;
15pub mod terraform;
16
17use std::path::{Path, PathBuf};
18use std::time::Instant;
19
20use anyhow::Result;
21use rayon::prelude::*;
22
23use verum_nucleus::{
24    matchable_path, panic_guard, FileId, FileInfo, Finding, Framework, Ir, Language, SymbolId,
25};
26
27/// Deterministic string hash (FNV-1a) for symbol/file ids and source hashes.
28/// ahash - even `AHasher::default()` - is seeded per process, so ids and
29/// hashes built with it change on every run; two invocations of `verum` on
30/// the same tree could never be compared. FNV-1a is stable across runs,
31/// platforms, and builds.
32pub fn stable_hash(s: &str) -> u64 {
33    verum_nucleus::stable_hash(s)
34}
35
36/// Strip comments from source text before normalization so that comment
37/// wording never affects `normalized_hash` - two functions that differ only in
38/// comments must hash identically. String literals are preserved verbatim
39/// (a `//` inside `"http://..."` is not a comment).
40///
41/// `slash`: strip `//` and `/* */` (PHP/JS/TS/Rust/Go). Disabled for Python,
42/// where `//` is floor division. `hash`: strip `#` line comments (PHP/Python).
43/// `single_quote`: treat `'` as a string delimiter - off for Rust, where a
44/// `'a` lifetime would open a phantom string and swallow real code from the
45/// normalized hash.
46pub(crate) fn strip_comments(source: &str, slash: bool, hash: bool, single_quote: bool) -> String {
47    let chars: Vec<char> = source.chars().collect();
48    let mut out = String::with_capacity(source.len());
49    let mut i = 0;
50    while i < chars.len() {
51        let c = chars[i];
52        // Rust mode: consume a char literal ('x', '\n', '\u{2026}') as a unit
53        // so a quote inside it can't open a phantom string. Anything that
54        // doesn't close like a char literal is a lifetime - plain text.
55        if !single_quote && c == '\'' {
56            let lit_end = if i + 1 < chars.len() && chars[i + 1] == '\\' {
57                (i + 2..(i + 12).min(chars.len())).find(|&j| chars[j] == '\'')
58            } else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\'' {
59                Some(i + 2)
60            } else {
61                None
62            };
63            if let Some(end) = lit_end {
64                for ch in &chars[i..=end] {
65                    out.push(*ch);
66                }
67                i = end + 1;
68            } else {
69                out.push(c);
70                i += 1;
71            }
72            continue;
73        }
74        if c == '"' || (single_quote && c == '\'') || c == '`' {
75            let quote = c;
76            out.push(c);
77            i += 1;
78            while i < chars.len() {
79                let ch = chars[i];
80                out.push(ch);
81                i += 1;
82                if ch == '\\' && i < chars.len() {
83                    out.push(chars[i]);
84                    i += 1;
85                } else if ch == quote {
86                    break;
87                }
88            }
89            continue;
90        }
91        if slash && c == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
92            while i < chars.len() && chars[i] != '\n' {
93                i += 1;
94            }
95            continue;
96        }
97        if slash && c == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
98            i += 2;
99            while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
100                i += 1;
101            }
102            i = (i + 2).min(chars.len());
103            continue;
104        }
105        if hash && c == '#' {
106            while i < chars.len() && chars[i] != '\n' {
107                i += 1;
108            }
109            continue;
110        }
111        out.push(c);
112        i += 1;
113    }
114    out
115}
116
117/// Per-thread, per-language reuse of `tree_sitter::Parser` instances.
118///
119/// Constructing a `Parser` and loading a grammar for every file is pure
120/// overhead in the rayon parse loop - each worker thread only ever needs one
121/// parser per language. A parser given no old tree is stateless between
122/// `parse` calls, so reuse cannot change the resulting tree.
123pub(crate) mod parser_pool {
124    use std::cell::RefCell;
125
126    use tree_sitter::{Language, Parser, Tree};
127
128    thread_local! {
129        // Keyed by a static language name. At most a handful of entries, so a
130        // linear scan over a Vec beats hashing.
131        static PARSERS: RefCell<Vec<(&'static str, Parser)>> = const { RefCell::new(Vec::new()) };
132    }
133
134    /// Parse `source` with this thread's cached parser for `key`, creating
135    /// (and caching) one via `language` on first use per thread.
136    pub(crate) fn parse(
137        key: &'static str,
138        language: impl FnOnce() -> Language,
139        source: &str,
140    ) -> Option<Tree> {
141        PARSERS.with(|cell| {
142            let mut pool = cell.borrow_mut();
143            if let Some((_, parser)) = pool.iter_mut().find(|(k, _)| *k == key) {
144                return parser.parse(source, None);
145            }
146            let mut parser = Parser::new();
147            parser.set_language(&language()).ok()?;
148            let tree = parser.parse(source, None);
149            pool.push((key, parser));
150            tree
151        })
152    }
153}
154
155/// Configuration for the Atlas code mapper.
156#[derive(Debug, Clone)]
157pub struct AtlasConfig {
158    pub root: PathBuf,
159    pub language: Language,
160    pub exclude_patterns: Vec<String>,
161    pub cache_path: Option<PathBuf>,
162    pub delta_mode: bool,
163}
164
165impl Default for AtlasConfig {
166    fn default() -> Self {
167        Self {
168            root: PathBuf::from("."),
169            language: Language::Php,
170            exclude_patterns: Vec::new(),
171            cache_path: None,
172            delta_mode: false,
173        }
174    }
175}
176
177/// Atlas maps a codebase into the Verum IR.
178pub struct Atlas {
179    pub config: AtlasConfig,
180}
181
182/// Per-phase timing when VERUM_PROFILE is set in the environment, mirroring
183/// the pass timing in verum-lumen. Timing is observation only - it never
184/// influences what gets mapped.
185fn profile_phase(profile: bool, name: &str, since: Instant) -> Instant {
186    if profile {
187        eprintln!(
188            "  atlas {:<18} {:>6.2}s",
189            name,
190            since.elapsed().as_secs_f64()
191        );
192    }
193    Instant::now()
194}
195
196impl Atlas {
197    pub fn new(config: AtlasConfig) -> Self {
198        Self { config }
199    }
200
201    /// Build the IR from the configured root directory.
202    pub fn build(&self) -> Result<Ir> {
203        let start = Instant::now();
204        let profile = std::env::var("VERUM_PROFILE").is_ok();
205        let mut mark = Instant::now();
206
207        let (files, infra_files) = self.collect_all();
208        tracing::info!("Collected {} files", files.len());
209        mark = profile_phase(profile, "walk", mark);
210
211        // Each file parses under the panic guard: a malformed file that
212        // panics an extractor becomes a ParseFailure diagnostic instead of
213        // taking down the whole run (see `verum_nucleus::panic_guard`).
214        let partial_irs: Vec<Ir> = files
215            .par_iter()
216            .filter_map(|path| match panic_guard::catch(|| self.parse_file(path)) {
217                Some(Ok(ir)) => Some(ir),
218                Some(Err(e)) => {
219                    tracing::warn!("Failed to parse {}: {}", path.display(), e);
220                    None
221                }
222                None => {
223                    tracing::warn!("Parser panicked on {}; file isolated", path.display());
224                    Some(parse_failure_ir(path))
225                }
226            })
227            .collect();
228        mark = profile_phase(profile, "parse", mark);
229
230        let mut ir = partial_irs.into_iter().fold(Ir::new(), |mut acc, partial| {
231            acc.merge(partial);
232            acc
233        });
234        mark = profile_phase(profile, "merge", mark);
235
236        if !infra_files.is_empty() {
237            tracing::info!("Collected {} infrastructure files", infra_files.len());
238            let infra_irs: Vec<Ir> = infra_files
239                .par_iter()
240                .filter_map(
241                    |path| match panic_guard::catch(|| self.parse_infra_file(path)) {
242                        Some(Ok(partial)) => Some(partial),
243                        Some(Err(e)) => {
244                            tracing::warn!("Failed to parse infra file {}: {}", path.display(), e);
245                            None
246                        }
247                        None => {
248                            tracing::warn!(
249                                "Parser panicked on infra file {}; file isolated",
250                                path.display()
251                            );
252                            Some(parse_failure_ir(path))
253                        }
254                    },
255                )
256                .collect();
257            for partial in infra_irs {
258                ir.merge(partial);
259            }
260        }
261
262        let framework = composer::detect_framework(&self.config.root);
263        ir.framework = framework;
264
265        // Extract Laravel routes BEFORE the resolver pass so route-file call
266        // edges (controller references, provider bindings) get resolved too.
267        if ir.framework == Framework::Laravel {
268            laravel::extract_routes(&self.config.root, &mut ir);
269        }
270        mark = profile_phase(profile, "infra+framework", mark);
271
272        resolver::resolve(&mut ir);
273        mark = profile_phase(profile, "resolve", mark);
274
275        java_web::extract_routes(&mut ir);
276
277        // Promote wrapper calls (`request('/x')` through a project fetch/axios
278        // wrapper) to real HTTP calls before linking.
279        endpoints::promote_wrapper_calls(&mut ir);
280
281        // Stitch client HTTP calls to the routes that serve them, so the call
282        // graph spans the frontend/backend language boundary.
283        endpoints::link(&mut ir);
284
285        detect_entry_points(&mut ir);
286        profile_phase(profile, "link+entrypoints", mark);
287
288        let elapsed = start.elapsed();
289        ir.metadata.build_time_ms = elapsed.as_millis() as u64;
290        ir.metadata.total_symbols = ir.symbols.len();
291        ir.metadata.language = self.config.language.clone();
292        ir.metadata.verum_version = env!("CARGO_PKG_VERSION").to_string();
293
294        Ok(ir)
295    }
296
297    /// Collect source and infrastructure files (K8s YAML, Dockerfiles,
298    /// Terraform) in one walk over the tree.
299    ///
300    /// The walk respects the repository's own `.gitignore` and
301    /// `.git/info/exclude` - a gitignored `venv/` or scratch directory is not
302    /// shipped code, and mapping it both costs time and floods findings.
303    /// Machine-dependent rules (the user's global gitignore, ignore files
304    /// above the root) are deliberately NOT applied: the same tree must map
305    /// identically on every machine. Both result lists are sorted, so the
306    /// downstream merge order never depends on directory readdir order.
307    fn collect_all(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
308        let mut files = Vec::new();
309        let mut infra_files = Vec::new();
310
311        let walker = ignore::WalkBuilder::new(&self.config.root)
312            .follow_links(false)
313            // Keep dotfiles visible (`.eslintrc.js`, CI YAML under `.github/`
314            // were always mapped); only `.git` itself is pruned below.
315            .hidden(false)
316            .git_ignore(true)
317            .git_exclude(true)
318            // Machine state must not change findings.
319            .git_global(false)
320            .parents(false)
321            // `.ignore` files are tool-specific; only git's rules apply.
322            .ignore(false)
323            .require_git(true)
324            .filter_entry(|e| e.file_name() != ".git")
325            .build();
326
327        for entry in walker.filter_map(|e| e.ok()) {
328            let path = entry.path();
329
330            if !path.is_file() {
331                continue;
332            }
333
334            let path_str = matchable_path(path);
335            if path_str.contains("vendor/") || path_str.contains("node_modules/") {
336                continue;
337            }
338            if is_build_output(&path_str) {
339                continue;
340            }
341
342            let excluded = self
343                .config
344                .exclude_patterns
345                .iter()
346                .any(|pat| path_str.contains(pat.as_str()));
347            if excluded {
348                continue;
349            }
350
351            // Size cap, checked on metadata BEFORE any read: hand-written
352            // source is essentially never this large, so anything bigger is
353            // generated output or data that would cost parse time for zero
354            // signal.
355            if entry
356                .metadata()
357                .map(|m| m.len() > MAX_SOURCE_FILE_BYTES)
358                .unwrap_or(false)
359            {
360                continue;
361            }
362
363            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
364            if file_name == "Dockerfile"
365                || file_name.ends_with(".dockerfile")
366                || file_name.starts_with("Dockerfile.")
367            {
368                infra_files.push(path.to_path_buf());
369                continue;
370            }
371
372            let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
373                continue;
374            };
375
376            match ext {
377                "yaml" | "yml" => {
378                    // Only files that look like K8s manifests.
379                    if let Ok(content) = std::fs::read_to_string(path) {
380                        if content.contains("apiVersion:") && content.contains("kind:") {
381                            infra_files.push(path.to_path_buf());
382                        }
383                    }
384                    continue;
385                }
386                "tf" => {
387                    infra_files.push(path.to_path_buf());
388                    continue;
389                }
390                _ => {}
391            }
392
393            if language_for_extension(ext).is_none() {
394                continue;
395            }
396
397            // Blade templates carry a `.php` extension but are not standalone PHP
398            // source. Parsing them as PHP yields garbage symbols and false-positive
399            // security findings, so skip them from the source scan.
400            if is_blade_template(path) {
401                continue;
402            }
403
404            // Skip minified / generated bundles. These slip past exclude_paths when a
405            // build directory isn't excluded and otherwise flood dead-code findings
406            // with mangled single-letter identifiers.
407            if is_minified_or_generated(path) {
408                continue;
409            }
410
411            // A NUL byte in the head of the file marks it as binary data
412            // wearing a source extension; parsing it yields garbage symbols.
413            if looks_binary(path) {
414                continue;
415            }
416
417            files.push(path.to_path_buf());
418        }
419
420        files.sort();
421        infra_files.sort();
422        (files, infra_files)
423    }
424
425    fn parse_infra_file(&self, path: &Path) -> Result<Ir> {
426        let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
427
428        if file_name == "Dockerfile"
429            || file_name.ends_with(".dockerfile")
430            || file_name.starts_with("Dockerfile.")
431        {
432            return dockerfile::parse_file(path);
433        }
434
435        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
436            match ext {
437                "yaml" | "yml" => return kubernetes::parse_file(path),
438                "tf" => return terraform::parse_file(path),
439                _ => {}
440            }
441        }
442
443        anyhow::bail!("Unknown infrastructure file type: {}", path.display())
444    }
445
446    /// Parse a single file into a partial IR, detecting language from extension.
447    fn parse_file(&self, path: &Path) -> Result<Ir> {
448        // Test-only hook: this exact file name forces a panic inside the
449        // guarded parse loop so the isolation path is testable end to end
450        // without depending on a live parser bug. Compiled out of every
451        // non-test build.
452        #[cfg(test)]
453        if path.file_name().and_then(|n| n.to_str()) == Some("__verum_panic_hook__.rs") {
454            panic!("deliberate test-only parse panic");
455        }
456
457        let ext = path.extension().and_then(|e| e.to_str());
458
459        // HTML shares the JavaScript language tag (its inline scripts are JS),
460        // so it must be routed by extension before the language match.
461        if matches!(ext, Some("html") | Some("htm")) {
462            return html::parse_file(path);
463        }
464
465        let lang = ext
466            .and_then(language_for_extension)
467            .unwrap_or_else(|| self.config.language.clone());
468
469        match &lang {
470            Language::Php => php::parse_file(path),
471            Language::Python => python::parse_file(path),
472            Language::Rust => rust_lang::parse_file(path),
473            Language::Go => go_lang::parse_file(path),
474            Language::Java => java::parse_file(path),
475            Language::JavaScript => javascript::parse_file(path, false),
476            Language::TypeScript => javascript::parse_file(path, true),
477            _ => {
478                // Stub for other languages: just register the file
479                let mut ir = Ir::new();
480                let source = std::fs::read_to_string(path)?;
481                let line_count = source.lines().count() as u32;
482                let size_bytes = std::fs::metadata(path)?.len();
483
484                let file_id = FileId(crate::stable_hash(path.to_string_lossy().as_ref()));
485                ir.files.insert(
486                    path.to_path_buf(),
487                    FileInfo {
488                        id: file_id,
489                        path: path.to_path_buf(),
490                        language: lang,
491                        line_count,
492                        size_bytes,
493                        last_modified: 0,
494                        hash: 0,
495                        symbols: Vec::new(),
496                    },
497                );
498                ir.metadata.total_files += 1;
499                ir.metadata.total_lines += line_count as u64;
500
501                Ok(ir)
502            }
503        }
504    }
505}
506
507/// Files larger than this are skipped before reading (see
508/// [`Atlas::collect_all`]). 5 MiB: no hand-written source file reaches this;
509/// generated bundles, test corpora and data files do.
510const MAX_SOURCE_FILE_BYTES: u64 = 5 * 1024 * 1024;
511
512/// Maximum depth any recursive extractor walk descends into an AST (or a
513/// nested `use` group).
514///
515/// A hostile file - 10k nested parens, or a megabyte-long `1+1+...` chain -
516/// parses into a tree whose depth tracks the input, and recursive descent
517/// over it overflows the thread's stack. Unlike a panic, a stack overflow
518/// ABORTS the process: `catch_unwind` never runs, so the per-file panic
519/// guard cannot contain it. The walkers therefore stop descending at this
520/// fixed depth and skip anything deeper.
521///
522/// Deterministic by construction: the cutoff depends only on the input's
523/// tree shape, never on wall-clock time or stack headroom, so identical
524/// inputs truncate identically on every machine. Hand-written code nests a
525/// few dozen levels at most; 512 leaves an order of magnitude of margin
526/// while bounding worst-case stack use well inside the smallest (2 MiB)
527/// worker stacks.
528pub(crate) const MAX_RECURSION_DEPTH: usize = 512;
529
530/// The partial IR recording that `path`'s parse panicked and was isolated.
531/// No symbols are extracted (the parser cannot be trusted on this input), but
532/// the diagnostic rides the normal IR merge so the finding surfaces in every
533/// report. The message is a fixed phrase - never the panic payload - so
534/// identical inputs produce byte-identical findings (see
535/// [`Finding::parse_failure`]).
536fn parse_failure_ir(path: &Path) -> Ir {
537    let mut ir = Ir::new();
538    ir.parse_failures
539        .push(Finding::parse_failure(path, "parser panicked on this file"));
540    ir
541}
542
543/// True when the first 8 KiB contain a NUL byte - the standard cheap test for
544/// binary content (git uses the same heuristic). Read errors are not treated
545/// as binary; the parser will surface them.
546fn looks_binary(path: &Path) -> bool {
547    use std::io::Read;
548    let Ok(file) = std::fs::File::open(path) else {
549        return false;
550    };
551    let mut buf = [0u8; 8192];
552    let mut head = file.take(buf.len() as u64);
553    let Ok(n) = head.read(&mut buf) else {
554        return false;
555    };
556    buf[..n].contains(&0)
557}
558
559/// Returns true for Blade template files (`*.blade.php`).
560///
561/// `Path::extension` only sees the trailing `php`, so the full file name must be
562/// inspected to distinguish a Blade view from a plain PHP source file.
563fn is_blade_template(path: &Path) -> bool {
564    path.file_name()
565        .and_then(|n| n.to_str())
566        .map(|n| n.ends_with(".blade.php"))
567        .unwrap_or(false)
568}
569
570/// Heuristic detection of minified or generated assets that should not be
571/// analyzed as hand-written source.
572///
573/// Catches `*.min.js` / `*.min.css` by name, and otherwise samples the file: a
574/// very long maximum line length (typical of bundlers) with few newlines marks
575/// the file as generated.
576fn is_minified_or_generated(path: &Path) -> bool {
577    if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
578        if name.ends_with(".min.js") || name.ends_with(".min.css") {
579            return true;
580        }
581    }
582
583    // Only sample text assets we'd otherwise parse.
584    let is_scannable = path
585        .extension()
586        .and_then(|e| e.to_str())
587        .map(|e| matches!(e, "js" | "jsx" | "ts" | "tsx" | "css"))
588        .unwrap_or(false);
589    if !is_scannable {
590        return false;
591    }
592
593    // Sample up to 64 KiB; bundlers emit one enormous line.
594    if let Ok(file) = std::fs::File::open(path) {
595        use std::io::Read;
596        let mut buf = vec![0u8; 64 * 1024];
597        if let Ok(n) = file.take(64 * 1024).read(&mut buf[..]) {
598            let sample = String::from_utf8_lossy(&buf[..n]);
599            let longest_line = sample.lines().map(|l| l.len()).max().unwrap_or(0);
600            if longest_line > 5000 {
601                return true;
602            }
603        }
604    }
605
606    false
607}
608
609/// Compiled/generated output directories - a SvelteKit/Next/webpack `build/`
610/// or `dist/` holds bundled, minified output, not hand-written source, and
611/// analyzing it floods dead-code/duplicate/naming findings with mangled names.
612fn is_build_output(path_str: &str) -> bool {
613    const DIRS: &[&str] = &[
614        "/build/",
615        "/dist/",
616        "/.svelte-kit/",
617        "/.next/",
618        "/.nuxt/",
619        "/.output/",
620        "/out/",
621        "/coverage/",
622        "/.turbo/",
623    ];
624    DIRS.iter().any(|d| path_str.contains(d))
625}
626
627fn language_for_extension(ext: &str) -> Option<Language> {
628    match ext {
629        "php" => Some(Language::Php),
630        "rs" => Some(Language::Rust),
631        "js" | "jsx" => Some(Language::JavaScript),
632        "ts" | "tsx" => Some(Language::TypeScript),
633        "py" => Some(Language::Python),
634        "go" => Some(Language::Go),
635        "java" => Some(Language::Java),
636        "html" | "htm" => Some(Language::JavaScript),
637        _ => None,
638    }
639}
640
641/// Mark route-mapped controllers, framework-magic Laravel classes, and React
642/// page components as entry points.
643fn detect_entry_points(ir: &mut Ir) {
644    let mut entry_point_ids: Vec<SymbolId> = Vec::new();
645
646    // Route-mapped controllers are entry points
647    for route in &ir.routes {
648        if let Some(controller_id) = &route.controller {
649            entry_point_ids.push(*controller_id);
650        }
651    }
652
653    let is_laravel = ir.framework == Framework::Laravel;
654
655    for (id, sym) in &ir.symbols {
656        let path_str = matchable_path(&sym.file);
657
658        if path_str.contains("Controller")
659            && matches!(
660                sym.kind,
661                verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
662            )
663        {
664            entry_point_ids.push(*id);
665            continue;
666        }
667
668        if is_laravel {
669            if path_str.contains("/Providers/")
670                && matches!(
671                    sym.kind,
672                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
673                )
674            {
675                entry_point_ids.push(*id);
676                continue;
677            }
678            if path_str.contains("/Middleware/")
679                && matches!(
680                    sym.kind,
681                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
682                )
683            {
684                entry_point_ids.push(*id);
685                continue;
686            }
687            if path_str.contains("/Console/")
688                && matches!(
689                    sym.kind,
690                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
691                )
692            {
693                entry_point_ids.push(*id);
694                continue;
695            }
696            if (path_str.contains("/Listeners/") || path_str.contains("/Events/"))
697                && matches!(
698                    sym.kind,
699                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
700                )
701            {
702                entry_point_ids.push(*id);
703                continue;
704            }
705            if path_str.contains("/Jobs/")
706                && matches!(
707                    sym.kind,
708                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
709                )
710            {
711                entry_point_ids.push(*id);
712                continue;
713            }
714            if path_str.contains("/Notifications/")
715                && matches!(
716                    sym.kind,
717                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
718                )
719            {
720                entry_point_ids.push(*id);
721                continue;
722            }
723            // Models (accessors, mutators, scopes are called magically)
724            if path_str.contains("/Models/")
725                && matches!(
726                    sym.kind,
727                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
728                )
729            {
730                entry_point_ids.push(*id);
731                continue;
732            }
733            // Transformers (Fractal includes)
734            if path_str.contains("/Transformers/")
735                && matches!(
736                    sym.kind,
737                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
738                )
739            {
740                entry_point_ids.push(*id);
741                continue;
742            }
743            if path_str.contains("/Observers/")
744                && matches!(
745                    sym.kind,
746                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
747                )
748            {
749                entry_point_ids.push(*id);
750                continue;
751            }
752            if path_str.contains("/Policies/")
753                && matches!(
754                    sym.kind,
755                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
756                )
757            {
758                entry_point_ids.push(*id);
759                continue;
760            }
761            if path_str.contains("/Rules/")
762                && matches!(
763                    sym.kind,
764                    verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
765                )
766            {
767                entry_point_ids.push(*id);
768                continue;
769            }
770        }
771
772        // React: exported components under routers/ or pages/
773        if matches!(
774            sym.language,
775            verum_nucleus::Language::TypeScript | verum_nucleus::Language::JavaScript
776        ) && matches!(sym.visibility, verum_nucleus::Visibility::Public)
777            && (path_str.contains("/routers/") || path_str.contains("/pages/"))
778        {
779            entry_point_ids.push(*id);
780        }
781    }
782
783    for id in &entry_point_ids {
784        if let Some(sym) = ir.symbols.get_mut(id) {
785            sym.is_entry_point = true;
786        }
787    }
788
789    ir.entry_points.extend(entry_point_ids);
790}
791
792#[cfg(test)]
793mod panic_isolation_tests {
794    use super::*;
795
796    /// A scratch tree that removes itself when dropped, so a failing assert
797    /// never leaves litter in the system temp directory.
798    struct ScratchTree(PathBuf);
799
800    impl ScratchTree {
801        fn new(tag: &str) -> Self {
802            let dir = std::env::temp_dir().join(format!(
803                "verum_mappa_{}_{}_{}",
804                tag,
805                std::process::id(),
806                std::thread::current()
807                    .name()
808                    .unwrap_or("t")
809                    .replace("::", "_"),
810            ));
811            let _ = std::fs::remove_dir_all(&dir);
812            std::fs::create_dir_all(&dir).expect("create scratch dir");
813            Self(dir)
814        }
815    }
816
817    impl Drop for ScratchTree {
818        fn drop(&mut self) {
819            let _ = std::fs::remove_dir_all(&self.0);
820        }
821    }
822
823    #[test]
824    fn a_panicking_parse_is_isolated_and_reported() {
825        let tree = ScratchTree::new("panic_hook");
826        // The hook file trips the test-only panic in `parse_file`; the healthy
827        // neighbour proves the run continued past the isolated file.
828        std::fs::write(tree.0.join("__verum_panic_hook__.rs"), "fn broken() {}\n")
829            .expect("write hook file");
830        std::fs::write(
831            tree.0.join("healthy.rs"),
832            "pub fn fine() { helper(); }\nfn helper() {}\n",
833        )
834        .expect("write healthy file");
835
836        let ir = Atlas::new(AtlasConfig {
837            root: tree.0.clone(),
838            language: Language::Rust,
839            ..Default::default()
840        })
841        .build()
842        .expect("the run must complete despite the panicking file");
843
844        assert_eq!(
845            ir.parse_failures.len(),
846            1,
847            "exactly the hook file is isolated"
848        );
849        let failure = &ir.parse_failures[0];
850        assert_eq!(failure.kind, verum_nucleus::FindingKind::ParseFailure);
851        assert_eq!(failure.severity, verum_nucleus::Severity::Low);
852        assert!(
853            failure
854                .message
855                .starts_with("parser panicked on this file: "),
856            "fixed phrase, never the panic payload: {}",
857            failure.message
858        );
859        assert!(failure.message.ends_with("__verum_panic_hook__.rs"));
860        assert!(
861            !failure.message.contains("deliberate test-only"),
862            "the panic payload must not leak into the finding"
863        );
864        // The healthy file parsed normally.
865        assert!(
866            ir.symbols.values().any(|s| s.name == "fine"),
867            "the rest of the tree still maps"
868        );
869    }
870
871    #[test]
872    fn a_clean_tree_reports_no_parse_failures() {
873        let tree = ScratchTree::new("clean");
874        std::fs::write(tree.0.join("lib.rs"), "pub fn ok() {}\n").expect("write file");
875
876        let ir = Atlas::new(AtlasConfig {
877            root: tree.0.clone(),
878            language: Language::Rust,
879            ..Default::default()
880        })
881        .build()
882        .expect("clean tree builds");
883
884        assert!(ir.parse_failures.is_empty());
885    }
886}