llmlint 0.2.7

LLM-as-judge linter: enforce code-quality checks deterministic linters can't express, by driving real coding harnesses through oneharness.
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
//! Assemble rule outcomes into a report: human-readable text or stable JSON,
//! plus the process exit code.

use serde_json::{json, Value};

use crate::domain::verdict::{Outcome, RuleOutcome, Violation};

/// The full result of a lint run.
#[derive(Debug, Clone)]
pub struct Report {
    pub outcomes: Vec<RuleOutcome>,
    /// Judge runs that could not produce a usable verdict (oneharness/schema
    /// failures). Their presence makes the run exit `2` (could not complete).
    pub run_errors: Vec<String>,
}

impl Report {
    pub fn new(mut outcomes: Vec<RuleOutcome>, run_errors: Vec<String>) -> Self {
        outcomes.sort_by(|a, b| a.name.cmp(&b.name));
        Report {
            outcomes,
            run_errors,
        }
    }

    fn counts(&self) -> (usize, usize, usize) {
        let mut pass = 0;
        let mut fail = 0;
        let mut skip = 0;
        for o in &self.outcomes {
            match o.outcome {
                Outcome::Pass => pass += 1,
                Outcome::Fail => fail += 1,
                Outcome::Skipped => skip += 1,
            }
        }
        (pass, fail, skip)
    }

    /// Exit code: `2` if any judge run errored (incomplete), else `1` if any
    /// rule failed, else `0`.
    pub fn exit_code(&self) -> i32 {
        if !self.run_errors.is_empty() {
            2
        } else if self.outcomes.iter().any(|o| o.outcome == Outcome::Fail) {
            1
        } else {
            0
        }
    }

    /// Render the report for humans at the given verbosity. Level `0` (default)
    /// lists failing rules and their locations; `1`+ additionally itemizes every
    /// passing and skipped rule. Operational errors (a run that couldn't
    /// complete) are surfaced at every level, since they explain a `2` exit the
    /// summary only counts. A blank line separates any per-rule/error detail
    /// from the trailing summary. (The oneharness command/result debug view is
    /// emitted separately to stderr at `-v` by the `lint` command.)
    pub fn to_human(&self, verbosity: u8) -> String {
        let mut out = String::new();
        for o in &self.outcomes {
            match o.outcome {
                // Failures are shown even at the default level — they are the
                // actionable result of a lint run.
                Outcome::Fail => {
                    out.push_str(&format!("FAIL {}{}\n", o.name, votes_suffix(o)));
                    // A failure is the actionable result, so its reasoning shows
                    // at every level (right after the header, before locations).
                    push_reasoning(&mut out, o);
                    for v in &o.violations {
                        out.push_str(&format!("     {}\n", format_violation(v)));
                    }
                }
                // Passing and skipped rules are only itemized at `-v`; at the
                // default level the summary alone accounts for them.
                Outcome::Pass if verbosity >= 1 => {
                    out.push_str(&format!("PASS {}{}\n", o.name, votes_suffix(o)));
                    push_reasoning(&mut out, o);
                }
                Outcome::Skipped if verbosity >= 1 => {
                    out.push_str(&format!("SKIP {} (no files matched)\n", o.name))
                }
                Outcome::Pass | Outcome::Skipped => {}
            }
        }
        for e in &self.run_errors {
            out.push_str(&format!("ERROR {e}\n"));
        }
        if !out.is_empty() {
            out.push('\n');
        }
        let (pass, fail, skip) = self.counts();
        out.push_str(&format!(
            "{} rules: {} passed, {} failed, {} skipped",
            self.outcomes.len(),
            pass,
            fail,
            skip
        ));
        if !self.run_errors.is_empty() {
            out.push_str(&format!(", {} errored", self.run_errors.len()));
        }
        out.push('\n');
        out
    }

    pub fn to_json(&self) -> Value {
        let (pass, fail, skip) = self.counts();
        json!({
            "summary": {
                "total": self.outcomes.len(),
                "passed": pass,
                "failed": fail,
                "skipped": skip,
                "errored": self.run_errors.len(),
            },
            "rules": self.outcomes,
            "errors": self.run_errors,
        })
    }
}

/// The `(X/Y judges held)` suffix for a multi-judge rule, else empty.
fn votes_suffix(o: &RuleOutcome) -> String {
    if o.votes_total > 1 {
        format!(" ({}/{} judges held)", o.votes_hold, o.votes_total)
    } else {
        String::new()
    }
}

/// Append a rule's reasoning under its header. For a multi-judge rule this is a
/// per-judge breakdown — each judge's result (`held`/`violated`) and rationale,
/// so disagreement is visible; for a single judge it is the one rationale line.
fn push_reasoning(out: &mut String, o: &RuleOutcome) {
    if !o.judges.is_empty() {
        for (i, j) in o.judges.iter().enumerate() {
            let verdict = if j.holds { "held" } else { "violated" };
            match j
                .rationale
                .as_deref()
                .map(str::trim)
                .filter(|r| !r.is_empty())
            {
                Some(r) => out.push_str(&format!("     judge {} {verdict}: {r}\n", i + 1)),
                None => out.push_str(&format!("     judge {} {verdict}\n", i + 1)),
            }
        }
    } else if let Some(r) = &o.rationale {
        let r = r.trim();
        if !r.is_empty() {
            out.push_str(&format!("     rationale: {r}\n"));
        }
    }
}

fn format_violation(v: &Violation) -> String {
    let mut loc = String::new();
    if let Some(file) = &v.file {
        loc.push_str(file);
        if let Some(line) = v.line {
            loc.push_str(&format!(":{line}"));
            if let Some(end) = v.end_line {
                loc.push_str(&format!("-{end}"));
            }
        }
    }
    let msg = v.message.as_deref().unwrap_or("violation");
    if loc.is_empty() {
        msg.to_string()
    } else {
        format!("{loc}: {msg}")
    }
}

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

    use crate::domain::verdict::JudgeOpinion;

    fn fail(name: &str, v: Vec<Violation>) -> RuleOutcome {
        RuleOutcome {
            name: name.into(),
            rationale: None,
            outcome: Outcome::Fail,
            votes_total: 1,
            votes_hold: 0,
            judges: vec![],
            violations: v,
        }
    }
    fn pass(name: &str) -> RuleOutcome {
        RuleOutcome {
            name: name.into(),
            rationale: None,
            outcome: Outcome::Pass,
            votes_total: 1,
            votes_hold: 1,
            judges: vec![],
            violations: vec![],
        }
    }
    fn with_rationale(mut o: RuleOutcome, why: &str) -> RuleOutcome {
        o.rationale = Some(why.into());
        o
    }
    fn opinion(holds: bool, why: Option<&str>) -> JudgeOpinion {
        JudgeOpinion {
            holds,
            rationale: why.map(Into::into),
        }
    }

    #[test]
    fn exit_codes() {
        assert_eq!(Report::new(vec![pass("a")], vec![]).exit_code(), 0);
        assert_eq!(Report::new(vec![fail("a", vec![])], vec![]).exit_code(), 1);
        assert_eq!(
            Report::new(vec![pass("a")], vec!["boom".into()]).exit_code(),
            2
        );
    }

    #[test]
    fn default_output_lists_failures_but_not_passes_or_skips() {
        let r = Report::new(
            vec![
                fail(
                    "no_inline_sql",
                    vec![
                        Violation {
                            file: Some("src/db.rs".into()),
                            line: Some(42),
                            end_line: Some(45),
                            message: Some("inline SQL".into()),
                        },
                        Violation {
                            message: Some("architectural drift".into()),
                            ..Default::default()
                        },
                    ],
                ),
                pass("layered"),
                RuleOutcome::skipped("nofiles"),
            ],
            vec![],
        );
        let text = r.to_human(0);
        // Failing rule and its locations are shown at the default level...
        assert!(text.contains("FAIL no_inline_sql"));
        assert!(text.contains("src/db.rs:42-45: inline SQL"));
        assert!(text.contains("architectural drift"));
        // ...but passing/skipped rules are only counted, not itemized.
        assert!(!text.contains("PASS layered"));
        assert!(!text.contains("SKIP nofiles"));
        assert!(text.contains("3 rules: 1 passed, 1 failed, 1 skipped"));
    }

    #[test]
    fn all_passing_default_output_is_just_the_summary() {
        let r = Report::new(vec![pass("a"), pass("b")], vec![]);
        // No failures, default verbosity: a single line, no leading blank line.
        assert_eq!(r.to_human(0), "2 rules: 2 passed, 0 failed, 0 skipped\n");
    }

    #[test]
    fn verbose_itemizes_passing_and_skipped_rules_too() {
        let r = Report::new(
            vec![
                fail(
                    "no_inline_sql",
                    vec![Violation {
                        file: Some("src/db.rs".into()),
                        line: Some(42),
                        end_line: Some(45),
                        message: Some("inline SQL".into()),
                    }],
                ),
                pass("layered"),
                RuleOutcome::skipped("nofiles"),
            ],
            vec![],
        );
        let text = r.to_human(1);
        assert!(text.contains("FAIL no_inline_sql"));
        assert!(text.contains("src/db.rs:42-45: inline SQL"));
        assert!(text.contains("PASS layered"));
        assert!(text.contains("SKIP nofiles (no files matched)"));
        assert!(text.contains("3 rules: 1 passed, 1 failed, 1 skipped"));
    }

    #[test]
    fn vote_split_shows_at_default_errors_at_every_level() {
        let r = Report::new(
            vec![
                RuleOutcome {
                    name: "voted".into(),
                    rationale: None,
                    outcome: Outcome::Fail,
                    votes_total: 3,
                    votes_hold: 1,
                    judges: vec![],
                    violations: vec![],
                },
                RuleOutcome::skipped("nofiles"),
            ],
            vec!["judge timed out".into()],
        );
        // Default: the failure (with vote split) and the operational error are
        // both shown; the skipped rule is not itemized.
        let quiet = r.to_human(0);
        assert!(quiet.contains("FAIL voted (1/3 judges held)"));
        assert!(quiet.contains("ERROR judge timed out"));
        assert!(quiet.contains("1 errored"));
        assert!(!quiet.contains("SKIP nofiles"));

        // Verbose itemizes the skipped rule as well.
        let text = r.to_human(1);
        assert!(text.contains("SKIP nofiles (no files matched)"));
    }

    #[test]
    fn rationale_shows_for_failures_at_default_and_for_all_rules_at_verbose() {
        let r = Report::new(
            vec![
                with_rationale(
                    fail(
                        "no_inline_sql",
                        vec![Violation {
                            message: Some("inline SQL".into()),
                            ..Default::default()
                        }],
                    ),
                    "raw SQL string built in db.rs",
                ),
                with_rationale(pass("layered"), "imports only flow downward"),
            ],
            vec![],
        );

        // Default: the failing rule's rationale is shown (before its violation);
        // the passing rule isn't itemized at all, so neither is its rationale.
        let quiet = r.to_human(0);
        assert!(quiet.contains("FAIL no_inline_sql"));
        assert!(quiet.contains("     rationale: raw SQL string built in db.rs"));
        let fail_idx = quiet.find("rationale:").unwrap();
        let viol_idx = quiet.find("inline SQL").unwrap();
        assert!(fail_idx < viol_idx, "rationale precedes the violation");
        assert!(!quiet.contains("imports only flow downward"));

        // Verbose: every evaluated rule shows its rationale.
        let loud = r.to_human(1);
        assert!(loud.contains("PASS layered"));
        assert!(loud.contains("     rationale: imports only flow downward"));
    }

    #[test]
    fn multi_judge_shows_each_judges_result_and_rationale() {
        let mut failing = fail(
            "voted_rule",
            vec![Violation {
                message: Some("inline SQL".into()),
                ..Default::default()
            }],
        );
        failing.votes_total = 3;
        failing.votes_hold = 1;
        failing.judges = vec![
            opinion(false, Some("raw SQL at db.rs:42")),
            opinion(true, Some("uses the query layer")),
            opinion(false, None), // a judge that gave no rationale
        ];
        let mut passing = pass("agreed");
        passing.votes_total = 3;
        passing.votes_hold = 2;
        passing.judges = vec![
            opinion(true, Some("clean")),
            opinion(false, Some("looked off")),
            opinion(true, Some("fine")),
        ];
        let r = Report::new(vec![failing, passing], vec![]);

        // Default: the failure shows every judge's result + rationale (a missing
        // rationale still shows the bare result), plus the aggregated violation.
        let quiet = r.to_human(0);
        assert!(quiet.contains("FAIL voted_rule (1/3 judges held)"));
        assert!(quiet.contains("judge 1 violated: raw SQL at db.rs:42"));
        assert!(quiet.contains("judge 2 held: uses the query layer"));
        assert!(quiet.contains("judge 3 violated\n"));
        assert!(quiet.contains("inline SQL"));
        // The passing rule isn't itemized at the default level.
        assert!(!quiet.contains("agreed"));

        // Verbose: the passing multi-judge rule shows its breakdown too, with the
        // dissent visible.
        let loud = r.to_human(1);
        assert!(loud.contains("PASS agreed (2/3 judges held)"));
        assert!(loud.contains("judge 2 violated: looked off"));
    }

    #[test]
    fn rationale_is_carried_in_json_when_present() {
        let r = Report::new(
            vec![with_rationale(pass("a"), "all good"), fail("b", vec![])],
            vec![],
        );
        let j = r.to_json();
        assert_eq!(j["rules"][0]["rationale"], "all good");
        // A rule with no rationale omits the key entirely.
        assert!(j["rules"][1].get("rationale").is_none());
    }

    #[test]
    fn json_output_is_stable_shape() {
        let r = Report::new(vec![pass("a"), fail("b", vec![])], vec![]);
        let j = r.to_json();
        assert_eq!(j["summary"]["total"], 2);
        assert_eq!(j["summary"]["passed"], 1);
        assert_eq!(j["summary"]["failed"], 1);
        // Outcomes are sorted by name.
        assert_eq!(j["rules"][0]["name"], "a");
        assert_eq!(j["rules"][0]["outcome"], "pass");
        assert_eq!(j["rules"][1]["outcome"], "fail");
    }
}