repopilot 0.10.0

Local-first CLI for repository audit, architecture risk detection, baseline tracking, and CI-friendly code review.
Documentation
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
use crate::audits::context::{AuditContext, FileRole, FrameworkKind, LanguageKind, classify_file};
use crate::audits::traits::FileAudit;
use crate::findings::types::{Confidence, Evidence, Finding, FindingCategory, Severity};
use crate::knowledge::decision::decide_for_audit_context;
use crate::scan::config::ScanConfig;
use crate::scan::facts::FileFacts;
use crate::scan::path_classification::is_low_signal_audit_path;
use std::path::Path;

mod brace;
mod python;

const RULE_ID: &str = "code-quality.long-function";

pub struct LongFunctionAudit;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct LongFunctionPolicy {
    pub threshold: usize,
    pub severity: Severity,
    pub confidence: Confidence,
    pub context_label: &'static str,
    pub confidence_reason: &'static str,
    pub recommendation: &'static str,
}

impl FileAudit for LongFunctionAudit {
    fn audit(&self, file: &FileFacts, config: &ScanConfig) -> Vec<Finding> {
        if is_low_signal_audit_path(&file.path) {
            return vec![];
        }

        let content = file.content.as_deref().unwrap_or("");

        if content.is_empty() {
            return vec![];
        }

        let Some(language) = file.language.as_deref() else {
            return vec![];
        };

        let context = classify_file(file);
        let decision = decide_for_audit_context(RULE_ID, &context, Severity::Medium, None);

        if decision.is_suppressed() {
            return vec![];
        }

        let mut policy = long_function_policy(&context, config.long_function_loc_threshold);
        policy.severity = decision.severity.min(policy.severity);

        detect_long_functions(content, language, &file.path, policy)
    }
}

fn detect_long_functions(
    content: &str,
    language: &str,
    path: &Path,
    policy: LongFunctionPolicy,
) -> Vec<Finding> {
    if language == "Python" {
        python::detect_python(content, path, policy)
    } else {
        brace::detect_brace_based(content, language, path, policy)
    }
}

fn long_function_policy(context: &AuditContext, base_threshold: usize) -> LongFunctionPolicy {
    if context.has_role(FileRole::Config) {
        return LongFunctionPolicy {
            threshold: usize::MAX,
            severity: Severity::Info,
            confidence: Confidence::Low,
            context_label: "configuration file",
            confidence_reason: "configuration files often encode declarative setup rather than executable business logic",
            recommendation: "Configuration files are not evaluated with the generic long-function threshold.",
        };
    }

    if context.is_react_component() {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(3),
            severity: Severity::Low,
            confidence: Confidence::Low,
            context_label: "React component",
            confidence_reason: "JSX, hooks, and layout markup often make component files longer without implying mixed responsibilities",
            recommendation: "Split only if state, effects, rendering, or data-shaping concerns are mixed. Prefer extracting child components, hooks, or view-model helpers at clear boundaries.",
        };
    }

    if context.is_react_hook() {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(2),
            severity: Severity::Low,
            confidence: Confidence::Low,
            context_label: "React hook",
            confidence_reason: "hooks often combine state and effect orchestration that can be longer than a pure helper function",
            recommendation: "For large hooks, consider splitting state/effect orchestration from data mapping or side-effect helpers.",
        };
    }

    if context.has_role(FileRole::UnityMonoBehaviour) || context.has_framework(FrameworkKind::Unity)
    {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(2),
            severity: Severity::Low,
            confidence: Confidence::Low,
            context_label: "Unity MonoBehaviour",
            confidence_reason: "engine lifecycle methods can accumulate setup and event wiring that is not always business logic",
            recommendation: "For large Unity behaviours, consider moving domain logic out of lifecycle methods and into smaller services or components.",
        };
    }

    if context.has_role(FileRole::DotNetController) {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(2),
            severity: Severity::Low,
            confidence: Confidence::Low,
            context_label: ".NET controller",
            confidence_reason: "controller actions often include request/response wiring that can be longer than domain logic",
            recommendation: "For large controllers, prefer moving business logic into services, handlers, or application-layer use cases.",
        };
    }

    if context.has_role(FileRole::DotNetService) {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(3) / 2,
            severity: Severity::Medium,
            confidence: Confidence::High,
            context_label: ".NET service",
            confidence_reason: "service classes usually carry reusable production orchestration where long methods signal mixed responsibilities",
            recommendation: "For large services, consider splitting orchestration, validation, persistence, and external integration logic.",
        };
    }

    if context.has_role(FileRole::RustTest) || context.is_test {
        return LongFunctionPolicy {
            threshold: base_threshold.saturating_mul(2),
            severity: Severity::Low,
            confidence: Confidence::Low,
            context_label: "test code",
            confidence_reason: "tests often include setup and assertions that are naturally longer than production helpers",
            recommendation: "For large tests, consider extracting builders, fixtures, or assertion helpers, but test setup can be naturally longer than production logic.",
        };
    }

    if context.language == LanguageKind::Rust {
        return LongFunctionPolicy {
            threshold: base_threshold,
            severity: Severity::Medium,
            confidence: Confidence::High,
            context_label: "Rust production code",
            confidence_reason: "production Rust functions are usually explicit control-flow units where length increases review and error-handling risk",
            recommendation: "Consider extracting smaller functions or methods to isolate parsing, validation, IO, or transformation steps.",
        };
    }

    LongFunctionPolicy {
        threshold: base_threshold,
        severity: Severity::Medium,
        confidence: Confidence::High,
        context_label: "generic production code",
        confidence_reason: "production functions that exceed the threshold are more likely to mix responsibilities",
        recommendation: "Long functions are harder to test and reason about; consider extracting helper functions.",
    }
}

fn build_finding(
    path: &Path,
    start_line: usize,
    end_line: usize,
    fn_name: &str,
    fn_len: usize,
    policy: LongFunctionPolicy,
) -> Finding {
    let (title, name_display) = if fn_name.is_empty() {
        (
            format!("Large {} inline function", policy.context_label),
            "inline function".to_string(),
        )
    } else {
        (
            format!("Large {} function: `{fn_name}`", policy.context_label),
            format!("`{fn_name}`"),
        )
    };

    Finding {
        id: String::new(),
        rule_id: RULE_ID.to_string(),
        recommendation: policy.recommendation.to_string(),
        title,
        description: format!(
            "This is a long function in {context_label}; confidence is {confidence} because {confidence_reason}. Function {name_display} spans {fn_len} lines, exceeding the context-aware {threshold}-line threshold. Large functions are harder to review, test, and safely change.",
            confidence = policy.confidence.label(),
            confidence_reason = policy.confidence_reason,
            threshold = policy.threshold,
            context_label = policy.context_label,
        ),
        category: FindingCategory::CodeQuality,
        severity: policy.severity,
        confidence: policy.confidence,
        evidence: vec![Evidence {
            path: path.to_path_buf(),
            line_start: start_line,
            line_end: Some(end_line),
            snippet: format!(
                "function spans lines {start_line}–{end_line} ({fn_len} lines, threshold {})",
                policy.threshold
            ),
        }],
        workspace_package: None,
        docs_url: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scan::facts::FileFacts;
    use std::path::PathBuf;

    #[test]
    fn uses_larger_threshold_for_react_component() {
        let file = facts(
            "src/components/ProfileCard.tsx",
            Some("TypeScript React"),
            &large_react_component(80),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert!(
            findings.is_empty(),
            "React component should not be flagged by the generic 50-line threshold"
        );
    }

    #[test]
    fn still_reports_very_large_react_component_with_low_severity() {
        let file = facts(
            "src/components/ProfileCard.tsx",
            Some("TypeScript React"),
            &large_react_component(170),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::Low);
        assert_eq!(findings[0].confidence, Confidence::Low);
        assert!(findings[0].title.contains("React component"));
        assert!(
            findings[0]
                .description
                .contains("confidence is LOW because JSX")
        );
        assert!(findings[0].recommendation.contains("Split only if state"));
    }

    #[test]
    fn uses_larger_threshold_for_react_hook() {
        let file = facts(
            "src/hooks/useProfile.ts",
            Some("TypeScript"),
            &large_hook(80),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert!(findings.is_empty());
    }

    #[test]
    fn still_reports_generic_typescript_utility() {
        let file = facts(
            "src/utils/buildPayload.ts",
            Some("TypeScript"),
            &large_typescript_function(60),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].severity, Severity::Medium);
        assert_eq!(findings[0].confidence, Confidence::High);
        assert!(findings[0].title.contains("generic production code"));
    }

    #[test]
    fn uses_larger_threshold_for_unity_monobehaviour() {
        let file = facts(
            "Assets/Scripts/PlayerController.cs",
            Some("CSharp"),
            &large_unity_method(80),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert!(findings.is_empty());
    }

    #[test]
    fn uses_larger_threshold_for_dotnet_controller() {
        let file = facts(
            "src/Controllers/UsersController.cs",
            Some("CSharp"),
            &large_dotnet_controller_action(80),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert!(findings.is_empty());
    }

    #[test]
    fn uses_larger_threshold_for_rust_tests() {
        let file = facts(
            "tests/integration_test.rs",
            Some("Rust"),
            &large_rust_test(80),
            false,
        );

        let findings = LongFunctionAudit.audit(
            &file,
            &ScanConfig {
                long_function_loc_threshold: 50,
                ..ScanConfig::default()
            },
        );

        assert!(findings.is_empty());
    }

    fn facts(
        path: &str,
        language: Option<&str>,
        content: &str,
        has_inline_tests: bool,
    ) -> FileFacts {
        FileFacts {
            path: PathBuf::from(path),
            language: language.map(str::to_string),
            lines_of_code: content.lines().count(),
            branch_count: 0,
            imports: Vec::new(),
            content: Some(content.to_string()),
            has_inline_tests,
        }
    }

    fn large_react_component(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "  <Text>Profile</Text>");

        format!(
            "import React from 'react';\nexport function ProfileCard() {{\n  return (\n    <View>\n{body}\n    </View>\n  );\n}}\n"
        )
    }

    fn large_hook(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "  const value = state + 1;");

        format!(
            "import {{ useEffect, useState }} from 'react';\nexport function useProfile() {{\n  const [state, setState] = useState(0);\n  useEffect(() => {{ setState(1); }}, []);\n{body}\n  return state;\n}}\n"
        )
    }

    fn large_typescript_function(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "  payload.items.push(item);");

        format!("export function buildPayload(payload: any) {{\n{body}\n  return payload;\n}}\n")
    }

    fn large_unity_method(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "        transform.position += Vector3.forward;");

        format!(
            "using UnityEngine;\npublic class PlayerController : MonoBehaviour {{\n    void Update() {{\n{body}\n    }}\n}}\n"
        )
    }

    fn large_dotnet_controller_action(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "        var value = request.Id;");

        format!(
            "using Microsoft.AspNetCore.Mvc;\n[ApiController]\npublic class UsersController : ControllerBase {{\n    public IActionResult GetUser(Request request) {{\n{body}\n        return Ok();\n    }}\n}}\n"
        )
    }

    fn large_rust_test(body_lines: usize) -> String {
        let body = repeated_lines(body_lines, "    let value = 1 + 1;");

        format!("#[test]\nfn long_integration_test() {{\n{body}\n    assert_eq!(value, 2);\n}}\n")
    }

    fn repeated_lines(count: usize, line: &str) -> String {
        std::iter::repeat_n(line, count)
            .collect::<Vec<_>>()
            .join("\n")
    }
}