Skip to content

Commit 6c2c9f9

Browse files
committed
Make unresolvable-revspec diff tests hermetic
1 parent 7bd093c commit 6c2c9f9

30 files changed

Lines changed: 1510 additions & 107 deletions

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ checkpoint.json
1010
file_hashes.json
1111
.cortexkit
1212
todo.md
13+
scripts/coverage-baseline.json

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [1.2.0] - 2026-12-02
11+
1012
### Added
1113
- Taint-mode semgrep presets for JavaScript (`presets/javascript.toml`) and Go (`presets/go.toml`), with taint-source/sink rules for SQLi, command injection, and path traversal
1214
- Taint-mode rules added to existing PHP and Python presets
1315
- `max_target_bytes` config field under `[scanner.semgrep]` to cap file size passed to semgrep via `--max-target-bytes`
1416
- Incremental scanning: `[scanner] incremental_scan = true` (requires `prior_runs.enabled = true`) skips LLM analysis for files unchanged since the last completed run and carries their previous findings forward; the changed/unchanged decision hashes every file, comparison uses one predicate for both the restriction and the carry, and `<output>/file-hashes.json` is written only after a scan completes fully
1517
- Graduated verification gate: individual check results (reachability, controllability, preconditions, context, impact) are recorded separately instead of a single binary kill
18+
- LLM circuit breaker: a model that fails 3 times consecutively is demoted to the end of the failover order for the rest of the run instead of stalling every call until timeout
19+
- `suppressions_file` under `[scanner]`: persistent TOML suppressions that filter recurring findings before severity counting, reporting, and evidence tiers
1620

1721
### Changed
1822
- Default `project.languages` in `config.example.toml` expanded from `["c", "python"]` to include `go`, `javascript`, `php`
1923
- Semgrep runner no longer aborts the entire scan on a non-zero exit code; partial JSON findings from stdout are preserved
2024
- Verification gate downgrades to `NeedsReview` instead of `FalsePositive` when a single check fails, preserving incremental evidence
25+
- Default runtime LLM temperature reduced from 0.5 to 0.0 so repeated scans on the same input produce identical findings
26+
- Agent verifications that reach the turn limit are marked `NeedsReview` instead of being counted as supported findings
27+
- Hunt prompt domains are derived from the `prompts/hunt/` directory (one domain per `.md` file stem); adding a prompt module no longer requires a code change
2128

2229
### Removed
2330
- Experimental pipeline tier: the `CpgSlice`, `RuleSynthesis`, `SecurityAgentVerification`, `ThreatModeling`, `AutoPatching`, `PocCompiler`, `ExploitSynth`, and `VariantSearch` phases, along with the `[scanner] profile` option and their configuration and LLM-phase slots. The pipeline is now a fixed 15-phase core (3 parallel + 12 sequential); `Validate` is a core phase.
2431

2532
### Fixed
2633
- Finding ID collisions: `generate_id` now includes `rule_id` and a snippet discriminator byte in the hash, preventing distinct vulnerabilities on the same file/line/CWE from sharing an ID
2734
- `generate_id` distinguishes `None` from `Some("")` snippets via a discriminator byte
35+
- Resumed scans produce the same outputs as fresh scans (markdown report, evidence tiers, suppression filtering) instead of only `findings.json`
36+
- Hunt prompt loader no longer silently drops on-disk modules (`memory_safety` and `authz_absence` existed but were never loaded)
37+
- Diff tests no longer resolve the external `v1.0.0` tag; they generate hermetic temporary rev-specs
2838

2939
## [1.1.0] - 2026-09-15
3040

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "baco"
3-
version = "1.1.0"
3+
version = "1.2.0"
44
edition = "2024"
55
homepage = "https://github.com/CodeAtCode/baco-scanner"
66
documentation = "https://github.com/CodeAtCode/baco-scanner/tree/master/docs"

‎config.example.toml‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ exclude_paths = ["tests/", "docs/", "target/"]
4141
# written only after a scan completes fully, so an interrupted scan never
4242
# marks files as already analyzed.
4343
incremental_scan = false
44+
# Optional path to a TOML file containing suppression entries.
45+
# When set, findings matching the suppression criteria are filtered
46+
# out before reporting. The file format uses [[suppression]] arrays:
47+
#
48+
# [[suppression]]
49+
# file_path = "src/lib_json/json_value.cpp"
50+
# cwe_id = "CWE-120"
51+
# line = 128
52+
# reason = "destination size clamped by preceding malloc"
53+
#
54+
# Matching rules:
55+
# - file_path: suffix match (finding path must end with this value)
56+
# - cwe_id: prefix match (finding CWE must start with this value)
57+
# - line: optional; ±5 line tolerance when set
58+
# - reason: required; shown in suppression logs
59+
# suppressions_file = "suppressions.toml"
4460

4561
[scanner.semgrep]
4662
# Rulesets can be a single string or an array of strings
@@ -118,8 +134,8 @@ retry_backoff_ms = 2000
118134
# Maximum concurrent LLM requests (default: 4)
119135
max_concurrent = 4
120136
# LLM temperature for response randomness (0.0 = deterministic, 1.0 = creative)
121-
# Default: 0.5 for security scanner determinism
122-
temperature = 0.5
137+
# Runtime default is 0.0; set an explicit value only when you want sampling variance
138+
temperature = 0.0
123139
# Enable LLM response caching to avoid redundant API calls
124140
enable_llm_cache = false
125141
# P2.1: Truncated generation — caps reasoning tokens before forcing final answer

‎docs/configuration.md‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,35 @@ enable_cve_bootstrap = true
130130
enable_hunt_prompts = true
131131
```
132132

133+
#### Suppressions File
134+
135+
An optional TOML file that filters out known false positives before reporting:
136+
137+
```toml
138+
# suppressions.toml
139+
[[suppression]]
140+
file_path = "src/lib_json/json_value.cpp"
141+
cwe_id = "CWE-120"
142+
line = 128
143+
reason = "destination size clamped by preceding malloc"
144+
```
145+
146+
Enable it in `[scanner]`:
147+
148+
```toml
149+
[scanner]
150+
# ...
151+
suppressions_file = "suppressions.toml"
152+
```
153+
154+
**Matching rules:**
155+
- `file_path`: suffix match (finding path must end with this value)
156+
- `cwe_id`: prefix match (finding CWE must start with this value)
157+
- `line`: optional; when set, finding line must be within ±5 lines
158+
- `reason`: required; shown in suppression logs
159+
160+
A finding with `line_number = None` never matches a line-constrained entry.
161+
133162
| Flag | Default | Side effects |
134163
| --- | --- | --- |
135164
| `early_termination_threshold` | `1000.0` | None |
@@ -207,7 +236,7 @@ enabled = false
207236

208237
BACO supports single or multiple models per phase. When multiple models are configured, they are used in round-robin fashion to distribute load across different models/providers.
209238

210-
**Default temperature:** `0.5` (controlled randomness for better security analysis)
239+
**Default temperature:** `0.0` (deterministic — repeated scans of an unchanged tree produce comparable findings; set an explicit value when you want sampling variance)
211240

212241
**Default max_reasoning_tokens:** unset (`None` — no cap unless configured)
213242

@@ -220,7 +249,7 @@ timeout_secs = 60
220249
max_retries = 3
221250
retry_backoff_ms = 1000
222251
max_concurrent = 4
223-
temperature = 0.5
252+
temperature = 0.0
224253
enable_llm_cache = false
225254
cache_dir = null
226255
```
@@ -258,15 +287,15 @@ Timeout configuration operates at two levels:
258287
- Max retries: Configured via `[llm] max_retries` (default: 3)
259288
- Source: `src/llm/mod.rs:254-269`
260289

261-
Retries are bounded; after exhausting retries on one model, the client fails over to the next configured model (if multiple models are specified).
290+
Retries are bounded; after exhausting retries on one model, the client fails over to the next configured model (if multiple models are specified). Within a single scan, a model that is exhausted consecutively `BREAKER_THRESHOLD` (3) times is skipped by the circuit breaker for the rest of the run instead of being retried first on every request.
262291

263292
**Single model:**
264293
```toml
265294
[llm.phases.discovery]
266295
base_url = "https://api.mistral.ai/v1"
267296
api_key = "${MISTRAL_API_KEY}" # or set env var
268297
model = "mistral-small"
269-
temperature = 0.5
298+
temperature = 0.0
270299
max_reasoning_tokens = 2048
271300
```
272301

‎src/agent/session.rs‎

Lines changed: 39 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -400,12 +400,17 @@ impl AgentSession {
400400
let mut test_source_path = None;
401401
let mut compile_path = None;
402402
let mut tools_used = Vec::new();
403+
let mut incomplete_reason: Option<String> = None;
403404

404405
loop {
405406
turn += 1;
406407
if turn > self.max_turns {
407408
turn -= 1;
408409
tracing::warn!("Max turns ({}) during verification", self.max_turns);
410+
incomplete_reason = Some(format!(
411+
"max turns ({}) reached without a final verdict",
412+
self.max_turns
413+
));
409414
break;
410415
}
411416

@@ -454,23 +459,17 @@ impl AgentSession {
454459
Err(e) => {
455460
test_log = format!("Error: {}", e);
456461
tracing::error!("LLM verification error turn {}: {}", turn, e);
462+
incomplete_reason = Some(format!("verification aborted by LLM error: {}", e));
457463
break;
458464
}
459465
}
460466
}
461467

462468
let verdict = parse_agent_verdict(&test_log);
463-
let confirmed = verdict.compiled && verdict.test_passed;
464469
let mut verified_finding = finding.clone();
465-
verified_finding.verification_status = Some(if confirmed {
466-
crate::findings::VerificationStatus::Confirmed
467-
} else {
468-
crate::findings::VerificationStatus::NeedsReview
469-
});
470-
verified_finding.verification_notes = Some(format!(
471-
"compiled={}, test_passed={}\n\n{}",
472-
verdict.compiled, verdict.test_passed, verdict.log
473-
));
470+
let (status, notes) = resolve_verification_outcome(incomplete_reason.as_deref(), &verdict);
471+
verified_finding.verification_status = status;
472+
verified_finding.verification_notes = Some(notes);
474473

475474
Ok(AgentFinding {
476475
finding: verified_finding,
@@ -494,6 +493,36 @@ pub struct AgentVerdict {
494493
pub log: String,
495494
}
496495

496+
/// Outcome of an agent verification run: the status to record and the notes to keep.
497+
///
498+
/// `incomplete_reason` is `Some` when the loop ended without a final verdict — max
499+
/// turns reached, or an LLM error mid-run. A partial run is not evidence: verdict
500+
/// flags parsed from a truncated log say nothing about the finding, so the status
501+
/// is always NeedsReview and the notes lead with the reason.
502+
pub fn resolve_verification_outcome(
503+
incomplete_reason: Option<&str>,
504+
verdict: &AgentVerdict,
505+
) -> (Option<crate::findings::VerificationStatus>, String) {
506+
if let Some(reason) = incomplete_reason {
507+
return (
508+
Some(crate::findings::VerificationStatus::NeedsReview),
509+
format!("verification incomplete: {}\n\n{}", reason, verdict.log),
510+
);
511+
}
512+
let status = if verdict.compiled && verdict.test_passed {
513+
crate::findings::VerificationStatus::Confirmed
514+
} else {
515+
crate::findings::VerificationStatus::NeedsReview
516+
};
517+
(
518+
Some(status),
519+
format!(
520+
"compiled={}, test_passed={}\n\n{}",
521+
verdict.compiled, verdict.test_passed, verdict.log
522+
),
523+
)
524+
}
525+
497526
/// Models emit either the documented key=value protocol (`compiled=true`) or a
498527
/// JSON envelope (`compiled`/`test_passed`/`log` fields); accept both.
499528
pub fn parse_agent_verdict(content: &str) -> AgentVerdict {

‎src/cli/scan.rs‎

Lines changed: 57 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ pub async fn run_resume(
218218

219219
let output_dir = PathBuf::from(&config.output.dir);
220220
std::fs::create_dir_all(&output_dir)?;
221+
let config_ref = config.clone();
221222

222223
// Create scanner with existing findings from checkpoint
223224
let target_path = PathBuf::from(&checkpoint.project_path);
@@ -232,15 +233,6 @@ pub async fn run_resume(
232233

233234
let findings = scanner.run().await?;
234235

235-
// Calculate summary
236-
let mut severity_counts = std::collections::HashMap::new();
237-
for finding in &findings {
238-
*severity_counts
239-
.entry(finding.severity.to_string())
240-
.or_insert(0) += 1;
241-
}
242-
let new_findings_count = findings.len().saturating_sub(prev_findings_count);
243-
244236
// The scanner persists its own progress during run(), so the checkpoint on
245237
// disk is ahead of the one loaded before the run. Reload it, or the phase
246238
// state this run advanced is lost and the next resume redoes the tail.
@@ -258,43 +250,42 @@ pub async fn run_resume(
258250
if !quiet {
259251
tracing::info!("✅ Resume completed!");
260252
tracing::info!("══════════════════════════════════════");
261-
}
262-
263-
if new_findings_count > 0 && !quiet {
264-
tracing::info!(
265-
"🎉 Found {} new finding{}",
266-
new_findings_count,
267-
if new_findings_count > 1 { "s" } else { "" }
268-
);
269-
}
270-
tracing::info!("📊 Total findings: {}", findings.len());
271-
272-
if !severity_counts.is_empty() && !quiet {
273-
let mut sorted: Vec<_> = severity_counts.iter().collect();
274-
sorted.sort_by(|a, b| b.1.cmp(a.1));
275-
let mut parts = Vec::new();
276-
for (severity, count) in sorted {
277-
parts.push(format!("{}: {}", severity, count));
253+
let new_findings_count = findings.len().saturating_sub(prev_findings_count);
254+
if new_findings_count > 0 {
255+
tracing::info!(
256+
"🎉 Found {} new finding{}",
257+
new_findings_count,
258+
if new_findings_count > 1 { "s" } else { "" }
259+
);
278260
}
279-
tracing::warn!("⚠️ Severity breakdown: {}", parts.join(", "));
280261
}
281262

282-
if !quiet {
283-
tracing::info!("══════════════════════════════════════\n");
284-
}
285-
286-
// Save findings to output directory
287-
let findings_path = output_dir.join("findings.json");
288-
let json = serde_json::to_string_pretty(&findings)?;
289-
std::fs::write(&findings_path, json)?;
290-
291-
if !quiet {
292-
tracing::info!("💾 Findings saved to {}", findings_path.display());
293-
}
263+
// Same summary path as a fresh scan: suppressions, evidence tiers,
264+
// findings.json and findings.md all come from print_scan_summary.
265+
finalize_scan_output(&findings, &config_ref, &output_dir, quiet)?;
294266

295267
Ok(())
296268
}
297269

270+
/// Shared output tail for the CLI scan flows: routes findings through
271+
/// print_scan_summary with the real config so suppression, evidence gating and
272+
/// the report writers apply identically to fresh and resumed scans.
273+
pub fn finalize_scan_output(
274+
findings: &[crate::findings::VulnerabilityFinding],
275+
config: &crate::config::ScannerConfig,
276+
output_dir: &Path,
277+
quiet: bool,
278+
) -> Result<(), Box<dyn std::error::Error>> {
279+
print_scan_summary(
280+
findings,
281+
output_dir,
282+
&config.project.name,
283+
config.output.evidence_gate,
284+
Some(config),
285+
quiet,
286+
)
287+
}
288+
298289
pub fn format_phase(phase: &crate::checkpoint::ScanPhase) -> String {
299290
// Delegate to PhaseGraph for data-driven display names
300291
// This keeps phase numbering in sync with PhaseGraph (single source of truth)
@@ -312,12 +303,36 @@ pub fn print_scan_summary(
312303
quiet: bool,
313304
) -> Result<(), Box<dyn std::error::Error>> {
314305
let ui = crate::ui::Ui::new(quiet);
306+
307+
// Apply suppressions if configured
308+
let findings = if let Some(cfg) = config {
309+
if let Some(ref suppressions_path) = cfg.scanner.suppressions_file {
310+
let path = std::path::Path::new(suppressions_path);
311+
let entries = crate::scanner::suppressions::load(path).map_err(|e| {
312+
tracing::error!("Failed to load suppressions file: {}", e);
313+
e
314+
})?;
315+
let (filtered, suppressed_count) =
316+
crate::scanner::suppressions::apply(findings.to_vec(), &entries);
317+
tracing::info!(
318+
"{} finding(s) suppressed by {}",
319+
suppressed_count,
320+
suppressions_path
321+
);
322+
filtered
323+
} else {
324+
findings.to_vec()
325+
}
326+
} else {
327+
findings.to_vec()
328+
};
329+
315330
ui.line("═══════════════════════════════════════");
316331
ui.line(format!("Scan complete: {} findings", findings.len()));
317332

318333
// Count by severity
319334
let mut severity_counts = std::collections::HashMap::new();
320-
for finding in findings {
335+
for finding in &findings {
321336
*severity_counts
322337
.entry(finding.severity.to_string())
323338
.or_insert(0) += 1;
@@ -333,7 +348,7 @@ pub fn print_scan_summary(
333348
// Evidence tier summary when gating is active
334349
if evidence_gate_enabled {
335350
let mut tier_counts = (0, 0, 0); // (verified, supported, unverified)
336-
for finding in findings {
351+
for finding in &findings {
337352
let tier =
338353
crate::evidence::classify_finding(&finding.evidence, finding.confidence_score);
339354
match tier {
@@ -362,7 +377,7 @@ pub fn print_scan_summary(
362377

363378
// findings.md: gated findings when gate is on (use real config, not None)
364379
let findings_md = if evidence_gate_enabled {
365-
crate::report::apply_evidence_gate(findings, config)
380+
crate::report::apply_evidence_gate(&findings, config)
366381
} else {
367382
findings.to_vec()
368383
};

0 commit comments

Comments
 (0)