Skip to main content

reflex/pulse/
map.rs

1//! Architecture map generation
2//!
3//! Produces dependency diagrams in mermaid or d2 format.
4//! Modules come from [`ModuleGraph`], the same source modules the site's Internals tab shows.
5
6use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, HashSet};
9
10use crate::cache::CacheManager;
11use crate::dependency::DependencyIndex;
12
13use super::build::modules::ModuleGraph;
14use super::extract::Corpus;
15
16/// One map node: a module of [`ModuleGraph`].
17#[derive(Debug, Clone)]
18pub struct ModuleDefinition {
19    /// Module path (e.g. "src", "src/parsers").
20    pub path: String,
21    /// 1 = top-level, 2 = a submodule.
22    pub tier: u8,
23    pub file_count: usize,
24}
25
26/// The source modules of the index (depth 2), without the root pseudo-module.
27fn detect_modules(cache: &CacheManager) -> Result<Vec<ModuleDefinition>> {
28    let corpus = Corpus::load(cache)?;
29    let graph = ModuleGraph::build(&corpus, 2, 1);
30    Ok(graph
31        .modules
32        .iter()
33        .filter(|m| !m.is_root())
34        .map(|m| ModuleDefinition {
35            path: m.id.as_str().to_string(),
36            tier: m.tier,
37            file_count: m.files.len(),
38        })
39        .collect())
40}
41
42/// Zoom level for the architecture map
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub enum MapZoom {
45    /// Whole-repo view: modules as nodes
46    Repo,
47    /// Single module view: files within module as nodes
48    Module(String),
49}
50
51/// Output format for the map
52#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
53pub enum MapFormat {
54    Mermaid,
55    D2,
56}
57
58impl std::str::FromStr for MapFormat {
59    type Err = anyhow::Error;
60    fn from_str(s: &str) -> Result<Self> {
61        match s.to_lowercase().as_str() {
62            "mermaid" => Ok(MapFormat::Mermaid),
63            "d2" => Ok(MapFormat::D2),
64            _ => anyhow::bail!("Unknown map format: {}. Supported: mermaid, d2", s),
65        }
66    }
67}
68
69/// Generate an architecture map
70pub fn generate_map(cache: &CacheManager, zoom: &MapZoom, format: MapFormat) -> Result<String> {
71    match zoom {
72        MapZoom::Repo => generate_repo_map(cache, format),
73        MapZoom::Module(module) => generate_module_map(cache, module, format),
74    }
75}
76
77fn generate_repo_map(cache: &CacheManager, format: MapFormat) -> Result<String> {
78    let db_path = cache.path().join("meta.db");
79    let conn = crate::cache::open_meta_db(&db_path)?;
80
81    let modules = detect_modules(cache)?;
82
83    // Build module info for node labels
84    let module_info: Vec<(String, usize)> = modules
85        .iter()
86        .map(|m| (m.path.clone(), m.file_count))
87        .collect();
88
89    // Get all file-level dependency edges
90    let mut stmt = conn.prepare(
91        "SELECT f1.path, f2.path
92         FROM import_edges e
93         JOIN files f1 ON e.src = f1.id
94         JOIN files f2 ON e.dst = f2.id",
95    )?;
96
97    let file_edges: Vec<(String, String)> = stmt
98        .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
99        .collect::<Result<Vec<_>, _>>()?;
100
101    // Aggregate file-level edges to module-level edges
102    let mut module_edges: HashMap<(String, String), usize> = HashMap::new();
103    for (src_file, tgt_file) in &file_edges {
104        let src_module = find_owning_module(src_file, &modules);
105        let tgt_module = find_owning_module(tgt_file, &modules);
106
107        if src_module != tgt_module {
108            *module_edges.entry((src_module, tgt_module)).or_insert(0) += 1;
109        }
110    }
111
112    let mut edges: Vec<(String, String, usize)> = module_edges
113        .into_iter()
114        .map(|((s, t), c)| (s, t, c))
115        .collect();
116    edges.sort_by_key(|a| std::cmp::Reverse(a.2));
117
118    // Get hotspots for highlighting
119    let deps_index = DependencyIndex::new(cache.clone());
120    let hotspots = deps_index.find_hotspots(Some(10), 5).unwrap_or_default();
121    let hotspot_modules: HashSet<String> = hotspots
122        .iter()
123        .filter_map(|(id, _)| {
124            deps_index
125                .get_file_paths(&[*id])
126                .ok()
127                .and_then(|paths| paths.get(id).cloned())
128                .map(|p| find_owning_module(&p, &modules))
129        })
130        .collect();
131
132    match format {
133        MapFormat::Mermaid => render_mermaid_repo(&module_info, &edges, &hotspot_modules),
134        MapFormat::D2 => render_d2_repo(&module_info, &edges, &hotspot_modules),
135    }
136}
137
138/// Find the most-specific module that owns a given file path
139fn find_owning_module(file_path: &str, modules: &[ModuleDefinition]) -> String {
140    let mut best_match = String::new();
141    let mut best_len = 0;
142
143    for module in modules {
144        let prefix = format!("{}/", module.path);
145        if file_path.starts_with(&prefix) && module.path.len() > best_len {
146            best_match = module.path.clone();
147            best_len = module.path.len();
148        }
149    }
150
151    if best_match.is_empty() {
152        file_path.split('/').next().unwrap_or("root").to_string()
153    } else {
154        best_match
155    }
156}
157
158fn generate_module_map(
159    cache: &CacheManager,
160    module_path: &str,
161    format: MapFormat,
162) -> Result<String> {
163    let db_path = cache.path().join("meta.db");
164    let conn = crate::cache::open_meta_db(&db_path)?;
165    let pattern = format!("{}/%", module_path);
166
167    // Get files in this module
168    let mut stmt = conn.prepare("SELECT id, path FROM files WHERE path LIKE ?1 ORDER BY path")?;
169    let files: Vec<(i64, String)> = stmt
170        .query_map([&pattern], |row| Ok((row.get(0)?, row.get(1)?)))?
171        .collect::<Result<Vec<_>, _>>()?;
172
173    // Get intra-module edges
174    let mut stmt = conn.prepare(
175        "SELECT f1.path, f2.path
176         FROM import_edges e
177         JOIN files f1 ON e.src = f1.id
178         JOIN files f2 ON e.dst = f2.id
179         WHERE f1.path LIKE ?1 AND f2.path LIKE ?1",
180    )?;
181    let edges: Vec<(String, String)> = stmt
182        .query_map([&pattern], |row| Ok((row.get(0)?, row.get(1)?)))?
183        .collect::<Result<Vec<_>, _>>()?;
184
185    match format {
186        MapFormat::Mermaid => render_mermaid_module(module_path, &files, &edges),
187        MapFormat::D2 => render_d2_module(module_path, &files, &edges),
188    }
189}
190
191/// Create a Mermaid-safe node ID with a prefix to avoid reserved word collisions.
192/// Mermaid v11 can choke on IDs that match internal keywords or contain certain patterns.
193fn sanitize_id(s: &str) -> String {
194    format!("m_{}", s.replace(['/', '.', '-', ' '], "_"))
195}
196
197fn render_mermaid_repo(
198    modules: &[(String, usize)],
199    edges: &[(String, String, usize)],
200    hotspot_modules: &HashSet<String>,
201) -> Result<String> {
202    let mut out = String::from("graph LR\n");
203
204    // Only emit modules that participate in at least one edge
205    let connected: HashSet<&str> = edges
206        .iter()
207        .flat_map(|(s, t, _)| [s.as_str(), t.as_str()])
208        .collect();
209
210    for (module, count) in modules {
211        if !connected.contains(module.as_str()) {
212            continue;
213        }
214        let id = sanitize_id(module);
215        out.push_str(&format!("  {}[\"{}/ ({} files)\"]\n", id, module, count));
216    }
217
218    out.push('\n');
219
220    // Track thick edges for linkStyle directives
221    let mut thick_edge_indices: Vec<usize> = Vec::new();
222    for (i, (src, tgt, count)) in edges.iter().enumerate() {
223        let src_id = sanitize_id(src);
224        let tgt_id = sanitize_id(tgt);
225        out.push_str(&format!("  {} -->|{}| {}\n", src_id, count, tgt_id));
226        if *count > 5 {
227            thick_edge_indices.push(i);
228        }
229    }
230
231    // Apply thick stroke to high-count edges via linkStyle
232    for idx in &thick_edge_indices {
233        out.push_str(&format!(
234            "  linkStyle {} stroke-width:3px,stroke:#a78bfa\n",
235            idx
236        ));
237    }
238
239    // High-contrast styling for dark theme
240    out.push_str("\n  classDef default fill:#1a1a2e,stroke:#a78bfa,color:#e0e0e0\n");
241    out.push_str("  classDef hotspot fill:#2a1030,stroke:#f472b6,color:#f472b6\n");
242    if !hotspot_modules.is_empty() {
243        for module in hotspot_modules {
244            if !connected.contains(module.as_str()) {
245                continue;
246            }
247            let id = sanitize_id(module);
248            out.push_str(&format!("  class {} hotspot\n", id));
249        }
250    }
251
252    Ok(out)
253}
254
255/// Generate a layered (top-to-bottom) architecture diagram with Tier 1 subgraphs containing Tier 2 children
256pub fn generate_layered_map(cache: &CacheManager, format: MapFormat) -> Result<String> {
257    let db_path = cache.path().join("meta.db");
258    let conn = crate::cache::open_meta_db(&db_path)?;
259    let modules = detect_modules(cache)?;
260
261    let module_info: Vec<(String, usize, u8)> = modules
262        .iter()
263        .map(|m| (m.path.clone(), m.file_count, m.tier))
264        .collect();
265
266    // Get module-level edges
267    let mut stmt = conn.prepare(
268        "SELECT f1.path, f2.path
269         FROM import_edges e
270         JOIN files f1 ON e.src = f1.id
271         JOIN files f2 ON e.dst = f2.id",
272    )?;
273    let file_edges: Vec<(String, String)> = stmt
274        .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
275        .collect::<Result<Vec<_>, _>>()?;
276
277    let mut module_edges: HashMap<(String, String), usize> = HashMap::new();
278    for (src_file, tgt_file) in &file_edges {
279        let src_module = find_owning_module(src_file, &modules);
280        let tgt_module = find_owning_module(tgt_file, &modules);
281        if src_module != tgt_module {
282            *module_edges.entry((src_module, tgt_module)).or_insert(0) += 1;
283        }
284    }
285
286    let mut edges: Vec<(String, String, usize)> = module_edges
287        .into_iter()
288        .map(|((s, t), c)| (s, t, c))
289        .collect();
290    edges.sort_by_key(|a| std::cmp::Reverse(a.2));
291
292    let deps_index = DependencyIndex::new(cache.clone());
293    let hotspots = deps_index.find_hotspots(Some(10), 5).unwrap_or_default();
294    let hotspot_modules: HashSet<String> = hotspots
295        .iter()
296        .filter_map(|(id, _)| {
297            deps_index
298                .get_file_paths(&[*id])
299                .ok()
300                .and_then(|paths| paths.get(id).cloned())
301                .map(|p| find_owning_module(&p, &modules))
302        })
303        .collect();
304
305    match format {
306        MapFormat::Mermaid => render_mermaid_layered(&module_info, &edges, &hotspot_modules),
307        MapFormat::D2 => render_d2_repo(
308            &module_info
309                .iter()
310                .map(|(p, c, _)| (p.clone(), *c))
311                .collect::<Vec<_>>(),
312            &edges,
313            &hotspot_modules,
314        ),
315    }
316}
317
318fn render_mermaid_layered(
319    modules: &[(String, usize, u8)],
320    edges: &[(String, String, usize)],
321    hotspot_modules: &HashSet<String>,
322) -> Result<String> {
323    let mut out = String::from("flowchart TB\n");
324
325    // Only emit modules that participate in at least one edge
326    let connected: HashSet<&str> = edges
327        .iter()
328        .flat_map(|(s, t, _)| [s.as_str(), t.as_str()])
329        .collect();
330
331    // Group Tier 2 modules under their Tier 1 parent
332    let tier1: Vec<&(String, usize, u8)> = modules.iter().filter(|m| m.2 == 1).collect();
333    let tier2: Vec<&(String, usize, u8)> = modules.iter().filter(|m| m.2 == 2).collect();
334
335    // Build proxy map: Tier 1 modules that become subgraphs get an inner proxy node.
336    // Mermaid v11 cannot target subgraph IDs with edges or classDef,
337    // so we create a real node inside the subgraph to receive those interactions.
338    let mut proxy_map: HashMap<String, String> = HashMap::new();
339
340    for t1 in &tier1 {
341        if !connected.contains(t1.0.as_str()) {
342            continue;
343        }
344        let t1_id = sanitize_id(&t1.0);
345        let children: Vec<&&(String, usize, u8)> = tier2
346            .iter()
347            .filter(|t2| {
348                t2.0.starts_with(&format!("{}/", t1.0)) && connected.contains(t2.0.as_str())
349            })
350            .collect();
351
352        if children.is_empty() {
353            // Standalone Tier 1 node (no subgraph needed)
354            out.push_str(&format!("  {}[\"{}/ ({} files)\"]\n", t1_id, t1.0, t1.1));
355        } else {
356            // Subgraph with proxy node for edges and styling
357            let proxy_id = format!("{}_self", t1_id);
358            proxy_map.insert(t1.0.clone(), proxy_id.clone());
359
360            out.push_str(&format!("  subgraph {} [\"{}/ \"]\n", t1_id, t1.0));
361            out.push_str(&format!(
362                "    {}[\"{}/ ({} files)\"]\n",
363                proxy_id, t1.0, t1.1
364            ));
365            for child in &children {
366                let child_id = sanitize_id(&child.0);
367                let short = child
368                    .0
369                    .strip_prefix(&format!("{}/", t1.0))
370                    .unwrap_or(&child.0);
371                out.push_str(&format!(
372                    "    {}[\"{}/ ({} files)\"]\n",
373                    child_id, short, child.1
374                ));
375            }
376            out.push_str("  end\n");
377        }
378    }
379
380    // Orphan Tier 2 modules (no matching Tier 1 parent)
381    for t2 in &tier2 {
382        if !connected.contains(t2.0.as_str()) {
383            continue;
384        }
385        let has_parent = tier1
386            .iter()
387            .any(|t1| t2.0.starts_with(&format!("{}/", t1.0)));
388        if !has_parent {
389            let id = sanitize_id(&t2.0);
390            out.push_str(&format!("  {}[\"{}/ ({} files)\"]\n", id, t2.0, t2.1));
391        }
392    }
393
394    out.push('\n');
395
396    // Track thick edges for linkStyle directives
397    // Resolve edge endpoints through proxy_map so edges target proxy nodes, not subgraphs
398    let mut thick_edge_indices: Vec<usize> = Vec::new();
399    for (i, (src, tgt, count)) in edges.iter().enumerate() {
400        let src_id = proxy_map
401            .get(src)
402            .cloned()
403            .unwrap_or_else(|| sanitize_id(src));
404        let tgt_id = proxy_map
405            .get(tgt)
406            .cloned()
407            .unwrap_or_else(|| sanitize_id(tgt));
408        out.push_str(&format!("  {} -->|{}| {}\n", src_id, count, tgt_id));
409        if *count > 5 {
410            thick_edge_indices.push(i);
411        }
412    }
413
414    // Apply thick stroke to high-count edges via linkStyle
415    for idx in &thick_edge_indices {
416        out.push_str(&format!(
417            "  linkStyle {} stroke-width:3px,stroke:#a78bfa\n",
418            idx
419        ));
420    }
421
422    // Styling — apply classDef to proxy nodes, not subgraph containers
423    out.push_str("\n  classDef default fill:#1a1a2e,stroke:#a78bfa,color:#e0e0e0\n");
424    out.push_str("  classDef hotspot fill:#2a1030,stroke:#f472b6,color:#f472b6\n");
425    for module in hotspot_modules {
426        if !connected.contains(module.as_str()) {
427            continue;
428        }
429        let id = proxy_map
430            .get(module)
431            .cloned()
432            .unwrap_or_else(|| sanitize_id(module));
433        out.push_str(&format!("  class {} hotspot\n", id));
434    }
435
436    Ok(out)
437}
438
439fn render_d2_repo(
440    modules: &[(String, usize)],
441    edges: &[(String, String, usize)],
442    hotspot_modules: &HashSet<String>,
443) -> Result<String> {
444    let mut out = String::new();
445
446    for (module, count) in modules {
447        let id = sanitize_id(module);
448        out.push_str(&format!("{}: \"{}/ ({} files)\"\n", id, module, count));
449        if hotspot_modules.contains(module) {
450            out.push_str(&format!("{}.style.fill: \"#ff6b6b\"\n", id));
451        }
452    }
453
454    out.push('\n');
455
456    for (src, tgt, count) in edges {
457        let src_id = sanitize_id(src);
458        let tgt_id = sanitize_id(tgt);
459        out.push_str(&format!("{} -> {}: {}\n", src_id, tgt_id, count));
460    }
461
462    Ok(out)
463}
464
465fn render_mermaid_module(
466    module_path: &str,
467    files: &[(i64, String)],
468    edges: &[(String, String)],
469) -> Result<String> {
470    let mut out = format!("graph LR\n  subgraph {}\n", module_path);
471
472    for (_, path) in files {
473        let id = sanitize_id(path);
474        let short_name = path.rsplit('/').next().unwrap_or(path);
475        out.push_str(&format!("    {}[\"{}\"]\n", id, short_name));
476    }
477
478    for (src, tgt) in edges {
479        let src_id = sanitize_id(src);
480        let tgt_id = sanitize_id(tgt);
481        out.push_str(&format!("    {} --> {}\n", src_id, tgt_id));
482    }
483
484    out.push_str("  end\n");
485
486    Ok(out)
487}
488
489fn render_d2_module(
490    module_path: &str,
491    files: &[(i64, String)],
492    edges: &[(String, String)],
493) -> Result<String> {
494    let mut out = format!("{}: {{\n", sanitize_id(module_path));
495
496    for (_, path) in files {
497        let id = sanitize_id(path);
498        let short_name = path.rsplit('/').next().unwrap_or(path);
499        out.push_str(&format!("  {}: \"{}\"\n", id, short_name));
500    }
501
502    for (src, tgt) in edges {
503        let src_id = sanitize_id(src);
504        let tgt_id = sanitize_id(tgt);
505        out.push_str(&format!("  {} -> {}\n", src_id, tgt_id));
506    }
507
508    out.push_str("}\n");
509
510    Ok(out)
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    #[test]
518    fn test_sanitize_id() {
519        assert_eq!(sanitize_id("src/parsers"), "m_src_parsers");
520        assert_eq!(sanitize_id("my-module.rs"), "m_my_module_rs");
521    }
522
523    #[test]
524    fn test_mermaid_repo_output() {
525        let modules = vec![("src".to_string(), 50), ("tests".to_string(), 10)];
526        let edges = vec![("src".to_string(), "tests".to_string(), 3)];
527        let hotspots = HashSet::new();
528
529        let result = render_mermaid_repo(&modules, &edges, &hotspots).unwrap();
530        assert!(result.contains("graph LR"));
531        assert!(result.contains("src"));
532        assert!(result.contains("tests"));
533        assert!(result.contains("-->"));
534    }
535
536    #[test]
537    fn test_d2_repo_output() {
538        let modules = vec![("src".to_string(), 50)];
539        let edges = vec![];
540        let hotspots = HashSet::from(["src".to_string()]);
541
542        let result = render_d2_repo(&modules, &edges, &hotspots).unwrap();
543        assert!(result.contains("src:"));
544        assert!(result.contains("#ff6b6b"));
545    }
546
547    #[test]
548    fn test_mermaid_repo_filters_orphans() {
549        let modules = vec![
550            ("src".to_string(), 50),
551            ("tests".to_string(), 10),
552            ("docs".to_string(), 5),    // orphan — no edges
553            ("scripts".to_string(), 2), // orphan — no edges
554        ];
555        let edges = vec![("src".to_string(), "tests".to_string(), 3)];
556        let hotspots = HashSet::from(["docs".to_string()]);
557
558        let result = render_mermaid_repo(&modules, &edges, &hotspots).unwrap();
559
560        // Connected modules are present
561        assert!(
562            result.contains("m_src["),
563            "connected module 'src' should be in output"
564        );
565        assert!(
566            result.contains("m_tests["),
567            "connected module 'tests' should be in output"
568        );
569
570        // Orphan modules are excluded
571        assert!(
572            !result.contains("m_docs"),
573            "orphan 'docs' should not be in output"
574        );
575        assert!(
576            !result.contains("m_scripts"),
577            "orphan 'scripts' should not be in output"
578        );
579
580        // Hotspot styling for orphan should not appear
581        assert!(
582            !result.contains("class m_docs hotspot"),
583            "orphan hotspot should not be styled"
584        );
585    }
586
587    #[test]
588    fn test_mermaid_layered_proxy_nodes() {
589        let modules = vec![
590            ("src".to_string(), 80, 1u8),
591            ("src/parsers".to_string(), 15, 2u8),
592            ("tests".to_string(), 10, 1u8),
593        ];
594        let edges = vec![
595            ("src/parsers".to_string(), "src".to_string(), 16),
596            ("src".to_string(), "tests".to_string(), 3),
597        ];
598        let hotspots = HashSet::from(["src".to_string()]);
599
600        let result = render_mermaid_layered(&modules, &edges, &hotspots).unwrap();
601
602        // Subgraph for src should exist (it has children)
603        assert!(
604            result.contains("subgraph m_src ["),
605            "Tier 1 with children should be a subgraph"
606        );
607
608        // Proxy node inside the subgraph
609        assert!(
610            result.contains("m_src_self["),
611            "subgraph should contain proxy node"
612        );
613
614        // Edges should target proxy node, not subgraph ID
615        assert!(
616            result.contains("m_src_self"),
617            "edges should reference proxy node"
618        );
619        assert!(
620            !result.contains(" -->|16| m_src\n"),
621            "edges should NOT target bare subgraph ID"
622        );
623
624        // classDef should target proxy node
625        assert!(
626            result.contains("class m_src_self hotspot"),
627            "hotspot class should target proxy node"
628        );
629
630        // tests is standalone Tier 1 (no children), should be a regular node
631        assert!(
632            result.contains("m_tests["),
633            "standalone Tier 1 should be a regular node"
634        );
635        assert!(
636            !result.contains("subgraph m_tests"),
637            "standalone Tier 1 should not be a subgraph"
638        );
639    }
640
641    #[test]
642    fn test_find_owning_module() {
643        let modules = vec![
644            ModuleDefinition {
645                path: "src".to_string(),
646                tier: 1,
647                file_count: 80,
648            },
649            ModuleDefinition {
650                path: "src/parsers".to_string(),
651                tier: 2,
652                file_count: 15,
653            },
654        ];
655
656        assert_eq!(
657            find_owning_module("src/parsers/rust.rs", &modules),
658            "src/parsers"
659        );
660        assert_eq!(find_owning_module("src/main.rs", &modules), "src");
661        assert_eq!(
662            find_owning_module("tests/integration.rs", &modules),
663            "tests"
664        );
665    }
666}