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
//! Confidence enrichment pipeline — Phase 1 signals.
//!
//! Adjusts finding confidence using contextual signals. This runs AFTER
//! default confidence assignment (Step 0.5) and BEFORE output filtering,
//! so every finding already has `confidence = Some(...)` when we get here.
//!
//! # Phase 1 signals
//!
//! | Signal | Condition | Delta |
//! |-------------------------|-----------------------------------------------|--------|
//! | Bundled code | Path matches bundled patterns (dist/, .min.) | -0.40 |
//! | Non-production path | Path in scripts/, tests/, examples/ etc. | -0.15 |
//! | Multi-detector agreement| `detector_count` in threshold_metadata >= 2 | +0.10/extra (max +0.30) |
//! | Test/fixture file | Path contains /test, /fixture, /mock | -0.20 |
//!
//! After all signals are applied the confidence is clamped to `[0.05, 0.99]`.
//! Signal provenance is stored in `threshold_metadata["confidence_signals"]`
//! as a comma-separated string.
use crate::dual_branch::{PredictionReason, PredictionReasonKind};
use crate::models::Finding;
/// Minimum allowed confidence after enrichment.
const CONFIDENCE_FLOOR: f64 = 0.05;
/// Maximum allowed confidence after enrichment.
const CONFIDENCE_CEILING: f64 = 0.99;
/// A single contextual signal that was applied to a finding's confidence.
#[derive(Debug, Clone)]
pub struct ConfidenceSignal {
/// Short machine-readable signal name (e.g. `"bundled_code"`).
pub signal: String,
/// The delta that was added to confidence (negative = decreased).
pub delta: f64,
/// Human-readable explanation of why the signal fired.
pub reason: String,
}
impl ConfidenceSignal {
/// Construct a typed dual-branch `PredictionReason` from this signal.
///
/// The caller supplies the `kind` directly because every Phase 1b
/// call site already knows the typed variant at construction time
/// (it just constructed the matching `ConfidenceSignal` next to
/// it). Forcing the caller to name the variant has two benefits:
///
/// 1. **No string-to-variant mapping that can drift.** A previous
/// iteration of this code had a `to_prediction_reason()` method
/// that did `match self.signal.as_str() { "bundled_code" => ... }`.
/// That mapping silently became wrong if a future author
/// renamed a signal string without updating the match arms, and
/// silently fell through to `Custom` for signal types whose
/// typed variant needed extra data the string couldn't carry
/// (notably `MultiDetectorAgreement { count }`). Forcing the
/// caller to name the variant eliminates the failure mode.
///
/// 2. **The typed variant becomes self-documenting at the call
/// site.** A reader of `enrich_confidence` can see exactly which
/// `PredictionReasonKind` each signal maps to without chasing
/// a separate match statement.
///
/// # Sign convention (the load-bearing decision)
///
/// `ConfidenceSignal::delta` and `PredictionReason::weight` use
/// **opposite sign conventions**:
///
/// | Field | Positive value means |
/// |-----------------------------|-------------------------------------|
/// | `ConfidenceSignal::delta` | Boost confidence (more likely real) |
/// | `PredictionReason::weight` | Lean toward the **Benign** branch |
///
/// So `weight = -delta`. A signal that reduces confidence (e.g.
/// `bundled_code` with `delta = -0.4`) translates to a positive
/// weight (`+0.4`) leaning Benign — bundled code is *evidence the
/// finding is benign*. The
/// `bridge_sign_convention_inverts_delta` test pins this so a
/// future change to either convention surfaces immediately.
pub fn to_prediction_reason(&self, kind: PredictionReasonKind) -> PredictionReason {
PredictionReason {
kind,
// Sign-flip: positive delta (boost confidence) → negative
// weight (lean RealBug); see method-level docs above.
weight: -self.delta as f32,
note: self.reason.clone(),
}
}
}
/// Enrich a single finding's confidence with Phase 1 contextual signals.
///
/// Returns the list of signals that were applied (empty if none matched).
/// The finding's `confidence` field is mutated in place and the signal
/// provenance is stored in `threshold_metadata["confidence_signals"]`.
pub fn enrich_confidence(finding: &mut Finding) -> Vec<ConfidenceSignal> {
let mut signals: Vec<ConfidenceSignal> = Vec::new();
// We need a file path to evaluate path-based signals.
let file_path = finding
.affected_files
.first()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
// ── Signal 1: Bundled code ──────────────────────────────────────
if !file_path.is_empty()
&& crate::detectors::content_classifier::is_likely_bundled_path(&file_path)
{
let signal = ConfidenceSignal {
signal: "bundled_code".into(),
delta: -0.4,
reason: format!("File path matches bundled pattern: {}", file_path),
};
// Phase 1b dual-branch bridge: typed reason for the predictor.
// The typed variant is named explicitly here so a future rename
// of the signal string can't silently desynchronize from the
// typed variant.
finding
.prediction_reasons
.push(signal.to_prediction_reason(PredictionReasonKind::BundledCode));
signals.push(signal);
}
// ── Signal 2: Non-production path ───────────────────────────────
if !file_path.is_empty()
&& crate::detectors::content_classifier::is_non_production_path(&file_path)
{
let signal = ConfidenceSignal {
signal: "non_production_path".into(),
delta: -0.15,
reason: format!("File in non-production path: {}", file_path),
};
finding
.prediction_reasons
.push(signal.to_prediction_reason(PredictionReasonKind::NonProductionPath));
signals.push(signal);
}
// ── Signal 3: Multi-detector agreement ──────────────────────────
if let Some(count_str) = finding.threshold_metadata.get("detector_count") {
if let Ok(count) = count_str.parse::<u32>() {
if count >= 2 {
let extra = (count - 1).min(3); // cap at +0.3
let delta = extra as f64 * 0.1;
let signal = ConfidenceSignal {
signal: "multi_detector_agreement".into(),
delta,
reason: format!("{} detectors agree ({}extra x +0.1)", count, extra),
};
// The typed `count` is in scope here; pass it through
// to the typed variant directly. (This was the original
// motivation for taking the kind from the caller — the
// typed count can't be recovered downstream from
// `signal: String` and `reason: String` alone.)
finding.prediction_reasons.push(
signal.to_prediction_reason(PredictionReasonKind::MultiDetectorAgreement {
count,
}),
);
signals.push(signal);
}
}
}
// ── Signal 4: Test/fixture file ─────────────────────────────────
if !file_path.is_empty() && is_test_or_fixture_path(&file_path) {
let signal = ConfidenceSignal {
signal: "test_fixture_file".into(),
delta: -0.2,
reason: format!("File path is a test/fixture/mock: {}", file_path),
};
finding
.prediction_reasons
.push(signal.to_prediction_reason(PredictionReasonKind::TestFixtureFile));
signals.push(signal);
}
// ── Apply signals ───────────────────────────────────────────────
if !signals.is_empty() {
let base = finding.confidence.unwrap_or(0.70);
let total_delta: f64 = signals.iter().map(|s| s.delta).sum();
let adjusted = (base + total_delta).clamp(CONFIDENCE_FLOOR, CONFIDENCE_CEILING);
finding.confidence = Some(adjusted);
// Store provenance
let names: Vec<&str> = signals.iter().map(|s| s.signal.as_str()).collect();
finding
.threshold_metadata
.insert("confidence_signals".into(), names.join(","));
}
signals
}
/// Check if a file path looks like a test, fixture, or mock file.
///
/// This is a path-heuristic check complementary to
/// `content_classifier::is_non_production_path` — it targets individual
/// test/fixture/mock files rather than entire directory subtrees.
fn is_test_or_fixture_path(path: &str) -> bool {
let lower = path.to_lowercase();
// Directory segments
lower.contains("/test/")
|| lower.contains("/tests/")
|| lower.contains("/__tests__/")
|| lower.contains("/fixture/")
|| lower.contains("/fixtures/")
|| lower.contains("/__fixtures__/")
|| lower.contains("/mock/")
|| lower.contains("/mocks/")
|| lower.contains("/__mocks__/")
// File-name patterns
|| lower.contains("_test.")
|| lower.contains(".test.")
|| lower.contains("_spec.")
|| lower.contains(".spec.")
|| lower.contains("_mock.")
|| lower.contains(".mock.")
}
/// Batch-enrich all findings in place.
///
/// This is the main entry point called from the postprocess pipeline.
/// Findings that don't match any signal are left untouched.
pub fn enrich_all(findings: &mut [Finding]) {
let mut enriched = 0usize;
for finding in findings.iter_mut() {
let signals = enrich_confidence(finding);
if !signals.is_empty() {
enriched += 1;
}
}
if enriched > 0 {
tracing::debug!(
"Confidence enrichment: adjusted {} findings with contextual signals",
enriched
);
}
}
// ────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
/// Helper: build a minimal finding with a given file path and optional confidence.
fn make_finding(path: &str, confidence: Option<f64>) -> Finding {
Finding {
detector: "TestDetector".into(),
severity: crate::models::Severity::Medium,
title: "Test finding".into(),
description: "desc".into(),
affected_files: if path.is_empty() {
vec![]
} else {
vec![PathBuf::from(path)]
},
confidence,
..Default::default()
}
}
// ── Bundled code signal ──────────────────────────────────────────
#[test]
fn test_bundled_code_dist() {
let mut f = make_finding("project/dist/bundle.js", Some(0.75));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "bundled_code"));
assert!(f.confidence.unwrap() < 0.75);
}
#[test]
fn test_bundled_code_min() {
let mut f = make_finding("lib/react.min.js", Some(0.80));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "bundled_code"));
}
#[test]
fn test_bundled_code_build() {
let mut f = make_finding("project/build/output.js", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "bundled_code"));
}
// ── Non-production path signal ───────────────────────────────────
#[test]
fn test_non_production_scripts() {
let mut f = make_finding("scripts/deploy.sh", Some(0.75));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "non_production_path"));
assert!(f.confidence.unwrap() < 0.75);
}
#[test]
fn test_non_production_examples() {
let mut f = make_finding("examples/demo.py", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "non_production_path"));
}
// ── Multi-detector agreement signal ──────────────────────────────
#[test]
fn test_multi_detector_two() {
let mut f = make_finding("src/app.py", Some(0.70));
f.threshold_metadata
.insert("detector_count".into(), "2".into());
let signals = enrich_confidence(&mut f);
assert!(signals
.iter()
.any(|s| s.signal == "multi_detector_agreement"));
// +0.1 for one extra detector
assert!((f.confidence.unwrap() - 0.80).abs() < f64::EPSILON);
}
#[test]
fn test_multi_detector_four_capped() {
let mut f = make_finding("src/app.py", Some(0.60));
f.threshold_metadata
.insert("detector_count".into(), "4".into());
let signals = enrich_confidence(&mut f);
let sig = signals
.iter()
.find(|s| s.signal == "multi_detector_agreement")
.expect("signal present");
// 4 detectors => 3 extra, capped at +0.3
assert!((sig.delta - 0.3).abs() < f64::EPSILON);
assert!((f.confidence.unwrap() - 0.90).abs() < f64::EPSILON);
}
#[test]
fn test_multi_detector_five_capped_at_three() {
let mut f = make_finding("src/app.py", Some(0.50));
f.threshold_metadata
.insert("detector_count".into(), "5".into());
let signals = enrich_confidence(&mut f);
let sig = signals
.iter()
.find(|s| s.signal == "multi_detector_agreement")
.expect("signal present");
// 5 detectors => 4 extra, but capped at 3 => +0.3
assert!((sig.delta - 0.3).abs() < f64::EPSILON);
}
#[test]
fn test_multi_detector_one_no_signal() {
let mut f = make_finding("src/app.py", Some(0.70));
f.threshold_metadata
.insert("detector_count".into(), "1".into());
let signals = enrich_confidence(&mut f);
assert!(!signals
.iter()
.any(|s| s.signal == "multi_detector_agreement"));
}
// ── Test/fixture file signal ─────────────────────────────────────
#[test]
fn test_test_file() {
let mut f = make_finding("src/tests/test_utils.py", Some(0.75));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "test_fixture_file"));
assert!(f.confidence.unwrap() < 0.75);
}
#[test]
fn test_fixture_file() {
let mut f = make_finding("tests/fixtures/bad_code.py", Some(0.80));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "test_fixture_file"));
}
#[test]
fn test_mock_file() {
let mut f = make_finding("src/__mocks__/api.js", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "test_fixture_file"));
}
#[test]
fn test_spec_file() {
let mut f = make_finding("src/utils.spec.ts", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.iter().any(|s| s.signal == "test_fixture_file"));
}
// ── Clamping ─────────────────────────────────────────────────────
#[test]
fn test_clamp_floor() {
// Bundled (-0.4) + test/fixture (-0.2) + non-production (-0.15) = -0.75
// Starting at 0.30 => 0.30 - 0.75 = -0.45, clamped to 0.05
let mut f = make_finding("dist/fixtures/test.min.js", Some(0.30));
enrich_confidence(&mut f);
assert!((f.confidence.unwrap() - CONFIDENCE_FLOOR).abs() < f64::EPSILON);
}
#[test]
fn test_clamp_ceiling() {
// Multi-detector +0.3 on a base of 0.95 => 1.25, clamped to 0.99
let mut f = make_finding("src/app.py", Some(0.95));
f.threshold_metadata
.insert("detector_count".into(), "4".into());
enrich_confidence(&mut f);
assert!((f.confidence.unwrap() - CONFIDENCE_CEILING).abs() < f64::EPSILON);
}
// ── No signals ───────────────────────────────────────────────────
#[test]
fn test_no_signals_no_change() {
let mut f = make_finding("src/main.rs", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.is_empty());
assert!((f.confidence.unwrap() - 0.70).abs() < f64::EPSILON);
assert!(!f.threshold_metadata.contains_key("confidence_signals"));
}
#[test]
fn test_no_file_path_no_signals() {
let mut f = make_finding("", Some(0.70));
let signals = enrich_confidence(&mut f);
assert!(signals.is_empty());
}
// ── Multiple signals combined ────────────────────────────────────
#[test]
fn test_multiple_signals_combined() {
// dist/ triggers bundled (-0.4) and test/fixture (-0.2 from /fixtures/ in bundled path)
// Actually dist/fixtures/ triggers bundled AND test_fixture
let mut f = make_finding("project/dist/fixtures/helper.js", Some(0.80));
let signals = enrich_confidence(&mut f);
assert!(signals.len() >= 2);
// Check provenance stored
let provenance = f
.threshold_metadata
.get("confidence_signals")
.expect("signals stored");
assert!(provenance.contains("bundled_code"));
}
// ── Provenance ───────────────────────────────────────────────────
#[test]
fn test_provenance_stored() {
let mut f = make_finding("scripts/setup.sh", Some(0.75));
enrich_confidence(&mut f);
let provenance = f
.threshold_metadata
.get("confidence_signals")
.expect("stored");
assert!(provenance.contains("non_production_path"));
}
// ── enrich_all batch ─────────────────────────────────────────────
#[test]
fn test_enrich_all_batch() {
let mut findings = vec![
make_finding("src/main.rs", Some(0.70)), // no signals
make_finding("project/dist/bundle.js", Some(0.80)), // bundled
make_finding("tests/test_foo.py", Some(0.75)), // test file + non-prod
];
enrich_all(&mut findings);
// First finding untouched
assert!((findings[0].confidence.unwrap() - 0.70).abs() < f64::EPSILON);
// Second finding reduced (bundled -0.4)
assert!(findings[1].confidence.unwrap() < 0.80);
// Third finding reduced (test/fixture -0.2, non-prod -0.15)
assert!(findings[2].confidence.unwrap() < 0.75);
}
#[test]
fn test_enrich_all_empty() {
let mut findings: Vec<Finding> = vec![];
enrich_all(&mut findings);
assert!(findings.is_empty());
}
#[test]
fn enrich_all_populates_prediction_reasons_for_each_matched_finding() {
// Wiring test: the actual function called from
// `cli/analyze/postprocess.rs::postprocess_findings` is
// `enrich_all`, not `enrich_confidence`. If a future refactor
// accidentally bypasses the per-finding bridge inside
// `enrich_all` (e.g. by introducing a fast path that calls
// some other function), this test catches it. The same
// verification at the `enrich_confidence` level would not.
let mut findings = vec![
make_finding("src/main.rs", Some(0.70)), // no signals
make_finding("project/dist/bundle.js", Some(0.80)), // bundled
make_finding("tests/fixtures/bad.py", Some(0.75)), // test/fixture
];
enrich_all(&mut findings);
// Finding 0: no signals, no prediction reasons.
assert!(
findings[0].prediction_reasons.is_empty(),
"no-signal finding must not gain prediction reasons; \
got {:?}",
findings[0].prediction_reasons,
);
// Finding 1: bundled_code → BundledCode.
assert!(
findings[1]
.prediction_reasons
.iter()
.any(|r| matches!(r.kind, PredictionReasonKind::BundledCode)),
"bundled finding must carry BundledCode reason after enrich_all; \
got {:?}",
findings[1].prediction_reasons,
);
// Finding 2: test_fixture_file → TestFixtureFile.
assert!(
findings[2]
.prediction_reasons
.iter()
.any(|r| matches!(r.kind, PredictionReasonKind::TestFixtureFile)),
"test/fixture finding must carry TestFixtureFile reason after enrich_all; \
got {:?}",
findings[2].prediction_reasons,
);
}
// ── is_test_or_fixture_path ──────────────────────────────────────
#[test]
fn test_is_test_or_fixture_path_positive() {
assert!(is_test_or_fixture_path("src/tests/foo.py"));
assert!(is_test_or_fixture_path("foo/__tests__/bar.js"));
assert!(is_test_or_fixture_path("src/fixture/data.json"));
assert!(is_test_or_fixture_path("project/mocks/api.ts"));
assert!(is_test_or_fixture_path("lib/utils_test.go"));
assert!(is_test_or_fixture_path("src/app.test.tsx"));
assert!(is_test_or_fixture_path("src/app.spec.ts"));
assert!(is_test_or_fixture_path("src/helper_mock.py"));
assert!(is_test_or_fixture_path("src/data.mock.ts"));
}
#[test]
fn test_is_test_or_fixture_path_negative() {
assert!(!is_test_or_fixture_path("src/main.rs"));
assert!(!is_test_or_fixture_path("lib/utils.py"));
assert!(!is_test_or_fixture_path("src/testing_utils.py")); // "testing" != "test/"
}
// ── Phase 1b dual-branch bridge tests ──
//
// These tests pin the contracts that:
// 1. ConfidenceSignal -> PredictionReason mapping covers every
// known signal name with a typed variant (no Custom fallback
// for in-tree signals).
// 2. The sign convention is correctly inverted (delta is
// confidence-positive; weight is Benign-positive).
// 3. enrich_confidence populates Finding::prediction_reasons
// additively without disturbing the existing string-typed
// threshold_metadata provenance.
#[test]
fn bridge_sign_convention_inverts_delta() {
// The single most important Phase 1b invariant: a signal that
// *reduces* confidence (delta < 0, leaning Benign) must produce
// a *positive* weight (leaning Benign). If this ever flips, the
// predictor in Phase 1c will collapse to the wrong branch.
let signal = ConfidenceSignal {
signal: "bundled_code".into(),
delta: -0.4,
reason: "test".into(),
};
let reason = signal.to_prediction_reason(PredictionReasonKind::BundledCode);
assert!(
(reason.weight - 0.4).abs() < 1e-6,
"weight must equal -delta = +0.4 for a confidence-reducing signal; \
got weight={} for delta={}",
reason.weight,
signal.delta,
);
// Same check the other direction: a confidence-boosting signal
// (delta > 0) must produce a negative weight (RealBug-leaning).
let signal = ConfidenceSignal {
signal: "multi_detector_agreement".into(),
delta: 0.2,
reason: "test".into(),
};
let reason =
signal.to_prediction_reason(PredictionReasonKind::MultiDetectorAgreement { count: 3 });
assert!(
(reason.weight - (-0.2)).abs() < 1e-6,
"weight must equal -delta = -0.2 for a confidence-boosting signal; \
got weight={} for delta={}",
reason.weight,
signal.delta,
);
}
#[test]
fn enrich_confidence_uses_matching_typed_variant_per_signal() {
// The actual contract we care about: the four call sites in
// `enrich_confidence` each pass the typed variant that
// semantically matches the signal string. Drive it end-to-end
// by triggering each signal individually and asserting the
// resulting prediction_reason carries the expected variant.
//
// This test replaces an earlier version that asserted a
// string→variant mapping inside a `to_prediction_reason()`
// method. That method was deleted in favor of forcing every
// call site to name the variant directly (see
// `ConfidenceSignal::to_prediction_reason` doc); this test
// verifies that every call site does so correctly.
use std::path::PathBuf;
// ── bundled_code → BundledCode ──
let mut f = Finding {
id: "f".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Low,
affected_files: vec![PathBuf::from("dist/bundle.min.js")],
..Default::default()
};
let signals = enrich_confidence(&mut f);
assert!(
signals.iter().any(|s| s.signal == "bundled_code"),
"dist/bundle.min.js should trigger bundled_code"
);
assert!(
f.prediction_reasons
.iter()
.any(|r| matches!(r.kind, PredictionReasonKind::BundledCode)),
"bundled_code call site must use PredictionReasonKind::BundledCode; \
got reasons: {:?}",
f.prediction_reasons,
);
// ── non_production_path → NonProductionPath ──
let mut f = Finding {
id: "f".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Low,
affected_files: vec![PathBuf::from("scripts/build.py")],
..Default::default()
};
let signals = enrich_confidence(&mut f);
assert!(
signals.iter().any(|s| s.signal == "non_production_path"),
"scripts/build.py should trigger non_production_path"
);
assert!(
f.prediction_reasons
.iter()
.any(|r| matches!(r.kind, PredictionReasonKind::NonProductionPath)),
"non_production_path call site must use PredictionReasonKind::NonProductionPath",
);
// ── test_fixture_file → TestFixtureFile ──
let mut f = Finding {
id: "f".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Low,
// Path picked to match the existing classifier; see
// `tests::test_fixture_file` for the canonical fixture.
affected_files: vec![PathBuf::from("tests/fixtures/bad_code.py")],
..Default::default()
};
let signals = enrich_confidence(&mut f);
assert!(
signals.iter().any(|s| s.signal == "test_fixture_file"),
"tests/fixtures/bad_code.py should trigger test_fixture_file"
);
assert!(
f.prediction_reasons
.iter()
.any(|r| matches!(r.kind, PredictionReasonKind::TestFixtureFile)),
"test_fixture_file call site must use PredictionReasonKind::TestFixtureFile",
);
// ── multi_detector_agreement → MultiDetectorAgreement { count } ──
// Covered separately in `bridge_multi_detector_uses_typed_count`
// because it requires a different setup (detector_count
// metadata rather than a path).
}
#[test]
fn bridge_enrich_populates_prediction_reasons_additively() {
// Calling enrich_confidence on a finding that triggers a path-
// based signal must:
// 1. push exactly one PredictionReason per applied signal,
// 2. preserve the existing string-typed
// threshold_metadata["confidence_signals"] provenance,
// 3. preserve any pre-existing prediction_reasons (so a
// detector that already populated some reasons can call
// enrich without losing them — additive contract).
use std::path::PathBuf;
let pre_existing = PredictionReason {
kind: PredictionReasonKind::Custom {
description: "pre-existing".into(),
},
weight: 0.0,
note: "should survive enrich".into(),
};
let mut finding = Finding {
id: "f1".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Medium,
affected_files: vec![PathBuf::from("tests/test_foo.py")],
..Default::default()
};
finding.prediction_reasons.push(pre_existing.clone());
let signals = enrich_confidence(&mut finding);
assert!(
!signals.is_empty(),
"tests/test_foo.py should trigger test_fixture_file signal"
);
// Every applied signal must have produced a typed reason in
// addition to the legacy string metadata.
assert_eq!(
finding.prediction_reasons.len(),
1 + signals.len(),
"should have pre-existing + one reason per signal; \
got reasons={:?}, signals={:?}",
finding.prediction_reasons,
signals,
);
// Pre-existing reason untouched and at the front (push order).
assert_eq!(finding.prediction_reasons[0], pre_existing);
// Legacy provenance still present.
assert!(
finding
.threshold_metadata
.contains_key("confidence_signals"),
"legacy string provenance must still be populated"
);
}
#[test]
fn bridge_enrich_no_signals_means_no_reasons_added() {
// Findings whose path doesn't match any enrichment signal must
// not have any prediction reasons added by the bridge. This is
// the "no behavior change for non-matching findings" guarantee.
use std::path::PathBuf;
let mut finding = Finding {
id: "f1".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Medium,
affected_files: vec![PathBuf::from("src/main.rs")],
..Default::default()
};
let before = finding.prediction_reasons.len();
let signals = enrich_confidence(&mut finding);
assert!(signals.is_empty(), "src/main.rs should match no signals");
assert_eq!(
finding.prediction_reasons.len(),
before,
"no signals applied means no prediction reasons added"
);
}
#[test]
fn bridge_multi_detector_uses_typed_count() {
// The multi_detector_agreement signal carries a `count` that
// can't be recovered from the string-only converter. Verify the
// inline-bridge path in enrich_confidence supplies it correctly.
use std::path::PathBuf;
let mut finding = Finding {
id: "f1".into(),
detector: "TestDetector".into(),
severity: crate::models::Severity::Medium,
affected_files: vec![PathBuf::from("src/main.rs")],
..Default::default()
};
finding
.threshold_metadata
.insert("detector_count".into(), "3".into());
let signals = enrich_confidence(&mut finding);
assert!(
signals
.iter()
.any(|s| s.signal == "multi_detector_agreement"),
"detector_count=3 should trigger multi_detector_agreement"
);
let multi_reason = finding
.prediction_reasons
.iter()
.find(|r| matches!(r.kind, PredictionReasonKind::MultiDetectorAgreement { .. }))
.expect("MultiDetectorAgreement reason should be present");
match &multi_reason.kind {
PredictionReasonKind::MultiDetectorAgreement { count } => {
assert_eq!(*count, 3, "typed count must match detector_count metadata");
}
_ => unreachable!(),
}
}
}