keyhog 0.5.43

keyhog detects leaked credentials in source trees, git history, archives, and remote sources
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Main scan run loop: hardening, sources, baseline, reporting, exit codes.

use super::allowlist::{load_allowlist, load_rule_suppressor};
use super::reporting::{
    dump_dogfood_trace, report_completion_summary, report_skip_summary, TickerGuard,
};
use super::ScanOrchestrator;
use crate::baseline::Baseline;
use crate::exit_codes::{
    EXIT_FINDINGS, EXIT_LIVE_CREDENTIALS, EXIT_REQUIRE_GPU_UNMET, EXIT_SCANNER_PANIC,
    EXIT_SOURCE_FAILED, EXIT_SUCCESS, EXIT_SYSTEM_ERROR,
};
use crate::style;
use anyhow::Result;
use keyhog_core::{VerificationResult, VerifiedFinding};
use std::io::IsTerminal;
use std::time::Instant;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct ScanOutcome {
    pub(super) autoroute_calibration: bool,
    pub(super) scanner_panicked: bool,
    pub(super) has_live_credentials: bool,
    pub(super) has_new_entries: bool,
    pub(super) incremental_cache_failed: bool,
    pub(super) source_coverage_incomplete: bool,
}

/// Resolve scan terminal state with reliability failures ahead of findings.
///
/// Autoroute calibration is a measurement command and returns success once its
/// routing evidence was persisted, except that a scanner panic still makes the
/// measurement untrustworthy. For ordinary scans, a panic outranks live or
/// unverified findings, then finding states outrank cache and coverage errors
/// because the caller already has actionable credential evidence to preserve.
pub(super) fn resolve_scan_exit(outcome: ScanOutcome) -> u8 {
    if outcome.autoroute_calibration && !outcome.scanner_panicked {
        EXIT_SUCCESS
    } else if outcome.scanner_panicked {
        EXIT_SCANNER_PANIC
    } else if outcome.has_live_credentials {
        EXIT_LIVE_CREDENTIALS
    } else if outcome.has_new_entries {
        EXIT_FINDINGS
    } else if outcome.incremental_cache_failed {
        EXIT_SYSTEM_ERROR
    } else if outcome.source_coverage_incomplete {
        EXIT_SOURCE_FAILED
    } else {
        EXIT_SUCCESS
    }
}

impl ScanOrchestrator {
    pub async fn run(mut self) -> Result<std::process::ExitCode> {
        crate::reset_scan_runtime_state();
        let start = Instant::now();
        let wall_start = chrono::Utc::now();
        let stderr_is_tty = std::io::stderr().is_terminal();
        // `--no-color` forces plain output everywhere in the scan path; it
        // rides the same `NO_COLOR` convention the palette helpers already read
        // so a single env set covers the report formatter, the ticker, and the
        // diagnostic palette without threading a flag through every call.
        if self.args.no_color {
            std::env::set_var("NO_COLOR", "1");
        }
        let no_color = self.args.no_color || crate::style::no_color_requested();
        // Fold the `NO_COLOR` env convention into the flag so the stdout report
        // formatter (which honors `args.no_color`) also drops color on a TTY
        // when the operator set `NO_COLOR`, matching the ticker/palette.
        self.args.no_color = no_color;
        // `--quiet` suppresses the interactive chrome (banner / ticker /
        // completion summary) while leaving coverage FAIL/WARN and fatal errors
        // intact, so a quiet scan is never mistaken for a clean one.
        let show_progress = !self.args.quiet && (self.args.progress || stderr_is_tty);
        let progress_ansi = stderr_is_tty && !no_color;

        if self.args.dogfood {
            keyhog_scanner::telemetry::enable_dogfood();
        }

        let hardening = keyhog_core::apply_protections(false);
        if !hardening.failures.is_empty() {
            tracing::warn!(
                failures = ?hardening.failures,
                "default hardening protections did not fully apply"
            );
        }

        if self.args.lockdown {
            #[cfg(feature = "verify")]
            if self.effective_config.report.verify {
                anyhow::bail!(
                    "lockdown mode forbids --verify (would send credentials \
                     to outbound HTTPS endpoints). Drop --verify or drop --lockdown."
                );
            }

            if self.effective_config.report.show_secrets {
                anyhow::bail!(
                    "lockdown mode forbids --show-secrets (would print plaintext credentials \
                     to stdout/stderr). Drop --show-secrets or drop --lockdown."
                );
            }

            let lockdown = keyhog_core::apply_protections_with_persistence_paths(
                true,
                self.lockdown_persistence_cache_paths(),
            );
            if !lockdown.failures.is_empty() {
                anyhow::bail!(
                    "lockdown mode requested but protections failed to apply: {:?}",
                    lockdown.failures
                );
            }
            tracing::info!(
                mlocked = lockdown.mlocked,
                "lockdown mode active: mlocked + coredump-blocked + cache-free"
            );
            let palette = style::for_stderr();
            eprintln!(
                "{} LOCKDOWN MODE: no findings cache on disk, mlocked, no live verifier",
                style::info("INFO", &palette)
            );

            if self.args.no_default_excludes {
                anyhow::bail!(
                    "lockdown mode forbids --no-default-excludes (would scan untrusted \
                     lock files / minified bundles / vendor dirs that are common \
                     credential-leak vectors)."
                );
            }
            if self.args.no_unicode_norm {
                anyhow::bail!(
                    "lockdown mode forbids --no-unicode-norm (would let homoglyph \
                     attackers hide secrets behind visually identical Unicode)."
                );
            }
            if self.args.no_decode {
                anyhow::bail!(
                    "lockdown mode forbids --no-decode (encoded secrets like \
                     base64('AKIA…') would slip through entirely)."
                );
            }
            if self.args.no_entropy {
                anyhow::bail!(
                    "lockdown mode forbids --no-entropy (entropy detection is the \
                     only catch for novel / unknown high-entropy secrets)."
                );
            }
            if self.args.no_ml {
                anyhow::bail!(
                    "lockdown mode forbids --no-ml (ML confidence gating reduces \
                     false-negative rate on hand-crafted near-misses)."
                );
            }
            if self.args.fast {
                anyhow::bail!(
                    "lockdown mode forbids --fast (it disables decode + entropy + ML \
                     simultaneously, the largest detection blind spot we ship)."
                );
            }
        }

        let hw = keyhog_scanner::hw_probe::probe_hardware();
        let scanner_status = self.scanner.runtime_status();
        let backend_policy = if self.effective_config.autoroute_calibration {
            "calibrate"
        } else if let Some(backend) = self.effective_config.backend_override {
            backend.label()
        } else {
            "auto:persisted-per-workload"
        };
        tracing::info!(
            backend_policy,
            gpu_available = hw.gpu_available,
            gpu_software = hw.gpu_is_software,
            hyperscan = hw.hyperscan_available,
            avx512 = hw.has_avx512,
            avx2 = hw.has_avx2,
            neon = hw.has_neon,
            "scan backend policy configured"
        );
        if show_progress {
            if let Err(error) =
                crate::write_banner(&mut std::io::stderr(), progress_ansi, self.detectors.len())
            {
                tracing::debug!(%error, "banner write error");
            }
            let gpu_candidates = self.scanner.gpu_backend_candidates();
            let gpu_label = gpu_candidates
                .iter()
                .filter(|candidate| candidate.is_eligible())
                .map(|candidate| candidate.backend.label())
                .collect::<Vec<_>>()
                .join(",");
            let gpu_label = if gpu_label.is_empty() {
                "none"
            } else {
                gpu_label.as_str()
            };
            eprintln!(
                "{} | backend={backend_policy} | gpu={gpu_label}",
                keyhog_scanner::hw_probe::startup_banner(
                    hw,
                    self.detectors.len(),
                    scanner_status.pattern_count,
                )
            );
            for candidate in gpu_candidates
                .iter()
                .filter(|candidate| !candidate.is_eligible())
            {
                if let Some(error) = candidate.acquisition_error.as_deref() {
                    eprintln!(
                        "gpu candidate unavailable | backend={} | error={error}",
                        candidate.backend.label()
                    );
                } else if candidate.available {
                    eprintln!(
                        "gpu candidate ineligible | backend={} | software={} | complete_identity={}",
                        candidate.backend.label(),
                        candidate.is_software,
                        candidate.has_complete_identity(),
                    );
                }
            }
        }

        // Require-GPU preflight, independent of backend routing. When
        // `--require-gpu` is resolved and no usable GPU adapter is present (or
        // the GPU self-test fails), fail closed with the dedicated scan exit
        // code BEFORE warming a backend or scanning a byte. Routing the failure
        // through the CLI ExitCode here - rather than a scanner-lib
        // process::exit - keeps the exit contract in the CLI layer.
        if let Err(diagnostic) = keyhog_scanner::gpu::require_gpu_preflight() {
            eprintln!("keyhog: {diagnostic}");
            return Ok(std::process::ExitCode::from(EXIT_REQUIRE_GPU_UNMET));
        }

        let calibration_mode = self.effective_config.autoroute_calibration;
        if calibration_mode {
            // LAW10: calibration prewarm skip is perf-only and recall-safe
            // because calibration measures all eligible backends directly.
            tracing::debug!(
                target: "keyhog::routing",
                "backend prewarm skipped during autoroute calibration"
            );
        } else if let Some(preferred) = self.effective_config.backend_override {
            // An automatic route is keyed by the real workload bucket and must
            // come from persisted fastest-correct evidence. At this point no
            // chunks have been collected, so a zero-byte heuristic cannot know
            // which calibrated backend the dispatcher will select. Prewarm only
            // explicit diagnostic overrides; automatic backends initialize when
            // the cache-backed router resolves the first real batch.
            let warm_started = Instant::now();
            let warmed = self.scanner.warm_backend(preferred);
            let warm_ms = warm_started.elapsed().as_millis();
            tracing::debug!(
                target: "keyhog::routing",
                backend = preferred.label(),
                warmed,
                elapsed_ms = warm_ms as u64,
                "backend warmed"
            );
        } else {
            tracing::debug!(
                target: "keyhog::routing",
                "automatic backend prewarm awaits the persisted workload decision"
            );
        }

        if self.args.benchmark {
            // Name the GPU that produced the GPU row so the operator can tell
            // which adapter the throughput figures came from.
            eprintln!("benchmark | gpu={}", crate::benchmark::format_gpu_summary());
            let results = crate::benchmark::run_benchmark(&self)?;
            let baseline_mb = results
                .iter()
                .map(|r| r.mb_per_sec)
                .fold(f64::INFINITY, f64::min)
                .max(f64::EPSILON);
            for result in &results {
                let speedup = result.mb_per_sec / baseline_mb;
                eprintln!(
                    "benchmark | backend={:<14} | throughput={:>8.2} MiB/s | speedup={:>5.2}× | findings={:>4} | bytes={}",
                    result.backend.label(),
                    result.mb_per_sec,
                    speedup,
                    result.findings,
                    result.bytes_scanned
                );
            }
            if let Some(fastest) = results
                .iter()
                .max_by(|a, b| a.mb_per_sec.total_cmp(&b.mb_per_sec))
            {
                eprintln!(
                    "benchmark winner: {} at {:.2} MiB/s",
                    fastest.backend.label(),
                    fastest.mb_per_sec
                );
            }
            return Ok(std::process::ExitCode::SUCCESS);
        }

        let allowlist =
            load_allowlist(self.args.path.as_deref(), &self.effective_config.allowlist)?;
        let incremental_cache_path = self.incremental_cache_path()?;
        let merkle = self.build_merkle_index(incremental_cache_path.as_deref());

        let sources = crate::sources::build_sources(
            &self.args,
            &self.effective_config,
            allowlist.ignored_paths.as_ref().to_vec(),
            merkle.clone(),
        )?;
        if sources.is_empty() {
            anyhow::bail!(
                "no input source specified. Use --path, --stdin, --git, --git-diff, --git-history, --github-org, --gitlab-group, --bitbucket-workspace, --s3-bucket, --gcs-bucket, --azure-container-url, or --docker-image"
            );
        }

        let all_matches =
            self.scan_sources(sources, show_progress, merkle, incremental_cache_path)?;
        let filtered = self.filter_and_resolve(all_matches, &allowlist)?;
        let findings_pre_rules = self.finalize(filtered).await?;

        let rule_suppressor = load_rule_suppressor(self.args.path.as_deref())?;
        let pre_rule_count = findings_pre_rules.len();
        let hide_client_safe = self.effective_config.report.hide_client_safe;
        let mut client_safe_dropped = 0usize;
        let findings: Vec<VerifiedFinding> = findings_pre_rules
            .into_iter()
            .filter(|f| {
                if rule_suppressor.matches(f) {
                    return false;
                }
                if hide_client_safe && f.severity == keyhog_core::Severity::ClientSafe {
                    client_safe_dropped += 1;
                    return false;
                }
                true
            })
            .collect();

        // KH-GAP-096: if a requested source failed ENTIRELY, produced zero
        // chunks AND errored (e.g. --git-history / --git-diff on a non-repo or
        // bad ref, --github-org with a bad token, an unreachable --url), and
        // there are no findings, the requested scan never ran. Do NOT fall
        // through to "no findings, all clean" + exit 0: a CI gate would read
        // that as a clean tree when nothing was scanned. Fail closed with a
        // diagnostic. A partial failure (some files unreadable in a tree that
        // still produced chunks) does NOT trip this, that source produced
        // data, so FAILED_SOURCES stays 0, nor does a failed source that runs
        // alongside another source which DID surface findings (exit 1 wins).
        if findings.is_empty()
            && crate::FAILED_SOURCES.load(std::sync::atomic::Ordering::Relaxed) > 0
        {
            eprintln!(
                "error: a requested scan source failed to read and produced no data (see the \
                 warnings above). Not reporting \"clean\": that scan did not run. Check the \
                 repository path, ref, token, or URL and re-run."
            );
            return Ok(std::process::ExitCode::from(EXIT_SOURCE_FAILED));
        }

        if show_progress {
            let dropped = pre_rule_count - findings.len() - client_safe_dropped;
            if dropped > 0 {
                eprintln!(
                    "\n  Suppressed {} finding(s) via .keyhogignore.toml",
                    dropped
                );
            }
        }
        if show_progress && client_safe_dropped > 0 {
            eprintln!(
                "\n  Suppressed {} client-safe finding(s) via --hide-client-safe (public-by-design keys)",
                client_safe_dropped
            );
        }

        // Reliability outcomes gate baseline mutation (KH-504 / KH-1352).
        // Panic, incremental-cache failure, or FAIL-class coverage gaps must
        // not mint a "successful" baseline. Deliberate WARN skips (binary,
        // over-max-size) do not poison baseline writes.
        let scanner_panicked = crate::SCANNER_PANICKED.load(std::sync::atomic::Ordering::Relaxed);
        let incremental_cache_failed =
            crate::INCREMENTAL_CACHE_ERRORS.load(std::sync::atomic::Ordering::Relaxed) > 0;
        let source_coverage_incomplete = source_coverage_incomplete();
        let baseline_coverage_failed = baseline_coverage_untrustworthy();
        let baseline_untrustworthy =
            scanner_panicked || incremental_cache_failed || baseline_coverage_failed;

        if let Some(ref path) = self.args.create_baseline {
            if baseline_untrustworthy {
                let exit = resolve_scan_exit(ScanOutcome {
                    autoroute_calibration: false,
                    scanner_panicked,
                    has_live_credentials: false,
                    has_new_entries: false,
                    incremental_cache_failed,
                    source_coverage_incomplete: baseline_coverage_failed,
                });
                eprintln!(
                    "error: refusing --create-baseline: scan is untrustworthy \
                     (panic={}, coverage_failed={}, incremental_cache_failed={}). \
                     Prior baseline left unchanged.",
                    scanner_panicked, baseline_coverage_failed, incremental_cache_failed
                );
                for (reason, count) in crate::reporting::coverage_gap_summary(
                    &crate::reporting::CoverageCounts::current(),
                ) {
                    if count > 0 {
                        eprintln!("  coverage gap: {count} {reason}");
                    }
                }
                return Ok(std::process::ExitCode::from(exit));
            }
            let baseline = Baseline::from_findings(&findings);
            baseline.save(path)?;
            if show_progress {
                eprintln!(
                    "\n📝 Baseline created with {} entries at {}",
                    baseline.entries.len(),
                    path.display()
                );
            }
            // Snapshot still writes even with findings (exit 0), but Live must
            // not collapse to green: CI that combines --create-baseline --verify
            // needs exit 10 (KH-1439).
            let has_live = findings
                .iter()
                .any(|f| matches!(f.verification, VerificationResult::Live));
            if has_live {
                return Ok(std::process::ExitCode::from(EXIT_LIVE_CREDENTIALS));
            }
            return Ok(std::process::ExitCode::SUCCESS);
        }

        let (report_findings, has_new_entries) = if let Some(ref path) = self.args.update_baseline {
            if baseline_untrustworthy {
                let exit = resolve_scan_exit(ScanOutcome {
                    autoroute_calibration: false,
                    scanner_panicked,
                    has_live_credentials: false,
                    has_new_entries: false,
                    incremental_cache_failed,
                    source_coverage_incomplete: baseline_coverage_failed,
                });
                eprintln!(
                    "error: refusing --update-baseline: scan is untrustworthy \
                     (panic={}, coverage_failed={}, incremental_cache_failed={}). \
                     Prior baseline left byte-identical.",
                    scanner_panicked, baseline_coverage_failed, incremental_cache_failed
                );
                for (reason, count) in crate::reporting::coverage_gap_summary(
                    &crate::reporting::CoverageCounts::current(),
                ) {
                    if count > 0 {
                        eprintln!("  coverage gap: {count} {reason}");
                    }
                }
                return Ok(std::process::ExitCode::from(exit));
            }
            let mut baseline = if path.exists() {
                Baseline::load(path)?
            } else {
                Baseline::empty()
            };
            let new_findings = baseline.filter_new(&findings);
            let had_new = !new_findings.is_empty();
            baseline.merge(&findings);
            baseline.save(path)?;
            if show_progress {
                eprintln!(
                    "\n📝 Baseline updated: added {} new entries at {}",
                    new_findings.len(),
                    path.display()
                );
            }
            (new_findings, had_new)
        } else if let Some(ref path) = self.args.baseline {
            let baseline = Baseline::load(path)?;
            let filtered_findings = baseline.filter_new(&findings);
            let suppressed_count = findings.len() - filtered_findings.len();
            let has_new = !filtered_findings.is_empty();
            if show_progress && suppressed_count > 0 {
                eprintln!("\n  Suppressed {} baseline finding(s)", suppressed_count);
            }
            (filtered_findings, has_new)
        } else {
            let has_findings = !findings.is_empty();
            (findings, has_findings)
        };

        let has_live_credentials = scan_exit_code(&report_findings) == EXIT_LIVE_CREDENTIALS;

        // `--stream`: emit one redacted `[stream]` preview per REPORTED finding.
        // Wired to the resolved report stream (post filter_and_resolve /
        // suppression / --min-confidence / baseline) rather than the raw scanner
        // matches, so a streamed line always corresponds to a finding the report
        // and exit code agree on. (AUD-testing_dogfood-1: the old wiring streamed
        // raw matches the report later dropped, lying about the result.)
        if self.args.stream {
            super::reporting::stream_report_previews(&report_findings);
        }

        let report_finished_at = chrono::Utc::now();
        let report_metadata = crate::reporting::report_metadata_from_scan_run(
            &self.args,
            wall_start,
            report_finished_at,
            start.elapsed().as_millis(),
            crate::SCANNED_CHUNKS.load(std::sync::atomic::Ordering::Relaxed),
            crate::SCANNED_BYTES.load(std::sync::atomic::Ordering::Relaxed),
            self.detectors.len(),
            Some(crate::orchestrator_config::autoroute_config_digest(
                &self.effective_config,
            )),
        );
        let show_reporting_progress = show_progress
            && !self.args.stream
            && (self.args.output.is_some() || !std::io::stdout().is_terminal());
        let report_finding_count = report_findings.len();
        let reporting_progress = show_reporting_progress.then(|| {
            TickerGuard::spawn("reporting", move |done, started| {
                super::reporting::reporting_ticker(done, started, report_finding_count)
            })
        });
        let report_result = crate::reporting::report_findings_with_metadata(
            &report_findings,
            &self.args,
            &report_metadata,
        );
        if let Some(guard) = reporting_progress {
            guard.stop();
        }
        report_result?;

        let elapsed = start.elapsed().as_secs_f64();
        if show_progress {
            report_completion_summary(
                &report_findings,
                elapsed,
                progress_ansi,
                self.effective_config.backend_override,
            );
        } else {
            report_skip_summary(false);
        }
        dump_dogfood_trace();

        tracing::info!(
            "Done in {:.1}s. {} findings",
            elapsed,
            report_findings.len()
        );

        let exit = resolve_scan_exit(ScanOutcome {
            autoroute_calibration: self.args.autoroute_calibrate,
            scanner_panicked,
            has_live_credentials,
            has_new_entries,
            incremental_cache_failed,
            source_coverage_incomplete,
        });
        if exit == EXIT_SOURCE_FAILED {
            eprintln!(
                "error: input coverage was incomplete (see coverage warnings above). Not \
                 reporting \"clean\": some requested bytes were not scanned."
            );
        }
        Ok(std::process::ExitCode::from(exit))
    }
}

/// Pure exit-code mapping for the *reported* findings set: the single source of
/// truth for the "live credentials found" scan exit signal.
///
/// Returns [`EXIT_LIVE_CREDENTIALS`] (10) when ANY reported finding was
/// confirmed [`VerificationResult::Live`] by the verifier, else [`EXIT_SUCCESS`]
/// (0). Every other verification state: `Skipped` (the default when `--verify`
/// is off), `Dead`, `Revoked`, `RateLimited`, `Error(..)`, `Unverifiable`: is
/// NOT live and does not raise the code here (a dead/unverified finding is exit
/// 1, decided by the caller's findings branch). A single `Live` anywhere in the
/// set trips 10 even when it is mixed with non-live findings.
///
/// Keeping this a pure `&[VerifiedFinding] -> u8` function (rather than an
/// inline `.any(..)` in `run()`) makes the live-credential exit contract unit
/// testable without spawning a scan, and gives the code exactly one definitional
/// home.
pub(crate) fn scan_exit_code(findings: &[VerifiedFinding]) -> u8 {
    if findings
        .iter()
        .any(|f| matches!(f.verification, VerificationResult::Live))
    {
        EXIT_LIVE_CREDENTIALS
    } else {
        EXIT_SUCCESS
    }
}

/// Incomplete exit 13 and baseline refusal share the CoverageGapKind FAIL set
/// (KH-1347 / KH-1352). WARN skips (binary, over-max-size, deliberate exclude,
/// advisory scanner truncations) must not flip a clean scan to exit 13.
fn source_coverage_incomplete() -> bool {
    fail_class_coverage_gaps() > 0
}

fn baseline_coverage_untrustworthy() -> bool {
    fail_class_coverage_gaps() > 0
}

fn fail_class_coverage_gaps() -> usize {
    // Single owner: CoverageGapKind severity table via CoverageCounts (KH-1410).
    crate::reporting::CoverageCounts::current().fail_class_total()
}