Skip to main content

lean_ctx_ext/
heatmap.rs

1// SPDX-License-Identifier: Apache-2.0
2use crate::core::graph_provider::{self, GraphProvider};
3use std::collections::HashMap;
4
5struct HeatEntry {
6    path: String,
7    token_count: usize,
8    connections: usize,
9    heat_score: f64,
10}
11
12pub fn cmd_heatmap(args: &[String]) {
13    let project_root = std::env::current_dir()
14        .ok()
15        .and_then(|d| d.to_str().map(String::from))
16        .unwrap_or_else(|| ".".to_string());
17
18    let top_n: usize = args
19        .iter()
20        .find_map(|a| a.strip_prefix("--top="))
21        .and_then(|v| v.parse().ok())
22        .unwrap_or(20);
23
24    let dir_filter: Option<&str> = args
25        .iter()
26        .find_map(|a| a.strip_prefix("--dir="))
27        .map(|s| s.trim_end_matches('/'));
28
29    let sort_by = if args.iter().any(|a| a == "--by=connections") {
30        SortBy::Connections
31    } else if args.iter().any(|a| a == "--by=tokens") {
32        SortBy::Tokens
33    } else {
34        SortBy::Heat
35    };
36
37    let json_output = args.iter().any(|a| a == "--json");
38
39    let Some(open) = graph_provider::open_or_build(&project_root) else {
40        eprintln!("No graph available for project.");
41        return;
42    };
43
44    let entries = build_heat_entries(&open.provider, dir_filter);
45
46    if entries.is_empty() {
47        eprintln!("No files found in project graph.");
48        eprintln!("  Run: lean-ctx setup  (to build the project graph)");
49        return;
50    }
51
52    let mut sorted = entries;
53    match sort_by {
54        SortBy::Heat => sorted.sort_by(|a, b| {
55            b.heat_score
56                .partial_cmp(&a.heat_score)
57                .unwrap_or(std::cmp::Ordering::Equal)
58        }),
59        SortBy::Tokens => sorted.sort_by_key(|x| std::cmp::Reverse(x.token_count)),
60        SortBy::Connections => sorted.sort_by_key(|x| std::cmp::Reverse(x.connections)),
61    }
62
63    let top = &sorted[..sorted.len().min(top_n)];
64
65    if json_output {
66        print_json(top);
67    } else {
68        print_heatmap(&project_root, top, &sorted);
69    }
70}
71
72enum SortBy {
73    Heat,
74    Tokens,
75    Connections,
76}
77
78fn build_heat_entries(gp: &GraphProvider, dir_filter: Option<&str>) -> Vec<HeatEntry> {
79    let all_edges = gp.edges();
80    let mut connection_counts: HashMap<String, usize> = HashMap::new();
81    for edge in &all_edges {
82        *connection_counts.entry(edge.from.clone()).or_default() += 1;
83        *connection_counts.entry(edge.to.clone()).or_default() += 1;
84    }
85
86    let paths = gp.file_paths();
87    let mut max_tokens = 1usize;
88    let mut file_entries: Vec<(String, usize)> = Vec::new();
89    for path in &paths {
90        if let Some(entry) = gp.get_file_entry(path) {
91            max_tokens = max_tokens.max(entry.token_count);
92            file_entries.push((path.clone(), entry.token_count));
93        }
94    }
95    let max_tokens = max_tokens as f64;
96    let max_connections = connection_counts.values().max().copied().unwrap_or(1) as f64;
97
98    file_entries
99        .into_iter()
100        .filter(|(path, _)| {
101            if let Some(dir) = dir_filter {
102                path.starts_with(dir) || path.starts_with(&format!("./{dir}"))
103            } else {
104                true
105            }
106        })
107        .map(|(path, token_count)| {
108            let connections = connection_counts.get(&path).copied().unwrap_or(0);
109            let token_norm = token_count as f64 / max_tokens;
110            let conn_norm = connections as f64 / max_connections;
111            let heat_score = token_norm * 0.4 + conn_norm * 0.6;
112
113            HeatEntry {
114                path,
115                token_count,
116                connections,
117                heat_score,
118            }
119        })
120        .collect()
121}
122
123fn heat_color(score: f64) -> &'static str {
124    if score > 0.8 {
125        "\x1b[91m" // bright red
126    } else if score > 0.6 {
127        "\x1b[31m" // red
128    } else if score > 0.4 {
129        "\x1b[33m" // yellow
130    } else if score > 0.2 {
131        "\x1b[36m" // cyan
132    } else {
133        "\x1b[34m" // blue
134    }
135}
136
137fn heat_bar(score: f64, width: usize) -> String {
138    let filled = (score * width as f64).round() as usize;
139    let blocks = "█".repeat(filled);
140    let empty = "░".repeat(width.saturating_sub(filled));
141    format!("{}{blocks}\x1b[38;5;239m{empty}\x1b[0m", heat_color(score))
142}
143
144fn print_heatmap(project_root: &str, entries: &[HeatEntry], all: &[HeatEntry]) {
145    let total_files = all.len();
146    let total_tokens: usize = all.iter().map(|e| e.token_count).sum();
147    let total_connections: usize = all.iter().map(|e| e.connections).sum();
148
149    let project_name = std::path::Path::new(project_root).file_name().map_or_else(
150        || project_root.to_string(),
151        |n| n.to_string_lossy().to_string(),
152    );
153
154    println!();
155    println!("\x1b[1;37m  Context Heat Map\x1b[0m  \x1b[38;5;239m{project_name}\x1b[0m");
156    println!(
157        "\x1b[38;5;239m  {total_files} files · {total_tokens} tokens · {total_connections} connections\x1b[0m"
158    );
159    println!();
160
161    let max_path_len = entries.iter().map(|e| e.path.len()).max().unwrap_or(30);
162    let path_width = max_path_len.min(50);
163
164    println!(
165        "  \x1b[38;5;239m{:<width$}  {:>6}  {:>5}  HEAT\x1b[0m",
166        "FILE",
167        "TOKENS",
168        "CONNS",
169        width = path_width
170    );
171    println!("  \x1b[38;5;239m{}\x1b[0m", "─".repeat(path_width + 32));
172
173    for entry in entries {
174        let display_path = if entry.path.len() > path_width {
175            let skip = entry.path.len() - path_width + 3;
176            format!("...{}", &entry.path[skip..])
177        } else {
178            entry.path.clone()
179        };
180
181        let bar = heat_bar(entry.heat_score, 16);
182
183        println!(
184            "  {color}{:<width$}\x1b[0m  \x1b[38;5;245m{:>6}\x1b[0m  \x1b[38;5;245m{:>5}\x1b[0m  {bar}  {color}{:.0}%\x1b[0m",
185            display_path,
186            entry.token_count,
187            entry.connections,
188            entry.heat_score * 100.0,
189            color = heat_color(entry.heat_score),
190            width = path_width,
191        );
192    }
193
194    println!();
195    println!(
196        "  \x1b[38;5;239mLegend: \x1b[91m█\x1b[38;5;239m hot  \x1b[33m█\x1b[38;5;239m warm  \x1b[36m█\x1b[38;5;239m cool  \x1b[34m█\x1b[38;5;239m cold\x1b[0m"
197    );
198    println!(
199        "  \x1b[38;5;239mOptions: --top=N  --dir=path  --by=tokens|connections  --json\x1b[0m"
200    );
201    println!();
202}
203
204fn print_json(entries: &[HeatEntry]) {
205    let items: Vec<serde_json::Value> = entries
206        .iter()
207        .map(|e| {
208            serde_json::json!({
209                "path": e.path,
210                "token_count": e.token_count,
211                "connections": e.connections,
212                "heat_score": (e.heat_score * 100.0).round() / 100.0,
213            })
214        })
215        .collect();
216
217    println!(
218        "{}",
219        serde_json::to_string_pretty(&items).unwrap_or_else(|_| "[]".to_string())
220    );
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn test_heat_color_ranges() {
229        assert_eq!(heat_color(0.9), "\x1b[91m");
230        assert_eq!(heat_color(0.7), "\x1b[31m");
231        assert_eq!(heat_color(0.5), "\x1b[33m");
232        assert_eq!(heat_color(0.3), "\x1b[36m");
233        assert_eq!(heat_color(0.1), "\x1b[34m");
234    }
235
236    #[test]
237    fn test_heat_bar_length() {
238        let bar = heat_bar(0.5, 10);
239        assert!(bar.contains("█████"));
240    }
241
242    #[test]
243    fn test_build_heat_entries_empty() {
244        let gp = GraphProvider::GraphIndex(crate::core::graph_index::ProjectIndex::new("."));
245        let entries = build_heat_entries(&gp, None);
246        assert!(entries.is_empty());
247    }
248}