1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
9
10use rusqlite::{Connection, params};
11
12#[derive(Debug, Clone)]
13pub struct GraphQuery;
14
15#[derive(Debug, Clone)]
16pub struct ImpactResult {
17 pub root_file: String,
18 pub affected_files: Vec<String>,
19 pub weak_files: Vec<String>,
22 pub max_depth_reached: usize,
23 pub edges_traversed: usize,
24}
25
26#[derive(Debug, Clone)]
27pub struct DependencyChain {
28 pub path: Vec<String>,
29 pub depth: usize,
30}
31
32const STRUCTURAL_EDGE_KINDS: &str = "'imports','calls','references','implements','extends','exports','type_ref','tested_by','module','cochange','sibling'";
34
35pub fn edge_weight(kind: &str) -> f64 {
37 match kind {
38 "imports" => 1.0,
39 "calls" | "references" => 0.8,
40 "exports" | "implements" | "extends" => 0.7,
41 "module" => 0.6,
42 "type_ref" => 0.5,
43 "tested_by" => 0.4,
44 "cochange" => 0.35,
45 "defines" => 0.3,
46 "sibling" => 0.25,
47 "changed_in" => 0.2,
48 _ => 0.1,
49 }
50}
51
52pub(super) fn dependents(conn: &Connection, file_path: &str) -> anyhow::Result<Vec<String>> {
54 let sql = format!(
55 "SELECT DISTINCT p_src.path
56 FROM edges e
57 JOIN nodes n_src ON e.source_id = n_src.id
58 JOIN nodes n_tgt ON e.target_id = n_tgt.id
59 JOIN paths p_src ON p_src.id = n_src.file_id
60 JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
61 WHERE p_tgt.path = ?1
62 AND p_src.path != ?1
63 AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
64 );
65 let mut stmt = conn.prepare(&sql)?;
66
67 let mut results: Vec<String> = stmt
68 .query_map(params![file_path], |row| row.get(0))?
69 .filter_map(std::result::Result::ok)
70 .collect();
71
72 results.sort();
73 results.dedup();
74 Ok(results)
75}
76
77pub(super) fn dependencies(conn: &Connection, file_path: &str) -> anyhow::Result<Vec<String>> {
79 let sql = format!(
80 "SELECT DISTINCT p_tgt.path
81 FROM edges e
82 JOIN nodes n_src ON e.source_id = n_src.id
83 JOIN nodes n_tgt ON e.target_id = n_tgt.id
84 JOIN paths p_src ON p_src.id = n_src.file_id
85 JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
86 WHERE p_src.path = ?1
87 AND p_tgt.path != ?1
88 AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
89 );
90 let mut stmt = conn.prepare(&sql)?;
91
92 let mut results: Vec<String> = stmt
93 .query_map(params![file_path], |row| row.get(0))?
94 .filter_map(std::result::Result::ok)
95 .collect();
96
97 results.sort();
98 results.dedup();
99 Ok(results)
100}
101
102pub(super) fn impact_analysis(
106 conn: &Connection,
107 file_path: &str,
108 max_depth: usize,
109) -> anyhow::Result<ImpactResult> {
110 let file_path = file_path.replace('\\', "/");
113 let file_path = file_path.as_str();
114 let reverse_graph = build_weighted_reverse_graph(conn)?;
115
116 let all = propagate(&reverse_graph, file_path, max_depth, false);
117 let strong = propagate(&reverse_graph, file_path, max_depth, true);
122 let weak_files: Vec<String> = all.reached.difference(&strong.reached).cloned().collect();
123
124 Ok(ImpactResult {
125 root_file: file_path.to_string(),
126 affected_files: all.reached.into_iter().collect(),
127 weak_files,
128 max_depth_reached: all.max_depth_reached,
129 edges_traversed: all.edges_traversed,
130 })
131}
132
133struct Propagation {
134 reached: BTreeSet<String>,
135 max_depth_reached: usize,
136 edges_traversed: usize,
137}
138
139fn propagate(
147 reverse_graph: &ReverseGraph,
148 root: &str,
149 max_depth: usize,
150 strong_only: bool,
151) -> Propagation {
152 const PROPAGATION_THRESHOLD: f64 = 0.1;
153 let mut best: HashMap<&str, f64> = HashMap::from([(root, 1.0)]);
155 let mut first_depth: BTreeMap<&str, usize> = BTreeMap::new();
156 let mut layer: BTreeMap<&str, f64> = BTreeMap::from([(root, 1.0)]);
157 let mut edges_traversed = 0;
158
159 for depth in 1..=max_depth {
160 let mut next: BTreeMap<&str, f64> = BTreeMap::new();
161 for (file, weight) in &layer {
162 for dep in reverse_graph.get(*file).into_iter().flatten() {
163 let Some(edge_weight) = (if strong_only {
164 dep.strong_weight
165 } else {
166 Some(dep.weight)
167 }) else {
168 continue;
169 };
170 edges_traversed += 1;
171 let propagated = weight * edge_weight;
172 if propagated < PROPAGATION_THRESHOLD
173 || best
174 .get(dep.file.as_str())
175 .is_some_and(|b| *b >= propagated)
176 {
177 continue;
178 }
179 let slot = next.entry(dep.file.as_str()).or_insert(0.0);
180 *slot = slot.max(propagated);
181 }
182 }
183 if next.is_empty() {
184 break;
185 }
186 for (file, weight) in &next {
187 best.insert(file, *weight);
188 first_depth.entry(file).or_insert(depth);
189 }
190 layer = next;
191 }
192 first_depth.remove(root);
193 Propagation {
194 max_depth_reached: first_depth.values().copied().max().unwrap_or(0),
195 reached: first_depth.into_keys().map(str::to_string).collect(),
196 edges_traversed,
197 }
198}
199
200pub(super) fn dependency_chain(
202 conn: &Connection,
203 from: &str,
204 to: &str,
205) -> anyhow::Result<Option<DependencyChain>> {
206 let from = from.replace('\\', "/");
208 let to = to.replace('\\', "/");
209 let from = from.as_str();
210 let to = to.as_str();
211 let forward_graph = build_forward_graph(conn)?;
212
213 let mut visited: HashSet<String> = HashSet::new();
214 let mut parent: HashMap<String, String> = HashMap::new();
215 let mut queue: VecDeque<String> = VecDeque::new();
216
217 visited.insert(from.to_string());
218 queue.push_back(from.to_string());
219
220 while let Some(current) = queue.pop_front() {
221 if current == to {
222 let mut path = vec![to.to_string()];
223 let mut cursor = to.to_string();
224 while let Some(prev) = parent.get(&cursor) {
225 path.push(prev.clone());
226 cursor = prev.clone();
227 }
228 path.reverse();
229 let depth = path.len() - 1;
230 return Ok(Some(DependencyChain { path, depth }));
231 }
232
233 if let Some(deps) = forward_graph.get(¤t) {
234 for dep in deps {
235 if visited.insert(dep.clone()) {
236 parent.insert(dep.clone(), current.clone());
237 queue.push_back(dep.clone());
238 }
239 }
240 }
241 }
242
243 Ok(None)
244}
245
246pub fn related_files(
249 conn: &Connection,
250 file_path: &str,
251 limit: usize,
252) -> anyhow::Result<Vec<(String, f64)>> {
253 let sql = format!(
254 "SELECT p_other.path, e.kind, e.metadata
255 FROM edges e
256 JOIN nodes n_self ON (e.source_id = n_self.id OR e.target_id = n_self.id)
257 JOIN nodes n_other ON (
258 (e.source_id = n_other.id AND e.target_id = n_self.id)
259 OR (e.target_id = n_other.id AND e.source_id = n_self.id)
260 )
261 JOIN paths p_self ON p_self.id = n_self.file_id
262 JOIN paths p_other ON p_other.id = n_other.file_id
263 WHERE p_self.path = ?1
264 AND p_other.path != ?1
265 AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
266 );
267 let mut stmt = conn.prepare(&sql)?;
268
269 let mut strongest: BTreeMap<(String, String), f64> = BTreeMap::new();
276 let rows = stmt.query_map(params![file_path], |row| {
277 Ok((
278 row.get::<_, String>(0)?,
279 row.get::<_, String>(1)?,
280 row.get::<_, Option<String>>(2)?,
281 ))
282 })?;
283 for row in rows {
284 let (path, kind, metadata) = row?;
285 let w = evidence_weight(&kind, metadata.as_deref());
286 let slot = strongest.entry((path, kind)).or_insert(0.0);
287 if w > *slot {
288 *slot = w;
289 }
290 }
291
292 let mut scores: BTreeMap<String, f64> = BTreeMap::new();
293 for ((path, _), w) in strongest {
294 *scores.entry(path).or_default() += w;
295 }
296
297 let mut results: Vec<(String, f64)> = scores.into_iter().collect();
298 results.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
301 results.truncate(limit);
302 Ok(results)
303}
304
305pub(super) fn evidence_weight(kind: &str, metadata: Option<&str>) -> f64 {
309 edge_weight(kind) * crate::core::semantic::EdgeEvidence::weight_factor_of(metadata)
310}
311
312pub fn file_connectivity(
314 conn: &Connection,
315 file_path: &str,
316) -> anyhow::Result<HashMap<String, (usize, usize)>> {
317 let mut result: HashMap<String, (usize, usize)> = HashMap::new();
318
319 let mut stmt_out = conn.prepare(
320 "SELECT e.kind, COUNT(*)
321 FROM edges e JOIN nodes n ON e.source_id = n.id
322 JOIN paths p ON p.id = n.file_id
323 WHERE p.path = ?1
324 GROUP BY e.kind",
325 )?;
326 let rows = stmt_out.query_map(params![file_path], |row| {
327 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
328 })?;
329 for row in rows {
330 let (kind, count) = row?;
331 result.entry(kind).or_insert((0, 0)).0 = count as usize;
332 }
333
334 let mut stmt_in = conn.prepare(
335 "SELECT e.kind, COUNT(*)
336 FROM edges e JOIN nodes n ON e.target_id = n.id
337 JOIN paths p ON p.id = n.file_id
338 WHERE p.path = ?1
339 GROUP BY e.kind",
340 )?;
341 let rows = stmt_in.query_map(params![file_path], |row| {
342 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
343 })?;
344 for row in rows {
345 let (kind, count) = row?;
346 result.entry(kind).or_insert((0, 0)).1 = count as usize;
347 }
348
349 Ok(result)
350}
351
352struct Dependent {
354 file: String,
355 weight: f64,
357 strong_weight: Option<f64>,
359}
360
361type ReverseGraph = BTreeMap<String, Vec<Dependent>>;
363
364fn build_weighted_reverse_graph(conn: &Connection) -> anyhow::Result<ReverseGraph> {
365 let sql = format!(
366 "SELECT p_tgt.path, p_src.path, e.kind, e.metadata
367 FROM edges e
368 JOIN nodes n_src ON e.source_id = n_src.id
369 JOIN nodes n_tgt ON e.target_id = n_tgt.id
370 JOIN paths p_src ON p_src.id = n_src.file_id
371 JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
372 WHERE e.kind IN ({STRUCTURAL_EDGE_KINDS})
373 AND p_src.path != p_tgt.path"
374 );
375 let mut stmt = conn.prepare(&sql)?;
376
377 let mut graph: BTreeMap<String, BTreeMap<String, (f64, Option<f64>)>> = BTreeMap::new();
378 let rows = stmt.query_map([], |row| {
379 Ok((
380 row.get::<_, String>(0)?,
381 row.get::<_, String>(1)?,
382 row.get::<_, String>(2)?,
383 row.get::<_, Option<String>>(3)?,
384 ))
385 })?;
386
387 for row in rows {
388 let (target, source, kind, metadata) = row?;
389 let w = evidence_weight(&kind, metadata.as_deref());
390 let strong = crate::core::semantic::EdgeEvidence::from_metadata(metadata.as_deref())
393 .is_none_or(|e| e.grade != crate::core::semantic::EvidenceGrade::HeuristicStructural);
394 let entry = graph
395 .entry(target)
396 .or_default()
397 .entry(source)
398 .or_insert((0.0, None));
399 entry.0 = entry.0.max(w);
400 if strong {
401 entry.1 = Some(entry.1.map_or(w, |s| s.max(w)));
402 }
403 }
404
405 Ok(graph
406 .into_iter()
407 .map(|(k, v)| {
408 (
409 k,
410 v.into_iter()
411 .map(|(file, (weight, strong_weight))| Dependent {
412 file,
413 weight,
414 strong_weight,
415 })
416 .collect(),
417 )
418 })
419 .collect())
420}
421
422fn build_forward_graph(conn: &Connection) -> anyhow::Result<HashMap<String, Vec<String>>> {
423 let sql = format!(
424 "SELECT DISTINCT p_src.path, p_tgt.path
425 FROM edges e
426 JOIN nodes n_src ON e.source_id = n_src.id
427 JOIN nodes n_tgt ON e.target_id = n_tgt.id
428 JOIN paths p_src ON p_src.id = n_src.file_id
429 JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
430 WHERE e.kind IN ({STRUCTURAL_EDGE_KINDS})
431 AND p_src.path != p_tgt.path"
432 );
433 let mut stmt = conn.prepare(&sql)?;
434
435 let mut graph: HashMap<String, Vec<String>> = HashMap::new();
436 let rows = stmt.query_map([], |row| {
437 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
438 })?;
439
440 for row in rows {
441 let (source, target) = row?;
442 graph.entry(source).or_default().push(target);
443 }
444
445 for deps in graph.values_mut() {
446 deps.sort();
447 deps.dedup();
448 }
449 Ok(graph)
450}