1use std::collections::{HashMap, HashSet, VecDeque};
9use std::path::Path;
10use std::time::Duration;
11
12use lean_ctx::core::graph_index;
13use lean_ctx::core::graph_provider::{self, EdgeInfo};
14use lean_ctx::core::protocol::shorten_path;
15use lean_ctx::core::tokens::count_tokens;
16use lean_ctx_ext::core::graph_analysis::dependency_edges;
17
18struct BlastIndex {
20 rev: HashMap<String, Vec<String>>,
21}
22
23impl BlastIndex {
24 fn build(edges: &[EdgeInfo]) -> Self {
25 let mut rev: HashMap<String, Vec<String>> = HashMap::new();
26 for (from, to) in dependency_edges(edges) {
27 rev.entry(to.to_string())
28 .or_default()
29 .push(from.to_string());
30 }
31 Self { rev }
32 }
33
34 fn transitive_dependents(&self, start: &str, cap: usize) -> usize {
37 let mut visited: HashSet<&str> = HashSet::new();
38 let mut queue: VecDeque<&str> = VecDeque::new();
39 visited.insert(start);
40 queue.push_back(start);
41 while let Some(cur) = queue.pop_front() {
42 if visited.len() > cap {
43 break;
44 }
45 if let Some(deps) = self.rev.get(cur) {
46 for d in deps {
47 if visited.insert(d.as_str()) {
48 queue.push_back(d.as_str());
49 }
50 }
51 }
52 }
53 visited.len().saturating_sub(1)
54 }
55
56 fn direct_dependents(&self, file: &str) -> usize {
57 self.rev.get(file).map_or(0, Vec::len)
58 }
59}
60
61struct DiffEntry {
63 status: char,
64 path: String,
65 in_graph: bool,
66 direct: usize,
67 blast: usize,
68 is_god: bool,
69 is_bridge: bool,
70}
71
72fn parse_name_status(raw: &str) -> Vec<(char, String)> {
75 let mut out = Vec::new();
76 for line in raw.lines() {
77 let mut cols = line.split('\t');
78 let Some(status) = cols.next() else { continue };
79 let code = status.chars().next().unwrap_or('?');
80 let path = if matches!(code, 'R' | 'C') {
81 cols.nth(1)
83 } else {
84 cols.next()
85 };
86 if let Some(p) = path.map(str::trim).filter(|p| !p.is_empty()) {
87 out.push((code, p.to_string()));
88 }
89 }
90 out
91}
92
93pub fn diff(since: Option<&str>, root: &str, format: Option<&str>) -> String {
94 let base = since
95 .map(str::trim)
96 .filter(|s| !s.is_empty())
97 .unwrap_or("HEAD~1");
98
99 if !lean_ctx::core::git::git_available() {
100 return "git is not available — cannot compute a graph diff.".to_string();
101 }
102 let root_path = Path::new(root);
103
104 let name_status = match lean_ctx::core::git::run_git(
105 &["diff", "--name-status", &format!("{base}..HEAD")],
106 root_path,
107 Duration::from_secs(30),
108 &[],
109 ) {
110 Ok(o) if o.success => o.stdout,
111 Ok(o) => {
112 let msg = o.stderr.trim();
113 return format!(
114 "git diff failed: {}\nIs '{base}' a valid commit/ref reachable from HEAD?",
115 if msg.is_empty() { "unknown error" } else { msg }
116 );
117 }
118 Err(e) => return format!("git diff failed: {e}"),
119 };
120
121 let changes = parse_name_status(&name_status);
122 if changes.is_empty() {
123 return format!("No file changes between {base} and HEAD.");
124 }
125
126 let Some(open) = graph_provider::open_or_build(root) else {
127 return "No graph index found. Run ctx_graph with action='build' first.".to_string();
128 };
129 let gp = &open.provider;
130 let edges = gp.edges();
131 let blast = BlastIndex::build(&edges);
132 let node_set: HashSet<String> = gp.file_paths().into_iter().collect();
133 let god: HashSet<String> = lean_ctx_ext::core::graph_analysis::compute_god_nodes(&edges, 25)
134 .into_iter()
135 .map(|g| g.path)
136 .collect();
137 let bridge: HashSet<String> =
138 lean_ctx_ext::core::graph_analysis::compute_bridge_nodes(&edges, 25)
139 .into_iter()
140 .map(|b| b.path)
141 .collect();
142
143 let mut entries: Vec<DiffEntry> = changes
144 .into_iter()
145 .map(|(status, path)| {
146 let key = graph_index::graph_match_key(&path);
147 let in_graph = node_set.contains(&key);
148 let (direct, blast_n) = if in_graph {
149 (
150 blast.direct_dependents(&key),
151 blast.transitive_dependents(&key, 5000),
152 )
153 } else {
154 (0, 0)
155 };
156 DiffEntry {
157 status,
158 in_graph,
159 direct,
160 blast: blast_n,
161 is_god: god.contains(&key),
162 is_bridge: bridge.contains(&key),
163 path: key,
164 }
165 })
166 .collect();
167
168 entries.sort_by(|a, b| {
169 b.blast
170 .cmp(&a.blast)
171 .then_with(|| b.direct.cmp(&a.direct))
172 .then_with(|| a.path.cmp(&b.path))
173 });
174
175 if matches!(format, Some(f) if f.eq_ignore_ascii_case("json")) {
176 return render_json(base, &entries);
177 }
178 render_text(base, &entries)
179}
180
181fn counts(entries: &[DiffEntry]) -> (usize, usize, usize, usize, usize) {
182 let mut added = 0;
183 let mut modified = 0;
184 let mut deleted = 0;
185 let mut renamed = 0;
186 for e in entries {
187 match e.status {
188 'A' => added += 1,
189 'M' => modified += 1,
190 'D' => deleted += 1,
191 'R' | 'C' => renamed += 1,
192 _ => {}
193 }
194 }
195 let in_graph = entries.iter().filter(|e| e.in_graph).count();
196 (added, modified, deleted, renamed, in_graph)
197}
198
199fn render_text(base: &str, entries: &[DiffEntry]) -> String {
200 let (added, modified, deleted, renamed, in_graph) = counts(entries);
201 let mut out = format!("Graph diff: {base}..HEAD\n");
202 out.push_str(&format!(
203 "{} files changed (A:{added} M:{modified} D:{deleted} R:{renamed}) · {in_graph} in graph\n",
204 entries.len()
205 ));
206
207 let high: Vec<&DiffEntry> = entries
208 .iter()
209 .filter(|e| e.in_graph && (e.blast > 0 || e.is_god || e.is_bridge))
210 .collect();
211 if !high.is_empty() {
212 out.push_str("\nHigh-impact changes (by blast radius):\n");
213 for e in &high {
214 out.push_str(&format!(
215 " [{}] {:<46} blast {:<5} direct {}{}\n",
216 e.status,
217 shorten_path(&e.path),
218 e.blast,
219 e.direct,
220 flags(e)
221 ));
222 }
223 }
224
225 let low: Vec<&DiffEntry> = entries
226 .iter()
227 .filter(|e| e.in_graph && e.blast == 0 && !e.is_god && !e.is_bridge)
228 .collect();
229 if !low.is_empty() {
230 out.push_str("\nOther changed files in graph (no known dependents):\n");
231 for e in low.iter().take(40) {
232 out.push_str(&format!(" [{}] {}\n", e.status, shorten_path(&e.path)));
233 }
234 if low.len() > 40 {
235 out.push_str(&format!(" … and {} more\n", low.len() - 40));
236 }
237 }
238
239 let off: Vec<&DiffEntry> = entries.iter().filter(|e| !e.in_graph).collect();
240 if !off.is_empty() {
241 out.push_str(&format!(
242 "\nChanged but not in graph ({}, e.g. docs/config/assets):\n",
243 off.len()
244 ));
245 for e in off.iter().take(20) {
246 out.push_str(&format!(" [{}] {}\n", e.status, shorten_path(&e.path)));
247 }
248 if off.len() > 20 {
249 out.push_str(&format!(" … and {} more\n", off.len() - 20));
250 }
251 }
252
253 let tokens = count_tokens(&out);
254 format!("{out}[ctx_graph diff: {tokens} tok]")
255}
256
257fn flags(e: &DiffEntry) -> String {
258 let mut tags = Vec::new();
259 if e.is_god {
260 tags.push("god-node");
261 }
262 if e.is_bridge {
263 tags.push("bridge");
264 }
265 if tags.is_empty() {
266 String::new()
267 } else {
268 format!(" ({})", tags.join(", "))
269 }
270}
271
272fn render_json(base: &str, entries: &[DiffEntry]) -> String {
273 let (added, modified, deleted, renamed, in_graph) = counts(entries);
274 let items: Vec<_> = entries
275 .iter()
276 .map(|e| {
277 serde_json::json!({
278 "status": e.status.to_string(),
279 "path": e.path,
280 "in_graph": e.in_graph,
281 "direct_dependents": e.direct,
282 "blast_radius": e.blast,
283 "is_god_node": e.is_god,
284 "is_bridge": e.is_bridge,
285 })
286 })
287 .collect();
288 let val = serde_json::json!({
289 "base": base,
290 "summary": {
291 "total": entries.len(),
292 "added": added,
293 "modified": modified,
294 "deleted": deleted,
295 "renamed": renamed,
296 "in_graph": in_graph,
297 },
298 "changes": items,
299 });
300 serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string())
301}
302
303#[cfg(test)]
304mod tests {
305 use super::*;
306
307 #[test]
308 fn parses_simple_statuses() {
309 let raw = "M\tsrc/a.rs\nA\tsrc/b.rs\nD\tsrc/c.rs\n";
310 let parsed = parse_name_status(raw);
311 assert_eq!(
312 parsed,
313 vec![
314 ('M', "src/a.rs".to_string()),
315 ('A', "src/b.rs".to_string()),
316 ('D', "src/c.rs".to_string()),
317 ]
318 );
319 }
320
321 #[test]
322 fn rename_uses_destination_path() {
323 let raw = "R096\tsrc/old.rs\tsrc/new.rs\n";
324 let parsed = parse_name_status(raw);
325 assert_eq!(parsed, vec![('R', "src/new.rs".to_string())]);
326 }
327
328 #[test]
329 fn ignores_blank_lines() {
330 {
331 let found = &parse_name_status("\n\n");
332 assert!(found.is_empty(), "{found:?}");
333 }
334 }
335
336 #[test]
337 fn blast_radius_is_transitive() {
338 let edges = vec![
340 EdgeInfo {
341 from: "a.rs".into(),
342 to: "b.rs".into(),
343 kind: "import".into(),
344 weight: 1.0,
345 },
346 EdgeInfo {
347 from: "b.rs".into(),
348 to: "c.rs".into(),
349 kind: "import".into(),
350 weight: 1.0,
351 },
352 ];
353 let idx = BlastIndex::build(&edges);
354 assert_eq!(idx.transitive_dependents("c.rs", 100), 2);
355 assert_eq!(idx.direct_dependents("c.rs"), 1);
356 assert_eq!(idx.transitive_dependents("a.rs", 100), 0);
357 }
358
359 #[test]
360 fn blast_radius_ignores_heuristic_edges() {
361 let edges = vec![EdgeInfo {
363 from: "a.rs".into(),
364 to: "b.rs".into(),
365 kind: "sibling".into(),
366 weight: 1.0,
367 }];
368 let idx = BlastIndex::build(&edges);
369 assert_eq!(idx.transitive_dependents("b.rs", 100), 0);
370 }
371}