From 6f2e278969a45f0f8ec66e1a619c82523bdaebfc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Mon, 5 Oct 2026 22:29:44 +0000 Subject: [PATCH] fix(triage): every critical/high finding gets a verdict, stored on rescans too (#462) (#472) The LLM triage of the first pilot scans left 74 of 75 findings without a triage_action. Three causes: - Partial answers: 30 findings per call with a 4096-token budget that a reasoning model spends on thinking and the answer together. The answer was cut off after a few verdicts; #457 only retries an empty answer. Verdicts were also matched by position and the echoed id was ignored, so a finding the model left out shifted every later verdict. - Not persisted: write_back stored triage fields only on rows this run inserted. A rescan (or a scan restarted after stages 1-4 had saved its findings) triaged them, then dropped the result. - Unanswered findings were marked "triaged" and counted as "passed". Now: - 10 findings per call with a 12k budget (below #457's retry budget); verdicts matched by id (the finding's number in the chunk, or its fingerprint), by position only when the answer carries no ids - findings without a verdict are asked again by id in chunks half the size, then each critical/high one on its own - one call per fingerprint: copies (gitleaks reports a secret once per commit) share the verdict - low/info findings are not sent; recorded as triage_action "skipped", rationale "skipped: low"; likewise "skipped: over cap" and "skipped: no answer". Skipped findings keep their status (open). - write_back stores triage on rows an earlier run stored while nobody has decided about them (open/triaged/needs_review); a skip never replaces an earlier verdict; status still only onto open rows - one summary line per scan replaces "N findings passed confidence threshold": triaged by outcome, skipped by reason, LLM calls - dismissed and low-confidence findings stay as needs_review (#367): nothing is dropped Tests drive the triage with a fake model: partial answer then retry by id, malformed chunks, model down, threshold, lows and copies, and the stored updates for new and earlier rows. Closes #462 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- compliance-agent/src/llm/client.rs | 70 +- compliance-agent/src/llm/triage.rs | 1017 +++++++++++++---- .../src/pipeline/finding_store.rs | 233 +++- compliance-agent/src/pipeline/orchestrator.rs | 6 +- 4 files changed, 1069 insertions(+), 257 deletions(-) diff --git a/compliance-agent/src/llm/client.rs b/compliance-agent/src/llm/client.rs index 4755794..31a262e 100644 --- a/compliance-agent/src/llm/client.rs +++ b/compliance-agent/src/llm/client.rs @@ -87,6 +87,53 @@ impl LlmClient { }) } + /// Like [`Self::chat`], with a token budget of `max_tokens` (a reasoning + /// model spends it on thinking and the answer together), and whether the + /// answer was cut off at that budget (`finish_reason: length`): a cut-off + /// answer is returned as far as it got, for the caller to use what is + /// complete in it. + /// + /// # Errors + /// + /// As [`Self::chat`]. + pub async fn chat_with_budget( + &self, + system_prompt: &str, + user_prompt: &str, + temperature: Option, + max_tokens: u32, + ) -> Result { + let messages = vec![ + ChatMessage { + role: "system".to_string(), + content: Some(system_prompt.to_string()), + tool_calls: None, + tool_call_id: None, + }, + ChatMessage { + role: "user".to_string(), + content: Some(user_prompt.to_string()), + tool_calls: None, + tool_call_id: None, + }, + ]; + let request_body = ChatCompletionRequest { + model: self.model.clone(), + messages, + temperature, + max_tokens: Some(max_tokens), + tools: None, + }; + let (response, finish_reason) = self.send_chat_request_with_reason(&request_body).await?; + Ok(ChatAnswer { + content: match response { + LlmResponse::Content(c) => c, + LlmResponse::ToolCalls { .. } => String::new(), + }, + cut_off: finish_reason.as_deref() == Some("length"), + }) + } + /// Chat with a list of (role, content) messages → text response #[allow(dead_code)] pub async fn chat_with_messages( @@ -171,9 +218,19 @@ impl LlmClient { &self, request_body: &ChatCompletionRequest, ) -> Result { + self.send_chat_request_with_reason(request_body) + .await + .map(|(response, _)| response) + } + + /// [`Self::send_chat_request`], and the reason the model stopped. + async fn send_chat_request_with_reason( + &self, + request_body: &ChatCompletionRequest, + ) -> Result<(LlmResponse, Option), AgentError> { let (response, finish_reason) = self.send_once(request_body).await?; if !exhausted(&response, finish_reason.as_deref()) { - return Ok(response); + return Ok((response, finish_reason)); } if request_body.max_tokens.unwrap_or(0) >= REASONING_RETRY_TOKENS { return Err(AgentError::Other(REASONING_EXHAUSTED.to_string())); @@ -190,7 +247,7 @@ impl LlmClient { if exhausted(&response, finish_reason.as_deref()) { return Err(AgentError::Other(REASONING_EXHAUSTED.to_string())); } - Ok(response) + Ok((response, finish_reason)) } /// One chat completion request, and the reason the model stopped. @@ -262,6 +319,15 @@ impl LlmClient { } } +/// A text answer, and whether the model stopped at its token budget. +#[derive(Debug, Clone, PartialEq)] +pub struct ChatAnswer { + /// The answer, without the model's reasoning. + pub content: String, + /// The model was cut off at its token budget: the answer may be partial. + pub cut_off: bool, +} + /// The token budget of the second request when the first ran out while the /// model was still reasoning. const REASONING_RETRY_TOKENS: u32 = 16384; diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index fce0fe3..5d71025 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -1,15 +1,22 @@ -use std::ops::Range; -use std::sync::Arc; +use std::collections::HashMap; +use std::fmt; -use compliance_core::models::{Finding, FindingStatus}; +use compliance_core::models::{Finding, FindingStatus, Severity}; use serde::{Deserialize, Deserializer}; use serde_json::Value; +use crate::error::AgentError; +use crate::llm::client::ChatAnswer; use crate::llm::LlmClient; use crate::pipeline::orchestrator::GraphContext; -/// Maximum number of findings to include in a single LLM triage call. -const TRIAGE_CHUNK_SIZE: usize = 30; +/// Findings in one LLM triage call. A reasoning model spends its token budget +/// on thinking and the answer together; with 30 findings per call the answer +/// was cut off after a few verdicts (#462). +const TRIAGE_CHUNK_SIZE: usize = 10; +/// Token budget of one triage call. Below the client's larger retry budget, +/// so a model that spends all of it thinking is still asked again (#457). +const TRIAGE_MAX_TOKENS: u32 = 12_288; const TRIAGE_SYSTEM_PROMPT: &str = r#"You are a pragmatic security triage expert. Your job is to filter out noise and keep only findings that a developer should actually fix. Be aggressive about dismissing false positives — a clean, high-signal list is more valuable than a comprehensive one. @@ -49,46 +56,212 @@ Confidence scoring (0-10): - 3-4: Uncertain, needs manual review - 0-2: Almost certainly a false positive -Respond with a JSON array, one entry per finding in the same order presented (no markdown fences): -[{"id": "", "action": "confirm|downgrade|upgrade|dismiss", "confidence": 0-10, "rationale": "1-2 sentences", "remediation": "optional fix"}, ...]"#; +Respond with a JSON array, one entry per finding (no markdown fences). "id" is the number of the finding as given in "Finding (id: )": +[{"id": 1, "action": "confirm|downgrade|upgrade|dismiss", "confidence": 0-10, "rationale": "1-2 sentences", "remediation": "optional fix"}, ...]"#; /// Most findings one scan sends to the LLM triage, the most severe first. /// A large tree can yield thousands (12,000 on an RTOS reference project); the -/// rest stay open, untriaged, which is where they would be without an LLM. +/// rest stay open and are recorded as "skipped: over cap". const TRIAGE_MAX_FINDINGS: usize = 600; /// Triage calls in flight at once. const TRIAGE_CONCURRENCY: usize = 4; /// How much of an unreadable model answer goes to the debug log. const RESPONSE_SAMPLE_CHARS: usize = 500; -/// The findings the LLM triage looks at, by index: the most severe first, at -/// most [`TRIAGE_MAX_FINDINGS`]. -fn triage_selection(findings: &[Finding]) -> Vec { - let mut selected: Vec = (0..findings.len()).collect(); - // Stable, so equally severe findings keep their scan order. - selected.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity)); - selected.truncate(TRIAGE_MAX_FINDINGS); - selected +/// `triage_action` of a finding the LLM triage gave no verdict; the reason is +/// in `triage_rationale`, which starts with `skipped: `. +pub const SKIPPED_ACTION: &str = "skipped"; + +/// The model the triage asks. A trait so tests can drive the triage with a +/// fake model. +#[allow(async_fn_in_trait)] +pub trait TriageModel: Send + Sync { + /// The model's answer to one triage prompt. + /// + /// # Errors + /// + /// The model could not be reached or gave no answer. + async fn answer( + &self, + system_prompt: &str, + user_prompt: &str, + ) -> Result; } -/// The model's answer for one chunk: its verdicts in chunk order, at most one -/// per finding. Fewer (none at all when the call failed or its answer could -/// not be read) leave the rest of the chunk without a verdict. -async fn triage_chunk( - llm: &LlmClient, - chunk: &[&Finding], - graph_context: Option<&GraphContext>, - chunk_start: usize, -) -> Vec { - let mut user_prompt = String::new(); +impl TriageModel for LlmClient { + async fn answer( + &self, + system_prompt: &str, + user_prompt: &str, + ) -> Result { + self.chat_with_budget(system_prompt, user_prompt, Some(0.1), TRIAGE_MAX_TOKENS) + .await + } +} - for (i, finding) in chunk.iter().enumerate() { +/// Why a finding got no verdict from the LLM triage. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SkipReason { + /// Low and info findings are not sent to the model. + Low, + /// Beyond the [`TRIAGE_MAX_FINDINGS`] most severe of the scan. + OverCap, + /// The model gave no readable verdict, also when asked again. + NoAnswer, +} + +impl SkipReason { + /// The `triage_rationale` recorded on the finding. + pub fn rationale(self) -> &'static str { + match self { + Self::Low => "skipped: low (low and info findings are not sent to the LLM triage)", + Self::OverCap => { + "skipped: over cap (only the most severe findings of a scan are triaged)" + } + Self::NoAnswer => { + "skipped: no answer (the model gave no verdict, also when asked again)" + } + } + } +} + +/// What a verdict did to a finding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Outcome { + Confirmed, + Downgraded, + Upgraded, + /// Flagged as a false positive: kept, as needs review. + Dismissed, + /// Confirmed with too little confidence: kept, as needs review. + LowConfidence, +} + +/// What one scan's LLM triage did, counted per distinct finding +/// (fingerprint). +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct TriageSummary { + /// Findings handed to the triage, copies included. + pub findings: usize, + /// Distinct findings among them (one per fingerprint). + pub unique: usize, + pub confirmed: usize, + pub downgraded: usize, + pub upgraded: usize, + /// Dismissed by the model: kept as needs review. + pub dismissed: usize, + /// Confirmed below the confidence threshold: kept as needs review. + pub low_confidence: usize, + pub skipped_low: usize, + pub skipped_over_cap: usize, + pub skipped_no_answer: usize, + /// Critical and high findings among `skipped_no_answer`. + pub skipped_no_answer_severe: usize, + /// Calls made to the model. + pub calls: usize, +} + +impl TriageSummary { + /// Distinct findings with a verdict. + pub fn triaged(&self) -> usize { + self.confirmed + self.downgraded + self.upgraded + self.dismissed + self.low_confidence + } + + /// Distinct findings without a verdict. + pub fn skipped(&self) -> usize { + self.skipped_low + self.skipped_over_cap + self.skipped_no_answer + } + + fn count(&mut self, outcome: Outcome) { + match outcome { + Outcome::Confirmed => self.confirmed += 1, + Outcome::Downgraded => self.downgraded += 1, + Outcome::Upgraded => self.upgraded += 1, + Outcome::Dismissed => self.dismissed += 1, + Outcome::LowConfidence => self.low_confidence += 1, + } + } + + fn count_skip(&mut self, reason: SkipReason, severity: &Severity) { + match reason { + SkipReason::Low => self.skipped_low += 1, + SkipReason::OverCap => self.skipped_over_cap += 1, + SkipReason::NoAnswer => { + self.skipped_no_answer += 1; + if *severity >= Severity::High { + self.skipped_no_answer_severe += 1; + } + } + } + } +} + +impl fmt::Display for TriageSummary { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "LLM triage: {} findings ({} distinct); triaged {} (confirmed {}, downgraded {}, \ + upgraded {}, dismissed {} and low confidence {} kept as needs review); skipped {} \ + (low {}, over cap {}, no answer {} of which {} critical/high); {} LLM calls", + self.findings, + self.unique, + self.triaged(), + self.confirmed, + self.downgraded, + self.upgraded, + self.dismissed, + self.low_confidence, + self.skipped(), + self.skipped_low, + self.skipped_over_cap, + self.skipped_no_answer, + self.skipped_no_answer_severe, + self.calls, + ) + } +} + +/// Which distinct findings (positions in `findings`, one per fingerprint in +/// `distinct`) go to the model, the most severe first, and which are skipped +/// and why: low and info findings, and those beyond [`TRIAGE_MAX_FINDINGS`]. +fn triage_selection( + findings: &[Finding], + distinct: &[usize], +) -> (Vec, Vec<(usize, SkipReason)>) { + let mut skipped = Vec::new(); + let mut sent: Vec = Vec::with_capacity(distinct.len()); + for &i in distinct { + if findings[i].severity <= Severity::Low { + skipped.push((i, SkipReason::Low)); + } else { + sent.push(i); + } + } + // Stable, so equally severe findings keep their scan order. + sent.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity)); + if sent.len() > TRIAGE_MAX_FINDINGS { + skipped.extend( + sent.drain(TRIAGE_MAX_FINDINGS..) + .map(|i| (i, SkipReason::OverCap)), + ); + } + (sent, skipped) +} + +/// The prompt for the findings at `chunk`, numbered from 1 in chunk order. +fn chunk_prompt( + findings: &[Finding], + chunk: &[usize], + graph_context: Option<&GraphContext>, +) -> String { + let mut user_prompt = String::new(); + for (n, &i) in chunk.iter().enumerate() { + let finding = &findings[i]; let file_classification = classify_file_path(finding.file_path.as_deref()); + let number = n + 1; user_prompt.push_str(&format!( - "\n--- Finding {} (id: {}) ---\nScanner: {}\nRule: {}\nSeverity: {}\nTitle: {}\nDescription: {}\nFile: {}\nLine: {}\nCode: {}\nFile classification: {}", - i + 1, - finding.fingerprint, + "\n--- Finding {number} (id: {number}) ---\nScanner: {}\nRule: {}\nSeverity: {}\nTitle: {}\nDescription: {}\nFile: {}\nLine: {}\nCode: {}\nFile classification: {}", finding.scanner, finding.rule_id.as_deref().unwrap_or("N/A"), finding.severity, @@ -140,203 +313,291 @@ async fn triage_chunk( user_prompt.push('\n'); } + user_prompt +} - let response = match llm - .chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1)) - .await - { - Ok(response) => response, +/// Ask the model about the findings at `chunk` (positions in `findings`). +/// +/// # Returns +/// +/// The verdicts the answer holds, by position in `findings`; none when the +/// call failed or its answer could not be read. +async fn triage_chunk( + model: &M, + findings: &[Finding], + chunk: &[usize], + graph_context: Option<&GraphContext>, +) -> Vec<(usize, TriageResult)> { + let user_prompt = chunk_prompt(findings, chunk, graph_context); + let answer = match model.answer(TRIAGE_SYSTEM_PROMPT, &user_prompt).await { + Ok(answer) => answer, Err(e) => { tracing::warn!( - "LLM batch triage failed for chunk starting at {chunk_start}: {e}; {} findings \ - affected, left unchanged unless a retry answers them", + "LLM batch triage failed for a chunk of {} findings: {e}; asked again unless \ + this was the last try", chunk.len() ); return Vec::new(); } }; - let mut verdicts = match parse_triage_response(&response) { + let verdicts = match parse_triage_response(&answer.content) { Ok(verdicts) => verdicts, Err(e) => { tracing::warn!( - "Failed to parse batch triage response for chunk starting at {chunk_start}: {e}; \ - {} findings affected, left unchanged unless a retry answers them", - chunk.len() + "Failed to parse batch triage response for a chunk of {} findings{}: {e}; \ + asked again unless this was the last try", + chunk.len(), + if answer.cut_off { + " (cut off at the token budget)" + } else { + "" + }, ); // A sample of the answer only, never the prompt (it carries the code). - let sample: String = response.chars().take(RESPONSE_SAMPLE_CHARS).collect(); + let sample: String = answer.content.chars().take(RESPONSE_SAMPLE_CHARS).collect(); tracing::debug!( "Unreadable batch triage response (first {RESPONSE_SAMPLE_CHARS} chars): {sample}" ); return Vec::new(); } }; - if verdicts.len() < chunk.len() { + let fingerprints: Vec<&str> = chunk + .iter() + .map(|&i| findings[i].fingerprint.as_str()) + .collect(); + let matched: Vec<(usize, TriageResult)> = match_verdicts(&fingerprints, verdicts) + .into_iter() + .zip(chunk) + .filter_map(|(verdict, &i)| verdict.map(|v| (i, v))) + .collect(); + if matched.len() < chunk.len() { tracing::warn!( - "Batch triage for chunk starting at {chunk_start} answered {} of {} findings", - verdicts.len(), - chunk.len() + "Batch triage for a chunk of {} findings answered {} of them{}; the rest are asked \ + again by id", + chunk.len(), + matched.len(), + if answer.cut_off { + " (cut off at the token budget)" + } else { + "" + }, ); } - // Extra verdicts belong to no finding of this chunk. - verdicts.truncate(chunk.len()); + matched +} + +/// The verdict for each finding of a chunk (`fingerprints`, in chunk order), +/// matched by the `id` the model echoed: the finding's number in the chunk +/// (from 1), or its fingerprint. Only when no verdict carries an id that names +/// a finding of the chunk are they matched by position; a verdict without a +/// usable id in an answer that has ids is left out rather than guessed, and +/// its finding is asked about again. +fn match_verdicts(fingerprints: &[&str], verdicts: Vec) -> Vec> { + let mut slots: Vec> = (0..fingerprints.len()).map(|_| None).collect(); + let slot_of = |verdict: &TriageResult| { + verdict + .id + .as_deref() + .and_then(|id| slot_for_id(id, fingerprints)) + }; + if verdicts.iter().any(|v| slot_of(v).is_some()) { + for verdict in verdicts { + if let Some(slot) = slot_of(&verdict) { + // The first verdict for a finding counts. + if slots[slot].is_none() { + slots[slot] = Some(verdict); + } + } + } + } else { + for (slot, verdict) in slots.iter_mut().zip(verdicts) { + *slot = Some(verdict); + } + } + slots +} + +/// The position in the chunk an echoed `id` names: a fingerprint of the chunk, +/// or a finding number from 1 (also as `"#3"`). +fn slot_for_id(id: &str, fingerprints: &[&str]) -> Option { + let id = id.trim(); + if let Some(slot) = fingerprints.iter().position(|fp| *fp == id) { + return Some(slot); + } + let number: usize = id.trim_start_matches('#').trim().parse().ok()?; + (1..=fingerprints.len()) + .contains(&number) + .then(|| number - 1) +} + +/// Ask the model about the findings at `ask`, `size` per call and +/// [`TRIAGE_CONCURRENCY`] calls at a time. +async fn ask_in_chunks( + model: &M, + findings: &[Finding], + ask: &[usize], + size: usize, + graph_context: Option<&GraphContext>, + calls: &mut usize, +) -> Vec<(usize, TriageResult)> { + let chunks: Vec<&[usize]> = ask.chunks(size.max(1)).collect(); + let mut answered = Vec::new(); + for group in chunks.chunks(TRIAGE_CONCURRENCY) { + *calls += group.len(); + let answers = futures_util::future::join_all( + group + .iter() + .map(|chunk| triage_chunk(model, findings, chunk, graph_context)), + ) + .await; + answered.extend(answers.into_iter().flatten()); + } + answered +} + +/// The tries of the triage: the chunk size of each, and which findings still +/// without a verdict it asks about. First all in full chunks, then the +/// unanswered ones in chunks half the size, then each critical and high one +/// still unanswered on its own. +const TRIES: [(usize, Severity); 3] = [ + (TRIAGE_CHUNK_SIZE, Severity::Info), + (TRIAGE_CHUNK_SIZE.div_ceil(2), Severity::Info), + (1, Severity::High), +]; + +/// Ask the model about every finding at `sent`, and again by id about those it +/// gave no verdict (see [`TRIES`]). +/// +/// # Returns +/// +/// The verdicts, by position in `findings`. +async fn ask_all( + model: &M, + findings: &[Finding], + sent: &[usize], + graph_context: Option<&GraphContext>, + calls: &mut usize, +) -> HashMap { + let mut verdicts: HashMap = HashMap::new(); + for (try_number, (size, least_severity)) in TRIES.iter().enumerate() { + let ask: Vec = sent + .iter() + .copied() + .filter(|i| !verdicts.contains_key(i) && findings[*i].severity >= *least_severity) + .collect(); + if ask.is_empty() { + continue; + } + if try_number > 0 { + tracing::info!( + "LLM triage: asking again about {} findings without a verdict, {} per call", + ask.len(), + size + ); + } + for (i, verdict) in ask_in_chunks(model, findings, &ask, *size, graph_context, calls).await + { + verdicts.entry(i).or_insert(verdict); + } + } verdicts } -/// Ask the model about each batch of positions in `selected`, -/// [`TRIAGE_CONCURRENCY`] batches at a time, and record its verdicts in -/// `verdicts` (indexed like `selected`). +/// Triage `findings` with the LLM: confirm, re-rate or flag each one. Nothing +/// is removed; a flagged finding is kept as "needs review". +/// +/// Each fingerprint is asked about once (a scanner can report the same finding +/// more than once, gitleaks once per commit), and the verdict goes to every +/// copy. Critical, high and medium findings go to the model, the most severe +/// first, at most [`TRIAGE_MAX_FINDINGS`]; findings it gave no verdict for are +/// asked about again by id (see [`TRIES`]). A finding without a verdict keeps +/// its status and gets `triage_action` [`SKIPPED_ACTION`] with the reason +/// (low, over cap, no answer) in its rationale. /// /// # Returns /// -/// The positions the model gave no verdict for: one range per batch that fell -/// short. -async fn triage_batches( - llm: &LlmClient, - findings: &[Finding], - selected: &[usize], - batches: &[Range], - graph_context: Option<&GraphContext>, - verdicts: &mut [Option], -) -> Vec> { - let chunks: Vec> = batches - .iter() - .map(|range| { - selected[range.clone()] - .iter() - .map(|&i| &findings[i]) - .collect() - }) - .collect(); - // A few calls at once; the answers stay in batch order. - let mut answers: Vec> = Vec::with_capacity(batches.len()); - for (group, ranges) in chunks - .chunks(TRIAGE_CONCURRENCY) - .zip(batches.chunks(TRIAGE_CONCURRENCY)) - { - let calls = group - .iter() - .zip(ranges) - .map(|(chunk, range)| triage_chunk(llm, chunk, graph_context, range.start)); - answers.extend(futures_util::future::join_all(calls).await); - } - - let mut missing = Vec::new(); - for (range, answer) in batches.iter().zip(answers) { - let answered = answer.len(); - for (slot, verdict) in verdicts[range.clone()].iter_mut().zip(answer) { - *slot = Some(verdict); - } - if answered < range.len() { - missing.push(range.start + answered..range.end); - } - } - missing -} - -/// Split each range in two halves (the first one the larger) for a retry in -/// smaller chunks; a single position stays as it is. -fn halves(ranges: &[Range]) -> Vec> { - ranges - .iter() - .flat_map(|range| { - let mid = range.start + range.len().div_ceil(2); - [range.start..mid, mid..range.end] - }) - .filter(|range| !range.is_empty()) - .collect() -} - -/// 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". The -/// most severe findings go first, at most [`TRIAGE_MAX_FINDINGS`], and -/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time. Findings a chunk got -/// no verdict for (the call failed, the answer was unreadable or cut short) -/// are asked about once more, in chunks half the size; whatever is still -/// unanswered then stays as reported. -/// -/// # Returns -/// -/// How many findings passed triage (confirmed, re-rated, or left unchanged). -pub async fn triage_findings( - llm: &Arc, +/// What the triage did, for the scan's log. +pub async fn triage_findings( + model: &M, findings: &mut [Finding], graph_context: Option<&GraphContext>, -) -> usize { - let selected = triage_selection(findings); - if selected.len() < findings.len() { - tracing::info!( - "LLM triage: the {} most severe of {} findings; the rest stay open", - selected.len(), - findings.len() - ); - } +) -> TriageSummary { + let mut summary = TriageSummary { + findings: findings.len(), + ..TriageSummary::default() + }; - // Ask for every chunk first (read-only), then apply the answers. - let mut verdicts: Vec> = (0..selected.len()).map(|_| None).collect(); - let batches: Vec> = (0..selected.len()) - .step_by(TRIAGE_CHUNK_SIZE) - .map(|start| start..(start + TRIAGE_CHUNK_SIZE).min(selected.len())) - .collect(); - let missing = triage_batches( - llm, - findings, - &selected, - &batches, - graph_context, - &mut verdicts, - ) - .await; - if !missing.is_empty() { - // One retry only, in smaller chunks: whatever is left after it stays as reported. - let retry = halves(&missing); - tracing::info!( - "LLM triage: retrying {} findings in {} smaller chunks", - retry.iter().map(Range::len).sum::(), - retry.len() - ); - let unanswered: usize = triage_batches( - llm, - findings, - &selected, - &retry, - graph_context, - &mut verdicts, - ) - .await - .iter() - .map(Range::len) - .sum(); - if unanswered > 0 { - tracing::warn!( - "LLM triage: no verdict for {unanswered} findings after a retry; \ - they stay unchanged, as reported" - ); + // One finding per fingerprint, and the positions of all its copies. + let mut first_of: HashMap<&str, usize> = HashMap::new(); + let mut copies: Vec> = Vec::new(); + let mut distinct: Vec = Vec::new(); + for (i, finding) in findings.iter().enumerate() { + match first_of.get(finding.fingerprint.as_str()) { + Some(&group) => copies[group].push(i), + None => { + first_of.insert(finding.fingerprint.as_str(), copies.len()); + copies.push(vec![i]); + distinct.push(i); + } + } + } + drop(first_of); + summary.unique = distinct.len(); + + let (sent, skipped) = triage_selection(findings, &distinct); + let mut verdicts = ask_all(model, findings, &sent, graph_context, &mut summary.calls).await; + let mut skip_reasons: HashMap = skipped.into_iter().collect(); + for &i in &sent { + if !verdicts.contains_key(&i) { + skip_reasons.insert(i, SkipReason::NoAnswer); } } - let mut passed = 0; - for (&i, verdict) in selected.iter().zip(&verdicts) { - let finding = &mut findings[i]; - // No usable answer for this finding: keep it as reported. - let Some(result) = verdict else { - finding.status = FindingStatus::Triaged; - passed += 1; - continue; - }; - let file_classification = classify_file_path(finding.file_path.as_deref()); - let adjusted_confidence = adjust_confidence(result.confidence, &file_classification); - finding.confidence = Some(adjusted_confidence); - finding.triage_action = Some(result.action.clone()); - finding.triage_rationale = Some(result.rationale.clone()); - if let Some(ref remediation) = result.remediation { - finding.remediation = Some(remediation.clone()); - } - if apply_action(finding, &result.action, adjusted_confidence) { - passed += 1; + for (group, &first) in copies.iter().zip(&distinct) { + if let Some(result) = verdicts.remove(&first) { + let mut outcome = None; + for &i in group { + outcome = Some(apply_verdict(&mut findings[i], &result)); + } + if let Some(outcome) = outcome { + summary.count(outcome); + } + } else if let Some(&reason) = skip_reasons.get(&first) { + summary.count_skip(reason, &findings[first].severity); + for &i in group { + mark_skipped(&mut findings[i], reason); + } } } - passed + if summary.skipped_no_answer_severe > 0 { + tracing::warn!( + "LLM triage: no verdict for {} critical/high findings after {} tries; recorded as \ + skipped: no answer, status unchanged", + summary.skipped_no_answer_severe, + TRIES.len() + ); + } + summary +} + +/// Record the model's verdict `result` on `finding`. +fn apply_verdict(finding: &mut Finding, result: &TriageResult) -> Outcome { + let file_classification = classify_file_path(finding.file_path.as_deref()); + let adjusted_confidence = adjust_confidence(result.confidence, &file_classification); + finding.confidence = Some(adjusted_confidence); + finding.triage_action = Some(result.action.clone()); + finding.triage_rationale = Some(result.rationale.clone()); + if let Some(ref remediation) = result.remediation { + finding.remediation = Some(remediation.clone()); + } + apply_action(finding, &result.action, adjusted_confidence) +} + +/// Record on `finding` that the triage gave it no verdict, and why. Its status +/// stays as reported. +fn mark_skipped(finding: &mut Finding, reason: SkipReason) { + finding.triage_action = Some(SKIPPED_ACTION.to_string()); + finding.triage_rationale = Some(reason.rationale().to_string()); } /// Why a batch triage answer could not be read. @@ -476,39 +737,43 @@ fn drop_trailing_comma(json: &mut String) { } } -/// Apply the model's `action` to `finding`; `true` when it passed triage. +/// Apply the model's `action` to `finding`. /// /// 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 { +fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> Outcome { match action { "dismiss" => { finding.status = FindingStatus::NeedsReview; - false + Outcome::Dismissed } "downgrade" => { finding.severity = downgrade_severity(&finding.severity); finding.status = FindingStatus::Triaged; - true + Outcome::Downgraded } "upgrade" => { finding.severity = upgrade_severity(&finding.severity); finding.status = FindingStatus::Triaged; - true + Outcome::Upgraded } // "confirm" or unknown: kept as reported when the model is confident. - _ if adjusted_confidence >= 3.0 => { + _ if adjusted_confidence >= CONFIDENCE_THRESHOLD => { finding.status = FindingStatus::Triaged; - true + Outcome::Confirmed } _ => { finding.status = FindingStatus::NeedsReview; - false + Outcome::LowConfidence } } } +/// Least confidence (after [`adjust_confidence`]) at which a confirmed +/// finding counts as triaged; below it the finding needs review. +const CONFIDENCE_THRESHOLD: f64 = 3.0; + /// Read ~50 lines of surrounding code from the file at the finding's location fn read_surrounding_context(finding: &Finding) -> Option { let file_path = finding.file_path.as_deref()?; @@ -614,13 +879,15 @@ fn upgrade_severity( } } -/// The model's verdict on one finding. Verdicts are matched to findings by -/// position, so the echoed `id` is not read (a model may echo the finding -/// number instead of the fingerprint). Every field is read leniently: a -/// `null`, a number sent as a string, or a missing field takes the default -/// rather than failing the whole verdict. -#[derive(Deserialize)] +/// The model's verdict on one finding. The echoed `id` (the finding's number +/// in its chunk, or its fingerprint) says which finding it is for; see +/// [`match_verdicts`]. Every field is read leniently: a `null`, a number sent +/// as a string, or a missing field takes the default rather than failing the +/// whole verdict. +#[derive(Debug, Deserialize)] struct TriageResult { + #[serde(default, deserialize_with = "lenient_id")] + id: Option, #[serde(default = "default_action", deserialize_with = "action_or_default")] action: String, #[serde(default, deserialize_with = "lenient_number")] @@ -640,6 +907,15 @@ fn action_or_default<'de, D: Deserializer<'de>>(deserializer: D) -> Result::deserialize(deserializer)?.unwrap_or_else(default_action)) } +/// An id sent as a number or a string; `None` for anything else. +fn lenient_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + Ok(match Value::deserialize(deserializer)? { + Value::Number(n) => Some(n.to_string()), + Value::String(s) => Some(s), + Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => None, + }) +} + /// A string field, with `null` read as empty. fn null_as_empty<'de, D: Deserializer<'de>>(deserializer: D) -> Result { Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) @@ -660,7 +936,7 @@ mod tests { #[test] fn the_triage_takes_the_most_severe_findings_first_and_stops_at_the_cap() { - use compliance_core::models::{ScanType, Severity}; + use compliance_core::models::ScanType; let finding = |severity| { Finding::new( "t".into(), @@ -676,13 +952,20 @@ mod tests { finding(Severity::Low), finding(Severity::Critical), finding(Severity::Medium), + finding(Severity::Info), ]; - assert_eq!(triage_selection(&findings), [1, 2, 0]); + let (sent, skipped) = triage_selection(&findings, &[0, 1, 2, 3]); + assert_eq!(sent, [1, 2]); + assert_eq!(skipped, [(0, SkipReason::Low), (3, SkipReason::Low)]); let many: Vec = (0..TRIAGE_MAX_FINDINGS + 10) - .map(|_| finding(Severity::Info)) + .map(|_| finding(Severity::Medium)) .collect(); - assert_eq!(triage_selection(&many).len(), TRIAGE_MAX_FINDINGS); + let all: Vec = (0..many.len()).collect(); + let (sent, skipped) = triage_selection(&many, &all); + assert_eq!(sent.len(), TRIAGE_MAX_FINDINGS); + assert_eq!(skipped.len(), 10); + assert!(skipped.iter().all(|(_, r)| *r == SkipReason::OverCap)); } use super::*; use compliance_core::models::scan::ScanType; @@ -702,22 +985,28 @@ mod tests { #[test] fn a_dismissed_finding_is_kept_for_review() { let mut f = finding(); - assert!(!apply_action(&mut f, "dismiss", 9.0)); + assert_eq!(apply_action(&mut f, "dismiss", 9.0), Outcome::Dismissed); assert_eq!(f.status, FindingStatus::NeedsReview); let mut unsure = finding(); - assert!(!apply_action(&mut unsure, "confirm", 2.0)); + assert_eq!( + apply_action(&mut unsure, "confirm", 2.0), + Outcome::LowConfidence + ); 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!(apply_action(&mut f, "confirm", 7.0), Outcome::Confirmed); assert_eq!(f.status, FindingStatus::Triaged); let mut lower = finding(); - assert!(apply_action(&mut lower, "downgrade", 7.0)); + assert_eq!( + apply_action(&mut lower, "downgrade", 7.0), + Outcome::Downgraded + ); assert_eq!(lower.severity, Severity::Medium); } use compliance_core::models::Severity; @@ -1016,10 +1305,304 @@ mod tests { } } + // ── Verdicts matched by id ─────────────────────────────────── + + fn verdict(json: &str) -> TriageResult { + serde_json::from_str(json).unwrap() + } + + fn matched_actions(fingerprints: &[&str], answer: &str) -> Vec> { + match_verdicts(fingerprints, parse_triage_response(answer).unwrap()) + .into_iter() + .map(|v| v.map(|v| v.action)) + .collect() + } + #[test] - fn the_retry_halves_each_unanswered_range() { - assert_eq!(halves(&[Range { start: 0, end: 9 }]), [0..5, 5..9]); - assert_eq!(halves(&[3..4, 30..60]), [3..4, 30..45, 45..60]); - assert!(halves(&[]).is_empty()); + fn verdicts_are_matched_by_number_or_fingerprint_in_any_order() { + let fps = ["aa11", "bb22", "cc33"]; + let answer = r##"[{"id":3,"action":"dismiss"},{"id":"aa11","action":"upgrade"},{"id":"#2","action":"confirm"}]"##; + assert_eq!( + matched_actions(&fps, answer), + [ + Some("upgrade".into()), + Some("confirm".into()), + Some("dismiss".into()) + ] + ); + } + + #[test] + fn a_skipped_finding_is_not_given_the_next_verdict() { + // The model left out finding 2: by position, finding 3's verdict + // would have landed on it. + let fps = ["aa11", "bb22", "cc33"]; + let answer = r#"[{"id":1,"action":"confirm"},{"id":3,"action":"dismiss"},{"action":"upgrade"},{"id":9,"action":"upgrade"}]"#; + assert_eq!( + matched_actions(&fps, answer), + [Some("confirm".into()), None, Some("dismiss".into())] + ); + } + + #[test] + fn verdicts_without_ids_are_matched_by_position() { + let fps = ["aa11", "bb22", "cc33"]; + let answer = r#"[{"action":"confirm"},{"action":"dismiss"}]"#; + assert_eq!( + matched_actions(&fps, answer), + [Some("confirm".into()), Some("dismiss".into()), None] + ); + assert_eq!(verdict(r#"{"id":2}"#).id.as_deref(), Some("2")); + } + + // ── The triage run, with a fake model ──────────────────────── + + use std::sync::Mutex; + + /// A fake model: answers each prompt with the next scripted answer (or an + /// error once the script runs out) and records which finding numbers and + /// titles each prompt asked about. + struct FakeModel { + script: Mutex>>, + asked: Mutex>>, + /// Answer every prompt by confirming all findings it names. + confirm_all: bool, + } + + impl FakeModel { + fn scripted(answers: &[&str]) -> Self { + Self { + script: Mutex::new( + answers + .iter() + .rev() + .map(|a| { + Ok(ChatAnswer { + content: (*a).to_string(), + cut_off: false, + }) + }) + .collect(), + ), + asked: Mutex::new(Vec::new()), + confirm_all: false, + } + } + + fn confirming() -> Self { + Self { + confirm_all: true, + ..Self::scripted(&[]) + } + } + + fn asked(&self) -> Vec> { + self.asked.lock().unwrap().clone() + } + } + + /// The titles of the findings a prompt names, in prompt order. + fn titles_in(prompt: &str) -> Vec { + prompt + .lines() + .filter_map(|l| l.strip_prefix("Title: ")) + .map(str::to_owned) + .collect() + } + + impl TriageModel for FakeModel { + async fn answer(&self, system: &str, user: &str) -> Result { + assert_eq!(system, TRIAGE_SYSTEM_PROMPT); + let titles = titles_in(user); + self.asked.lock().unwrap().push(titles.clone()); + if self.confirm_all { + let verdicts: Vec = (1..=titles.len()) + .map(|n| { + format!( + r#"{{"id":{n},"action":"confirm","confidence":8,"rationale":"real"}}"# + ) + }) + .collect(); + return Ok(ChatAnswer { + content: format!("[{}]", verdicts.join(",")), + cut_off: false, + }); + } + self.script + .lock() + .unwrap() + .pop() + .unwrap_or_else(|| Err("no more answers".into())) + .map_err(AgentError::Other) + } + } + + fn numbered(n: usize, severity: Severity) -> Finding { + let mut f = Finding::new( + "repo".into(), + format!("fp-{n}"), + "semgrep".into(), + ScanType::Sast, + format!("finding {n}"), + "desc".into(), + severity, + ); + f.file_path = Some(format!("src/module_{n}.cs")); + f + } + + #[tokio::test] + async fn a_partial_answer_is_completed_by_asking_again_about_the_missing_ids() { + let mut findings: Vec = (1..=4).map(|n| numbered(n, Severity::High)).collect(); + let model = FakeModel::scripted(&[ + // Cut off after two verdicts, the second for finding 3. + r#"[{"id":1,"action":"confirm","confidence":8,"rationale":"input reaches it"},{"id":3,"action":"dismiss","confidence":9,"rationale":"test helper"},{"id":2,"act"#, + // The retry names findings 2 and 4 only, as 1 and 2. + r#"[{"id":2,"action":"downgrade","confidence":6,"rationale":"internal only"},{"id":1,"action":"confirm","confidence":7,"rationale":"reachable"}]"#, + ]); + let summary = triage_findings(&model, &mut findings, None).await; + + let asked = model.asked(); + assert_eq!(asked.len(), 2); + assert_eq!(asked[1], ["finding 2", "finding 4"]); + let actions: Vec<_> = findings + .iter() + .map(|f| f.triage_action.as_deref()) + .collect(); + assert_eq!( + actions, + [ + Some("confirm"), + Some("confirm"), + Some("dismiss"), + Some("downgrade") + ] + ); + assert_eq!(findings[1].triage_rationale.as_deref(), Some("reachable")); + assert_eq!(findings[3].severity, Severity::Medium); + assert_eq!(summary.triaged(), 4); + assert_eq!(summary.skipped(), 0); + assert_eq!(summary.calls, 2); + } + + #[tokio::test] + async fn a_malformed_chunk_is_asked_again_and_a_high_finding_alone_at_last() { + let mut findings: Vec = + vec![numbered(1, Severity::High), numbered(2, Severity::Medium)]; + let model = FakeModel::scripted(&[ + "I am sorry, the findings are [unclear", + "{\"action\": ", + r#"{"id":1,"action":"confirm","confidence":9,"rationale":"secret in config"}"#, + ]); + let summary = triage_findings(&model, &mut findings, None).await; + + let asked = model.asked(); + assert_eq!(asked.len(), 3); + // The last try asks about the high finding only, on its own. + assert_eq!(asked[2], ["finding 1"]); + assert_eq!(findings[0].triage_action.as_deref(), Some("confirm")); + assert_eq!(findings[0].status, FindingStatus::Triaged); + // The medium one is kept, as reported, with the reason. + assert_eq!(findings[1].triage_action.as_deref(), Some(SKIPPED_ACTION)); + assert!(findings[1] + .triage_rationale + .as_deref() + .unwrap() + .starts_with("skipped: no answer")); + assert_eq!(findings[1].status, FindingStatus::Open); + assert_eq!(summary.skipped_no_answer, 1); + assert_eq!(summary.skipped_no_answer_severe, 0); + } + + #[tokio::test] + async fn a_model_that_is_down_skips_but_keeps_every_finding() { + let mut findings: Vec = (1..=3).map(|n| numbered(n, Severity::Critical)).collect(); + let model = FakeModel::scripted(&[]); + let summary = triage_findings(&model, &mut findings, None).await; + assert_eq!(findings.len(), 3); + assert!(findings + .iter() + .all(|f| f.triage_action.as_deref() == Some(SKIPPED_ACTION) + && f.status == FindingStatus::Open)); + assert_eq!(summary.skipped_no_answer_severe, 3); + // One chunk, its retry, then each critical finding on its own. + assert_eq!(summary.calls, 5); + } + + #[tokio::test] + async fn the_threshold_flags_for_review_and_never_drops() { + let mut findings: Vec = (1..=4).map(|n| numbered(n, Severity::High)).collect(); + findings[3].file_path = Some("src/tests/helper_test.cs".into()); + let model = FakeModel::scripted(&[r#"[ + {"id":1,"action":"confirm","confidence":8,"rationale":"real"}, + {"id":2,"action":"confirm","confidence":2,"rationale":"unsure"}, + {"id":3,"action":"dismiss","confidence":9,"rationale":"not reachable"}, + {"id":4,"action":"confirm","confidence":5,"rationale":"test code"} + ]"#]); + let summary = triage_findings(&model, &mut findings, None).await; + + assert_eq!(findings.len(), 4, "nothing is removed"); + let statuses: Vec<_> = findings.iter().map(|f| f.status.clone()).collect(); + assert_eq!( + statuses, + [ + FindingStatus::Triaged, + FindingStatus::NeedsReview, + FindingStatus::NeedsReview, + // 5 in test code is 2.5 after the adjustment: below 3. + FindingStatus::NeedsReview, + ] + ); + // Every one keeps the model's action and rationale. + assert!(findings.iter().all(|f| f.triage_action.is_some())); + assert_eq!( + findings[2].triage_rationale.as_deref(), + Some("not reachable") + ); + assert_eq!(findings[3].confidence, Some(2.5)); + assert_eq!( + (summary.confirmed, summary.low_confidence, summary.dismissed), + (1, 2, 1) + ); + } + + #[tokio::test] + async fn lows_are_skipped_and_copies_share_one_verdict() { + let mut findings = vec![ + numbered(1, Severity::High), + numbered(1, Severity::High), // the same secret, another commit + numbered(2, Severity::Low), + numbered(3, Severity::Info), + ]; + let model = FakeModel::confirming(); + let summary = triage_findings(&model, &mut findings, None).await; + + assert_eq!(model.asked(), [vec!["finding 1".to_string()]]); + assert_eq!(findings[0].triage_action.as_deref(), Some("confirm")); + assert_eq!(findings[1].triage_action.as_deref(), Some("confirm")); + for low in &findings[2..] { + assert_eq!(low.triage_action.as_deref(), Some(SKIPPED_ACTION)); + assert!(low + .triage_rationale + .as_deref() + .unwrap() + .starts_with("skipped: low")); + assert_eq!(low.status, FindingStatus::Open); + } + assert_eq!((summary.findings, summary.unique), (4, 3)); + assert_eq!((summary.confirmed, summary.skipped_low), (1, 2)); + let line = summary.to_string(); + assert!(line.contains("triaged 1"), "{line}"); + assert!(line.contains("low 2"), "{line}"); + } + + #[tokio::test] + async fn a_large_scan_is_asked_in_chunks() { + let mut findings: Vec = (1..=25).map(|n| numbered(n, Severity::Medium)).collect(); + let model = FakeModel::confirming(); + let summary = triage_findings(&model, &mut findings, None).await; + let sizes: Vec = model.asked().iter().map(Vec::len).collect(); + assert_eq!(sizes, [10, 10, 5]); + assert_eq!(summary.confirmed, 25); } } diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index 080d37a..d278518 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -170,12 +170,9 @@ impl RunFindings { Ok(saved) } - /// Store what triage changed on the findings this run saved, and the - /// control refs of findings an earlier run stored. Findings no stage has - /// saved yet (the grounded surface checks) are saved first. - /// - /// A status is written only onto a row still `open`: a person who marked - /// a finding while the scan ran keeps their choice. + /// Store what triage changed on the findings this run saved and on those + /// an earlier run stored (see [`row_writes`]). Findings no stage has saved + /// yet (the grounded surface checks) are saved first. /// /// # Returns /// @@ -194,44 +191,29 @@ impl RunFindings { let mut new_findings = Vec::new(); let mut written: HashSet<&str> = HashSet::new(); - let mut refreshed = 0_u32; + let (mut retriaged, mut refreshed) = (0_u32, 0_u32); for finding in findings.iter() { if !written.insert(finding.fingerprint.as_str()) { continue; } - match self.inserted.get(&finding.fingerprint) { - Some(id) => { - db.findings() - .update_one(doc! { "_id": id }, triage_update(finding)?) - .await?; - if finding.status != FindingStatus::Open { - db.findings() - .update_one( - doc! { "_id": id, "status": "open" }, - doc! { "$set": { "status": bson_of(&finding.status)? } }, - ) - .await?; - } - new_findings.push(finding.clone()); + let inserted = self.inserted.get(&finding.fingerprint).copied(); + for write in row_writes(finding, inserted)? { + let result = db.findings().update_one(write.filter, write.update).await?; + match write.kind { + WriteKind::EarlierTriage if result.matched_count > 0 => retriaged += 1, + WriteKind::EarlierControlRefs => refreshed += 1, + _ => {} } - // A mapping pass (newly enabled or tuned) computed refs for a - // finding first stored before it ran. - None if !finding.control_refs.is_empty() => { - db.findings() - .update_one( - doc! { "fingerprint": &finding.fingerprint }, - doc! { "$set": { "control_refs": finding.control_refs.clone() } }, - ) - .await?; - refreshed += 1; - } - None => {} + } + if inserted.is_some() { + new_findings.push(finding.clone()); } } - if refreshed > 0 { + if retriaged > 0 || refreshed > 0 { tracing::info!( scan_run_id = %self.scan_run_id, - "refreshed control_refs on {refreshed} existing findings" + "stored this run's triage on {retriaged} and refreshed control_refs on \ + {refreshed} findings an earlier run stored" ); } Ok(new_findings) @@ -369,6 +351,104 @@ fn bson_of(value: &T) -> Result { to_bson(value).map_err(|e| AgentError::Other(format!("encode finding field: {e}"))) } +/// What one update in [`RunFindings::write_back`] stores. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WriteKind { + /// The triage fields of a row this run saved. + NewTriage, + /// The triage's status of a row this run saved, while it is still open. + NewStatus, + /// The triage fields of a row an earlier run stored. + EarlierTriage, + /// The triage's status of a row an earlier run stored, while it is still open. + EarlierStatus, + /// The control refs of a row an earlier run stored. + EarlierControlRefs, +} + +/// One update of a finding's stored row. +#[derive(Debug)] +struct RowWrite { + kind: WriteKind, + filter: Document, + update: Document, +} + +/// The updates that store what the triage stages changed on `finding`: +/// `inserted` is its row id when this run saved it, `None` when an earlier +/// run stored it. +/// +/// - Triage fields (action, rationale, severity, confidence, remediation, +/// control refs) are stored on a row this run saved, and on an earlier row +/// nobody has decided about yet ([`UNDECIDED`]): a rescan triages the +/// findings an earlier run stored, and its result must not be lost (#462). +/// A "skipped" result never replaces an earlier verdict. +/// - A status is written only onto a row still `open`: a person who marked a +/// finding keeps their choice. +/// - The control refs of an earlier row are refreshed whatever its status (a +/// mapping pass newly enabled or tuned). +/// +/// # Errors +/// +/// A field that cannot be encoded. +fn row_writes(finding: &Finding, inserted: Option) -> Result, AgentError> { + let mut writes = Vec::new(); + let status = (finding.status != FindingStatus::Open) + .then(|| bson_of(&finding.status)) + .transpose()?; + match inserted { + Some(id) => { + writes.push(RowWrite { + kind: WriteKind::NewTriage, + filter: doc! { "_id": id }, + update: triage_update(finding)?, + }); + if let Some(status) = status { + writes.push(RowWrite { + kind: WriteKind::NewStatus, + filter: doc! { "_id": id, "status": "open" }, + update: doc! { "$set": { "status": status } }, + }); + } + } + None => { + if let Some(action) = &finding.triage_action { + let mut filter = doc! { + "fingerprint": &finding.fingerprint, + "status": { "$in": UNDECIDED.to_vec() }, + }; + if action == crate::llm::triage::SKIPPED_ACTION { + // Matches a row without a triage action too. + filter.insert( + "triage_action", + doc! { "$in": [Bson::Null, crate::llm::triage::SKIPPED_ACTION] }, + ); + } + writes.push(RowWrite { + kind: WriteKind::EarlierTriage, + filter, + update: triage_update(finding)?, + }); + if let Some(status) = status { + writes.push(RowWrite { + kind: WriteKind::EarlierStatus, + filter: doc! { "fingerprint": &finding.fingerprint, "status": "open" }, + update: doc! { "$set": { "status": status } }, + }); + } + } + if !finding.control_refs.is_empty() { + writes.push(RowWrite { + kind: WriteKind::EarlierControlRefs, + filter: doc! { "fingerprint": &finding.fingerprint }, + update: doc! { "$set": { "control_refs": finding.control_refs.clone() } }, + }); + } + } + } + Ok(writes) +} + /// The fields the triage stages set, as an update. fn triage_update(finding: &Finding) -> Result { Ok(doc! { "$set": { @@ -381,3 +461,86 @@ fn triage_update(finding: &Finding) -> Result { "updated_at": mongodb::bson::DateTime::now(), } }) } + +#[cfg(test)] +mod tests { + use compliance_core::models::{ScanType, Severity}; + + use super::*; + + fn triaged(action: &str, status: FindingStatus) -> Finding { + let mut f = Finding::new( + "repo".into(), + "fp-1".into(), + "semgrep".into(), + ScanType::Sast, + "unsafe deserialization".into(), + "desc".into(), + Severity::High, + ); + f.triage_action = Some(action.into()); + f.triage_rationale = Some("reachable from a request handler".into()); + f.status = status; + f + } + + fn set_of(write: &RowWrite) -> &Document { + write.update.get_document("$set").unwrap() + } + + #[test] + fn a_new_rows_triage_and_status_are_stored() { + let id = ObjectId::new(); + let writes = row_writes(&triaged("dismiss", FindingStatus::NeedsReview), Some(id)).unwrap(); + let kinds: Vec = writes.iter().map(|w| w.kind).collect(); + assert_eq!(kinds, [WriteKind::NewTriage, WriteKind::NewStatus]); + assert_eq!(set_of(&writes[0]).get_str("triage_action"), Ok("dismiss")); + assert_eq!( + set_of(&writes[0]).get_str("triage_rationale"), + Ok("reachable from a request handler") + ); + assert_eq!(writes[1].filter, doc! { "_id": id, "status": "open" }); + } + + #[test] + fn an_earlier_rows_triage_is_stored_unless_a_person_decided() { + // #462: a rescan's verdicts on rows an earlier run stored were dropped. + let writes = row_writes(&triaged("confirm", FindingStatus::Triaged), None).unwrap(); + let kinds: Vec = writes.iter().map(|w| w.kind).collect(); + assert_eq!(kinds, [WriteKind::EarlierTriage, WriteKind::EarlierStatus]); + assert_eq!(set_of(&writes[0]).get_str("triage_action"), Ok("confirm")); + assert_eq!( + set_of(&writes[0]).get_str("triage_rationale"), + Ok("reachable from a request handler") + ); + assert_eq!( + writes[0].filter, + doc! { "fingerprint": "fp-1", "status": { "$in": ["open", "triaged", "needs_review"] } } + ); + assert_eq!( + writes[1].filter, + doc! { "fingerprint": "fp-1", "status": "open" } + ); + } + + #[test] + fn a_skip_never_replaces_an_earlier_verdict() { + let writes = row_writes(&triaged("skipped", FindingStatus::Open), None).unwrap(); + assert_eq!(writes.len(), 1, "no status write for an open finding"); + assert_eq!( + writes[0].filter.get_document("triage_action").unwrap(), + &doc! { "$in": [Bson::Null, "skipped"] } + ); + } + + #[test] + fn an_untriaged_earlier_row_only_gets_its_control_refs() { + let mut f = triaged("confirm", FindingStatus::Open); + f.triage_action = None; + assert!(row_writes(&f, None).unwrap().is_empty()); + f.control_refs = vec!["CRA-1".into()]; + let writes = row_writes(&f, None).unwrap(); + assert_eq!(writes.len(), 1); + assert_eq!(writes[0].kind, WriteKind::EarlierControlRefs); + } +} diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 2e4a27e..534537e 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -563,13 +563,13 @@ impl PipelineOrchestrator { all_findings.len() ); self.update_phase(scan_run_id, ScanPhase::LlmTriage).await; - let triaged = crate::llm::triage::triage_findings( - &self.llm, + let triage = crate::llm::triage::triage_findings( + self.llm.as_ref(), &mut all_findings, graph_context.as_ref(), ) .await; - tracing::info!("[{repo_id}] Triaged: {triaged} findings passed confidence threshold"); + tracing::info!("[{repo_id}] {triage}"); // Stage 5b: control triage — stamp findings with the compliance control(s) // they're evidence for and flag control false positives (grounded LLM over