keyhog 0.5.73

GPU-accelerated secret scanner for code, Git history, cloud, containers, browser assets, and live credential verification
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Pure tests for the structured (SARIF/HTML) coverage-gap summary.
//!
//! `coverage_gap_summary` is a pure function of a [`CoverageCounts`] snapshot,
//! so every category can be exercised directly here without touching the
//! process-global counters. The contract these lock: the structured surface
//! reports EVERY coverage-gap category (a category the human end-of-scan summary
//! can print but the structured report omits is a false-clean, Law 10). Two
//! categories previously drifted out of the structured path, unreadable
//! *binaries* and the structured decode-through oversize skip, and are
//! regression-locked below.

use super::{coverage_gap_summary, CoverageCounts, CoverageGapKind, CoverageSeverity};
use keyhog_sources::SkipCounts;

/// Look up the count reported for the first category whose reason contains
/// `needle`, or `None` if that category was filtered out (count zero).
fn count_for(summary: &[(String, usize)], needle: &str) -> Option<usize> {
    summary
        .iter()
        .find(|(reason, _)| reason.contains(needle))
        .map(|(_, count)| *count)
}

fn with_skip(skip: SkipCounts) -> CoverageCounts {
    CoverageCounts {
        skip,
        ..Default::default()
    }
}

// ── empty / filtering ────────────────────────────────────────────────────────

#[test]
fn empty_snapshot_yields_no_entries() {
    let summary = coverage_gap_summary(&CoverageCounts::default());
    assert!(
        summary.is_empty(),
        "a scan with zero coverage gaps must produce no notifications, got {summary:?}"
    );
}

#[test]
fn zero_count_categories_are_filtered_out() {
    let counts = with_skip(SkipCounts {
        over_max_size: 4,
        ..Default::default()
    });
    let summary = coverage_gap_summary(&counts);
    assert_eq!(
        summary.len(),
        1,
        "only the single non-zero category may appear, got {summary:?}"
    );
    assert_eq!(
        count_for(
            &summary,
            "exceeded a configured size cap (--max-file-size or the matching --limit-*-bytes)"
        ),
        Some(4)
    );
}

// ── source-walker categories ─────────────────────────────────────────────────

#[test]
fn over_max_size_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        over_max_size: 7,
        ..Default::default()
    }));
    assert_eq!(
        count_for(
            &s,
            "exceeded a configured size cap (--max-file-size or the matching --limit-*-bytes)"
        ),
        Some(7)
    );
}

#[test]
fn binary_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        binary: 3,
        ..Default::default()
    }));
    assert_eq!(
        count_for(&s, "binary (extension or content sniff)"),
        Some(3)
    );
}

#[test]
fn excluded_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        excluded: 9,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "exclusion policy"), Some(9));
}

#[test]
fn unreadable_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        unreadable: 5,
        ..Default::default()
    }));
    assert_eq!(
        count_for(&s, "unreadable (permission denied or I/O error)"),
        Some(5)
    );
}

#[test]
fn git_object_unreadable_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        git_object_unreadable: 2,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "Git object unreadable"), Some(2));
}

#[test]
fn archive_truncated_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        archive_truncated: 6,
        ..Default::default()
    }));
    assert_eq!(
        count_for(&s, "extraction truncated by an unpack budget"),
        Some(6)
    );
}

#[test]
fn binary_section_name_unresolved_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        binary_section_name_unresolved: 1,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "binary section name unresolved"), Some(1));
}

#[test]
fn source_truncated_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        source_truncated: 8,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "source scan truncated by aggregate"), Some(8));
}

#[test]
fn structured_source_parse_failures_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        structured_source_parse_failures: 4,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "structured source parse failed"), Some(4));
}

#[test]
fn archive_duplicate_scan_unavailable_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        archive_duplicate_scan_unavailable: 3,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "archive duplicate-entry detection"), Some(3));
}

#[test]
fn git_lfs_pointer_surfaces() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        git_lfs_pointer: 2,
        ..Default::default()
    }));
    assert_eq!(count_for(&s, "Git-LFS pointer"), Some(2));
}

// ── silent-clean categories ──────────────────────────────────────────────────
//
// These two families were the difference between "no secrets here" and "I did
// not look". Both are regression-locked from the reproduced defects.

/// A finding the scanner matched and then dropped for its path must surface a
/// count, not disappear. The whole defect was that `app.min.js` findings left
/// no trace anywhere.
#[test]
fn vendored_path_suppressions_surface_with_their_count() {
    let s = coverage_gap_summary(&CoverageCounts {
        vendored_path_suppressions: 3,
        ..Default::default()
    });
    assert_eq!(count_for(&s, "vendored/minified path policy"), Some(3));
}

/// The vendored-path drop is WARN: the bytes WERE covered, and the operator can
/// reverse the drop with a flag. A `node_modules` tree would otherwise force
/// exit 13 on every ordinary scan.
#[test]
fn vendored_path_suppression_is_warn_not_fail() {
    assert_eq!(
        CoverageGapKind::VendoredPathSuppressed.severity(),
        CoverageSeverity::Warn
    );
    assert_eq!(
        CoverageCounts {
            vendored_path_suppressions: 9,
            ..Default::default()
        }
        .fail_class_total(),
        0,
        "a recoverable precision drop must not flip a scan to the incomplete exit"
    );
}

/// Zero bytes read with no skip recorded: nothing was there to scan.
#[test]
fn nothing_scanned_no_input_surfaces_and_fails_closed() {
    let counts = CoverageCounts {
        nothing_scanned_no_input: true,
        ..Default::default()
    };
    let s = coverage_gap_summary(&counts);
    assert_eq!(count_for(&s, "no skip was counted"), Some(1));
    assert_eq!(
        CoverageGapKind::NothingScannedNoInput.severity(),
        CoverageSeverity::Fail
    );
    assert_eq!(
        counts.fail_class_total(),
        1,
        "a scan that examined nothing must reach the incomplete exit"
    );
}

/// Zero bytes read with skips recorded: policy hid everything. Different
/// operator problem, different remedy, so a different row.
#[test]
fn nothing_scanned_all_skipped_is_a_distinct_row() {
    let counts = CoverageCounts {
        nothing_scanned_all_skipped: true,
        ..Default::default()
    };
    let s = coverage_gap_summary(&counts);
    assert_eq!(count_for(&s, "every candidate was skipped"), Some(1));
    assert_eq!(
        count_for(&s, "no skip was counted"),
        None,
        "the two nothing-scanned causes must never be reported together"
    );
    assert_eq!(counts.fail_class_total(), 1);
}

/// The negative that keeps the fix from becoming a new false alarm: a scan that
/// read bytes and skipped some by policy stays WARN-only, so exit 0.
#[test]
fn excluded_files_alone_do_not_reach_the_incomplete_exit() {
    let counts = with_skip(SkipCounts {
        excluded: 18,
        ..Default::default()
    });
    assert_eq!(
        counts.fail_class_total(),
        0,
        "policy exclusions on a scan that read bytes must stay exit 0"
    );
    assert!(
        !counts.covered_nothing(),
        "a default snapshot has not proved the scan covered nothing"
    );
}

// ── source errors + scanner telemetry ────────────────────────────────────────

#[test]
fn source_errors_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        source_errors: 5,
        ..Default::default()
    });
    assert_eq!(count_for(&s, "source emitted error rows"), Some(5));
}

#[test]
fn scanner_structured_parse_failures_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_structured_parse_failures: 3,
        ..Default::default()
    });
    assert_eq!(count_for(&s, "scanner structured parse failed"), Some(3));
}

/// Regression: the structured decode-through oversize skip was surfaced by the
/// human summary but omitted from the structured (SARIF/HTML) report.
#[test]
fn scanner_structured_oversize_skip_surfaces() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_structured_oversize_skips: 4,
        ..Default::default()
    });
    assert_eq!(
        count_for(&s, "scanner structured decode-through skipped by size cap"),
        Some(4),
        "structured decode-through oversize skips must reach the structured report"
    );
}

#[test]
fn scanner_decode_truncations_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_decode_truncations: 6,
        ..Default::default()
    });
    assert_eq!(count_for(&s, "scanner decode-through truncated"), Some(6));
}

#[test]
fn scanner_invalid_pattern_index_skips_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_invalid_pattern_index_skips: 2,
        ..Default::default()
    });
    assert_eq!(
        count_for(
            &s,
            "scanner pattern expansion skipped by invalid pattern index"
        ),
        Some(2)
    );
}

#[test]
fn scanner_boundary_cardinality_mismatches_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_boundary_cardinality_mismatches: 1,
        ..Default::default()
    });
    assert_eq!(
        count_for(&s, "scanner boundary reassembly skipped"),
        Some(1)
    );
}

#[test]
fn scanner_line_offset_mismatches_surface() {
    let s = coverage_gap_summary(&CoverageCounts {
        scanner_line_offset_mismatches: 3,
        ..Default::default()
    });
    assert_eq!(
        count_for(
            &s,
            "scanner multiline attribution used fallback source offsets"
        ),
        Some(3)
    );
}

// ── binary-source categories (the drift bug) ─────────────────────────────────

#[test]
fn binary_degraded_surfaces() {
    let s = coverage_gap_summary(&CoverageCounts {
        binary_degraded: 2,
        ..Default::default()
    });
    assert_eq!(
        count_for(&s, "binary deep analysis degraded to strings-only"),
        Some(2)
    );
}

/// Regression: unreadable *binaries* were surfaced by the human summary but
/// omitted from the structured (SARIF/HTML) report (a structured false-clean).
#[test]
fn binary_unreadable_surfaces() {
    let s = coverage_gap_summary(&CoverageCounts {
        binary_unreadable: 4,
        skip: SkipCounts {
            unreadable: 4,
            ..Default::default()
        },
        ..Default::default()
    });
    assert_eq!(
        count_for(
            &s,
            "binary unreadable (permission denied or I/O error; binary NOT scanned)"
        ),
        Some(4),
        "unreadable binaries must reach the structured report, not just the human summary"
    );
}

// ── double-count guard ───────────────────────────────────────────────────────

#[test]
fn unreadable_count_excludes_unreadable_binaries() {
    // The `unreadable` file-walk counter includes binaries dropped as unreadable.
    // Since those are reported as their own `binary unreadable` category, the
    // generic `unreadable` line must subtract them so the same file is not
    // double-counted across two notifications.
    let s = coverage_gap_summary(&CoverageCounts {
        binary_unreadable: 2,
        skip: SkipCounts {
            unreadable: 5,
            ..Default::default()
        },
        ..Default::default()
    });
    assert_eq!(
        count_for(&s, "unreadable (permission denied or I/O error)"),
        Some(3),
        "generic unreadable must exclude the 2 unreadable binaries (5 - 2 = 3)"
    );
    assert_eq!(
        count_for(&s, "binary unreadable (permission denied"),
        Some(2)
    );
}

#[test]
fn all_unreadable_being_binaries_drops_the_generic_line() {
    // When every unreadable file is a binary, the generic unreadable count is 0
    // and its line is filtered out, but the binary category still reports them.
    let s = coverage_gap_summary(&CoverageCounts {
        binary_unreadable: 3,
        skip: SkipCounts {
            unreadable: 3,
            ..Default::default()
        },
        ..Default::default()
    });
    assert_eq!(
        count_for(&s, "unreadable (permission denied or I/O error)"),
        None,
        "no non-binary unreadable files remain, so the generic line must be filtered out"
    );
    assert_eq!(
        count_for(&s, "binary unreadable (permission denied"),
        Some(3)
    );
}

// ── structural contracts ─────────────────────────────────────────────────────

/// Set EVERY counter and assert the summary is well-formed: one entry per
/// category, all reasons unique and non-empty. This is the drift guard, if a
/// new counter is added without a distinct reason it trips here.
fn all_ones() -> CoverageCounts {
    CoverageCounts {
        skip: SkipCounts {
            over_max_size: 1,
            binary: 1,
            excluded: 1,
            unreadable: 2, // 2 so 1 remains after subtracting binary_unreadable
            git_object_unreadable: 1,
            archive_truncated: 1,
            binary_section_name_unresolved: 1,
            source_truncated: 1,
            structured_source_parse_failures: 1,
            archive_duplicate_scan_unavailable: 1,
            git_lfs_pointer: 1,
        },
        source_errors: 1,
        batches_not_routed: 1,
        scanner_structured_parse_failures: 1,
        scanner_structured_oversize_skips: 1,
        scanner_decode_truncations: 1,
        scanner_decode_oversize_skips: 1,
        scanner_invalid_pattern_index_skips: 1,
        scanner_boundary_cardinality_mismatches: 1,
        scanner_line_offset_mismatches: 1,
        scanner_chunk_deadline_aborts: 1,
        scanner_binary_strings_named_exclusions: 1,
        binary_degraded: 1,
        binary_unreadable: 1,
        vendored_path_suppressions: 1,
        // Production sets at most one of these (a scan either found no input
        // or skipped everything it found). Both are set here because this
        // fixture's job is to prove every kind has a distinct reason string.
        nothing_scanned_no_input: true,
        nothing_scanned_all_skipped: true,
    }
}

#[test]
fn every_category_surfaces_when_all_counters_are_nonzero() {
    let s = coverage_gap_summary(&all_ones());
    // 11 skip fields + source_errors + batches_not_routed + 9 scanner
    // telemetry + 2 binary + vendored-path suppression + 2 nothing-scanned = 27.
    assert_eq!(
        s.len(),
        27,
        "every one of the 27 coverage-gap categories must surface, got {} ({s:?})",
        s.len()
    );
}

#[test]
fn all_reasons_are_unique() {
    let s = coverage_gap_summary(&all_ones());
    let mut reasons: Vec<&str> = s.iter().map(|(r, _)| r.as_str()).collect();
    reasons.sort_unstable();
    let unique = {
        let mut u = reasons.clone();
        u.dedup();
        u.len()
    };
    assert_eq!(
        unique,
        reasons.len(),
        "two categories share a reason string (a drift/copy bug): {reasons:?}"
    );
}

#[test]
fn all_reasons_are_nonempty() {
    let s = coverage_gap_summary(&all_ones());
    assert!(
        s.iter().all(|(r, _)| !r.trim().is_empty()),
        "every coverage-gap reason must be a non-empty sentence"
    );
}

#[test]
fn surfaced_count_equals_input_count() {
    let s = coverage_gap_summary(&with_skip(SkipCounts {
        over_max_size: 42,
        ..Default::default()
    }));
    assert_eq!(
        count_for(
            &s,
            "exceeded a configured size cap (--max-file-size or the matching --limit-*-bytes)"
        ),
        Some(42),
        "the surfaced count must be the exact input count, not a boolean/clamp"
    );
}

// ── canonical CoverageGapKind contract (the human ⇄ SARIF unification) ─────────
//
// Both the human end-of-scan summary (`report_skip_summary`) and the SARIF
// report (`coverage_gap_summary`) iterate the SAME `CoverageGapKind::ALL`. These
// lock the single-source contract so the two surfaces can never drift apart, a
// gap on one surface but not the other is a Law-10 false-clean.

#[test]
fn all_has_twenty_seven_kinds() {
    assert_eq!(
        CoverageGapKind::ALL.len(),
        27,
        "the canonical coverage-gap set must have exactly 27 categories"
    );
}

#[test]
fn all_kinds_are_distinct() {
    let mut seen: Vec<CoverageGapKind> = Vec::new();
    for kind in CoverageGapKind::ALL {
        assert!(
            !seen.contains(&kind),
            "{kind:?} appears more than once in CoverageGapKind::ALL"
        );
        seen.push(kind);
    }
}

#[test]
fn every_kind_is_nonzero_on_all_ones() {
    let counts = all_ones();
    for kind in CoverageGapKind::ALL {
        assert!(
            kind.count(&counts) > 0,
            "{kind:?} has a zero count when every counter is set: its field is unwired"
        );
    }
}

#[test]
fn every_kind_is_zero_on_empty() {
    let counts = CoverageCounts::default();
    for kind in CoverageGapKind::ALL {
        assert_eq!(
            kind.count(&counts),
            0,
            "{kind:?} must be zero for an all-zero snapshot"
        );
    }
}

#[test]
fn fail_severity_set_is_exact() {
    use CoverageGapKind::*;
    for kind in [
        ScannerStructuredParseFailure,
        SourceError,
        NonBinaryUnreadable,
        GitObjectUnreadable,
        ArchiveTruncated,
        BinarySectionNameUnresolved,
        SourceTruncated,
        StructuredSourceParseFailure,
        ArchiveDuplicateScanUnavailable,
        GitLfsPointer,
        BinaryDegraded,
        BinaryUnreadable,
        // KH-1347: line identity wrong → FAIL so incomplete exit shares this set.
        ScannerLineOffsetMismatch,
    ] {
        assert_eq!(
            kind.severity(),
            CoverageSeverity::Fail,
            "{kind:?} is a genuine coverage miss and must render as FAIL (red)"
        );
    }
}

#[test]
fn warn_severity_set_is_exact() {
    use CoverageGapKind::*;
    for kind in [
        OverMaxSize,
        Binary,
        Excluded,
        ScannerStructuredOversizeSkip,
        ScannerDecodeTruncation,
        ScannerDecodeOversizeSkip,
        ScannerInvalidPatternIndexSkip,
        ScannerBoundaryCardinalityMismatch,
        ScannerBinaryStringsNamedExclusion,
    ] {
        assert_eq!(
            kind.severity(),
            CoverageSeverity::Warn,
            "{kind:?} is advisory/partial and must render as WARN (yellow)"
        );
    }
}

/// Locks out leaving a coverage-gap kind unclassified after adding a new
/// fail-closed category to the canonical 27-kind partition.
#[test]
fn severity_partition_totals_all_kinds() {
    // 17 FAIL + 10 WARN = 27. ScannerLineOffsetMismatch is fail-closed because
    // wrong source coordinates make the reported finding incomplete, and
    // ScannerChunkDeadlineAbort because the chunk's tail was never matched.
    // Both NothingScanned kinds are fail-closed because a scan that read no
    // bytes has proved nothing. BatchNotRouted is fail-closed because the
    // batch's bytes reached the scanner and were then never scanned at all.
    // VendoredPathSuppressed and ScannerBinaryStringsNamedExclusion are WARN:
    // the bytes were covered and the drop is a precision trade the operator
    // can inspect.
    let fail = CoverageGapKind::ALL
        .iter()
        .filter(|k| k.severity() == CoverageSeverity::Fail)
        .count();
    let warn = CoverageGapKind::ALL
        .iter()
        .filter(|k| k.severity() == CoverageSeverity::Warn)
        .count();
    assert_eq!(fail, 17, "expected 17 FAIL categories, got {fail}");
    assert_eq!(warn, 10, "expected 10 WARN categories, got {warn}");
    assert_eq!(fail + warn, CoverageGapKind::ALL.len());
    assert_eq!(
        CoverageGapKind::fail_class_kinds().count(),
        fail,
        "fail_class_kinds() must match severity()==Fail filter (KH-1410)"
    );
}

/// Daemon `SourceCoverageGaps::fail_class_total` includes every source-skip
/// FAIL field plus client-acquisition failures. Pin the exact sum so mass
/// daemon source errors cannot be reported as clean.
#[test]
fn daemon_source_coverage_gaps_fail_class_matches_source_skip_fail_kinds() {
    use crate::daemon::protocol::SourceCoverageGaps;
    let gaps = SourceCoverageGaps {
        over_max_size: 1,
        binary: 1,
        unreadable: 2,
        git_object_unreadable: 3,
        archive_truncated: 4,
        binary_section_name_unresolved: 5,
        source_truncated: 6,
        structured_source_parse_failures: 7,
        archive_duplicate_scan_unavailable: 8,
        git_lfs_pointer: 9,
        source_failed: 10,
    };
    // WARN fields must not contribute.
    assert_eq!(
        gaps.fail_class_total(),
        2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
        "daemon fail_class_total must exclude only over_max_size and binary"
    );
    assert_eq!(gaps.total(), gaps.fail_class_total() + 1 + 1);
}

/// KH-1410: hand-rolled incomplete-exit sums cannot drift from CoverageGapKind.
#[test]
fn fail_class_total_sums_only_fail_kinds() {
    let counts = all_ones();
    let via_kinds: usize = CoverageGapKind::fail_class_kinds()
        .map(|k| k.count(&counts))
        .sum();
    assert_eq!(counts.fail_class_total(), via_kinds);
    // WARN-only categories must not contribute.
    for kind in CoverageGapKind::ALL {
        if kind.severity() == CoverageSeverity::Warn {
            // all_ones sets every counter to 1, so each WARN kind contributes 1
            // to total but 0 to fail_class_total.
            assert!(
                kind.count(&counts) > 0,
                "{kind:?} should be non-zero in all_ones fixture"
            );
        }
    }
    let warn_sum: usize = CoverageGapKind::ALL
        .iter()
        .filter(|k| k.severity() == CoverageSeverity::Warn)
        .map(|k| k.count(&counts))
        .sum();
    let all_sum: usize = CoverageGapKind::ALL.iter().map(|k| k.count(&counts)).sum();
    assert_eq!(
        counts.fail_class_total() + warn_sum,
        all_sum,
        "FAIL+WARN partition must cover every kind count"
    );
    assert!(
        counts.fail_class_total() < all_sum,
        "WARN categories must be excluded from fail_class_total"
    );
}

#[test]
fn sarif_reasons_are_all_unique() {
    let mut reasons: Vec<&str> = CoverageGapKind::ALL
        .iter()
        .map(|k| k.sarif_reason())
        .collect();
    let total = reasons.len();
    reasons.sort_unstable();
    reasons.dedup();
    assert_eq!(
        reasons.len(),
        total,
        "two kinds share a SARIF reason string"
    );
}

#[test]
fn sarif_reasons_are_all_nonempty() {
    for kind in CoverageGapKind::ALL {
        assert!(
            !kind.sarif_reason().trim().is_empty(),
            "{kind:?} has an empty SARIF reason"
        );
    }
}

#[test]
fn human_reasons_are_all_unique() {
    let mut reasons: Vec<String> = CoverageGapKind::ALL
        .iter()
        .map(|k| k.human_reason(1))
        .collect();
    let total = reasons.len();
    reasons.sort();
    reasons.dedup();
    assert_eq!(
        reasons.len(),
        total,
        "two kinds share a human reason string"
    );
}

#[test]
fn human_reasons_are_all_nonempty() {
    for kind in CoverageGapKind::ALL {
        assert!(
            !kind.human_reason(1).trim().is_empty(),
            "{kind:?} has an empty human reason"
        );
    }
}

#[test]
fn human_reason_embeds_the_count() {
    for kind in CoverageGapKind::ALL {
        let reason = kind.human_reason(4242);
        assert!(
            reason.contains("4242"),
            "{kind:?} human reason must include its count, got {reason:?}"
        );
    }
}

#[test]
fn sarif_summary_is_the_projection_of_all_kinds() {
    // Every kind with a non-zero count, and only those, must appear in the
    // SARIF summary keyed by its exact sarif_reason. This binds the SARIF surface
    // to the canonical set.
    let counts = all_ones();
    let summary = coverage_gap_summary(&counts);
    for kind in CoverageGapKind::ALL {
        assert!(
            summary.iter().any(|(r, _)| r == kind.sarif_reason()),
            "{kind:?} is non-zero on all_ones but its sarif_reason is missing from the summary"
        );
    }
    assert_eq!(
        summary.len(),
        CoverageGapKind::ALL.len(),
        "the SARIF summary must contain exactly one entry per non-zero kind"
    );
}

#[test]
fn both_surfaces_cover_the_identical_kind_set() {
    // The unification invariant: for one snapshot, the kinds the SARIF surface
    // reports are exactly the non-zero kinds the human surface would render. If a
    // kind lived on one surface only, the two counts would disagree.
    let counts = all_ones();
    let summary = coverage_gap_summary(&counts);
    let sarif_reasons: Vec<&str> = summary.iter().map(|(r, _)| r.as_str()).collect();

    let mut rendered = 0usize;
    for kind in CoverageGapKind::ALL {
        let n = kind.count(&counts);
        if n == 0 {
            continue;
        }
        assert!(
            !kind.human_reason(n).trim().is_empty(),
            "{kind:?} non-zero but the human surface renders nothing"
        );
        assert!(
            sarif_reasons.contains(&kind.sarif_reason()),
            "{kind:?} rendered by the human surface but missing from SARIF"
        );
        rendered += 1;
    }
    assert_eq!(
        rendered,
        summary.len(),
        "the human and SARIF surfaces must cover the identical set of kinds"
    );
    assert_eq!(rendered, 27, "all 27 kinds render on the all_ones snapshot");
}