repotoire 0.2.17

Graph-powered code analysis CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Dead code detector - finds unused functions and classes
//!
//! Detects code that is never called or instantiated, indicating:
//! - Leftover code from refactoring
//! - Unused features
//! - Test helpers that were never removed
//!
//! Uses graph analysis to find nodes with zero incoming CALLS relationships.

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphClient;
use crate::models::{Finding, Severity};
use anyhow::Result;
use std::collections::HashSet;
use std::path::PathBuf;
use tracing::{debug, info};
use uuid::Uuid;

/// Entry points that should not be flagged as dead code
static ENTRY_POINTS: &[&str] = &[
    "main",
    "__main__",
    "__init__",
    "setUp",
    "tearDown",
];

/// Special methods that are called implicitly
static MAGIC_METHODS: &[&str] = &[
    "__str__",
    "__repr__",
    "__enter__",
    "__exit__",
    "__call__",
    "__len__",
    "__iter__",
    "__next__",
    "__getitem__",
    "__setitem__",
    "__delitem__",
    "__eq__",
    "__ne__",
    "__lt__",
    "__le__",
    "__gt__",
    "__ge__",
    "__hash__",
    "__bool__",
    "__add__",
    "__sub__",
    "__mul__",
    "__truediv__",
    "__floordiv__",
    "__mod__",
    "__pow__",
    "__post_init__",
    "__init_subclass__",
    "__set_name__",
];

/// Thresholds for dead code detection
#[derive(Debug, Clone)]
pub struct DeadCodeThresholds {
    /// Base confidence for graph-only detection
    pub base_confidence: f64,
    /// Maximum functions to return
    pub max_results: usize,
}

impl Default for DeadCodeThresholds {
    fn default() -> Self {
        Self {
            base_confidence: 0.70,
            max_results: 100,
        }
    }
}

/// Detects dead code (unused functions and classes)
pub struct DeadCodeDetector {
    config: DetectorConfig,
    thresholds: DeadCodeThresholds,
    entry_points: HashSet<String>,
    magic_methods: HashSet<String>,
}

impl DeadCodeDetector {
    /// Create a new detector with default thresholds
    pub fn new() -> Self {
        Self::with_thresholds(DeadCodeThresholds::default())
    }

    /// Create with custom thresholds
    pub fn with_thresholds(thresholds: DeadCodeThresholds) -> Self {
        let entry_points: HashSet<String> = ENTRY_POINTS.iter().map(|s| s.to_string()).collect();
        let magic_methods: HashSet<String> = MAGIC_METHODS.iter().map(|s| s.to_string()).collect();

        Self {
            config: DetectorConfig::new(),
            thresholds,
            entry_points,
            magic_methods,
        }
    }

    /// Create with custom config
    pub fn with_config(config: DetectorConfig) -> Self {
        let thresholds = DeadCodeThresholds {
            base_confidence: config.get_option_or("base_confidence", 0.70),
            max_results: config.get_option_or("max_results", 100),
        };

        Self::with_thresholds(thresholds)
    }

    /// Check if a function name is an entry point
    fn is_entry_point(&self, name: &str) -> bool {
        self.entry_points.contains(name) || name.starts_with("test_")
    }

    /// Check if a function name is a magic method
    fn is_magic_method(&self, name: &str) -> bool {
        self.magic_methods.contains(name)
    }

    /// Check if function should be filtered out
    fn should_filter(&self, name: &str, is_method: bool, has_decorators: bool) -> bool {
        // Magic methods
        if self.is_magic_method(name) {
            return true;
        }

        // Entry points
        if self.is_entry_point(name) {
            return true;
        }

        // Public methods (may be called externally)
        if is_method && !name.starts_with('_') {
            return true;
        }

        // Decorated functions
        if has_decorators {
            return true;
        }

        // Common patterns that are often called dynamically
        let filter_patterns = [
            "handle",
            "on_",
            "callback",
            "load_data",
            "loader",
            "_loader",
            "load_",
            "create_",
            "build_",
            "make_",
            "_parse_",
            "_process_",
            "load_config",
            "generate_",
            "validate_",
            "setup_",
            "initialize_",
            "to_dict",
            "to_json",
            "from_dict",
            "from_json",
            "serialize",
            "deserialize",
            "_side_effect",
            "_effect",
            "_extract_",
            "_find_",
            "_calculate_",
            "_get_",
            "_set_",
            "_check_",
        ];

        let name_lower = name.to_lowercase();
        for pattern in filter_patterns {
            if name_lower.contains(pattern) {
                return true;
            }
        }

        false
    }

    /// Calculate severity for dead function
    fn calculate_function_severity(&self, complexity: usize) -> Severity {
        if complexity >= 20 {
            Severity::High
        } else if complexity >= 10 {
            Severity::Medium
        } else {
            Severity::Low
        }
    }

    /// Calculate severity for dead class
    fn calculate_class_severity(&self, method_count: usize, complexity: usize) -> Severity {
        if method_count >= 10 || complexity >= 50 {
            Severity::High
        } else if method_count >= 5 || complexity >= 20 {
            Severity::Medium
        } else {
            Severity::Low
        }
    }

    /// Create a finding for an unused function
    fn create_function_finding(
        &self,
        _qualified_name: String,
        name: String,
        file_path: String,
        line_start: Option<u32>,
        complexity: usize,
    ) -> Finding {
        let severity = self.calculate_function_severity(complexity);
        let confidence = self.thresholds.base_confidence;

        Finding {
            id: Uuid::new_v4().to_string(),
            detector: "DeadCodeDetector".to_string(),
            severity,
            title: format!("Unused function: {}", name),
            description: format!(
                "Function '{}' is never called in the codebase. \
                 It has complexity {}.\n\n\
                 **Confidence:** {:.0}% (graph analysis only)\n\
                 **Recommendation:** Review before removing",
                name,
                complexity,
                confidence * 100.0
            ),
            affected_files: vec![PathBuf::from(&file_path)],
            line_start,
            line_end: None,
            suggested_fix: Some(format!(
                "**REVIEW REQUIRED** (confidence: {:.0}%)\n\
                 1. Remove the function from {}\n\
                 2. Check for dynamic calls (getattr, eval) that might use it\n\
                 3. Verify it's not an API endpoint or callback",
                confidence * 100.0,
                file_path.split('/').last().unwrap_or(&file_path)
            )),
            estimated_effort: Some("Small (30-60 minutes)".to_string()),
            category: Some("dead_code".to_string()),
            cwe_id: Some("CWE-561".to_string()), // Dead Code
            why_it_matters: Some(
                "Dead code increases maintenance burden, confuses developers, \
                 and can hide bugs. Removing unused code improves readability \
                 and reduces the codebase size."
                    .to_string(),
            ),
        }
    }

    /// Create a finding for an unused class
    fn create_class_finding(
        &self,
        _qualified_name: String,
        name: String,
        file_path: String,
        method_count: usize,
        complexity: usize,
    ) -> Finding {
        let severity = self.calculate_class_severity(method_count, complexity);
        let confidence = self.thresholds.base_confidence;

        let effort = if method_count >= 10 {
            "Medium (2-4 hours)"
        } else if method_count >= 5 {
            "Small (1-2 hours)"
        } else {
            "Small (30 minutes)"
        };

        Finding {
            id: Uuid::new_v4().to_string(),
            detector: "DeadCodeDetector".to_string(),
            severity,
            title: format!("Unused class: {}", name),
            description: format!(
                "Class '{}' is never instantiated or inherited from. \
                 It has {} methods and complexity {}.\n\n\
                 **Confidence:** {:.0}% (graph analysis only)\n\
                 **Recommendation:** Review before removing",
                name,
                method_count,
                complexity,
                confidence * 100.0
            ),
            affected_files: vec![PathBuf::from(&file_path)],
            line_start: None,
            line_end: None,
            suggested_fix: Some(format!(
                "**REVIEW REQUIRED** (confidence: {:.0}%)\n\
                 1. Remove the class and its {} methods\n\
                 2. Check for dynamic instantiation (factory patterns, reflection)\n\
                 3. Verify it's not used in configuration or plugins",
                confidence * 100.0,
                method_count
            )),
            estimated_effort: Some(effort.to_string()),
            category: Some("dead_code".to_string()),
            cwe_id: Some("CWE-561".to_string()),
            why_it_matters: Some(
                "Unused classes bloat the codebase and increase cognitive load. \
                 They may also cause confusion about the system's actual behavior."
                    .to_string(),
            ),
        }
    }

    /// Find dead functions
    fn find_dead_functions(&self, graph: &GraphClient) -> Result<Vec<Finding>> {
        let query = r#"
            MATCH (f:Function)
            WHERE NOT (f.name STARTS WITH 'test_')
              AND NOT f.name IN ['main', '__main__', '__init__', 'setUp', 'tearDown']
            OPTIONAL MATCH (f)<-[rel:CALLS]-()
            OPTIONAL MATCH (f)<-[use:USES]-()
            WITH f, count(rel) AS call_count, count(use) AS use_count
            WHERE call_count = 0 AND use_count = 0
            OPTIONAL MATCH (file:File)-[:CONTAINS]->(f)
            RETURN f.qualifiedName AS qualified_name,
                   f.name AS name,
                   f.filePath AS file_path,
                   f.lineStart AS line_start,
                   f.complexity AS complexity,
                   file.filePath AS containing_file,
                   f.decorators AS decorators,
                   f.is_method AS is_method
            ORDER BY f.complexity DESC
            LIMIT 100
        "#;

        let results = graph.execute(query)?;
        let mut findings = Vec::new();

        for row in results {
            let name = row
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let is_method = row
                .get("is_method")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);

            let decorators = row
                .get("decorators")
                .and_then(|v| v.as_array())
                .map(|v| !v.is_empty())
                .unwrap_or(false);

            // Apply filters
            if self.should_filter(&name, is_method, decorators) {
                continue;
            }

            let qualified_name = row
                .get("qualified_name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let file_path = row
                .get("containing_file")
                .or_else(|| row.get("file_path"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let line_start = row
                .get("line_start")
                .and_then(|v| v.as_u64())
                .map(|v| v as u32);

            let complexity = row
                .get("complexity")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;

            findings.push(self.create_function_finding(
                qualified_name,
                name,
                file_path,
                line_start,
                complexity,
            ));

            if findings.len() >= self.thresholds.max_results {
                break;
            }
        }

        Ok(findings)
    }

    /// Find dead classes
    fn find_dead_classes(&self, graph: &GraphClient) -> Result<Vec<Finding>> {
        let query = r#"
            MATCH (file:File)-[:CONTAINS]->(c:Class)
            OPTIONAL MATCH (c)<-[rel:CALLS]-()
            OPTIONAL MATCH (c)<-[inherit:INHERITS]-()
            OPTIONAL MATCH (c)<-[use:USES]-()
            WITH c, file, count(rel) AS call_count, count(inherit) AS inherit_count, count(use) AS use_count
            WHERE call_count = 0 AND inherit_count = 0 AND use_count = 0
            RETURN c.qualifiedName AS qualified_name,
                   c.name AS name,
                   c.filePath AS file_path,
                   c.complexity AS complexity,
                   file.filePath AS containing_file,
                   c.decorators AS decorators
            ORDER BY c.complexity DESC
            LIMIT 50
        "#;

        let results = graph.execute(query)?;
        let mut findings = Vec::new();

        for row in results {
            let name = row
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            // Skip common patterns
            if name.ends_with("Error")
                || name.ends_with("Exception")
                || name.ends_with("Mixin")
                || name.contains("Mixin")
                || name.starts_with("Test")
                || name.ends_with("Test")
                || name == "ABC"
                || name == "Enum"
                || name == "Exception"
                || name == "BaseException"
            {
                continue;
            }

            // Skip decorated classes
            let decorators = row
                .get("decorators")
                .and_then(|v| v.as_array())
                .map(|v| !v.is_empty())
                .unwrap_or(false);

            if decorators {
                continue;
            }

            let qualified_name = row
                .get("qualified_name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let file_path = row
                .get("containing_file")
                .or_else(|| row.get("file_path"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let complexity = row
                .get("complexity")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;

            // TODO: Get actual method count from graph
            let method_count = 0usize;

            findings.push(self.create_class_finding(
                qualified_name,
                name,
                file_path,
                method_count,
                complexity,
            ));
        }

        Ok(findings)
    }
}

impl Default for DeadCodeDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl Detector for DeadCodeDetector {
    fn name(&self) -> &'static str {
        "DeadCodeDetector"
    }

    fn description(&self) -> &'static str {
        "Detects unused functions and classes"
    }

    fn category(&self) -> &'static str {
        "dead_code"
    }

    fn config(&self) -> Option<&DetectorConfig> {
        Some(&self.config)
    }

    fn detect(&self, graph: &GraphClient) -> Result<Vec<Finding>> {
        debug!("Starting dead code detection");

        let mut findings = Vec::new();

        // Find dead functions
        let function_findings = self.find_dead_functions(graph)?;
        findings.extend(function_findings);

        // Find dead classes
        let class_findings = self.find_dead_classes(graph)?;
        findings.extend(class_findings);

        // Sort by severity
        findings.sort_by(|a, b| b.severity.cmp(&a.severity));

        info!("DeadCodeDetector found {} dead code issues", findings.len());

        Ok(findings)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_entry_points() {
        let detector = DeadCodeDetector::new();

        assert!(detector.is_entry_point("main"));
        assert!(detector.is_entry_point("__init__"));
        assert!(detector.is_entry_point("test_something"));
        assert!(!detector.is_entry_point("my_function"));
    }

    #[test]
    fn test_magic_methods() {
        let detector = DeadCodeDetector::new();

        assert!(detector.is_magic_method("__str__"));
        assert!(detector.is_magic_method("__repr__"));
        assert!(!detector.is_magic_method("my_method"));
    }

    #[test]
    fn test_should_filter() {
        let detector = DeadCodeDetector::new();

        // Magic methods
        assert!(detector.should_filter("__str__", false, false));

        // Entry points
        assert!(detector.should_filter("main", false, false));
        assert!(detector.should_filter("test_foo", false, false));

        // Public methods
        assert!(detector.should_filter("public_method", true, false));
        assert!(!detector.should_filter("_private_method", true, false));

        // Decorated
        assert!(detector.should_filter("any_func", false, true));

        // Patterns
        assert!(detector.should_filter("load_config", false, false));
        assert!(detector.should_filter("to_dict", false, false));
    }

    #[test]
    fn test_severity() {
        let detector = DeadCodeDetector::new();

        assert_eq!(detector.calculate_function_severity(5), Severity::Low);
        assert_eq!(detector.calculate_function_severity(10), Severity::Medium);
        assert_eq!(detector.calculate_function_severity(25), Severity::High);

        assert_eq!(detector.calculate_class_severity(3, 10), Severity::Low);
        assert_eq!(detector.calculate_class_severity(5, 10), Severity::Medium);
        assert_eq!(detector.calculate_class_severity(10, 10), Severity::High);
    }
}