fix(triage): the automated review never hides a finding (#367) (#384)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m4s
CI / Deploy Dashboard (push) Successful in 5m55s
CI / Deploy Agent (push) Successful in 7m47s

This commit was merged in pull request #384.
This commit is contained in:
sharang committed 2026-09-25 08:39:16 +00:00
1 parent 79b8bef8ba
commit 5f7c947fb3
12 files changed
+325 -100

No files matched your search

+12 -3
View File
@@ -31,7 +31,11 @@ impl<J: ControlJudge> GroundedControlChecker<J> {
) -> Vec<Finding> {
let mut findings = Vec::new();
for region in regions {
let verdict = self.judge.judge(spec, region).await;
// No verdict (model down, unreadable answer) means no new finding
// here; this pass only adds findings, it never removes one.
let Ok(verdict) = self.judge.judge(spec, region).await else {
continue;
};
if let Some(finding) = ground(spec, region, &verdict, repo_id) {
findings.push(finding);
}
@@ -43,6 +47,7 @@ impl<J: ControlJudge> GroundedControlChecker<J> {
#[cfg(test)]
mod tests {
use super::*;
use crate::controls::JudgeError;
use compliance_core::control_check::LlmVerdict;
use compliance_core::models::finding::Severity;
@@ -53,8 +58,12 @@ mod tests {
}
impl ControlJudge for StubJudge {
async fn judge(&self, _spec: &ControlCheckSpec, _region: &CandidateRegion) -> LlmVerdict {
self.verdict.clone()
async fn judge(
&self,
_spec: &ControlCheckSpec,
_region: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError> {
Ok(self.verdict.clone())
}
}
+64 -39
View File
@@ -28,10 +28,32 @@ violate, set violates=false and leave snippet empty. (4) Prefer false over guess
Respond with STRICT JSON only, no prose: \
{\"violates\": bool, \"snippet\": \"<verbatim code or empty>\", \"cwe\": \"CWE-NNN or null\", \"confidence\": 0.0-1.0}";
/// Why the judge gave no verdict. Neither case says anything about the code,
/// so a caller must never read it as "no violation".
#[derive(Debug, thiserror::Error)]
pub enum JudgeError {
/// The model could not be reached or returned an error.
#[error("the control judge could not be reached: {0}")]
Unavailable(String),
/// The model answered, but not with a readable verdict.
#[error("the control judge's answer could not be read: {0}")]
Unreadable(String),
}
/// Judges one (control, region). Async-in-trait so a stub can drive tests.
#[allow(async_fn_in_trait)]
pub trait ControlJudge: Send + Sync {
async fn judge(&self, spec: &ControlCheckSpec, region: &CandidateRegion) -> LlmVerdict;
/// The verdict for `region` against `spec`.
///
/// # Errors
///
/// [`JudgeError`] when there is no verdict: the model was unavailable or
/// its answer unreadable.
async fn judge(
&self,
spec: &ControlCheckSpec,
region: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError>;
}
/// The real judge: the LLM at temperature 0 with the closed, verbatim-snippet prompt.
@@ -46,17 +68,21 @@ impl LlmControlJudge {
}
impl ControlJudge for LlmControlJudge {
async fn judge(&self, spec: &ControlCheckSpec, region: &CandidateRegion) -> LlmVerdict {
async fn judge(
&self,
spec: &ControlCheckSpec,
region: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError> {
let user = build_user_prompt(spec, region);
match self.llm.chat(SYSTEM_PROMPT, &user, Some(0.0)).await {
Ok(response) => parse_verdict(&response),
Err(e) => {
// Fail closed: a transient model error yields no finding, never a
// fabricated one.
let response = self
.llm
.chat(SYSTEM_PROMPT, &user, Some(0.0))
.await
.map_err(|e| {
tracing::warn!(control = %spec.control_id, error = %e, "control judge call failed");
no_violation()
}
}
JudgeError::Unavailable(e.to_string())
})?;
parse_verdict(&response)
}
}
@@ -84,36 +110,29 @@ struct RawVerdict {
confidence: f64,
}
/// Parse the model's JSON verdict, tolerant of ```json fencing. Any parse failure
/// degrades to a non-violation (never a fabricated finding).
fn parse_verdict(response: &str) -> LlmVerdict {
/// Parse the model's JSON verdict, tolerant of ```json fencing.
///
/// # Errors
///
/// [`JudgeError::Unreadable`] when the answer is not a verdict; that is no
/// decision either way, never a fabricated finding or a silent "no violation".
fn parse_verdict(response: &str) -> Result<LlmVerdict, JudgeError> {
let cleaned = response
.trim()
.trim_start_matches("```json")
.trim_start_matches("```")
.trim_end_matches("```")
.trim();
match serde_json::from_str::<RawVerdict>(cleaned) {
Ok(raw) => LlmVerdict {
violates: raw.violates,
snippet: raw.snippet,
cwe: raw.cwe.filter(|c| !c.trim().is_empty()),
confidence: raw.confidence,
},
Err(e) => {
tracing::debug!(error = %e, "failed to parse control verdict; treating as non-violation");
no_violation()
}
}
}
fn no_violation() -> LlmVerdict {
LlmVerdict {
violates: false,
snippet: String::new(),
cwe: None,
confidence: 0.0,
}
let raw = serde_json::from_str::<RawVerdict>(cleaned).map_err(|e| {
tracing::debug!(error = %e, "failed to parse control verdict");
JudgeError::Unreadable(e.to_string())
})?;
Ok(LlmVerdict {
violates: raw.violates,
snippet: raw.snippet,
cwe: raw.cwe.filter(|c| !c.trim().is_empty()),
confidence: raw.confidence,
})
}
#[cfg(test)]
@@ -134,21 +153,27 @@ mod tests {
#[test]
fn parses_plain_and_fenced_json() {
let plain = r#"{"violates": true, "snippet": "PASSWORD = \"x\"", "cwe": "CWE-798", "confidence": 0.9}"#;
let v = parse_verdict(plain);
let Ok(v) = parse_verdict(plain) else {
panic!("a plain JSON verdict parses");
};
assert!(v.violates);
assert_eq!(v.snippet, "PASSWORD = \"x\"");
assert_eq!(v.cwe.as_deref(), Some("CWE-798"));
let fenced = "```json\n{\"violates\": false, \"snippet\": \"\", \"cwe\": null, \"confidence\": 0.1}\n```";
assert!(!parse_verdict(fenced).violates);
assert!(matches!(parse_verdict(fenced), Ok(v) if !v.violates));
}
#[test]
fn garbage_and_empty_cwe_are_safe() {
assert!(!parse_verdict("not json at all").violates); // fail closed
fn an_unreadable_answer_is_an_error_not_a_verdict() {
// Neither "violates" nor "does not violate": the caller must not decide.
assert!(matches!(
parse_verdict("not json at all"),
Err(JudgeError::Unreadable(_))
));
let no_cwe =
parse_verdict(r#"{"violates": true, "snippet": "x", "cwe": " ", "confidence": 0.5}"#);
assert!(no_cwe.cwe.is_none()); // blank CWE normalised away
assert!(matches!(no_cwe, Ok(v) if v.cwe.is_none())); // blank CWE normalised away
}
#[test]
+1 -1
View File
@@ -16,7 +16,7 @@ mod triage;
pub use checker::GroundedControlChecker;
pub use index::ControlIndex;
pub use judge::{ControlJudge, LlmControlJudge, PROMPT_VERSION};
pub use judge::{ControlJudge, JudgeError, LlmControlJudge, PROMPT_VERSION};
pub use oscal_provider::OscalControlsProvider;
pub use scan_triage::{grounded_surface_findings, semantic_stamp_findings, triage_repo_findings};
pub use semantic::SemanticControlChecker;
+11 -4
View File
@@ -67,11 +67,18 @@ pub async fn triage_repo_findings(
finding.control_refs = controls;
tagged += 1;
}
TriageOutcome::FalsePositive => {
finding.status = FindingStatus::FalsePositive;
finding.triage_action = Some("control_false_positive".to_string());
// The judge refuted the mapping: the finding stays, for a person
// to decide.
TriageOutcome::NeedsReview => {
finding.status = FindingStatus::NeedsReview;
finding.triage_action = Some("control_not_confirmed".to_string());
finding.triage_rationale.get_or_insert_with(|| {
"The control check did not confirm the CRA requirements this \
finding maps to. Please review whether it is a real issue."
.to_string()
});
}
TriageOutcome::Unmapped => {}
TriageOutcome::Undecided | TriageOutcome::Unmapped => {}
}
}
tagged
+12 -3
View File
@@ -38,7 +38,11 @@ impl<J: ControlJudge> SemanticControlChecker<J> {
let candidates = index.nearest(query_embedding, k);
let mut findings = Vec::new();
for spec in &candidates {
let verdict = self.judge.judge(spec, region).await;
// No verdict (model down, unreadable answer) means no new finding
// here; this pass only adds findings, it never removes one.
let Ok(verdict) = self.judge.judge(spec, region).await else {
continue;
};
if let Some(finding) = ground(spec, region, &verdict, repo_id) {
findings.push(finding);
}
@@ -50,6 +54,7 @@ impl<J: ControlJudge> SemanticControlChecker<J> {
#[cfg(test)]
mod tests {
use super::*;
use crate::controls::JudgeError;
use compliance_core::control_check::{ControlCheckSpec, LlmVerdict};
use compliance_core::models::finding::Severity;
@@ -57,8 +62,12 @@ mod tests {
verdict: LlmVerdict,
}
impl ControlJudge for StubJudge {
async fn judge(&self, _s: &ControlCheckSpec, _r: &CandidateRegion) -> LlmVerdict {
self.verdict.clone()
async fn judge(
&self,
_s: &ControlCheckSpec,
_r: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError> {
Ok(self.verdict.clone())
}
}
+113 -23
View File
@@ -1,12 +1,15 @@
//! Triage step: confirm/refute a deterministic tool finding against the controls
//! it maps to (via the `control-map` LUT), grounding the judgment.
//!
//! This is where the LLM finally enters — as a **false-positive filter over tool
//! output**, never as the detector (the ZeroFalse / IRIS pattern). A tool
//! (semgrep, gitleaks, syft/osv) detects deterministically; `controls_for(tool,
//! cwe)` attaches the finding to the control(s) it's evidence for; the grounded
//! judge then confirms or refutes each, and only judgments anchored to real code
//! survive.
//! This is where the LLM finally enters — as a **reviewer of the mapping**, never
//! as the detector (the ZeroFalse / IRIS pattern). A tool (semgrep, gitleaks,
//! syft/osv) detects deterministically; `controls_for(tool, cwe)` attaches the
//! finding to the control(s) it's evidence for; the grounded judge then confirms
//! or refutes each, and only judgments anchored to real code count.
//!
//! The judge decides the mapping, never whether the finding exists: a refuted
//! finding goes to a person for review, and one without a verdict is left as it
//! is.
use std::collections::HashMap;
@@ -24,8 +27,12 @@ pub enum TriageOutcome {
/// Maps to controls and the grounded judge confirmed at least one — keep the
/// finding and tag it with these control ids.
Confirmed(Vec<String>),
/// Maps to controls but the judge grounded none — treat as a false positive.
FalsePositive,
/// Maps to controls, and the judge refuted every one it could check — a
/// person should look at it.
NeedsReview,
/// Maps to controls, but no verdict was reached (model unavailable, answer
/// unreadable, or no requirement text) — leave the finding as it is.
Undecided,
}
/// Triages tool findings against the control map, confirming with a grounded judge.
@@ -57,22 +64,37 @@ impl<J: ControlJudge> ControlTriage<J> {
}
let mut confirmed = Vec::new();
let mut refuted = 0_usize;
let mut undecided = 0_usize;
for entry in mapped {
let Some(spec) = self.specs.get(&entry.control) else {
undecided += 1;
continue;
};
let verdict = self.judge.judge(spec, region).await;
// The verdict only counts if it grounds to real code in the region.
if ground(spec, region, &verdict, &finding.repo_id).is_some() {
confirmed.push(entry.control.clone());
match self.judge.judge(spec, region).await {
// The verdict only counts if it grounds to real code in the region.
Ok(verdict) if ground(spec, region, &verdict, &finding.repo_id).is_some() => {
confirmed.push(entry.control.clone());
}
Ok(_) => refuted += 1,
Err(_) => undecided += 1,
}
}
if confirmed.is_empty() {
TriageOutcome::FalsePositive
} else {
TriageOutcome::Confirmed(confirmed)
}
outcome(confirmed, refuted, undecided)
}
}
/// The outcome from the per-control results: any confirmation wins; a
/// refutation needs every checkable control refuted, and a single missing
/// verdict leaves the finding undecided.
fn outcome(confirmed: Vec<String>, refuted: usize, undecided: usize) -> TriageOutcome {
if !confirmed.is_empty() {
TriageOutcome::Confirmed(confirmed)
} else if undecided == 0 && refuted > 0 {
TriageOutcome::NeedsReview
} else {
TriageOutcome::Undecided
}
}
@@ -83,12 +105,30 @@ mod tests {
use compliance_core::models::finding::Severity;
use compliance_core::models::scan::ScanType;
use crate::controls::JudgeError;
struct StubJudge {
verdict: LlmVerdict,
}
impl ControlJudge for StubJudge {
async fn judge(&self, _s: &ControlCheckSpec, _r: &CandidateRegion) -> LlmVerdict {
self.verdict.clone()
async fn judge(
&self,
_s: &ControlCheckSpec,
_r: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError> {
Ok(self.verdict.clone())
}
}
/// A judge that never answers, as when the model is down.
struct DownJudge;
impl ControlJudge for DownJudge {
async fn judge(
&self,
_s: &ControlCheckSpec,
_r: &CandidateRegion,
) -> Result<LlmVerdict, JudgeError> {
Err(JudgeError::Unavailable("connection refused".into()))
}
}
@@ -148,8 +188,22 @@ mod tests {
}
#[tokio::test]
async fn refuted_mapped_finding_is_false_positive() {
// Maps to cra-ai-8, but the judge doesn't confirm (no violation) → FP.
async fn refuted_mapped_finding_needs_review() {
// CWE-798 maps to cra-ai-8, 9 and 16; the judge confirms none of them,
// so a person decides.
let mut specs = specs();
for id in ["cra-ai-9", "cra-ai-16"] {
specs.insert(
id.to_string(),
ControlCheckSpec {
control_id: id.into(),
title: id.into(),
requirement: "requirement".into(),
default_cwe: None,
severity: Severity::Medium,
},
);
}
let triage = ControlTriage::new(
StubJudge {
verdict: LlmVerdict {
@@ -160,10 +214,46 @@ mod tests {
},
},
ControlMap::cra().unwrap(),
specs(),
specs,
);
let out = triage.triage(&semgrep_finding("CWE-798"), &region()).await;
assert_eq!(out, TriageOutcome::FalsePositive);
assert_eq!(out, TriageOutcome::NeedsReview);
}
#[tokio::test]
async fn a_judge_that_is_down_decides_nothing() {
let triage = ControlTriage::new(DownJudge, ControlMap::cra().unwrap(), specs());
let out = triage.triage(&semgrep_finding("CWE-798"), &region()).await;
assert_eq!(out, TriageOutcome::Undecided);
}
#[tokio::test]
async fn a_control_without_requirement_text_decides_nothing() {
// cra-ai-8 maps, but the catalog has no spec for it: nothing was judged.
let triage = ControlTriage::new(
StubJudge {
verdict: LlmVerdict {
violates: false,
snippet: String::new(),
cwe: None,
confidence: 0.1,
},
},
ControlMap::cra().unwrap(),
HashMap::new(),
);
let out = triage.triage(&semgrep_finding("CWE-798"), &region()).await;
assert_eq!(out, TriageOutcome::Undecided);
}
#[test]
fn one_missing_verdict_keeps_a_refutation_undecided() {
assert_eq!(outcome(vec![], 2, 0), TriageOutcome::NeedsReview);
assert_eq!(outcome(vec![], 1, 1), TriageOutcome::Undecided);
assert_eq!(
outcome(vec!["cra-ai-8".into()], 1, 1),
TriageOutcome::Confirmed(vec!["cra-ai-8".into()])
);
}
#[tokio::test]
+77 -26
View File
@@ -49,9 +49,15 @@ Confidence scoring (0-10):
Respond with a JSON array, one entry per finding in the same order presented (no markdown fences):
[{"id": "<fingerprint>", "action": "confirm|downgrade|upgrade|dismiss", "confidence": 0-10, "rationale": "1-2 sentences", "remediation": "optional fix"}, ...]"#;
/// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each
/// one. Nothing is removed; a flagged finding is kept as "needs review".
///
/// # Returns
///
/// How many findings passed triage (confirmed or re-rated).
pub async fn triage_findings(
llm: &Arc<LlmClient>,
findings: &mut Vec<Finding>,
findings: &mut [Finding],
graph_context: Option<&GraphContext>,
) -> usize {
let mut passed = 0;
@@ -167,29 +173,8 @@ pub async fn triage_findings(
finding.remediation = Some(remediation.clone());
}
match result.action.as_str() {
"dismiss" => {
finding.status = FindingStatus::FalsePositive;
}
"downgrade" => {
finding.severity = downgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
passed += 1;
}
"upgrade" => {
finding.severity = upgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
passed += 1;
}
_ => {
// "confirm" or unknown — keep as-is
if adjusted_confidence >= 3.0 {
finding.status = FindingStatus::Triaged;
passed += 1;
} else {
finding.status = FindingStatus::FalsePositive;
}
}
if apply_action(finding, &result.action, adjusted_confidence) {
passed += 1;
}
}
}
@@ -216,11 +201,42 @@ pub async fn triage_findings(
}
}
// Remove false positives
findings.retain(|f| f.status != FindingStatus::FalsePositive);
passed
}
/// Apply the model's `action` to `finding`; `true` when it passed triage.
///
/// A dismissed or low-confidence finding is kept as
/// [`FindingStatus::NeedsReview`], never deleted: the model's rationale goes
/// with it, and a person decides.
fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> bool {
match action {
"dismiss" => {
finding.status = FindingStatus::NeedsReview;
false
}
"downgrade" => {
finding.severity = downgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
true
}
"upgrade" => {
finding.severity = upgrade_severity(&finding.severity);
finding.status = FindingStatus::Triaged;
true
}
// "confirm" or unknown: kept as reported when the model is confident.
_ if adjusted_confidence >= 3.0 => {
finding.status = FindingStatus::Triaged;
true
}
_ => {
finding.status = FindingStatus::NeedsReview;
false
}
}
}
/// Read ~50 lines of surrounding code from the file at the finding's location
fn read_surrounding_context(finding: &Finding) -> Option<String> {
let file_path = finding.file_path.as_deref()?;
@@ -348,6 +364,41 @@ fn default_action() -> String {
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::scan::ScanType;
fn finding() -> Finding {
Finding::new(
"repo".into(),
"fp".into(),
"semgrep".into(),
ScanType::Sast,
"strcpy into a fixed buffer".into(),
"desc".into(),
Severity::High,
)
}
#[test]
fn a_dismissed_finding_is_kept_for_review() {
let mut f = finding();
assert!(!apply_action(&mut f, "dismiss", 9.0));
assert_eq!(f.status, FindingStatus::NeedsReview);
let mut unsure = finding();
assert!(!apply_action(&mut unsure, "confirm", 2.0));
assert_eq!(unsure.status, FindingStatus::NeedsReview);
}
#[test]
fn confirmed_and_rerated_findings_pass() {
let mut f = finding();
assert!(apply_action(&mut f, "confirm", 7.0));
assert_eq!(f.status, FindingStatus::Triaged);
let mut lower = finding();
assert!(apply_action(&mut lower, "downgrade", 7.0));
assert_eq!(lower.severity, Severity::Medium);
}
use compliance_core::models::Severity;
// ── classify_file_path ───────────────────────────────────────
+21
View File
@@ -35,6 +35,10 @@ pub enum FindingStatus {
Ignored,
/// Known and deliberately not fixed; the reason is in the status history.
AcceptedRisk,
/// Flagged by the automated review (the LLM triage or the control judge)
/// as possibly not a real issue. It stays open until a person decides; no
/// finding is ever hidden automatically.
NeedsReview,
}
impl std::fmt::Display for FindingStatus {
@@ -46,6 +50,7 @@ impl std::fmt::Display for FindingStatus {
Self::Resolved => write!(f, "resolved"),
Self::Ignored => write!(f, "ignored"),
Self::AcceptedRisk => write!(f, "accepted_risk"),
Self::NeedsReview => write!(f, "needs_review"),
}
}
}
@@ -157,3 +162,19 @@ impl Finding {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn needs_review_reads_and_writes_as_needs_review() {
let wire = serde_json::to_string(&FindingStatus::NeedsReview).unwrap_or_default();
assert_eq!(wire, "\"needs_review\"");
assert_eq!(FindingStatus::NeedsReview.to_string(), "needs_review");
assert!(matches!(
serde_json::from_str::<FindingStatus>("\"needs_review\""),
Ok(FindingStatus::NeedsReview)
));
}
}
+4
View File
@@ -49,6 +49,8 @@ fn finding_status_display_all_variants() {
assert_eq!(FindingStatus::FalsePositive.to_string(), "false_positive");
assert_eq!(FindingStatus::Resolved.to_string(), "resolved");
assert_eq!(FindingStatus::Ignored.to_string(), "ignored");
assert_eq!(FindingStatus::AcceptedRisk.to_string(), "accepted_risk");
assert_eq!(FindingStatus::NeedsReview.to_string(), "needs_review");
}
#[test]
@@ -59,6 +61,8 @@ fn finding_status_serde_roundtrip() {
FindingStatus::FalsePositive,
FindingStatus::Resolved,
FindingStatus::Ignored,
FindingStatus::AcceptedRisk,
FindingStatus::NeedsReview,
] {
let json = serde_json::to_string(&status).unwrap();
let back: FindingStatus = serde_json::from_str(&json).unwrap();
+6 -1
View File
@@ -1191,6 +1191,10 @@ pub mod findings {
de: "Risiko akzeptiert",
en: "Accepted risk",
},
FindingStatus::NeedsReview => Text {
de: "Zu prüfen",
en: "Needs review",
},
}
}
@@ -1238,8 +1242,9 @@ pub mod findings {
];
/// Every status, in the order the forms offer them.
pub const STATUSES: [FindingStatus; 6] = [
pub const STATUSES: [FindingStatus; 7] = [
FindingStatus::Open,
FindingStatus::NeedsReview,
FindingStatus::Triaged,
FindingStatus::Resolved,
FindingStatus::FalsePositive,
@@ -342,5 +342,8 @@ pub fn status_icon(status: &compliance_core::models::FindingStatus) -> Element {
FindingStatus::FalsePositive => rsx! { Icon { icon: BsXCircle, width: 12, height: 12 } },
FindingStatus::Ignored => rsx! { Icon { icon: BsDashCircle, width: 12, height: 12 } },
FindingStatus::AcceptedRisk => rsx! { Icon { icon: BsShieldCheck, width: 12, height: 12 } },
FindingStatus::NeedsReview => {
rsx! { Icon { icon: BsQuestionCircle, width: 12, height: 12 } }
}
}
}
+1
View File
@@ -229,6 +229,7 @@ pub async fn findings_summary(
"resolved",
"ignored",
"accepted_risk",
"needs_review",
] {
let mut filter = base_filter.clone();
filter.insert("status", status);