repotoire 0.3.112

Graph-powered code analysis CLI. 114 detectors for security, architecture, and code quality.
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
//! Degree centrality detector
//!
//! Uses in-degree and out-degree to detect coupling issues.
//! Now enhanced with function context for smarter role-based detection.

use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::function_context::{FunctionContextMap, FunctionRole};
use crate::graph::GraphStore;
use crate::models::{Finding, Severity};
use anyhow::Result;
use std::sync::Arc;
use tracing::debug;

/// Detects coupling issues using degree centrality.
///
/// Degree centrality measures direct connections:
/// - In-degree: How many functions call this function
/// - Out-degree: How many functions this function calls
///
/// Now uses FunctionContext to make smarter decisions:
/// - Utility functions: High fan-in expected, only flag if also high fan-out
/// - Orchestrators: High fan-out expected, only flag if also high fan-in
/// - Hubs: Both high fan-in and fan-out - genuine coupling problems
pub struct DegreeCentralityDetector {
    #[allow(dead_code)] // Stored for future config access
    config: DetectorConfig,
    /// Complexity threshold for severity escalation
    high_complexity_threshold: u32,
    /// Minimum total degree for coupling hotspot
    min_total_degree: usize,
    /// Minimum fan-in to be considered elevated
    min_elevated_fanin: usize,
    /// Minimum fan-out to be considered elevated
    min_elevated_fanout: usize,
}

impl DegreeCentralityDetector {
    /// Create a new detector with default config
    pub fn new() -> Self {
        Self {
            config: DetectorConfig::new(),
            high_complexity_threshold: 15,
            min_total_degree: 50,    // Raised from 30 (too noisy for C code)
            min_elevated_fanin: 15,  // Raised from 8
            min_elevated_fanout: 15, // Raised from 8
        }
    }

    /// Create with custom config
    #[allow(dead_code)] // Builder pattern method
    pub fn with_config(config: DetectorConfig) -> Self {
        // Apply coupling multiplier to thresholds (higher multiplier = more lenient)
        let multiplier = config.coupling_multiplier;
        Self {
            high_complexity_threshold: ((config.get_option_or("high_complexity_threshold", 15)
                as f64)
                * multiplier) as u32,
            min_total_degree: ((config.get_option_or("min_total_degree", 30) as f64) * multiplier)
                as usize,
            min_elevated_fanin: ((config.get_option_or("min_elevated_fanin", 8) as f64)
                * multiplier) as usize,
            min_elevated_fanout: ((config.get_option_or("min_elevated_fanout", 8) as f64)
                * multiplier) as usize,
            config,
        }
    }

    /// Calculate severity based on metrics and function role
    fn calculate_severity(&self, fan_in: usize, fan_out: usize, role: FunctionRole) -> Severity {
        let total = fan_in + fan_out;

        // Base severity from raw metrics (raised thresholds for C code)
        let base_severity = if total >= 100 && fan_in >= 25 && fan_out >= 25 {
            Severity::High
        } else if total >= 70 {
            Severity::Medium
        } else {
            Severity::Low
        };

        // Adjust based on function role
        match role {
            FunctionRole::Utility => {
                // Utilities are expected to have high fan-in
                // Only flag if fan-out is also problematic
                if fan_out < self.min_elevated_fanout * 2 {
                    Severity::Low // Expected behavior
                } else {
                    base_severity.min(Severity::Medium)
                }
            }
            FunctionRole::Orchestrator => {
                // Orchestrators are expected to have high fan-out
                // Only flag if fan-in is also problematic
                if fan_in < self.min_elevated_fanin * 2 {
                    Severity::Low // Expected behavior
                } else {
                    base_severity.min(Severity::Medium)
                }
            }
            FunctionRole::Leaf => {
                // Leaf functions shouldn't have high coupling
                base_severity.min(Severity::Medium)
            }
            FunctionRole::Test => Severity::Low,
            FunctionRole::Hub => {
                // Hubs are genuine coupling concerns
                base_severity
            }
            FunctionRole::EntryPoint | FunctionRole::Unknown => base_severity,
        }
    }

    /// Utility function patterns (designed to be highly connected)
    const UTILITY_PREFIXES: &[&str] = &[
        // Generic utility prefixes
        "util_",
        "helper_",
        "common_",
        "core_",
        "base_",
        "lib_",
        "shared_",
        // Memory/allocation functions (core runtime, called everywhere)
        "alloc_",
        "free_",
        "malloc_",
        "realloc_",
        "mem_",
        // Logging/debug (called from everywhere)
        "log_",
        "debug_",
        "trace_",
        "info_",
        "warn_",
        "error_",
        "print_",
        // String/buffer operations
        "str_",
        "buf_",
        "fmt_",
        // Common interpreter/runtime prefixes
        "py_",
        "pyobject_",
        "_py", // CPython
        "lua_",
        "lual_",
        "luav_", // Lua
        "rb_",
        "ruby_", // Ruby
        "v8_",
        "js_", // JavaScript engines
        "g_",
        "gtk_",
        "gdk_", // GLib/GTK
        "uv_",
        "uv__", // libuv
    ];

    /// Legacy name-based skip check (fallback when no context available)
    fn should_skip_by_name(&self, name: &str) -> bool {
        let name_lower = name.to_lowercase();

        // Skip utility function prefixes (designed to be called everywhere)
        if Self::UTILITY_PREFIXES
            .iter()
            .any(|p| name_lower.starts_with(p))
        {
            return true;
        }

        // Skip utility function suffixes
        if name_lower.ends_with("_util")
            || name_lower.ends_with("_utils")
            || name_lower.ends_with("_helper")
            || name_lower.ends_with("_common")
            || name_lower.ends_with("_cb")
            || name_lower.ends_with("_callback")
            || name_lower.ends_with("_handler")
            || name_lower.ends_with("_hook")
        {
            return true;
        }

        // Detect runtime/interpreter naming convention: short_prefix + underscore
        // Examples: u3r_word, Py_Initialize, lua_pushnil, rb_str_new
        if Self::has_runtime_prefix(name) {
            return true;
        }

        const SKIP_NAMES: &[&str] = &[
            "new",
            "default",
            "from",
            "into",
            "create",
            "build",
            "make",
            "with",
            "clone",
            "drop",
            "fmt",
            "eq",
            "hash",
            "cmp",
            "partial_cmp",
            "get",
            "set",
            "instance",
            "global",
            "shared",
            "current",
            "run",
            "main",
            "init",
            "setup",
            "start",
            "execute",
            "dispatch",
            "handle",
            "read",
            "write",
            "parse",
            "format",
            "render",
            "display",
            "detect",
            "analyze",
            "iter",
            "next",
            "map",
            "filter",
            "fold",
            "is_",
            "has_",
            "check_",
            "validate_",
            "should_",
            "can_",
            "find_",
            "calculate_",
            "compute_",
            "scan_",
            "extract_",
            "normalize_",
        ];

        let name_lower = name.to_lowercase();
        SKIP_NAMES.iter().any(|&skip| {
            name_lower == skip
                || name_lower.starts_with(&format!("{}_", skip))
                || name_lower.starts_with(skip)
        })
    }

    /// Detect common runtime/interpreter naming patterns
    /// Pattern: 2-4 alphanumeric prefix + underscore (e.g., u3r_, Py_, lua_, rb_)
    fn has_runtime_prefix(func_name: &str) -> bool {
        if let Some(underscore_pos) = func_name.find('_') {
            if (2..=4).contains(&underscore_pos) {
                let prefix = &func_name[..underscore_pos];
                if prefix.chars().all(|c| c.is_alphanumeric()) {
                    let prefix_lower = prefix.to_lowercase();
                    const COMMON_WORDS: &[&str] = &[
                        "get", "set", "is", "do", "can", "has", "new", "old", "add", "del", "pop",
                        "put", "run", "try", "end", "use", "for", "the", "and", "not", "dead",
                        "live", "test", "mock", "fake", "stub", "temp", "tmp", "foo", "bar", "baz",
                        "qux", "call", "read", "load", "save", "send", "recv",
                    ];
                    if !COMMON_WORDS.contains(&prefix_lower.as_str()) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Check if path is a natural hub file or utility location
    fn is_hub_file(&self, path: &str) -> bool {
        const SKIP_PATHS: &[&str] = &[
            // Natural hub files (entry points, module roots)
            "/mod.rs",
            "/lib.rs",
            "/main.rs",
            "/index.",
            "/cli/",
            "/handlers/",
            "/server.",
            "/router.",
            // Utility directories (expected to be highly connected)
            "/util/",
            "/utils/",
            "/common/",
            "/core/",
            "/lib/",
            "/helpers/",
            "/shared/",
            "/internal/",
            // Runtime/memory (naturally called from everywhere)
            "/allocator/",
            "/memory/",
            "/alloc/",
            "/runtime/",
        ];
        let path_lower = path.to_lowercase();
        SKIP_PATHS.iter().any(|&pat| path_lower.contains(pat))
    }

    /// Create a coupling finding
    fn create_finding(
        &self,
        name: &str,
        file_path: &str,
        line_start: u32,
        line_end: u32,
        fan_in: usize,
        fan_out: usize,
        role: FunctionRole,
    ) -> Finding {
        let severity = self.calculate_severity(fan_in, fan_out, role);
        let total = fan_in + fan_out;

        let role_note = match role {
            FunctionRole::Utility => " (utility - high fan-in expected)",
            FunctionRole::Orchestrator => " (orchestrator - high fan-out expected)",
            FunctionRole::Hub => " (architectural hub)",
            _ => "",
        };

        let title = format!("High Coupling: {}{}", name, role_note);

        let description = format!(
            "Function '{}' has {} connections ({} callers, {} callees). \
            High coupling increases change risk.\n\n\
            **Analysis:**\n\
            - In-degree (callers): {}\n\
            - Out-degree (callees): {}\n\
            - Total coupling: {}",
            name, total, fan_in, fan_out, fan_in, fan_out, total
        );

        let suggested_fix = match role {
            FunctionRole::Utility => "This utility is more coupled than expected. Consider:\n\
                - Breaking into smaller, focused helpers\n\
                - Reducing its dependencies on other modules"
                .to_string(),
            FunctionRole::Hub => "This is a coupling hotspot. Consider:\n\
                - Introducing abstraction layers\n\
                - Applying facade pattern\n\
                - Splitting by responsibility"
                .to_string(),
            _ => {
                "Consider breaking into smaller functions or using dependency injection".to_string()
            }
        };

        Finding {
            id: String::new(),
            detector: "DegreeCentralityDetector".to_string(),
            severity,
            title,
            description,
            affected_files: vec![file_path.into()],
            line_start: Some(line_start),
            line_end: Some(line_end),
            suggested_fix: Some(suggested_fix),
            estimated_effort: Some("Medium (2-4 hours)".to_string()),
            category: Some("coupling".to_string()),
            cwe_id: None,
            why_it_matters: Some(
                "Highly coupled code is harder to change and test. Changes cascade unpredictably."
                    .to_string(),
            ),
            ..Default::default()
        }
    }
}

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

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

    fn description(&self) -> &'static str {
        "Detects coupling issues using degree centrality"
    }

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

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

    /// Legacy detection without context
    fn detect(&self, graph: &dyn crate::graph::GraphQuery) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        for func in graph.get_functions() {
            // Skip by name or hub file
            if self.should_skip_by_name(&func.name) || self.is_hub_file(&func.file_path) {
                continue;
            }

            let fan_in = graph.call_fan_in(&func.qualified_name);
            let fan_out = graph.call_fan_out(&func.qualified_name);
            let total_degree = fan_in + fan_out;

            // Skip expected patterns
            if fan_in > 20 && fan_out < 5 {
                continue; // Utility pattern
            }
            if fan_out > 20 && fan_in < 5 {
                continue; // Orchestrator pattern
            }

            // Only flag when BOTH are elevated
            if total_degree >= self.min_total_degree
                && fan_in >= self.min_elevated_fanin
                && fan_out >= self.min_elevated_fanout
            {
                findings.push(self.create_finding(
                    &func.name,
                    &func.file_path,
                    func.line_start,
                    func.line_end,
                    fan_in,
                    fan_out,
                    FunctionRole::Unknown,
                ));
            }
        }

        Ok(findings)
    }

    /// Whether this detector uses function context
    fn uses_context(&self) -> bool {
        true
    }

    /// Enhanced detection with function context
    fn detect_with_context(
        &self,
        graph: &dyn crate::graph::GraphQuery,
        contexts: &Arc<FunctionContextMap>,
    ) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();
        let funcs = graph.get_functions();

        debug!(
            "DegreeCentralityDetector: analyzing {} functions with context",
            funcs.len()
        );

        for func in funcs {
            // Skip common utility/trait method names
            if self.should_skip_by_name(&func.name) {
                continue;
            }

            let ctx = contexts.get(&func.qualified_name);

            // Skip test functions
            if let Some(c) = ctx {
                if c.is_test || c.role == FunctionRole::Test {
                    continue;
                }
            }

            // Skip hub files (even with context)
            if self.is_hub_file(&func.file_path) {
                continue;
            }

            let (fan_in, fan_out, role) = if let Some(c) = ctx {
                (c.in_degree, c.out_degree, c.role)
            } else {
                let fan_in = graph.call_fan_in(&func.qualified_name);
                let fan_out = graph.call_fan_out(&func.qualified_name);
                (fan_in, fan_out, FunctionRole::Unknown)
            };

            let total_degree = fan_in + fan_out;

            // Role-aware filtering
            match role {
                FunctionRole::Utility => {
                    // Utilities can have high fan-in, only flag if extreme
                    if fan_out < self.min_elevated_fanout || total_degree < 50 {
                        continue;
                    }
                }
                FunctionRole::Orchestrator => {
                    // Orchestrators can have high fan-out, only flag if extreme
                    if fan_in < self.min_elevated_fanin || total_degree < 50 {
                        continue;
                    }
                }
                FunctionRole::Leaf => {
                    // Leaf functions shouldn't have high coupling - flag if elevated
                    if total_degree < self.min_total_degree {
                        continue;
                    }
                }
                FunctionRole::Hub => {
                    // Hubs are expected to have high coupling, but still flag extreme cases
                    if total_degree < self.min_total_degree * 2 {
                        continue;
                    }
                }
                _ => {
                    // Default: require both elevated
                    if total_degree < self.min_total_degree
                        || fan_in < self.min_elevated_fanin
                        || fan_out < self.min_elevated_fanout
                    {
                        continue;
                    }
                }
            }

            findings.push(self.create_finding(
                &func.name,
                &func.file_path,
                func.line_start,
                func.line_end,
                fan_in,
                fan_out,
                role,
            ));
        }

        debug!(
            "DegreeCentralityDetector: found {} findings",
            findings.len()
        );
        Ok(findings)
    }
}

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

    #[test]
    fn test_new_detector() {
        let detector = DegreeCentralityDetector::new();
        assert_eq!(detector.high_complexity_threshold, 15);
        assert_eq!(detector.min_elevated_fanin, 15); // Raised from 8
    }

    #[test]
    fn test_severity_with_role() {
        let detector = DegreeCentralityDetector::new();

        // Utility with high fan-in but low fan-out = Low severity (expected behavior)
        let sev = detector.calculate_severity(50, 5, FunctionRole::Utility);
        assert_eq!(sev, Severity::Low);

        // Hub with medium both = Low (total=80, needs 100+ for High)
        let sev = detector.calculate_severity(40, 40, FunctionRole::Hub);
        assert_eq!(sev, Severity::Medium);

        // Hub with very high both = High (total=100, fan_in=50, fan_out=50)
        let sev = detector.calculate_severity(50, 50, FunctionRole::Hub);
        assert_eq!(sev, Severity::High);
    }

    #[test]
    fn test_skip_by_name() {
        let detector = DegreeCentralityDetector::new();

        assert!(detector.should_skip_by_name("is_valid"));
        assert!(detector.should_skip_by_name("new"));
        assert!(detector.should_skip_by_name("get"));
        assert!(!detector.should_skip_by_name("process_orders"));
    }
}