Skip to main content

arbor_graph/
diff.rs

1//! Git-diff blast radius computation shared by CLI and MCP.
2
3use crate::{ArborGraph, NodeId};
4use serde::{Deserialize, Serialize};
5use std::collections::HashSet;
6use std::path::Path;
7
8/// Summary of blast radius for changed files (matches CLI `arbor diff` output).
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct BlastRadiusSummary {
11    pub changed_files: Vec<String>,
12    pub changed_symbols: usize,
13    pub direct_callers: usize,
14    pub indirect_callers: usize,
15    pub entrypoints_affected: usize,
16    pub files_likely_updates: usize,
17    pub blast_radius_nodes: usize,
18    pub mermaid_diagram: Option<String>,
19    pub risk_level: String,
20}
21
22fn normalize_slashes(input: &str) -> String {
23    input.replace('\\', "/")
24}
25
26/// Whether a graph node's file path matches a git-changed path.
27pub fn node_matches_changed_file(node_file: &str, changed_file: &str, project_root: &Path) -> bool {
28    let node_norm = normalize_slashes(node_file);
29    let changed_norm = normalize_slashes(changed_file);
30
31    if node_norm.ends_with(&changed_norm) {
32        return true;
33    }
34
35    let abs = project_root.join(&changed_norm);
36    let abs_norm = normalize_slashes(&abs.to_string_lossy());
37    node_norm == abs_norm
38}
39
40/// Collect node IDs whose files appear in the changed-files list.
41///
42/// This is *file* granularity: every symbol in a touched file is treated as
43/// changed. For a one-line edit in a 60-symbol file that overstates the blast
44/// radius by roughly 60x. Prefer [`changed_node_ids_for_ranges`] whenever the
45/// caller has the diff hunks — which any PR-driven integration does.
46pub fn changed_node_ids(
47    graph: &ArborGraph,
48    changed_files: &[String],
49    project_root: &Path,
50) -> Vec<NodeId> {
51    graph
52        .node_indexes()
53        .filter(|idx| {
54            graph.get(*idx).is_some_and(|node| {
55                changed_files
56                    .iter()
57                    .any(|f| node_matches_changed_file(&node.file, f, project_root))
58            })
59        })
60        .collect()
61}
62
63/// A contiguous run of changed lines within one file.
64///
65/// Lines are 1-indexed and both bounds are inclusive, matching how editors and
66/// `CodeNode::line_start`/`line_end` count.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct ChangedRange {
69    pub file: String,
70    pub start_line: u32,
71    pub end_line: u32,
72}
73
74impl ChangedRange {
75    pub fn new(file: impl Into<String>, start_line: u32, end_line: u32) -> Self {
76        Self {
77            file: file.into(),
78            start_line,
79            end_line,
80        }
81    }
82
83    /// Whether this range overlaps an inclusive `[start, end]` span.
84    fn overlaps(&self, start: u32, end: u32) -> bool {
85        self.start_line <= end && start <= self.end_line
86    }
87}
88
89/// Symbols touched by a set of changed line ranges.
90#[derive(Debug, Clone, Default)]
91pub struct ChangedSymbols {
92    /// Nodes overlapping at least one changed range, in graph order.
93    pub node_ids: Vec<NodeId>,
94
95    /// Files that changed but where no symbol overlapped the changed lines.
96    ///
97    /// Usually an import block, a top-level constant, a comment, or a
98    /// whitespace-only edit. Surfacing these lets a report say "this file
99    /// changed outside any tracked symbol" instead of silently reporting
100    /// zero impact — an honest unknown rather than an invisible one.
101    pub files_without_symbol_hits: Vec<String>,
102}
103
104/// Collect node IDs whose line spans overlap the given changed ranges.
105///
106/// A symbol counts as changed when any changed line falls inside its span.
107/// Symbols elsewhere in the same file are left out, which is the whole point:
108/// editing one function should not implicate its 59 neighbours.
109///
110/// Nodes whose line span is unset (`line_end == 0`, which some fallback
111/// parsers produce) cannot be positioned, so they are included whenever their
112/// file is touched. That is the conservative choice — better a slightly wide
113/// radius than a silently missing symbol.
114pub fn changed_node_ids_for_ranges(
115    graph: &ArborGraph,
116    ranges: &[ChangedRange],
117    project_root: &Path,
118) -> ChangedSymbols {
119    let mut node_ids = Vec::new();
120    let mut files_hit: HashSet<String> = HashSet::new();
121
122    for idx in graph.node_indexes() {
123        let Some(node) = graph.get(idx) else {
124            continue;
125        };
126
127        for range in ranges {
128            if !node_matches_changed_file(&node.file, &range.file, project_root) {
129                continue;
130            }
131
132            // Position-unknown nodes fall back to file granularity.
133            let positioned = node.line_end > 0;
134            if !positioned || range.overlaps(node.line_start, node.line_end) {
135                node_ids.push(idx);
136                files_hit.insert(range.file.clone());
137                break;
138            }
139        }
140    }
141
142    let mut files_without_symbol_hits: Vec<String> = ranges
143        .iter()
144        .map(|r| r.file.clone())
145        .filter(|f| !files_hit.contains(f))
146        .collect();
147    files_without_symbol_hits.sort();
148    files_without_symbol_hits.dedup();
149
150    ChangedSymbols {
151        node_ids,
152        files_without_symbol_hits,
153    }
154}
155
156/// Extract changed line ranges from a unified diff patch for one file.
157///
158/// Reads the `+` side of each `@@ -a,b +c,d @@` header, so the ranges refer to
159/// line numbers in the *new* file — the same numbering the indexed graph uses.
160///
161/// The full hunk span is returned, including its context lines. Context is
162/// deliberately kept: a hunk that only deletes lines has no added lines to
163/// point at, but the deletion still changes the enclosing symbol, and the
164/// surrounding context is what locates it. Over-including by the three context
165/// lines either side is immaterial next to the alternative of taking the whole
166/// file.
167///
168/// Malformed headers are skipped rather than failing the parse — a diff that
169/// partially parses still yields a far better radius than no ranges at all.
170pub fn parse_unified_diff_ranges(patch: &str, file: &str) -> Vec<ChangedRange> {
171    let mut ranges = Vec::new();
172
173    for line in patch.lines() {
174        if !line.starts_with("@@") {
175            continue;
176        }
177
178        // `@@ -12,7 +12,9 @@ fn context()` → we want the `+12,9`.
179        let Some(rest) = line.strip_prefix("@@") else {
180            continue;
181        };
182        let Some(plus) = rest.split('+').nth(1) else {
183            continue;
184        };
185        let spec = plus.split_whitespace().next().unwrap_or("");
186        let mut parts = spec.split(',');
187
188        let Some(Ok(start)) = parts.next().map(str::parse::<u32>) else {
189            continue;
190        };
191        // An omitted count means a single line.
192        let count = match parts.next() {
193            Some(c) => match c.parse::<u32>() {
194                Ok(n) => n,
195                Err(_) => continue,
196            },
197            None => 1,
198        };
199
200        if count == 0 {
201            // Pure deletion: the new file has no lines here. Anchor on the
202            // insertion point so the enclosing symbol is still found.
203            ranges.push(ChangedRange::new(file, start.max(1), start.max(1)));
204        } else {
205            ranges.push(ChangedRange::new(file, start, start + count - 1));
206        }
207    }
208
209    ranges
210}
211
212fn risk_level_for(blast_radius_nodes: usize) -> String {
213    if blast_radius_nodes > 50 {
214        "critical".to_string()
215    } else if blast_radius_nodes > 25 {
216        "high".to_string()
217    } else if blast_radius_nodes > 10 {
218        "medium".to_string()
219    } else {
220        "low".to_string()
221    }
222}
223
224/// Compute blast radius summary from an indexed graph and changed file list.
225pub fn compute_blast_radius(
226    graph: &ArborGraph,
227    changed_files: Vec<String>,
228    changed_node_ids: Vec<NodeId>,
229    max_depth: usize,
230    project_root: &Path,
231) -> BlastRadiusSummary {
232    let mut direct_callers = HashSet::new();
233    let mut indirect_callers = HashSet::new();
234    let mut affected_nodes = HashSet::new();
235    let mut affected_files = HashSet::new();
236
237    for node_id in changed_node_ids.iter().copied() {
238        let analysis = graph.analyze_impact(node_id, max_depth);
239
240        for up in &analysis.upstream {
241            affected_nodes.insert(up.node_info.id.clone());
242            affected_files.insert(up.node_info.file.clone());
243            if up.hop_distance <= 1 {
244                direct_callers.insert(up.node_info.id.clone());
245            } else {
246                indirect_callers.insert(up.node_info.id.clone());
247            }
248        }
249
250        for down in &analysis.downstream {
251            affected_nodes.insert(down.node_info.id.clone());
252            affected_files.insert(down.node_info.file.clone());
253        }
254    }
255
256    let entrypoints_affected = affected_nodes
257        .iter()
258        .filter_map(|id| graph.get_index(id))
259        .filter(|idx| graph.analyze_impact(*idx, 1).upstream.is_empty())
260        .count();
261
262    let changed_norm: Vec<String> = changed_files.iter().map(|f| normalize_slashes(f)).collect();
263    let files_likely_updates = affected_files
264        .iter()
265        .filter(|f| {
266            let f_norm = normalize_slashes(f);
267            !changed_norm.iter().any(|c| {
268                f_norm.ends_with(c)
269                    || f_norm == normalize_slashes(&project_root.join(c).to_string_lossy())
270            })
271        })
272        .count();
273
274    let mut mermaid_lines = Vec::new();
275    mermaid_lines.push("graph TD".to_string());
276    mermaid_lines.push(
277        "  classDef changed fill:#ef4444,stroke:#333,stroke-width:2px,color:#fff;".to_string(),
278    );
279    mermaid_lines.push(
280        "  classDef caller fill:#f59e0b,stroke:#333,stroke-width:1px,color:#fff;".to_string(),
281    );
282
283    let mut added_edges = HashSet::new();
284    let mut changed_node_names = HashSet::new();
285    let mut direct_caller_names = HashSet::new();
286
287    for node_id in changed_node_ids.iter().copied().take(5) {
288        if let Some(node) = graph.get(node_id) {
289            let target_name = node.name.replace([':', '<', '>', '(', ')', '[', ']'], "_");
290            changed_node_names.insert(target_name.clone());
291
292            let analysis = graph.analyze_impact(node_id, max_depth);
293
294            let mut caller_count = 0;
295            for up in &analysis.upstream {
296                if up.hop_distance == 1 {
297                    let caller_name = up
298                        .node_info
299                        .name
300                        .replace([':', '<', '>', '(', ')', '[', ']'], "_");
301                    direct_caller_names.insert(caller_name.clone());
302
303                    let edge = format!(
304                        "  {}[{}] --> {}[{}]",
305                        caller_name, up.node_info.name, target_name, node.name
306                    );
307                    if added_edges.insert(edge.clone()) {
308                        mermaid_lines.push(edge);
309                        caller_count += 1;
310                        if caller_count >= 3 {
311                            break;
312                        }
313                    }
314                }
315            }
316        }
317    }
318
319    for name in &changed_node_names {
320        mermaid_lines.push(format!("  class {} changed;", name));
321    }
322    for name in &direct_caller_names {
323        if !changed_node_names.contains(name) {
324            mermaid_lines.push(format!("  class {} caller;", name));
325        }
326    }
327
328    let mermaid_diagram = if mermaid_lines.len() > 3 {
329        Some(mermaid_lines.join("\n"))
330    } else {
331        None
332    };
333
334    let blast_radius_nodes = affected_nodes.len();
335
336    BlastRadiusSummary {
337        changed_files,
338        changed_symbols: changed_node_ids.len(),
339        direct_callers: direct_callers.len(),
340        indirect_callers: indirect_callers.len(),
341        entrypoints_affected,
342        files_likely_updates,
343        blast_radius_nodes,
344        mermaid_diagram,
345        risk_level: risk_level_for(blast_radius_nodes),
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352    use crate::ArborGraph;
353    use arbor_core::{CodeNode, NodeKind};
354
355    #[test]
356    fn compute_blast_radius_empty_changes() {
357        let graph = ArborGraph::new();
358        let summary = compute_blast_radius(&graph, vec![], vec![], 5, Path::new("."));
359        assert_eq!(summary.blast_radius_nodes, 0);
360        assert_eq!(summary.risk_level, "low");
361    }
362
363    #[test]
364    fn changed_node_ids_finds_nodes_in_file() {
365        let mut graph = ArborGraph::new();
366        let node = CodeNode::new("foo", "foo", NodeKind::Function, "src/lib.rs");
367        let id = graph.add_node(node);
368
369        let ids = changed_node_ids(&graph, &["src/lib.rs".to_string()], Path::new("."));
370        assert_eq!(ids.len(), 1);
371        assert_eq!(ids[0], id);
372    }
373
374    /// A 3-symbol file: `a` on 1-10, `b` on 20-30, `c` on 40-50.
375    fn three_symbol_file() -> (ArborGraph, NodeId, NodeId, NodeId) {
376        let mut graph = ArborGraph::new();
377        let a = graph
378            .add_node(CodeNode::new("a", "a", NodeKind::Function, "src/lib.rs").with_lines(1, 10));
379        let b = graph
380            .add_node(CodeNode::new("b", "b", NodeKind::Function, "src/lib.rs").with_lines(20, 30));
381        let c = graph
382            .add_node(CodeNode::new("c", "c", NodeKind::Function, "src/lib.rs").with_lines(40, 50));
383        (graph, a, b, c)
384    }
385
386    #[test]
387    fn ranges_select_only_the_edited_symbol() {
388        let (graph, _a, b, _c) = three_symbol_file();
389        let ranges = vec![ChangedRange::new("src/lib.rs", 22, 23)];
390
391        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
392        assert_eq!(
393            changed.node_ids,
394            vec![b],
395            "editing inside b must not implicate a or c"
396        );
397        assert!(changed.files_without_symbol_hits.is_empty());
398    }
399
400    #[test]
401    fn file_granularity_overstates_by_the_symbol_count() {
402        // The regression this whole API exists to prevent.
403        let (graph, _, _, _) = three_symbol_file();
404        let by_file = changed_node_ids(&graph, &["src/lib.rs".to_string()], Path::new("."));
405        let by_range = changed_node_ids_for_ranges(
406            &graph,
407            &[ChangedRange::new("src/lib.rs", 22, 23)],
408            Path::new("."),
409        );
410
411        assert_eq!(by_file.len(), 3);
412        assert_eq!(by_range.node_ids.len(), 1);
413    }
414
415    #[test]
416    fn range_spanning_two_symbols_selects_both() {
417        let (graph, _a, b, c) = three_symbol_file();
418        let ranges = vec![ChangedRange::new("src/lib.rs", 25, 45)];
419
420        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
421        assert_eq!(changed.node_ids, vec![b, c]);
422    }
423
424    #[test]
425    fn boundary_lines_count_as_overlap() {
426        let (graph, a, _b, _c) = three_symbol_file();
427
428        // Touching exactly the first and last line of `a`.
429        for line in [1u32, 10u32] {
430            let changed = changed_node_ids_for_ranges(
431                &graph,
432                &[ChangedRange::new("src/lib.rs", line, line)],
433                Path::new("."),
434            );
435            assert_eq!(changed.node_ids, vec![a], "line {line} should hit a");
436        }
437    }
438
439    #[test]
440    fn change_between_symbols_reports_no_symbol_hit() {
441        let (graph, _, _, _) = three_symbol_file();
442        // Line 15 sits in the gap between `a` and `b` — an import or comment.
443        let changed = changed_node_ids_for_ranges(
444            &graph,
445            &[ChangedRange::new("src/lib.rs", 15, 15)],
446            Path::new("."),
447        );
448
449        assert!(changed.node_ids.is_empty());
450        assert_eq!(
451            changed.files_without_symbol_hits,
452            vec!["src/lib.rs".to_string()],
453            "unmatched changes must be surfaced, not silently dropped"
454        );
455    }
456
457    #[test]
458    fn unpositioned_nodes_fall_back_to_file_granularity() {
459        let mut graph = ArborGraph::new();
460        // line_end == 0: some fallback parsers do not record positions.
461        let id = graph.add_node(CodeNode::new("x", "x", NodeKind::Function, "src/lib.rs"));
462
463        let changed = changed_node_ids_for_ranges(
464            &graph,
465            &[ChangedRange::new("src/lib.rs", 999, 999)],
466            Path::new("."),
467        );
468        assert_eq!(changed.node_ids, vec![id]);
469    }
470
471    #[test]
472    fn ranges_in_other_files_are_ignored() {
473        let (graph, _a, _b, _c) = three_symbol_file();
474        let changed = changed_node_ids_for_ranges(
475            &graph,
476            &[ChangedRange::new("src/other.rs", 1, 100)],
477            Path::new("."),
478        );
479        assert!(changed.node_ids.is_empty());
480        assert_eq!(changed.files_without_symbol_hits, vec!["src/other.rs"]);
481    }
482
483    #[test]
484    fn parses_standard_hunk_headers() {
485        let patch = "\
486@@ -12,7 +12,9 @@ fn context()
487-old
488+new
489@@ -40,3 +42,3 @@
490 ctx";
491        let ranges = parse_unified_diff_ranges(patch, "src/lib.rs");
492        assert_eq!(
493            ranges,
494            vec![
495                ChangedRange::new("src/lib.rs", 12, 20),
496                ChangedRange::new("src/lib.rs", 42, 44),
497            ]
498        );
499    }
500
501    #[test]
502    fn parses_hunk_header_with_omitted_count() {
503        // `+5` with no comma means exactly one line.
504        let ranges = parse_unified_diff_ranges("@@ -5 +5 @@\n+x", "a.rs");
505        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 5, 5)]);
506    }
507
508    #[test]
509    fn pure_deletion_anchors_on_insertion_point() {
510        // `+7,0`: the new file has no lines here, but the deletion still
511        // changes whatever symbol surrounds line 7.
512        let ranges = parse_unified_diff_ranges("@@ -7,3 +7,0 @@", "a.rs");
513        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 7, 7)]);
514    }
515
516    #[test]
517    fn malformed_headers_are_skipped_not_fatal() {
518        let patch = "\
519@@ garbage @@
520@@ -1,2 +1,2 @@
521+ok
522@@ -x,y +z,w @@";
523        let ranges = parse_unified_diff_ranges(patch, "a.rs");
524        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 1, 2)]);
525    }
526
527    #[test]
528    fn empty_patch_yields_no_ranges() {
529        assert!(parse_unified_diff_ranges("", "a.rs").is_empty());
530        assert!(parse_unified_diff_ranges("no hunks here", "a.rs").is_empty());
531    }
532
533    #[test]
534    fn end_to_end_patch_to_symbols() {
535        let (graph, _a, b, _c) = three_symbol_file();
536        // A hunk covering lines 21-24 — inside `b` only.
537        let patch = "@@ -21,4 +21,4 @@\n-old\n+new";
538        let ranges = parse_unified_diff_ranges(patch, "src/lib.rs");
539        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
540        assert_eq!(changed.node_ids, vec![b]);
541    }
542}