Skip to main content

lean_ctx_ext/core/
smells.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Code smell detection engine.
3//!
4//! Runs structural rules against the Property Graph (SQLite) and tree-sitter
5//! data to identify dead code, high complexity, god files, fan-out skew, etc.
6//! Each rule is a pure function: `&Connection -> Vec<SmellFinding>`.
7
8use rusqlite::Connection;
9use serde::Serialize;
10
11use crate::core::property_graph::GraphSource;
12
13#[derive(Debug, Clone, Serialize)]
14pub struct SmellFinding {
15    pub rule: &'static str,
16    pub severity: Severity,
17    pub file_path: String,
18    pub symbol: Option<String>,
19    pub line: Option<usize>,
20    pub message: String,
21    pub metric: Option<f64>,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
25#[serde(rename_all = "lowercase")]
26pub enum Severity {
27    Info,
28    Warning,
29    Error,
30}
31
32#[derive(Debug, Clone, Serialize)]
33pub struct SmellSummary {
34    pub rule: &'static str,
35    pub description: &'static str,
36    pub findings: usize,
37}
38
39pub struct SmellConfig {
40    pub long_function_lines: usize,
41    pub long_file_lines: usize,
42    pub god_file_symbols: usize,
43    pub fan_out_threshold: usize,
44}
45
46impl Default for SmellConfig {
47    fn default() -> Self {
48        Self {
49            long_function_lines: 100,
50            long_file_lines: 500,
51            god_file_symbols: 30,
52            fan_out_threshold: 15,
53        }
54    }
55}
56
57pub static RULES: &[(&str, &str)] = &[
58    ("dead_code", "Symbols defined but never referenced"),
59    ("long_function", "Functions exceeding line threshold"),
60    ("long_file", "Files exceeding line threshold"),
61    ("god_file", "Files with excessive symbol count"),
62    ("fan_out_skew", "Functions calling too many other symbols"),
63    (
64        "duplicate_definitions",
65        "Same symbol name defined in multiple files",
66    ),
67    (
68        "untested_function",
69        "Exported symbols without test coverage",
70    ),
71    (
72        "cyclomatic_complexity",
73        "Functions with high branching complexity",
74    ),
75];
76
77/// Every rule over `source`. Pass the opened `CodeGraph` for findings that
78/// are served: a finding that names other files (`duplicate_definitions`)
79/// then names and counts only those served now. The row of a finding — its
80/// own file and symbol — is checked by the caller.
81pub fn scan_all<S: GraphSource + ?Sized>(source: &S, cfg: &SmellConfig) -> Vec<SmellFinding> {
82    let mut all = Vec::new();
83    for &(rule, _) in RULES {
84        all.extend(scan_rule(source, rule, cfg));
85    }
86    all
87}
88
89pub fn scan_rule<S: GraphSource + ?Sized>(
90    source: &S,
91    rule: &str,
92    cfg: &SmellConfig,
93) -> Vec<SmellFinding> {
94    let conn = source.store();
95    if rule == "duplicate_definitions" {
96        return detect_duplicate_definitions(
97            conn,
98            source.checks_sources(),
99            &|path: &str, name: &str| source.symbol_served(path, name),
100        );
101    }
102    match rule {
103        "dead_code" => detect_dead_code(conn),
104        "long_function" => detect_long_functions(conn, cfg.long_function_lines),
105        "long_file" => detect_long_files(conn, cfg.long_file_lines),
106        "god_file" => detect_god_files(conn, cfg.god_file_symbols),
107        "fan_out_skew" => detect_fan_out(conn, cfg.fan_out_threshold),
108        "untested_function" => detect_untested(conn),
109        "cyclomatic_complexity" => detect_cyclomatic_complexity(conn),
110        _ => Vec::new(),
111    }
112}
113
114pub fn summarize(findings: &[SmellFinding]) -> Vec<SmellSummary> {
115    RULES
116        .iter()
117        .map(|&(rule, desc)| SmellSummary {
118            rule,
119            description: desc,
120            findings: findings.iter().filter(|f| f.rule == rule).count(),
121        })
122        .collect()
123}
124
125/// Symbols with no incoming `calls`/`type_ref`/`imports` edge.
126///
127/// Each finding carries a confidence signal (encoded via severity + an
128/// evidence note) so callers can tell a genuinely-dead private symbol from one
129/// that is merely *available* across files. The latter — exported symbols whose
130/// module is imported elsewhere — are reported at `Info` ("verify") rather than
131/// `Warning`, because a missing reference there can be an unresolved
132/// dynamic/re-export usage rather than true death (see GH #365).
133fn detect_dead_code(conn: &Connection) -> Vec<SmellFinding> {
134    let sql = "
135        SELECT n.name, p.path, n.line_start,
136               EXISTS(
137                   SELECT 1 FROM edges e2
138                   WHERE e2.source_id = n.id AND e2.kind = 'exports'
139               ) AS exported,
140               EXISTS(
141                   SELECT 1 FROM edges e3
142                   JOIN nodes f ON f.id = e3.target_id
143                   WHERE e3.kind = 'imports'
144                     AND f.kind = 'file'
145                     AND f.file_id = n.file_id
146               ) AS file_imported
147        FROM nodes n
148        JOIN paths p ON p.id = n.file_id
149        WHERE n.kind = 'symbol'
150          AND p.path NOT LIKE '%test%'
151          AND p.path NOT LIKE '%spec%'
152          AND n.name NOT IN ('main', 'new', 'default', 'fmt', 'drop', '<module>')
153          AND n.id NOT IN (
154              SELECT DISTINCT e.target_id FROM edges e
155              WHERE e.kind IN ('calls', 'type_ref', 'imports')
156          )
157        ORDER BY p.path, n.line_start
158        LIMIT 200
159    ";
160    let mut findings = Vec::new();
161    let Ok(mut stmt) = conn.prepare(sql) else {
162        return findings;
163    };
164    let Ok(rows) = stmt.query_map([], |row| {
165        Ok((
166            row.get::<_, String>(0)?,
167            row.get::<_, String>(1)?,
168            row.get::<_, Option<i64>>(2)?,
169            row.get::<_, bool>(3)?,
170            row.get::<_, bool>(4)?,
171        ))
172    }) else {
173        return findings;
174    };
175    for (name, path, line, exported, file_imported) in rows.flatten() {
176        let (severity, confidence) = if exported && file_imported {
177            (
178                Severity::Info,
179                "low confidence: exported and its module is imported elsewhere — \
180                 may be referenced via an unresolved import or dynamic access",
181            )
182        } else if exported {
183            (
184                Severity::Warning,
185                "high confidence: exported but its module is never imported",
186            )
187        } else {
188            (
189                Severity::Warning,
190                "high confidence: private symbol with no references",
191            )
192        };
193        findings.push(SmellFinding {
194            rule: "dead_code",
195            severity,
196            file_path: path.clone(),
197            symbol: Some(name.clone()),
198            line: line.map(|l| l as usize),
199            message: format!("'{name}' defined in {path} but never referenced ({confidence})"),
200            metric: None,
201        });
202    }
203    findings
204}
205
206fn detect_long_functions(conn: &Connection, threshold: usize) -> Vec<SmellFinding> {
207    let sql = format!(
208        "SELECT n.name, p.path, n.line_start,
209                (n.line_end - n.line_start) AS span
210         FROM nodes n
211        JOIN paths p ON p.id = n.file_id
212         WHERE n.kind = 'symbol'
213           AND n.line_start IS NOT NULL
214           AND n.line_end IS NOT NULL
215           AND (n.line_end - n.line_start) > {threshold}
216         ORDER BY span DESC
217         LIMIT 100"
218    );
219    query_findings_with_metric(
220        conn,
221        &sql,
222        "long_function",
223        Severity::Warning,
224        |name, _path, _line, metric| {
225            format!("'{name}' is {metric:.0} lines (threshold: {threshold})")
226        },
227    )
228}
229
230fn detect_long_files(conn: &Connection, threshold: usize) -> Vec<SmellFinding> {
231    let sql = format!(
232        "SELECT n.name, p.path, NULL,
233                CAST(n.metadata AS INTEGER) AS line_count
234         FROM nodes n
235        JOIN paths p ON p.id = n.file_id
236         WHERE n.kind = 'file'
237           AND n.metadata IS NOT NULL
238           AND CAST(n.metadata AS INTEGER) > {threshold}
239         ORDER BY line_count DESC
240         LIMIT 100"
241    );
242    query_findings_with_metric(
243        conn,
244        &sql,
245        "long_file",
246        Severity::Info,
247        |_name, path, _line, metric| {
248            format!("{path} has {metric:.0} lines (threshold: {threshold})")
249        },
250    )
251}
252
253fn detect_god_files(conn: &Connection, threshold: usize) -> Vec<SmellFinding> {
254    let sql = format!(
255        "SELECT COUNT(*) AS sym_count, p.path
256         FROM nodes n
257        JOIN paths p ON p.id = n.file_id
258         WHERE n.kind = 'symbol'
259         GROUP BY p.path
260         HAVING sym_count > {threshold}
261         ORDER BY sym_count DESC
262         LIMIT 50"
263    );
264    let mut findings = Vec::new();
265    let Ok(mut stmt) = conn.prepare(&sql) else {
266        return findings;
267    };
268    let Ok(rows) = stmt.query_map([], |row| {
269        Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
270    }) else {
271        return findings;
272    };
273    for row in rows.flatten() {
274        let (count, path) = row;
275        findings.push(SmellFinding {
276            rule: "god_file",
277            severity: Severity::Warning,
278            file_path: path.clone(),
279            symbol: None,
280            line: None,
281            message: format!("{path} has {count} symbols (threshold: {threshold})"),
282            metric: Some(count as f64),
283        });
284    }
285    findings
286}
287
288fn detect_fan_out(conn: &Connection, threshold: usize) -> Vec<SmellFinding> {
289    let sql = format!(
290        "SELECT n.name, p.path, n.line_start, COUNT(e.id) AS call_count
291         FROM nodes n
292        JOIN paths p ON p.id = n.file_id
293         JOIN edges e ON e.source_id = n.id AND e.kind = 'calls'
294         WHERE n.kind = 'symbol'
295         GROUP BY n.id
296         HAVING call_count > {threshold}
297         ORDER BY call_count DESC
298         LIMIT 100"
299    );
300    query_findings_with_metric(
301        conn,
302        &sql,
303        "fan_out_skew",
304        Severity::Warning,
305        |name, _path, _line, metric| {
306            format!("'{name}' calls {metric:.0} symbols (threshold: {threshold})")
307        },
308    )
309}
310
311/// Symbol names defined more than once. The finding names other files, so
312/// the definitions are checked here (G04): only a definition `served` admits
313/// (path, symbol name) is listed or counted, and a name is reported only
314/// while at least two such definitions remain.
315///
316/// With `checked` (a source that asks current sources) the finding is filed
317/// under the first of its definitions, so the caller's row check passes for
318/// a served file. A raw store cannot check the list; its finding keeps the
319/// whole list as its path, which no row check serves — the list never
320/// leaves unchecked.
321fn detect_duplicate_definitions(
322    conn: &Connection,
323    checked: bool,
324    served: &dyn Fn(&str, &str) -> bool,
325) -> Vec<SmellFinding> {
326    let sql = "
327        SELECT n.name, p.path
328        FROM nodes n
329        JOIN paths p ON p.id = n.file_id
330        WHERE n.kind = 'symbol'
331          AND n.name NOT IN ('new', 'default', 'fmt', 'from', 'into', 'drop', 'clone', 'eq')
332          AND n.name IN (
333              SELECT name FROM nodes WHERE kind = 'symbol' GROUP BY name HAVING COUNT(*) > 1
334          )
335        ORDER BY n.name, p.path
336    ";
337    let Ok(mut stmt) = conn.prepare(sql) else {
338        return Vec::new();
339    };
340    let Ok(rows) = stmt.query_map([], |row| {
341        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
342    }) else {
343        return Vec::new();
344    };
345    let mut definitions: std::collections::BTreeMap<String, Vec<String>> =
346        std::collections::BTreeMap::new();
347    for (name, path) in rows.flatten() {
348        if served(&path, &name) {
349            definitions.entry(name).or_default().push(path);
350        }
351    }
352    let mut duplicated: Vec<(String, Vec<String>)> = definitions
353        .into_iter()
354        .filter(|(_, files)| files.len() > 1)
355        .collect();
356    // Most definitions first; the name keeps the cut below stable (#498).
357    duplicated.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));
358    duplicated
359        .into_iter()
360        .take(50)
361        .map(|(name, files)| {
362            let count = files.len();
363            let listed = files.join(", ");
364            SmellFinding {
365                rule: "duplicate_definitions",
366                severity: Severity::Info,
367                file_path: if checked {
368                    files[0].clone()
369                } else {
370                    listed.clone()
371                },
372                message: format!("'{name}' defined in {count} files: {listed}"),
373                symbol: Some(name),
374                line: None,
375                metric: Some(count as f64),
376            }
377        })
378        .collect()
379}
380
381fn detect_untested(conn: &Connection) -> Vec<SmellFinding> {
382    let sql = "
383        SELECT n.name, p.path, n.line_start
384        FROM nodes n
385        JOIN paths p ON p.id = n.file_id
386        WHERE n.kind = 'symbol'
387          AND p.path NOT LIKE '%test%'
388          AND p.path NOT LIKE '%spec%'
389          AND n.metadata LIKE '%export%'
390          AND n.id NOT IN (
391              SELECT DISTINCT e.source_id FROM edges e WHERE e.kind = 'tested_by'
392          )
393          AND n.id NOT IN (
394              SELECT DISTINCT e.target_id FROM edges e WHERE e.kind = 'tested_by'
395          )
396        ORDER BY p.path, n.line_start
397        LIMIT 100
398    ";
399    query_findings(
400        conn,
401        sql,
402        "untested_function",
403        Severity::Info,
404        |name, path, _line| format!("'{name}' in {path} has no test coverage"),
405    )
406}
407
408fn detect_cyclomatic_complexity(conn: &Connection) -> Vec<SmellFinding> {
409    #[cfg(feature = "tree-sitter")]
410    {
411        detect_cyclomatic_tree_sitter(conn)
412    }
413    #[cfg(not(feature = "tree-sitter"))]
414    {
415        detect_cyclomatic_heuristic(conn)
416    }
417}
418
419/// Span × calls proxy when the `tree-sitter` feature is off (no AST available).
420#[cfg(not(feature = "tree-sitter"))]
421fn detect_cyclomatic_heuristic(conn: &Connection) -> Vec<SmellFinding> {
422    let sql = "
423        SELECT n.name, p.path, n.line_start,
424               (n.line_end - n.line_start) AS span,
425               (SELECT COUNT(*) FROM edges e WHERE e.source_id = n.id AND e.kind = 'calls') AS calls
426        FROM nodes n
427        JOIN paths p ON p.id = n.file_id
428        WHERE n.kind = 'symbol'
429          AND n.line_start IS NOT NULL
430          AND n.line_end IS NOT NULL
431          AND (n.line_end - n.line_start) > 20
432        ORDER BY (span * 0.3 + calls * 0.7) DESC
433        LIMIT 100
434    ";
435    let mut findings = Vec::new();
436    let Ok(mut stmt) = conn.prepare(sql) else {
437        return findings;
438    };
439    let Ok(rows) = stmt.query_map([], |row| {
440        Ok((
441            row.get::<_, String>(0)?,
442            row.get::<_, String>(1)?,
443            row.get::<_, Option<i64>>(2)?,
444            row.get::<_, i64>(3)?,
445            row.get::<_, i64>(4)?,
446        ))
447    }) else {
448        return findings;
449    };
450    for row in rows.flatten() {
451        let (name, path, line, span, calls) = row;
452        let complexity_proxy = (span as f64) * 0.3 + (calls as f64) * 0.7;
453        if complexity_proxy < 10.0 {
454            continue;
455        }
456        let severity = if complexity_proxy > 30.0 {
457            Severity::Error
458        } else if complexity_proxy > 20.0 {
459            Severity::Warning
460        } else {
461            Severity::Info
462        };
463        findings.push(SmellFinding {
464            rule: "cyclomatic_complexity",
465            severity,
466            file_path: path,
467            symbol: Some(name.clone()),
468            line: line.map(|l| l as usize),
469            message: format!(
470                "'{name}' complexity proxy {complexity_proxy:.1} (span={span}, calls={calls})"
471            ),
472            metric: Some(complexity_proxy),
473        });
474    }
475    findings
476}
477
478#[cfg(feature = "tree-sitter")]
479fn detect_cyclomatic_tree_sitter(conn: &Connection) -> Vec<SmellFinding> {
480    use std::collections::HashMap;
481    use std::path::Path;
482
483    const WARN_CC: u32 = 11;
484    const ERR_CC: u32 = 21;
485
486    let sql = "
487        SELECT DISTINCT p.path
488        FROM nodes n
489        JOIN paths p ON p.id = n.file_id
490        WHERE n.kind = 'symbol'
491          AND p.path IS NOT NULL
492          AND length(trim(p.path)) > 0
493        LIMIT 400
494    ";
495    let mut paths = Vec::new();
496    let Ok(mut stmt) = conn.prepare(sql) else {
497        return Vec::new();
498    };
499    let Ok(rows) = stmt.query_map([], |row| row.get::<_, String>(0)) else {
500        return Vec::new();
501    };
502    for row in rows.flatten() {
503        paths.push(row);
504    }
505
506    let mut per_file: HashMap<String, Vec<crate::core::cyclomatic::FunctionComplexity>> =
507        HashMap::new();
508
509    for path in paths {
510        if per_file.contains_key(&path) {
511            continue;
512        }
513        let Ok(content) = std::fs::read_to_string(&path) else {
514            continue;
515        };
516        let Some(ext) = Path::new(&path).extension().and_then(|e| e.to_str()) else {
517            continue;
518        };
519        let Some(metrics) = crate::core::cyclomatic::cyclomatic_per_function(&content, ext) else {
520            continue;
521        };
522        per_file.insert(path, metrics);
523    }
524
525    let mut findings = Vec::new();
526    for (path, metrics) in per_file {
527        for m in metrics {
528            if m.cyclomatic < WARN_CC {
529                continue;
530            }
531            let severity = if m.cyclomatic >= ERR_CC {
532                Severity::Error
533            } else {
534                Severity::Warning
535            };
536            findings.push(SmellFinding {
537                rule: "cyclomatic_complexity",
538                severity,
539                file_path: path.clone(),
540                symbol: Some(m.name.clone()),
541                line: Some(m.line),
542                message: format!(
543                    "'{}' cyclomatic complexity {} (thresholds: warning {WARN_CC}, error {ERR_CC})",
544                    m.name, m.cyclomatic
545                ),
546                metric: Some(f64::from(m.cyclomatic)),
547            });
548        }
549    }
550
551    findings.sort_by(|a, b| {
552        b.metric
553            .unwrap_or(0.0)
554            .partial_cmp(&a.metric.unwrap_or(0.0))
555            .unwrap_or(std::cmp::Ordering::Equal)
556    });
557    findings.truncate(100);
558    findings
559}
560
561fn query_findings(
562    conn: &Connection,
563    sql: &str,
564    rule: &'static str,
565    severity: Severity,
566    msg_fn: impl Fn(&str, &str, Option<usize>) -> String,
567) -> Vec<SmellFinding> {
568    let mut findings = Vec::new();
569    let Ok(mut stmt) = conn.prepare(sql) else {
570        return findings;
571    };
572    let Ok(rows) = stmt.query_map([], |row| {
573        Ok((
574            row.get::<_, String>(0)?,
575            row.get::<_, String>(1)?,
576            row.get::<_, Option<i64>>(2)?,
577        ))
578    }) else {
579        return findings;
580    };
581    for row in rows.flatten() {
582        let (name, path, line) = row;
583        let line_usize = line.map(|l| l as usize);
584        findings.push(SmellFinding {
585            rule,
586            severity,
587            file_path: path.clone(),
588            symbol: Some(name.clone()),
589            line: line_usize,
590            message: msg_fn(&name, &path, line_usize),
591            metric: None,
592        });
593    }
594    findings
595}
596
597fn query_findings_with_metric(
598    conn: &Connection,
599    sql: &str,
600    rule: &'static str,
601    severity: Severity,
602    msg_fn: impl Fn(&str, &str, Option<usize>, f64) -> String,
603) -> Vec<SmellFinding> {
604    let mut findings = Vec::new();
605    let Ok(mut stmt) = conn.prepare(sql) else {
606        return findings;
607    };
608    let Ok(rows) = stmt.query_map([], |row| {
609        Ok((
610            row.get::<_, String>(0)?,
611            row.get::<_, String>(1)?,
612            row.get::<_, Option<i64>>(2)?,
613            row.get::<_, f64>(3)?,
614        ))
615    }) else {
616        return findings;
617    };
618    for row in rows.flatten() {
619        let (name, path, line, metric) = row;
620        let line_usize = line.map(|l| l as usize);
621        findings.push(SmellFinding {
622            rule,
623            severity,
624            file_path: path.clone(),
625            symbol: Some(name.clone()),
626            line: line_usize,
627            message: msg_fn(&name, &path, line_usize, metric),
628            metric: Some(metric),
629        });
630    }
631    findings
632}
633
634#[cfg(test)]
635mod tests {
636    use super::*;
637    use crate::core::property_graph::{CodeGraph, Edge, EdgeKind, Node, NodeKind};
638
639    fn setup_graph() -> CodeGraph {
640        let g = CodeGraph::open_in_memory().unwrap();
641
642        let file_a = g.upsert_node(&Node::file("src/main.rs")).unwrap();
643        let file_b = g.upsert_node(&Node::file("src/lib.rs")).unwrap();
644        let file_c = g
645            .upsert_node(&Node::file("src/utils.rs").with_metadata("600"))
646            .unwrap();
647
648        let sym_used = g
649            .upsert_node(
650                &Node::symbol("process", "src/lib.rs", NodeKind::Symbol).with_lines(10, 50),
651            )
652            .unwrap();
653        let sym_dead = g
654            .upsert_node(
655                &Node::symbol("unused_helper", "src/lib.rs", NodeKind::Symbol).with_lines(60, 80),
656            )
657            .unwrap();
658        let sym_long = g
659            .upsert_node(
660                &Node::symbol("mega_function", "src/utils.rs", NodeKind::Symbol).with_lines(1, 200),
661            )
662            .unwrap();
663
664        g.upsert_edge(&Edge::new(file_a, file_b, EdgeKind::Imports))
665            .unwrap();
666        g.upsert_edge(&Edge::new(file_a, sym_used, EdgeKind::Calls))
667            .unwrap();
668
669        // sym_dead has no incoming edges -> dead code
670        let _ = sym_dead;
671        let _ = sym_long;
672        let _ = file_c;
673
674        g
675    }
676
677    #[test]
678    fn dead_code_detection() {
679        let g = setup_graph();
680        let findings = detect_dead_code(g.connection());
681        let dead: Vec<_> = findings
682            .iter()
683            .filter(|f| f.symbol.as_deref() == Some("unused_helper"))
684            .collect();
685        assert!(!dead.is_empty(), "Should detect unused_helper as dead code");
686    }
687
688    #[test]
689    fn dead_code_class_with_incoming_call_is_not_flagged() {
690        // Regression for GH #365: a class that is imported and instantiated
691        // cross-file must NOT be reported as dead code, the synthetic <module>
692        // caller must never be flagged, and remaining findings must carry a
693        // confidence signal (Info for exported-and-imported, Warning for private).
694        //   models/engine.py: class Engine / Orphan / _private  (Defines)
695        //   app.py: Engine(...) (Calls -> Engine) + imports models/engine.py
696        let g = CodeGraph::open_in_memory().unwrap();
697        let engine_file = g.upsert_node(&Node::file("models/engine.py")).unwrap();
698        let app_file = g.upsert_node(&Node::file("app.py")).unwrap();
699
700        let mk = |name: &str, lo: usize, hi: usize| {
701            g.upsert_node(
702                &Node::symbol(name, "models/engine.py", NodeKind::Symbol).with_lines(lo, hi),
703            )
704            .unwrap()
705        };
706        let engine = mk("Engine", 1, 6);
707        let orphan = mk("Orphan", 8, 12);
708        let private_dead = mk("_private", 14, 18);
709        // Synthetic module-level caller node, as emitted for top-level calls.
710        let module_caller = g
711            .upsert_node(&Node::symbol("<module>", "app.py", NodeKind::Symbol))
712            .unwrap();
713
714        for sym in [engine, orphan, private_dead] {
715            g.upsert_edge(&Edge::new(engine_file, sym, EdgeKind::Defines))
716                .unwrap();
717        }
718        // Engine + Orphan are exported; the module is imported by app.py.
719        g.upsert_edge(&Edge::new(engine, engine_file, EdgeKind::Exports))
720            .unwrap();
721        g.upsert_edge(&Edge::new(orphan, engine_file, EdgeKind::Exports))
722            .unwrap();
723        g.upsert_edge(&Edge::new(app_file, engine_file, EdgeKind::Imports))
724            .unwrap();
725        // Engine is actually instantiated -> incoming Calls edge.
726        g.upsert_edge(&Edge::new(module_caller, engine, EdgeKind::Calls))
727            .unwrap();
728
729        let findings = detect_dead_code(g.connection());
730        let by_name = |n: &str| findings.iter().find(|f| f.symbol.as_deref() == Some(n));
731
732        assert!(
733            by_name("Engine").is_none(),
734            "instantiated class must not be dead"
735        );
736        assert!(
737            by_name("<module>").is_none(),
738            "synthetic <module> must never be flagged"
739        );
740
741        let orphan_f = by_name("Orphan").expect("unused exported class should still be reported");
742        assert_eq!(
743            orphan_f.severity,
744            Severity::Info,
745            "exported + imported module = low confidence (Info)"
746        );
747        assert!(orphan_f.message.contains("low confidence"));
748
749        let priv_f = by_name("_private").expect("unused private symbol should be reported");
750        assert_eq!(
751            priv_f.severity,
752            Severity::Warning,
753            "private symbol = high confidence (Warning)"
754        );
755        assert!(priv_f.message.contains("high confidence"));
756    }
757
758    #[test]
759    fn long_function_detection() {
760        let g = setup_graph();
761        let findings = detect_long_functions(g.connection(), 100);
762        let long: Vec<_> = findings
763            .iter()
764            .filter(|f| f.symbol.as_deref() == Some("mega_function"))
765            .collect();
766        assert!(!long.is_empty(), "Should detect mega_function as too long");
767    }
768
769    #[test]
770    fn long_file_detection() {
771        let g = setup_graph();
772        let findings = detect_long_files(g.connection(), 500);
773        let long: Vec<_> = findings
774            .iter()
775            .filter(|f| f.file_path == "src/utils.rs")
776            .collect();
777        assert!(
778            !long.is_empty(),
779            "Should detect src/utils.rs as long file (600 lines)"
780        );
781    }
782
783    #[test]
784    fn scan_all_returns_findings() {
785        let g = setup_graph();
786        let cfg = SmellConfig::default();
787        let all = scan_all(g.connection(), &cfg);
788        assert!(!all.is_empty(), "Should find at least one smell");
789    }
790
791    #[test]
792    fn summarize_groups_by_rule() {
793        let g = setup_graph();
794        let cfg = SmellConfig::default();
795        let all = scan_all(g.connection(), &cfg);
796        let summary = summarize(&all);
797        assert_eq!(summary.len(), RULES.len());
798        for s in &summary {
799            assert!(!s.description.is_empty(), "`s.description` is empty");
800        }
801    }
802}