From ab04b2f6128881497b7a797b6f333ab6b58842ac Mon Sep 17 00:00:00 2001
From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Date: Mon, 28 Sep 2026 18:09:13 +0200
Subject: [PATCH] fix: findings from the first acceptance round
- Scans no longer run for hours on vendor-heavy trees. The iot-reference
scan produced 11,670 findings, 11,579 of them from ruff over vendor Python
under Middleware/, and the LLM triage worked through all of them, 30 at a
time, one call after another. Vendor code is now left out of the pattern,
secret and lint findings too (it already was for SAST); the LLM triage
takes the 600 most severe findings, 4 calls at a time, the rest staying
open; control triage runs 8 judge calls at a time.
- A reasoning model's block is removed before its answer is parsed,
ahead of the switch to Qwen3.8-27B.
- A file can be added to an existing target: the editor offers an upload
(archive, PLC project, firmware image, with its archive password) instead
of asking for a path; the wizard and the editor share the file-kind and
PLC-format helpers.
- The manual-findings form and the archive-password field in the editor use
the dashboard's form styling.
- A robots noindex meta tag in the page head, next to the X-Robots-Tag header.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
---
compliance-agent/src/controls/scan_triage.rs | 34 +-
compliance-agent/src/llm/client.rs | 42 ++-
compliance-agent/src/llm/triage.rs | 294 +++++++++++-------
compliance-agent/src/pipeline/orchestrator.rs | 26 +-
compliance-agent/src/pipeline/vendor.rs | 26 ++
compliance-dashboard/assets/main.css | 93 +++++-
compliance-dashboard/src/app.rs | 3 +
.../src/components/artifact_upload.rs | 135 ++++++++
.../src/components/manual_findings.rs | 2 +-
compliance-dashboard/src/components/mod.rs | 1 +
compliance-dashboard/src/i18n/texts.rs | 18 ++
.../src/infrastructure/onboarding.rs | 34 ++
compliance-dashboard/src/pages/onboarding.rs | 24 +-
compliance-dashboard/src/pages/target.rs | 27 +-
14 files changed, 598 insertions(+), 161 deletions(-)
create mode 100644 compliance-dashboard/src/components/artifact_upload.rs
diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs
index d0fe251..acdf550 100644
--- a/compliance-agent/src/controls/scan_triage.rs
+++ b/compliance-agent/src/controls/scan_triage.rs
@@ -28,6 +28,8 @@ use crate::llm::LlmClient;
/// Nearest master controls judged per code region in the semantic pass.
const SEMANTIC_TOP_K: usize = 5;
+/// Control-triage judge calls in flight at once.
+const CONTROL_TRIAGE_CONCURRENCY: usize = 8;
/// Most findings one scan maps semantically: each costs an embedding and up
/// to [`SEMANTIC_TOP_K`] judge calls, so an uncapped pass would add tens of
/// minutes to a large scan. The most severe unmapped ones go first.
@@ -63,15 +65,31 @@ pub async fn triage_repo_findings(
};
let triage = ControlTriage::new(LlmControlJudge::new(llm), map, specs);
+ // The judge reads each finding's code; its calls run a few at a time, and
+ // the outcomes are applied once all are in.
+ let candidates: Vec<(usize, CandidateRegion)> = findings
+ .iter()
+ .enumerate()
+ .filter_map(|(i, f)| {
+ let region = fetch_region(repo_path, f.file_path.as_deref()?, f.line_number?)?;
+ Some((i, region))
+ })
+ .collect();
+ let mut outcomes = Vec::with_capacity(candidates.len());
+ {
+ let read: &[Finding] = findings;
+ for group in candidates.chunks(CONTROL_TRIAGE_CONCURRENCY) {
+ let calls = group
+ .iter()
+ .map(|(i, region)| triage.triage(&read[*i], region));
+ outcomes.extend(futures_util::future::join_all(calls).await);
+ }
+ }
+
let mut tagged = 0;
- for finding in findings.iter_mut() {
- let (Some(file), Some(line)) = (finding.file_path.clone(), finding.line_number) else {
- continue;
- };
- let Some(region) = fetch_region(repo_path, &file, line) else {
- continue;
- };
- match triage.triage(finding, ®ion).await {
+ for ((i, _), outcome) in candidates.iter().zip(outcomes) {
+ let finding = &mut findings[*i];
+ match outcome {
TriageOutcome::Confirmed(controls) => {
finding.control_refs = controls;
tagged += 1;
diff --git a/compliance-agent/src/llm/client.rs b/compliance-agent/src/llm/client.rs
index 7f9e785..30135e9 100644
--- a/compliance-agent/src/llm/client.rs
+++ b/compliance-agent/src/llm/client.rs
@@ -216,7 +216,45 @@ impl LlmClient {
}
// Otherwise return content
- let content = choice.message.content.clone().unwrap_or_default();
- Ok(LlmResponse::Content(content))
+ let content = choice.message.content.as_deref().unwrap_or_default();
+ Ok(LlmResponse::Content(without_reasoning(content)))
+ }
+}
+
+/// `content` without a reasoning model's `…` blocks, which some
+/// gateways return inline ahead of the answer; the callers parse the answer as
+/// JSON. An unterminated block (the model ran out of tokens while thinking)
+/// leaves nothing to parse, so it becomes empty.
+fn without_reasoning(content: &str) -> String {
+ let mut rest = content;
+ let mut out = String::with_capacity(content.len());
+ while let Some(start) = rest.find("") {
+ out.push_str(&rest[..start]);
+ match rest[start..].find("") {
+ Some(end) => rest = &rest[start + end + "".len()..],
+ None => {
+ rest = "";
+ break;
+ }
+ }
+ }
+ out.push_str(rest);
+ out.trim().to_string()
+}
+
+#[cfg(test)]
+mod reasoning_tests {
+ use super::without_reasoning;
+
+ #[test]
+ fn a_reasoning_models_thinking_is_not_part_of_the_answer() {
+ assert_eq!(
+ without_reasoning(
+ "the finding is in a test file\n[{\"action\":\"dismiss\"}]"
+ ),
+ "[{\"action\":\"dismiss\"}]"
+ );
+ assert_eq!(without_reasoning("[1, 2]"), "[1, 2]");
+ assert_eq!(without_reasoning("still going"), "");
}
}
diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs
index 2d16b30..ab70e89 100644
--- a/compliance-agent/src/llm/triage.rs
+++ b/compliance-agent/src/llm/triage.rs
@@ -49,32 +49,37 @@ Confidence scoring (0-10):
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"}, ...]"#;
-/// 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,
- findings: &mut [Finding],
+/// 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.
+const TRIAGE_MAX_FINDINGS: usize = 600;
+/// Triage calls in flight at once.
+const TRIAGE_CONCURRENCY: usize = 4;
+
+/// 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
+}
+
+/// The model's answer for one chunk: its verdicts in chunk order, or `None`
+/// when the call failed or its answer could not be read.
+async fn triage_chunk(
+ llm: &LlmClient,
+ chunk: &[&Finding],
graph_context: Option<&GraphContext>,
-) -> usize {
- let mut passed = 0;
+ chunk_start: usize,
+) -> Option> {
+ let mut user_prompt = String::new();
- // Process findings in chunks to avoid overflowing the LLM context window.
- for chunk_start in (0..findings.len()).step_by(TRIAGE_CHUNK_SIZE) {
- let chunk_end = (chunk_start + TRIAGE_CHUNK_SIZE).min(findings.len());
- let chunk = &mut findings[chunk_start..chunk_end];
+ for (i, finding) in chunk.iter().enumerate() {
+ let file_classification = classify_file_path(finding.file_path.as_deref());
- // Build a combined prompt for the entire chunk.
- let mut user_prompt = String::new();
- let mut file_classifications: Vec = Vec::new();
-
- for (i, finding) in chunk.iter().enumerate() {
- let file_classification = classify_file_path(finding.file_path.as_deref());
-
- user_prompt.push_str(&format!(
+ user_prompt.push_str(&format!(
"\n--- Finding {} (id: {}) ---\nScanner: {}\nRule: {}\nSeverity: {}\nTitle: {}\nDescription: {}\nFile: {}\nLine: {}\nCode: {}\nFile classification: {}",
i + 1,
finding.fingerprint,
@@ -89,118 +94,144 @@ pub async fn triage_findings(
file_classification,
));
- // Enrich with surrounding code context if possible
- if let Some(context) = read_surrounding_context(finding) {
- user_prompt.push_str(&format!(
- "\n\n--- Surrounding Code (50 lines) ---\n{context}"
- ));
- }
+ // Enrich with surrounding code context if possible
+ if let Some(context) = read_surrounding_context(finding) {
+ user_prompt.push_str(&format!(
+ "\n\n--- Surrounding Code (50 lines) ---\n{context}"
+ ));
+ }
- // Enrich with graph context if available
- if let Some(ctx) = graph_context {
- if let Some(impact) = ctx
- .impacts
- .iter()
- .find(|im| im.finding_id == finding.fingerprint)
- {
- user_prompt.push_str(&format!(
- "\n\n--- Code Graph Context ---\n\
+ // Enrich with graph context if available
+ if let Some(ctx) = graph_context {
+ if let Some(impact) = ctx
+ .impacts
+ .iter()
+ .find(|im| im.finding_id == finding.fingerprint)
+ {
+ user_prompt.push_str(&format!(
+ "\n\n--- Code Graph Context ---\n\
Blast radius: {} nodes affected\n\
Entry points affected: {}\n\
Direct callers: {}\n\
Communities affected: {}\n\
Call chains: {}",
- impact.blast_radius,
- if impact.affected_entry_points.is_empty() {
- "none".to_string()
- } else {
- impact.affected_entry_points.join(", ")
- },
- if impact.direct_callers.is_empty() {
- "none".to_string()
- } else {
- impact.direct_callers.join(", ")
- },
- impact.affected_communities.len(),
- impact.call_chains.len(),
- ));
- }
+ impact.blast_radius,
+ if impact.affected_entry_points.is_empty() {
+ "none".to_string()
+ } else {
+ impact.affected_entry_points.join(", ")
+ },
+ if impact.direct_callers.is_empty() {
+ "none".to_string()
+ } else {
+ impact.direct_callers.join(", ")
+ },
+ impact.affected_communities.len(),
+ impact.call_chains.len(),
+ ));
}
-
- user_prompt.push('\n');
- file_classifications.push(file_classification);
}
- // Send the batch to the LLM.
- match llm
- .chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1))
- .await
- {
- Ok(response) => {
- let cleaned = response.trim();
- let cleaned = if cleaned.starts_with("```") {
- cleaned
- .trim_start_matches("```json")
- .trim_start_matches("```")
- .trim_end_matches("```")
- .trim()
- } else {
- cleaned
- };
+ user_prompt.push('\n');
+ }
- match serde_json::from_str::>(cleaned) {
- Ok(results) => {
- for (idx, finding) in chunk.iter_mut().enumerate() {
- // Match result by position; fall back to keeping the finding.
- let Some(result) = results.get(idx) else {
- finding.status = FindingStatus::Triaged;
- passed += 1;
- continue;
- };
+ let response = match llm
+ .chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1))
+ .await
+ {
+ Ok(response) => response,
+ Err(e) => {
+ tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}");
+ return None;
+ }
+ };
+ let cleaned = response.trim();
+ let cleaned = if cleaned.starts_with("```") {
+ cleaned
+ .trim_start_matches("```json")
+ .trim_start_matches("```")
+ .trim_end_matches("```")
+ .trim()
+ } else {
+ cleaned
+ };
+ match serde_json::from_str::>(cleaned) {
+ Ok(results) => Some(results),
+ Err(_) => {
+ tracing::warn!(
+ "Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}"
+ );
+ None
+ }
+ }
+}
- let file_classification = file_classifications
- .get(idx)
- .map(|s| s.as_str())
- .unwrap_or("unknown");
+/// 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.
+///
+/// # Returns
+///
+/// How many findings passed triage (confirmed or re-rated).
+pub async fn triage_findings(
+ llm: &Arc,
+ 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()
+ );
+ }
- 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());
+ // Ask for every chunk first (read-only), a few at a time, then apply the
+ // answers.
+ let chunks: Vec<&[usize]> = selected.chunks(TRIAGE_CHUNK_SIZE).collect();
+ let mut answers: Vec