cora-code 0.17.1

CLI-first AI code review — BYOK, diff/scan/branch, pre-commit hooks
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/// Rule engine — runs static rules against parsed diff chunks and merges findings
/// with LLM issues.
pub mod builtin;
pub mod matching;
pub mod types;

use tracing::debug;

use crate::engine::diff_parser::{DiffLineType, FileChunk, parse_diff};
use crate::engine::rules::types::{RuleFinding, RulesConfig};
use crate::engine::types::{ReviewIssue, Severity};

/// Map severity to a numeric rank for sorting (Critical=4, Major=3, Minor=2, Info=1).
fn severity_rank(sev: Severity) -> u8 {
    match sev {
        Severity::Critical => 4,
        Severity::Major => 3,
        Severity::Minor => 2,
        Severity::Info => 1,
    }
}

/// Run all rules (built-in + custom) against parsed diff chunks.
///
/// Returns findings capped by `config.max_findings`.
pub fn run_rules(chunks: &[FileChunk], config: &RulesConfig) -> Vec<RuleFinding> {
    if !config.enabled {
        debug!("rule engine is disabled");
        return Vec::new();
    }

    let mut all_rules = builtin::builtin_rules();
    all_rules.extend(config.custom_rules.clone());

    // Compile regex patterns once before the matching loop (Fix #41)
    for rule in &mut all_rules {
        rule.ensure_compiled();
    }

    debug!(
        rule_count = all_rules.len(),
        "running rules against diff chunks"
    );

    let mut findings = Vec::new();

    for file in chunks {
        let file_path = file
            .new_path
            .as_deref()
            .or(file.old_path.as_deref())
            .unwrap_or("unknown");

        for hunk in &file.chunks {
            for line in &hunk.lines {
                // Only check added lines (new code being introduced)
                if line.line_type != DiffLineType::Add {
                    continue;
                }

                for rule in &all_rules {
                    // Check language filter
                    if !matching::matches_language(rule, &file.language) {
                        continue;
                    }

                    // Check exclude filter
                    if matching::matches_exclude(rule, file_path) {
                        continue;
                    }

                    // Check pattern match
                    if !matching::match_rule_against_line(rule, &line.content) {
                        continue;
                    }

                    // Post-match filter (e.g., allow localhost URLs)
                    if builtin::post_match_filter(&rule.id, &line.content) {
                        continue;
                    }

                    let line_no = line.new_line_no.unwrap_or(0);

                    findings.push(RuleFinding {
                        rule_id: rule.id.clone(),
                        file: file_path.to_string(),
                        line: line_no,
                        severity: rule.severity,
                        title: format!("[{}] Rule: {}", rule.id, rule.id),
                        body: rule.message.clone(),
                    });
                }
            }
        }
    }

    // Sort by severity descending (Critical first) then by file + line
    findings.sort_by(|a, b| {
        let rank_a = severity_rank(a.severity);
        let rank_b = severity_rank(b.severity);
        rank_b
            .cmp(&rank_a)
            .then_with(|| a.file.cmp(&b.file))
            .then_with(|| a.line.cmp(&b.line))
    });

    // Deduplicate: same rule_id + file + line
    findings.dedup_by(|a, b| a.rule_id == b.rule_id && a.file == b.file && a.line == b.line);

    // Cap at max_findings
    let capped = findings.len().min(config.max_findings);
    if findings.len() > capped {
        debug!(total = findings.len(), capped, "capping rule findings");
        findings.truncate(capped);
    }

    debug!(findings = findings.len(), "rule engine complete");
    findings
}

/// Words that carry no topic (generic review vocabulary).
const STOPWORDS: &[&str] = &[
    "the",
    "and",
    "for",
    "with",
    "via",
    "from",
    "that",
    "this",
    "use",
    "using",
    "used",
    "rule",
    "bug",
    "sec",
    "possible",
    "potential",
    "detected",
    "found",
    "issue",
    "source",
    "code",
    "line",
    "file",
    "variable",
    "value",
    "committed",
    "missing",
    "unsafe",
    "should",
    "not",
    "are",
    "can",
    "may",
    "into",
    "stored",
    "exposed",
    "in",
    "of",
    "or",
    "an",
    "to",
    "is",
];

/// Topic words of a title / rule id: lowercase alphanumeric runs, plural `s`
/// dropped, generic vocabulary removed, and the secret family (password, key,
/// token, credential, secret) folded into one word, since reviewers and
/// scanners name the same hardcoded-secret problem differently.
fn topic_words(text: &str) -> std::collections::HashSet<String> {
    text.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|w| w.len() >= 3)
        .map(|w| w.strip_suffix('s').filter(|t| t.len() >= 3).unwrap_or(w))
        .filter(|w| !STOPWORDS.contains(w))
        .map(|w| match w {
            "password" | "passwd" | "pwd" | "credential" | "token" | "apikey" | "api_key"
            | "key" | "secret" => "secret".to_string(),
            other => other.to_string(),
        })
        .collect()
}

/// True when an LLM issue plausibly describes the same problem as a scanner
/// finding: they share at least one topic word (#609).
fn same_topic(issue: &ReviewIssue, finding: &RuleFinding) -> bool {
    let mut issue_words = topic_words(&issue.title);
    if let Some(kind) = &issue.issue_type {
        issue_words.extend(topic_words(kind));
    }
    let finding_words = topic_words(&format!("{} {}", finding.title, finding.rule_id));
    issue_words.iter().any(|w| finding_words.contains(w))
}

/// Merge rule-based findings with LLM-produced issues into a single list.
///
/// Rule findings are appended after LLM issues (LLM issues take priority). A
/// rule finding is skipped as a duplicate only when an LLM issue on the same
/// file+line is about the same topic (see [`same_topic`]); its id and title are
/// then recorded on that issue's `also_matches` (not serialized) so an inline
/// `cora-ignore:` / `ignore.rules` entry naming the scanner rule still
/// suppresses it (#597). An unrelated LLM issue on the same line is neither
/// aliased nor allowed to absorb the rule finding, so a marker naming one rule
/// cannot hide a different problem (#609).
pub fn merge_rule_findings(
    llm_issues: Vec<ReviewIssue>,
    rule_findings: Vec<RuleFinding>,
) -> Vec<ReviewIssue> {
    let mut result = llm_issues;

    // (file, line) -> indexes of the pre-existing issues at that location.
    let mut at_location: std::collections::HashMap<(String, u32), Vec<usize>> =
        std::collections::HashMap::new();
    for (idx, issue) in result.iter().enumerate() {
        if let Some(ln) = issue.line {
            at_location
                .entry((issue.file.clone(), ln))
                .or_default()
                .push(idx);
        }
    }

    for finding in rule_findings {
        let holder = at_location
            .get(&(finding.file.clone(), finding.line))
            .and_then(|idxs| {
                idxs.iter()
                    .copied()
                    .find(|&i| same_topic(&result[i], &finding))
            });
        if let Some(idx) = holder {
            let holder = &mut result[idx];
            holder.also_matches.push(finding.rule_id.clone());
            holder.also_matches.push(finding.title.clone());
            debug!(
                rule_id = %finding.rule_id,
                file = %finding.file,
                line = finding.line,
                "skipping rule finding (LLM already reported the same problem at this location)"
            );
            continue;
        }

        result.push(
            ReviewIssue::new(
                finding.file,
                Some(finding.line),
                finding.severity,
                finding.title,
            )
            .with_type("rule")
            .with_body(finding.body)
            .with_rule_id(finding.rule_id),
        );
    }

    result
}

/// Format rule findings as a context string for injection into the LLM prompt.
pub fn format_rule_context(findings: &[RuleFinding]) -> String {
    if findings.is_empty() {
        return String::new();
    }

    let mut ctx = String::from("Static rule engine findings (pre-verified):\n");
    ctx.push_str("---\n");

    for f in findings {
        ctx.push_str(&format!(
            "- [{}] {}:{} — {} ({}): {}",
            f.severity, f.file, f.line, f.rule_id, f.severity, f.body
        ));
        ctx.push('\n');
    }

    ctx.push_str("---\n");
    ctx
}

/// Convenience: parse diff + run rules in one step.
#[allow(dead_code)] // public API for future standalone usage
pub fn parse_and_run_rules(diff: &str, config: &RulesConfig) -> Vec<RuleFinding> {
    let chunks = parse_diff(diff);
    run_rules(&chunks, config)
}

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

    fn default_config() -> RulesConfig {
        RulesConfig {
            enabled: true,
            max_findings: 10,
            custom_rules: Vec::new(),
            index_skip_files: super::types::default_index_skip_files(),
        }
    }

    #[test]
    fn unwrap_rule_fires_on_rust_code() {
        let diff = r#"diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,2 +1,3 @@
 fn main() {
+    let x = something.unwrap();
 }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        let unwrap_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.rule_id == "bug-unwrap")
            .collect();
        assert!(
            !unwrap_findings.is_empty(),
            "should detect .unwrap() in added Rust code"
        );
    }

    #[test]
    fn todo_rule_fires() {
        let diff = r#"diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,2 +1,3 @@
 fn main() {
+    // TODO: fix this later
 }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        let todo_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.rule_id == "bug-todo")
            .collect();
        assert!(!todo_findings.is_empty(), "should detect TODO comment");
    }

    #[test]
    fn println_rule_fires_in_rust() {
        let diff = r#"diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,1 +1,2 @@
 pub fn greet() {
+    println!("hello");
 }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            findings.iter().any(|f| f.rule_id == "bug-println"),
            "should detect println! macro"
        );
    }

    #[test]
    fn console_log_rule_fires_in_ts() {
        let diff = r#"diff --git a/app.ts b/app.ts
--- a/app.ts
+++ b/app.ts
@@ -1,1 +1,2 @@
 function init() {
+    console.log("starting");
 }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            findings.iter().any(|f| f.rule_id == "bug-console-log"),
            "should detect console.log in TypeScript"
        );
    }

    #[test]
    fn language_filter_works() {
        // println! in a Python file should NOT fire bug-println (Rust only)
        let diff = r#"diff --git a/script.py b/script.py
--- a/script.py
+++ b/script.py
@@ -1,1 +1,2 @@
 def main():
+    println!("hello")
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            !findings.iter().any(|f| f.rule_id == "bug-println"),
            "bug-println should not fire on Python files"
        );
    }

    #[test]
    fn exclude_filter_works() {
        // unwrap in test/ directory should NOT fire
        let diff = r#"diff --git a/tests/integration.rs b/tests/integration.rs
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1,1 +1,2 @@
 #[test]
+fn test_something() { let _ = result.unwrap(); }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            !findings.iter().any(|f| f.rule_id == "bug-unwrap"),
            "bug-unwrap should not fire in tests/ directory"
        );
    }

    #[test]
    fn disabled_config_returns_no_findings() {
        let diff = r#"diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,2 +1,3 @@
 fn main() {
+    let x = something.unwrap();
 }
"#;
        let config = RulesConfig {
            enabled: false,
            ..default_config()
        };
        let findings = parse_and_run_rules(diff, &config);
        assert!(
            findings.is_empty(),
            "disabled config should produce no findings"
        );
    }

    #[test]
    fn max_findings_cap() {
        let diff = r#"diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,2 +1,8 @@
 fn main() {
+    let a = x.unwrap();
+    let b = y.clone();
+    let c = z.clone();
+    println!("debug");
+    // TODO: something
+    // FIXME: another
 }
"#;
        let config = RulesConfig {
            max_findings: 2,
            ..default_config()
        };
        let findings = parse_and_run_rules(diff, &config);
        assert!(findings.len() <= 2, "should cap findings at max_findings");
    }

    fn llm_issue(line: u32, title: &str, kind: Option<&str>) -> ReviewIssue {
        let issue = ReviewIssue::new("src/a.rs", Some(line), Severity::Major, title);
        match kind {
            Some(k) => issue.with_type(k),
            None => issue,
        }
    }

    fn secret_finding(line: u32) -> RuleFinding {
        RuleFinding {
            rule_id: "crypto/hardcoded-secret".to_string(),
            file: "src/a.rs".to_string(),
            line,
            severity: Severity::Critical,
            title: "Hardcoded password or secret in variable".to_string(),
            body: String::new(),
        }
    }

    #[test]
    fn same_topic_matches_secret_family_wording() {
        for t in [
            "Hardcoded password stored in source code",
            "Hardcoded API key committed",
            "Plaintext credentials in config",
            "Weak, low-entropy secret",
            "Token exposed in source",
        ] {
            assert!(
                same_topic(&llm_issue(1, t, None), &secret_finding(1)),
                "{t}"
            );
        }
    }

    #[test]
    fn unrelated_llm_issue_neither_absorbs_nor_aliases_rule_finding() {
        // #609: SQL injection on the same line as a hardcoded secret.
        let merged = merge_rule_findings(
            vec![llm_issue(
                5,
                "SQL injection via string concatenation",
                Some("security"),
            )],
            vec![secret_finding(5)],
        );
        assert_eq!(merged.len(), 2);
        assert!(merged[0].also_matches.is_empty());
        assert_eq!(
            merged[1].rule_id.as_deref(),
            Some("crypto/hardcoded-secret")
        );
    }

    #[test]
    fn alias_goes_to_the_related_issue_not_the_first_one() {
        let merged = merge_rule_findings(
            vec![
                llm_issue(5, "SQL injection via string concatenation", None),
                llm_issue(5, "Hardcoded password stored in source code", None),
            ],
            vec![secret_finding(5)],
        );
        assert_eq!(merged.len(), 2);
        assert!(merged[0].also_matches.is_empty());
        assert!(
            merged[1]
                .also_matches
                .contains(&"crypto/hardcoded-secret".to_string())
        );
    }

    #[test]
    fn merge_skips_duplicates() {
        let llm = vec![
            ReviewIssue::new(
                "src/main.rs",
                Some(5),
                Severity::Minor,
                "Unnecessary unwrap",
            )
            .with_type("bug")
            .with_body("Use proper error handling"),
        ];

        let rules = vec![RuleFinding {
            rule_id: "bug-unwrap".to_string(),
            file: "src/main.rs".to_string(),
            line: 5,
            severity: Severity::Minor,
            title: "[bug-unwrap] Rule: bug-unwrap".to_string(),
            body: "Can panic".to_string(),
        }];

        let merged = merge_rule_findings(llm, rules);
        // Should have 1 issue (LLM's), not 2 — rule finding at same location skipped
        assert_eq!(merged.len(), 1);
        // ...but its id and title stay addressable for suppression (#597).
        assert!(merged[0].also_matches.contains(&"bug-unwrap".to_string()));
        assert!(
            merged[0]
                .also_matches
                .contains(&"[bug-unwrap] Rule: bug-unwrap".to_string())
        );
        assert!(merged[0].rule_id.is_none());
    }

    #[test]
    fn merge_appends_unique_rule_findings() {
        let llm = vec![
            ReviewIssue::new("src/main.rs", Some(5), Severity::Minor, "Some issue")
                .with_type("bug")
                .with_body("Details"),
        ];

        let rules = vec![RuleFinding {
            rule_id: "bug-todo".to_string(),
            file: "src/main.rs".to_string(),
            line: 10,
            severity: Severity::Info,
            title: "[bug-todo] Rule: bug-todo".to_string(),
            body: "TODO found".to_string(),
        }];

        let merged = merge_rule_findings(llm, rules);
        assert_eq!(merged.len(), 2);
        assert_eq!(merged[1].issue_type.as_deref(), Some("rule"));
    }

    #[test]
    fn format_rule_context_non_empty() {
        let findings = vec![RuleFinding {
            rule_id: "bug-todo".to_string(),
            file: "src/lib.rs".to_string(),
            line: 42,
            severity: Severity::Info,
            title: "[bug-todo] Rule: bug-todo".to_string(),
            body: "TODO comment found".to_string(),
        }];
        let ctx = format_rule_context(&findings);
        assert!(ctx.contains("bug-todo"));
        assert!(ctx.contains("src/lib.rs:42"));
    }

    #[test]
    fn format_rule_context_empty() {
        let ctx = format_rule_context(&[]);
        assert!(ctx.is_empty());
    }

    #[test]
    fn hardcoded_secret_rule_fires() {
        let diff = r#"diff --git a/config.py b/config.py
--- a/config.py
+++ b/config.py
@@ -1,2 +1,3 @@
 # Config
+password = "super_secret_123"
 DB_HOST = "localhost"
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            findings.iter().any(|f| f.rule_id == "sec-hardcoded-secret"),
            "should detect hardcoded password"
        );
    }

    #[test]
    fn hardcoded_url_rule_fires() {
        let diff = r#"diff --git a/src/client.rs b/src/client.rs
--- a/src/client.rs
+++ b/src/client.rs
@@ -1,2 +1,3 @@
 fn get_url() -> &'static str {
+    "http://example.com/api/data"
 }
"#;
        let chunks = parse_diff(diff);
        eprintln!("DEBUG: {} chunks parsed", chunks.len());
        for (i, c) in chunks.iter().enumerate() {
            eprintln!(
                "DEBUG chunk[{}]: lang={}, new_path={:?}, hunks={}",
                i,
                c.language,
                c.new_path,
                c.chunks.len()
            );
            for (j, h) in c.chunks.iter().enumerate() {
                eprintln!("DEBUG   hunk[{}]: {} lines", j, h.lines.len());
                for l in &h.lines {
                    eprintln!("DEBUG     line: {:?} {:?}", l.line_type, l.content);
                }
            }
        }
        let findings = parse_and_run_rules(diff, &default_config());
        eprintln!("DEBUG: {} findings total", findings.len());
        for f in &findings {
            eprintln!("DEBUG finding: {:?}", f);
        }
        assert!(
            findings.iter().any(|f| f.rule_id == "sec-hardcoded-url"),
            "should detect non-localhost http:// URL"
        );
    }

    #[test]
    fn hardcoded_url_localhost_allowed() {
        let diff = r#"diff --git a/src/client.rs b/src/client.rs
--- a/src/client.rs
+++ b/src/client.rs
@@ -1,2 +1,3 @@
 fn get_url() -> &'static str {
+    "http://localhost:3000/health"
 }
"#;
        let findings = parse_and_run_rules(diff, &default_config());
        assert!(
            !findings.iter().any(|f| f.rule_id == "sec-hardcoded-url"),
            "localhost http URLs should be allowed"
        );
    }
}