1use crate::{ArborGraph, NodeId};
4use serde::{Deserialize, Serialize};
5use std::collections::HashSet;
6use std::path::Path;
7
8#[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
26pub 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
40pub fn changed_node_ids(
42 graph: &ArborGraph,
43 changed_files: &[String],
44 project_root: &Path,
45) -> Vec<NodeId> {
46 graph
47 .node_indexes()
48 .filter(|idx| {
49 graph.get(*idx).is_some_and(|node| {
50 changed_files
51 .iter()
52 .any(|f| node_matches_changed_file(&node.file, f, project_root))
53 })
54 })
55 .collect()
56}
57
58fn risk_level_for(blast_radius_nodes: usize) -> String {
59 if blast_radius_nodes > 50 {
60 "critical".to_string()
61 } else if blast_radius_nodes > 25 {
62 "high".to_string()
63 } else if blast_radius_nodes > 10 {
64 "medium".to_string()
65 } else {
66 "low".to_string()
67 }
68}
69
70pub fn compute_blast_radius(
72 graph: &ArborGraph,
73 changed_files: Vec<String>,
74 changed_node_ids: Vec<NodeId>,
75 max_depth: usize,
76 project_root: &Path,
77) -> BlastRadiusSummary {
78 let mut direct_callers = HashSet::new();
79 let mut indirect_callers = HashSet::new();
80 let mut affected_nodes = HashSet::new();
81 let mut affected_files = HashSet::new();
82
83 for node_id in changed_node_ids.iter().copied() {
84 let analysis = graph.analyze_impact(node_id, max_depth);
85
86 for up in &analysis.upstream {
87 affected_nodes.insert(up.node_info.id.clone());
88 affected_files.insert(up.node_info.file.clone());
89 if up.hop_distance <= 1 {
90 direct_callers.insert(up.node_info.id.clone());
91 } else {
92 indirect_callers.insert(up.node_info.id.clone());
93 }
94 }
95
96 for down in &analysis.downstream {
97 affected_nodes.insert(down.node_info.id.clone());
98 affected_files.insert(down.node_info.file.clone());
99 }
100 }
101
102 let entrypoints_affected = affected_nodes
103 .iter()
104 .filter_map(|id| graph.get_index(id))
105 .filter(|idx| graph.analyze_impact(*idx, 1).upstream.is_empty())
106 .count();
107
108 let changed_norm: Vec<String> = changed_files.iter().map(|f| normalize_slashes(f)).collect();
109 let files_likely_updates = affected_files
110 .iter()
111 .filter(|f| {
112 let f_norm = normalize_slashes(f);
113 !changed_norm.iter().any(|c| {
114 f_norm.ends_with(c)
115 || f_norm == normalize_slashes(&project_root.join(c).to_string_lossy())
116 })
117 })
118 .count();
119
120 let mut mermaid_lines = Vec::new();
121 mermaid_lines.push("graph TD".to_string());
122 mermaid_lines.push(
123 " classDef changed fill:#ef4444,stroke:#333,stroke-width:2px,color:#fff;".to_string(),
124 );
125 mermaid_lines.push(
126 " classDef caller fill:#f59e0b,stroke:#333,stroke-width:1px,color:#fff;".to_string(),
127 );
128
129 let mut added_edges = HashSet::new();
130 let mut changed_node_names = HashSet::new();
131 let mut direct_caller_names = HashSet::new();
132
133 for node_id in changed_node_ids.iter().copied().take(5) {
134 if let Some(node) = graph.get(node_id) {
135 let target_name = node.name.replace([':', '<', '>', '(', ')', '[', ']'], "_");
136 changed_node_names.insert(target_name.clone());
137
138 let analysis = graph.analyze_impact(node_id, max_depth);
139
140 let mut caller_count = 0;
141 for up in &analysis.upstream {
142 if up.hop_distance == 1 {
143 let caller_name = up
144 .node_info
145 .name
146 .replace([':', '<', '>', '(', ')', '[', ']'], "_");
147 direct_caller_names.insert(caller_name.clone());
148
149 let edge = format!(
150 " {}[{}] --> {}[{}]",
151 caller_name, up.node_info.name, target_name, node.name
152 );
153 if added_edges.insert(edge.clone()) {
154 mermaid_lines.push(edge);
155 caller_count += 1;
156 if caller_count >= 3 {
157 break;
158 }
159 }
160 }
161 }
162 }
163 }
164
165 for name in &changed_node_names {
166 mermaid_lines.push(format!(" class {} changed;", name));
167 }
168 for name in &direct_caller_names {
169 if !changed_node_names.contains(name) {
170 mermaid_lines.push(format!(" class {} caller;", name));
171 }
172 }
173
174 let mermaid_diagram = if mermaid_lines.len() > 3 {
175 Some(mermaid_lines.join("\n"))
176 } else {
177 None
178 };
179
180 let blast_radius_nodes = affected_nodes.len();
181
182 BlastRadiusSummary {
183 changed_files,
184 changed_symbols: changed_node_ids.len(),
185 direct_callers: direct_callers.len(),
186 indirect_callers: indirect_callers.len(),
187 entrypoints_affected,
188 files_likely_updates,
189 blast_radius_nodes,
190 mermaid_diagram,
191 risk_level: risk_level_for(blast_radius_nodes),
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use crate::ArborGraph;
199 use arbor_core::{CodeNode, NodeKind};
200
201 #[test]
202 fn compute_blast_radius_empty_changes() {
203 let graph = ArborGraph::new();
204 let summary = compute_blast_radius(&graph, vec![], vec![], 5, Path::new("."));
205 assert_eq!(summary.blast_radius_nodes, 0);
206 assert_eq!(summary.risk_level, "low");
207 }
208
209 #[test]
210 fn changed_node_ids_finds_nodes_in_file() {
211 let mut graph = ArborGraph::new();
212 let node = CodeNode::new("foo", "foo", NodeKind::Function, "src/lib.rs");
213 let id = graph.add_node(node);
214
215 let ids = changed_node_ids(&graph, &["src/lib.rs".to_string()], Path::new("."));
216 assert_eq!(ids.len(), 1);
217 assert_eq!(ids[0], id);
218 }
219}