ripr 0.10.0

Find static mutation-exposure gaps before expensive mutation testing
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
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
use super::super::rust_index::{OracleFact, TestSummary, extract_identifier_tokens};
use crate::domain::*;

pub(in crate::analysis) fn reveal_evidence(
    probe: &Probe,
    related_tests: &[(&TestSummary, RelationReason)],
) -> (StageEvidence, StageEvidence, Vec<RelatedTest>) {
    if related_tests.is_empty() {
        return (
            StageEvidence::new(
                StageState::No,
                Confidence::Medium,
                "No reachable test oracle found",
            ),
            StageEvidence::new(
                StageState::No,
                Confidence::Medium,
                "No assertion can discriminate the changed behavior without a reachable test",
            ),
            Vec::new(),
        );
    }

    let analysis = analyze_related_assertions(probe, related_tests);
    let related = finalize_related_tests(analysis.related);
    let observe = build_observe_evidence(analysis.matched_any);
    let discriminate = build_discriminate_evidence(
        &analysis.strongest,
        &analysis.strongest_kind,
        &probe.family,
        analysis.observation_unverified,
    );

    (observe, discriminate, related)
}

struct RevealAssertionAnalysis {
    related: Vec<RelatedTest>,
    strongest: OracleStrength,
    strongest_kind: OracleKind,
    matched_any: bool,
    /// True when this probe's family requires a `token_match` to confirm that
    /// an assertion actually references the specific changed sub-expression, and
    /// no such match has fired yet.
    ///
    /// Applies to: `MatchArm`, `ReturnValue`, `FieldConstruction`, `SideEffect`,
    /// `CallDeletion`, `ErrorPath`. For each of these families, the broad
    /// `family_match` or `assertion_count == 1` matcher alone is insufficient:
    /// it tells us an oracle of the right shape exists in a reachable test, but
    /// cannot confirm it observes *this particular* changed expression (vs. a
    /// sibling, an unrelated field, or a different call site).
    ///
    /// Confirmation differs by family:
    /// - **Value** families (MatchArm, ReturnValue, FieldConstruction,
    ///   ErrorPath): the only static signal of specificity is a `token_match` —
    ///   an assertion whose text contains an identifier token from the probe
    ///   expression. For `ErrorPath`, `assertion_matches_probe_detail`'s
    ///   `ExactErrorVariant` fast-path returns `has_token_match=true` when the
    ///   assertion text contains the probe's specific variant token (RIPR-SPEC-0106,
    ///   Part B), so a genuine variant-pinning oracle clears this guard. A sibling
    ///   variant, a broad `is_err()`, or a non-variant exact-value oracle does not.
    /// - **Effect** families (SideEffect, CallDeletion): the canonical observer
    ///   is a mock/expectation/snapshot that kind-matches the seam without
    ///   sharing a token, so a genuine effect observer (`effect_observer_confirms`)
    ///   confirms in addition to `token_match`.
    ///
    /// Cleared as soon as a confirming assertion fires.
    observation_unverified: bool,
}

/// Returns true for families where an assertion must specifically reference the
/// changed sub-expression to confirm observation. For **value** families
/// (MatchArm, ReturnValue, FieldConstruction, ErrorPath) the only static
/// confirmation signal is a `token_match`. For `ErrorPath`, a genuine
/// variant-pinning oracle (`ExactErrorVariant` whose text contains the probe's
/// specific variant token) sets `has_token_match=true` in
/// `assertion_matches_probe_detail` (RIPR-SPEC-0106, Part B), clearing this
/// guard. A broad `is_err()` or an exact-value oracle on a sibling result does
/// not. For **effect** families (SideEffect, CallDeletion) the legitimate
/// observer is often a mock/expectation that **kind-matches the seam** without
/// sharing any probe token; for those, a seam-kind match also confirms
/// observation (see `effect_observer_confirms`).
fn needs_token_confirmation(family: &ProbeFamily) -> bool {
    matches!(
        family,
        ProbeFamily::MatchArm
            | ProbeFamily::ReturnValue
            | ProbeFamily::FieldConstruction
            | ProbeFamily::SideEffect
            | ProbeFamily::CallDeletion
            | ProbeFamily::ErrorPath
    )
}

/// Returns true for the **effect** families (SideEffect, CallDeletion) whose
/// changed behavior is a side effect or outbound call. For these, the canonical
/// observer is a mock/expectation that kind-matches the seam rather than a
/// value assertion that names a token from the changed expression. A genuine
/// effect observer therefore confirms observation even without a `token_match`.
fn is_effect_family(family: &ProbeFamily) -> bool {
    matches!(family, ProbeFamily::SideEffect | ProbeFamily::CallDeletion)
}

/// Returns true when `assertion` is a genuine **effect observer** that
/// kind-matches an effect seam: a mock/expectation, a snapshot, or a
/// whole-object equality capturing the resulting state. This is intentionally
/// narrower than `oracle_matches_family` for effect families — it excludes the
/// broad `text.contains("assert")` / `text.contains("expect")` substring
/// matches, so a plain non-observing assertion (e.g. `assert!(result)`) does
/// **not** clear `observation_unverified`. Only a real expectation/snapshot
/// observer does.
fn effect_observer_confirms(assertion: &OracleFact) -> bool {
    matches!(
        assertion.kind,
        OracleKind::MockExpectation | OracleKind::Snapshot | OracleKind::WholeObjectEquality
    )
}

/// For a `MatchArm` probe expression, extract only the "variant" tokens —
/// the identifier segments that appear immediately after a `::` separator.
/// These are the arm-specific tokens that can confirm an assertion targets
/// this arm rather than a sibling sharing the same enum qualifier.
///
/// Example: `"Mode::Frozen => -1,"` → `["Frozen"]`.
/// Example: `"Status::Active | Status::Idle => 0,"` → `["Active", "Idle"]`.
/// Example: `"None => 0,"` → `[]` (no `::` in expression).
fn match_arm_variant_tokens(expression: &str) -> Vec<String> {
    let mut variants = Vec::new();
    let bytes = expression.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i + 1 < len {
        if bytes[i] == b':' && bytes[i + 1] == b':' {
            // skip "::"
            i += 2;
            // collect the identifier that follows
            let start = i;
            while i < len && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                i += 1;
            }
            if i > start {
                let variant = &expression[start..i];
                if extract_identifier_tokens(variant).contains(&variant.to_string()) {
                    variants.push(variant.to_string());
                }
            }
        } else {
            i += 1;
        }
    }
    variants
}

fn analyze_related_assertions(
    probe: &Probe,
    related_tests: &[(&TestSummary, RelationReason)],
) -> RevealAssertionAnalysis {
    let probe_tokens = extract_identifier_tokens(&probe.expression);
    // For MatchArm: collect variant-only tokens (post-`::`) for the specificity
    // check. Qualifier tokens (e.g. the type name before `::`) are excluded so
    // that a sibling-arm assertion sharing the qualifier cannot spuriously
    // confirm observation of this arm.
    let match_arm_variants = if matches!(probe.family, ProbeFamily::MatchArm) {
        match_arm_variant_tokens(&probe.expression)
    } else {
        Vec::new()
    };
    // For ErrorPath: collect the variant-only token (the identifier after the
    // last `::` in `Err(Type::Variant)`) so that a sibling-variant assertion
    // that pins a different variant of the same error type cannot spuriously
    // match this probe. RIPR-SPEC-0106 (Part B).
    let error_path_variant = if matches!(probe.family, ProbeFamily::ErrorPath) {
        error_path_variant_token(&probe.expression)
    } else {
        None
    };
    let confirm_required = needs_token_confirmation(&probe.family);
    let mut related = Vec::new();
    let mut strongest = OracleStrength::None;
    let mut strongest_kind = OracleKind::Unknown;
    let mut matched_any = false;
    // For families that need token confirmation: start pessimistic and clear
    // once a token_match fires.
    let mut observation_unverified = false;

    for (test, reason) in related_tests {
        let relation_reason = Some(*reason);
        let relation_confidence = Some(reason.confidence());
        if test.assertions.is_empty() {
            related.push(RelatedTest {
                name: test.name.clone(),
                file: test.file.clone(),
                line: test.start_line,
                oracle: None,
                oracle_kind: OracleKind::Unknown,
                oracle_strength: OracleStrength::None,
                relation_reason,
                relation_confidence,
            });
            continue;
        }
        for assertion in &test.assertions {
            let (matched, has_token_match) = assertion_matches_probe_detail(
                &probe_tokens,
                &match_arm_variants,
                error_path_variant.as_deref(),
                &probe.family,
                assertion,
                test.assertions.len(),
            );
            if matched {
                if confirm_required {
                    // Observation is confirmed when the assertion specifically
                    // references the changed sub-expression. For value families
                    // (MatchArm/ReturnValue/FieldConstruction) the only static
                    // signal is a `token_match`. For effect families
                    // (SideEffect/CallDeletion) the canonical observer is a
                    // mock/expectation/snapshot that kind-matches the seam
                    // without sharing a token, so a genuine effect observer also
                    // confirms. This prevents a real mock from being wrongly
                    // flagged `observation_unverified`, while a plain
                    // non-observing assertion (no token, no effect observer)
                    // stays unverified.
                    let observation_confirmed = has_token_match
                        || (is_effect_family(&probe.family) && effect_observer_confirms(assertion));
                    if !matched_any {
                        // First matching assertion: observation is unverified
                        // unless confirmed.
                        observation_unverified = !observation_confirmed;
                    } else if observation_confirmed {
                        // A later confirmed assertion clears the unverified flag.
                        observation_unverified = false;
                    }
                }
                matched_any = true;
                let relative_strength = probe_relative_oracle_strength(&probe.family, assertion);
                if relative_strength.rank() > strongest.rank() {
                    strongest = relative_strength.clone();
                    strongest_kind = assertion.kind.clone();
                }
                related.push(RelatedTest {
                    name: test.name.clone(),
                    file: test.file.clone(),
                    line: test.start_line,
                    oracle: Some(assertion.text.clone()),
                    oracle_kind: assertion.kind.clone(),
                    oracle_strength: relative_strength,
                    relation_reason,
                    relation_confidence,
                });
            }
        }
    }

    RevealAssertionAnalysis {
        related,
        strongest,
        strongest_kind,
        matched_any,
        observation_unverified,
    }
}

/// Extracts the variant identifier from an error-path probe expression.
///
/// For `return Err(CalcError::TooLarge);` → `Some("TooLarge")`.
/// For `return Err(anyhow!("..."));` → `None` (no qualified variant).
///
/// Used by RIPR-SPEC-0106 (Part B) to restrict `ExactErrorVariant` assertion
/// matching to the probe's specific variant, preventing sibling-variant
/// over-credit.
fn error_path_variant_token(expression: &str) -> Option<String> {
    use super::text::exact_error_variant;
    let variant_path = exact_error_variant(expression)?;
    // Last component after the final `::`.
    let last = variant_path.rsplit("::").next()?;
    if last
        .chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_uppercase())
    {
        Some(last.to_string())
    } else {
        None
    }
}

/// Returns `(matched, has_token_match)`.
///
/// `matched` is true when the assertion should be associated with this probe
/// (via token text, family kind, or single-assertion escape hatch).
/// `has_token_match` is true when the assertion text contains an identifier
/// token from the probe expression that is specific enough to confirm this
/// particular sub-expression is being observed.
///
/// For `MatchArm` probes, `has_token_match` uses only the **variant** tokens
/// (`match_arm_variants`, the identifiers immediately after `::` in the probe
/// expression). This prevents a sibling-arm assertion like `Mode::Warm` from
/// clearing `observation_unverified` for a probe on `Mode::Frozen`, because
/// the shared qualifier token `Mode` is excluded from the confirmation set.
/// When the expression contains no `::` (e.g. `None => 0,`), the variant
/// token list is empty and `has_token_match` is always false, reflecting that
/// the probe has no arm-specific identifier.
///
/// For `ErrorPath` probes with `ExactErrorVariant` assertions (RIPR-SPEC-0106,
/// Part B): when `error_path_variant` is `Some`, an `ExactErrorVariant` oracle
/// only `matched` when the assertion text contains the probe's specific variant
/// token. This prevents a sibling-variant assertion (`CalcError::Negative`)
/// from matching a `CalcError::TooLarge` probe — both share the `CalcError`
/// qualifier token, but only the variant token (`TooLarge`) is specific.
/// Without `error_path_variant` (probe has no qualified variant), falls back
/// to the standard `token_match` behavior.
fn assertion_matches_probe_detail(
    probe_tokens: &[String],
    match_arm_variants: &[String],
    error_path_variant: Option<&str>,
    family: &ProbeFamily,
    assertion: &OracleFact,
    assertion_count: usize,
) -> (bool, bool) {
    let token_match = probe_tokens
        .iter()
        .any(|token| token.len() > 3 && assertion.text.contains(token.as_str()));
    // For MatchArm probes, restrict the confirmation check to variant-only
    // tokens (post-`::`). The qualifier ("Mode" in "Mode::Frozen") is shared
    // across all arms and therefore cannot confirm this specific arm.
    let has_token_match = if matches!(family, ProbeFamily::MatchArm) {
        match_arm_variants
            .iter()
            .any(|v| v.len() > 3 && assertion.text.contains(v.as_str()))
    } else {
        token_match
    };
    // For ErrorPath probes with ExactErrorVariant assertions: restrict `matched`
    // to require the probe's specific variant token, not just the qualifier.
    // Fail-closed: if error_path_variant is None (no parseable variant in the
    // probe), fall through to the standard token_match + family_match check.
    if matches!(family, ProbeFamily::ErrorPath)
        && matches!(assertion.kind, OracleKind::ExactErrorVariant)
        && let Some(variant) = error_path_variant
    {
        let variant_matches = variant.len() > 3 && assertion.text.contains(variant);
        return (variant_matches, variant_matches);
        // Probe has no parseable variant: falls through to standard match below.
    }
    let family_match = oracle_matches_family(family, assertion);
    let matched = token_match || family_match || assertion_count == 1;
    (matched, has_token_match)
}

fn finalize_related_tests(mut related: Vec<RelatedTest>) -> Vec<RelatedTest> {
    related.sort_by(|a, b| a.name.cmp(&b.name).then(a.line.cmp(&b.line)));
    related.dedup_by(|a, b| a.name == b.name && a.oracle == b.oracle);
    related
}

fn build_observe_evidence(matched_any: bool) -> StageEvidence {
    if matched_any {
        StageEvidence::new(
            StageState::Yes,
            Confidence::Medium,
            "A related test observes a value or effect near the changed behavior",
        )
    } else {
        StageEvidence::new(
            StageState::No,
            Confidence::Medium,
            "Related tests were found, but no assertion appears to observe the changed value, error, field, or effect",
        )
    }
}

fn build_discriminate_evidence(
    strongest: &OracleStrength,
    strongest_kind: &OracleKind,
    family: &ProbeFamily,
    observation_unverified: bool,
) -> StageEvidence {
    // For families that require token confirmation (MatchArm, ReturnValue,
    // FieldConstruction, SideEffect, CallDeletion), a family_match or
    // assertion_count==1 alone cannot confirm that an assertion observes *this*
    // specific changed sub-expression. Without a token_match, downgrade to Weak
    // so classify() emits weakly_exposed (observation_unverified). A probe
    // with a token_match stays exposed.
    if observation_unverified {
        return StageEvidence::new(
            StageState::Weak,
            Confidence::Medium,
            "Discriminator unconfirmed: no assertion text references this probe's changed expression (observation_unverified)",
        );
    }
    match strongest {
        OracleStrength::Strong => StageEvidence::new(
            StageState::Yes,
            Confidence::Medium,
            match strongest_kind {
                OracleKind::ExactErrorVariant => {
                    "Strong oracle found: exact error variant assertion"
                }
                OracleKind::WholeObjectEquality => {
                    "Strong oracle found: whole-object equality assertion"
                }
                _ => "Strong oracle found: exact value or pattern assertion",
            },
        ),
        OracleStrength::Medium => StageEvidence::new(
            StageState::Weak,
            Confidence::Medium,
            match strongest_kind {
                OracleKind::Snapshot => {
                    "Medium oracle found: snapshot assertion observes the changed behavior"
                }
                OracleKind::MockExpectation => {
                    "Medium oracle found: mock or expectation observes the changed behavior"
                }
                _ => "Medium oracle found: property or partial structural assertion",
            },
        ),
        OracleStrength::Weak => StageEvidence::new(
            StageState::Weak,
            Confidence::High,
            match (strongest_kind, family) {
                (OracleKind::BroadError, ProbeFamily::ErrorPath) => {
                    "Only broad error oracle found; is_err() does not discriminate exact error variants"
                }
                (OracleKind::BroadError, _) => {
                    "Only broad error oracle found; it may not discriminate the changed behavior exactly"
                }
                (OracleKind::RelationalCheck, _) => {
                    "Only relational oracle found; it may not discriminate the changed value exactly"
                }
                _ => {
                    "Only weak oracle found, such as a broad relational assertion or non-empty check"
                }
            },
        ),
        OracleStrength::Smoke => StageEvidence::new(
            StageState::Weak,
            Confidence::High,
            "Only smoke oracle found, such as unwrap/expect or execution without a discriminator",
        ),
        OracleStrength::None => StageEvidence::new(
            StageState::No,
            Confidence::Medium,
            "No assertion found on related tests",
        ),
        OracleStrength::Unknown => StageEvidence::new(
            StageState::Unknown,
            Confidence::Low,
            "Assertions exist, but oracle strength is unknown",
        ),
    }
}

fn oracle_matches_family(family: &ProbeFamily, assertion: &OracleFact) -> bool {
    let text = assertion.text.as_str();
    match family {
        ProbeFamily::ErrorPath => {
            matches!(
                assertion.kind,
                OracleKind::ExactErrorVariant | OracleKind::BroadError
            ) || text.contains("Error::")
                || text.contains("Err")
        }
        ProbeFamily::SideEffect => {
            matches!(assertion.kind, OracleKind::MockExpectation)
                || text.contains("expect")
                || text.contains("mock")
                || text.contains("saved")
                || text.contains("published")
        }
        ProbeFamily::FieldConstruction => {
            matches!(
                assertion.kind,
                OracleKind::ExactValue
                    | OracleKind::WholeObjectEquality
                    | OracleKind::RelationalCheck
                    | OracleKind::Snapshot
            ) || text.contains('.')
        }
        ProbeFamily::Predicate => {
            matches!(
                assertion.kind,
                OracleKind::ExactValue
                    | OracleKind::RelationalCheck
                    | OracleKind::ExactErrorVariant
                    | OracleKind::Snapshot
            )
        }
        ProbeFamily::ReturnValue => [
            OracleKind::ExactValue,
            OracleKind::WholeObjectEquality,
            OracleKind::RelationalCheck,
            OracleKind::Snapshot,
            OracleKind::SmokeOnly,
        ]
        .contains(&assertion.kind),
        ProbeFamily::CallDeletion => {
            matches!(
                assertion.kind,
                OracleKind::MockExpectation
                    | OracleKind::ExactValue
                    | OracleKind::RelationalCheck
                    | OracleKind::SmokeOnly
            ) || text.contains("assert")
                || text.contains("expect")
        }
        ProbeFamily::MatchArm => [
            OracleKind::ExactErrorVariant,
            OracleKind::ExactValue,
            OracleKind::RelationalCheck,
            OracleKind::Snapshot,
        ]
        .contains(&assertion.kind),
        ProbeFamily::StaticUnknown => false,
    }
}

fn probe_relative_oracle_strength(family: &ProbeFamily, assertion: &OracleFact) -> OracleStrength {
    match family {
        ProbeFamily::ErrorPath => match assertion.kind {
            OracleKind::ExactErrorVariant => OracleStrength::Strong,
            OracleKind::BroadError => assertion.strength.clone(),
            OracleKind::SmokeOnly => OracleStrength::Smoke,
            _ => assertion.strength.clone(),
        },
        ProbeFamily::ReturnValue
        | ProbeFamily::Predicate
        | ProbeFamily::FieldConstruction
        | ProbeFamily::MatchArm => match assertion.kind {
            OracleKind::ExactValue
            | OracleKind::ExactErrorVariant
            | OracleKind::WholeObjectEquality => OracleStrength::Strong,
            OracleKind::Snapshot
            | OracleKind::MockExpectation
            | OracleKind::RelationalCheck
            | OracleKind::BroadError => assertion.strength.clone(),
            OracleKind::SmokeOnly => OracleStrength::Smoke,
            OracleKind::Unknown => OracleStrength::Unknown,
        },
        ProbeFamily::SideEffect | ProbeFamily::CallDeletion => match assertion.kind {
            OracleKind::MockExpectation => assertion.strength.clone(),
            OracleKind::ExactValue | OracleKind::WholeObjectEquality => OracleStrength::Strong,
            OracleKind::RelationalCheck | OracleKind::BroadError => assertion.strength.clone(),
            OracleKind::SmokeOnly => OracleStrength::Smoke,
            OracleKind::ExactErrorVariant => OracleStrength::Medium,
            OracleKind::Snapshot => assertion.strength.clone(),
            OracleKind::Unknown => OracleStrength::Unknown,
        },
        ProbeFamily::StaticUnknown => OracleStrength::Unknown,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn reveal_evidence_keeps_assertionless_related_test_without_observe_signal() {
        let probe = probe(ProbeFamily::ReturnValue, "score");
        let test = test_with_assertions("score_returns_value", Vec::new());
        let (observe, discriminate, related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(observe.state, StageState::No);
        assert_eq!(discriminate.state, StageState::No);
        assert_eq!(related.len(), 1);
        assert_eq!(related[0].name, "score_returns_value");
        assert_eq!(related[0].oracle, None);
    }

    #[test]
    fn reveal_evidence_records_matching_assertions_and_sorts_related_tests() {
        let probe = probe(
            ProbeFamily::ErrorPath,
            "return Err(AuthError::RevokedToken);",
        );
        let late = test_with_assertions(
            "z_error_path",
            vec![oracle(
                "assert!(score(\"\").is_err());",
                OracleKind::BroadError,
                OracleStrength::Weak,
            )],
        );
        let early = test_with_assertions(
            "a_error_path",
            vec![oracle(
                "assert_matches!(score(\"\"), Err(AuthError::RevokedToken));",
                OracleKind::ExactErrorVariant,
                OracleStrength::Strong,
            )],
        );
        let (observe, discriminate, related) = reveal_evidence(
            &probe,
            &[
                (&late, RelationReason::DirectOwnerCall),
                (&early, RelationReason::DirectOwnerCall),
            ],
        );

        assert_eq!(observe.state, StageState::Yes);
        assert_eq!(discriminate.state, StageState::Yes);
        assert_eq!(related.len(), 2);
        assert_eq!(related[0].name, "a_error_path");
        assert_eq!(related[0].oracle_strength, OracleStrength::Strong);
        assert_eq!(related[1].name, "z_error_path");
    }

    #[test]
    fn reveal_evidence_ignores_unmatched_assertions() {
        let probe = probe(ProbeFamily::StaticUnknown, "opaque_changed_expr");
        let test = test_with_assertions(
            "opaque_behavior",
            vec![
                oracle(
                    "assert_eq!(unrelated, 3);",
                    OracleKind::Unknown,
                    OracleStrength::Unknown,
                ),
                oracle(
                    "assert!(other_value);",
                    OracleKind::Unknown,
                    OracleStrength::Unknown,
                ),
            ],
        );
        let (observe, discriminate, related) =
            reveal_evidence(&probe, &[(&test, RelationReason::WeakTokenSubstring)]);

        assert_eq!(observe.state, StageState::No);
        assert_eq!(discriminate.state, StageState::No);
        assert!(related.is_empty());
    }

    #[test]
    fn assertion_matching_accepts_token_family_and_single_assertion_fallbacks() {
        let token_assertion = oracle(
            "assert_eq!(score, 3);",
            OracleKind::Unknown,
            OracleStrength::Unknown,
        );
        let (matched, has_token) = assertion_matches_probe_detail(
            &["score".to_string()],
            &[],
            None,
            &ProbeFamily::StaticUnknown,
            &token_assertion,
            2,
        );
        assert!(matched, "token match must fire");
        assert!(has_token, "token match must set has_token_match");

        let family_assertion = oracle(
            "assert!(result.is_err());",
            OracleKind::BroadError,
            OracleStrength::Weak,
        );
        let (matched, has_token) = assertion_matches_probe_detail(
            &["err".to_string()],
            &[],
            None,
            &ProbeFamily::ErrorPath,
            &family_assertion,
            2,
        );
        assert!(matched, "family match must fire");
        assert!(!has_token, "family-only match must not set has_token_match");

        let fallback_assertion = oracle(
            "assert!(ran);",
            OracleKind::Unknown,
            OracleStrength::Unknown,
        );
        let (matched, has_token) = assertion_matches_probe_detail(
            &["run".to_string()],
            &[],
            None,
            &ProbeFamily::StaticUnknown,
            &fallback_assertion,
            1,
        );
        assert!(matched, "single-assertion fallback must fire");
        assert!(
            !has_token,
            "escape-hatch-only match must not set has_token_match"
        );

        let (matched, _) = assertion_matches_probe_detail(
            &["run".to_string()],
            &[],
            None,
            &ProbeFamily::StaticUnknown,
            &fallback_assertion,
            2,
        );
        assert!(!matched, "fallback must not fire for assertion_count > 1");
    }

    // RIPR-SPEC-0106 Control 2 (SIBLING-VARIANT): a Negative-pinning assertion
    // must not match a TooLarge error_path probe.
    #[test]
    fn sibling_variant_assertion_does_not_match_too_large_probe() {
        let sibling_assertion = oracle(
            "assert_eq!(err, CalcError::Negative);",
            OracleKind::ExactErrorVariant,
            OracleStrength::Strong,
        );
        // Probe expression names TooLarge; error_path_variant = Some("TooLarge").
        let (matched, has_token) = assertion_matches_probe_detail(
            &["CalcError".to_string(), "TooLarge".to_string()],
            &[],
            Some("TooLarge"),
            &ProbeFamily::ErrorPath,
            &sibling_assertion,
            2,
        );
        assert!(
            !matched,
            "sibling-variant Negative assertion must not match TooLarge probe"
        );
        assert!(
            !has_token,
            "sibling-variant assertion must not set has_token_match for TooLarge probe"
        );
    }

    // RIPR-SPEC-0106 Control 1 (POSITIVE): exact variant assertion DOES match
    // the probe when the specific variant token is present.
    #[test]
    fn exact_variant_assertion_matches_matching_probe() {
        let exact_assertion = oracle(
            "assert_eq!(err, CalcError::Negative);",
            OracleKind::ExactErrorVariant,
            OracleStrength::Strong,
        );
        let (matched, has_token) = assertion_matches_probe_detail(
            &["CalcError".to_string(), "Negative".to_string()],
            &[],
            Some("Negative"),
            &ProbeFamily::ErrorPath,
            &exact_assertion,
            2,
        );
        assert!(
            matched,
            "exact variant assertion must match the probe when variant token matches"
        );
        assert!(
            has_token,
            "matching variant assertion must set has_token_match"
        );
    }

    #[test]
    fn discriminate_evidence_names_strength_and_oracle_kind() {
        let cases = [
            (
                OracleStrength::Strong,
                OracleKind::ExactErrorVariant,
                ProbeFamily::ErrorPath,
                StageState::Yes,
                "Strong oracle found: exact error variant assertion",
            ),
            (
                OracleStrength::Strong,
                OracleKind::WholeObjectEquality,
                ProbeFamily::ReturnValue,
                StageState::Yes,
                "Strong oracle found: whole-object equality assertion",
            ),
            (
                OracleStrength::Strong,
                OracleKind::ExactValue,
                ProbeFamily::ReturnValue,
                StageState::Yes,
                "Strong oracle found: exact value or pattern assertion",
            ),
            (
                OracleStrength::Medium,
                OracleKind::Snapshot,
                ProbeFamily::ReturnValue,
                StageState::Weak,
                "Medium oracle found: snapshot assertion observes the changed behavior",
            ),
            (
                OracleStrength::Medium,
                OracleKind::MockExpectation,
                ProbeFamily::SideEffect,
                StageState::Weak,
                "Medium oracle found: mock or expectation observes the changed behavior",
            ),
            (
                OracleStrength::Medium,
                OracleKind::ExactValue,
                ProbeFamily::ReturnValue,
                StageState::Weak,
                "Medium oracle found: property or partial structural assertion",
            ),
            (
                OracleStrength::Weak,
                OracleKind::BroadError,
                ProbeFamily::ErrorPath,
                StageState::Weak,
                "Only broad error oracle found; is_err() does not discriminate exact error variants",
            ),
            (
                OracleStrength::Weak,
                OracleKind::BroadError,
                ProbeFamily::ReturnValue,
                StageState::Weak,
                "Only broad error oracle found; it may not discriminate the changed behavior exactly",
            ),
            (
                OracleStrength::Weak,
                OracleKind::RelationalCheck,
                ProbeFamily::Predicate,
                StageState::Weak,
                "Only relational oracle found; it may not discriminate the changed value exactly",
            ),
            (
                OracleStrength::Weak,
                OracleKind::ExactValue,
                ProbeFamily::ReturnValue,
                StageState::Weak,
                "Only weak oracle found, such as a broad relational assertion or non-empty check",
            ),
            (
                OracleStrength::Smoke,
                OracleKind::SmokeOnly,
                ProbeFamily::ReturnValue,
                StageState::Weak,
                "Only smoke oracle found, such as unwrap/expect or execution without a discriminator",
            ),
            (
                OracleStrength::None,
                OracleKind::Unknown,
                ProbeFamily::ReturnValue,
                StageState::No,
                "No assertion found on related tests",
            ),
            (
                OracleStrength::Unknown,
                OracleKind::Unknown,
                ProbeFamily::ReturnValue,
                StageState::Unknown,
                "Assertions exist, but oracle strength is unknown",
            ),
        ];

        for (strength, kind, family, state, summary) in cases {
            let evidence = build_discriminate_evidence(&strength, &kind, &family, false);
            assert_eq!(evidence.state, state);
            assert_eq!(evidence.summary, summary);
        }
    }

    #[test]
    fn oracle_family_matching_covers_family_specific_shapes() {
        assert!(oracle_matches_family(
            &ProbeFamily::ErrorPath,
            &oracle(
                "assert_matches!(result, Err(AuthError::RevokedToken));",
                OracleKind::ExactErrorVariant,
                OracleStrength::Strong,
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::ErrorPath,
            &oracle(
                "assert!(result.is_err());",
                OracleKind::BroadError,
                OracleStrength::Weak
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::ErrorPath,
            &oracle(
                "assert!(matches!(result, Err(_)));",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::ErrorPath,
            &oracle(
                "assert_eq!(kind, Error::Denied);",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::SideEffect,
            &oracle(
                "mock.expect_send();",
                OracleKind::MockExpectation,
                OracleStrength::Medium
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::SideEffect,
            &oracle(
                "assert!(event.saved);",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::SideEffect,
            &oracle(
                "assert!(event.published);",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::FieldConstruction,
            &oracle(
                "assert_eq!(item.id, 3);",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::FieldConstruction,
            &oracle(
                "assert_debug_snapshot!(item);",
                OracleKind::Snapshot,
                OracleStrength::Medium
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::Predicate,
            &oracle(
                "assert!(value >= 3);",
                OracleKind::RelationalCheck,
                OracleStrength::Weak
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::ReturnValue,
            &oracle(
                "assert_eq!(score(), 3);",
                OracleKind::ExactValue,
                OracleStrength::Strong
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::ReturnValue,
            &oracle(
                "score().unwrap();",
                OracleKind::SmokeOnly,
                OracleStrength::Smoke
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::CallDeletion,
            &oracle(
                "assert!(sent);",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::CallDeletion,
            &oracle(
                "expect_send_called();",
                OracleKind::Unknown,
                OracleStrength::Unknown
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::CallDeletion,
            &oracle(
                "mock.expect_send();",
                OracleKind::MockExpectation,
                OracleStrength::Medium
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::MatchArm,
            &oracle(
                "assert_matches!(kind, Ready);",
                OracleKind::ExactErrorVariant,
                OracleStrength::Strong
            )
        ));
        assert!(oracle_matches_family(
            &ProbeFamily::MatchArm,
            &oracle(
                "assert_eq!(kind, Ready);",
                OracleKind::ExactValue,
                OracleStrength::Strong
            )
        ));
        assert!(!oracle_matches_family(
            &ProbeFamily::StaticUnknown,
            &oracle(
                "assert_eq!(value, 3);",
                OracleKind::ExactValue,
                OracleStrength::Strong
            )
        ));
    }

    #[test]
    fn probe_relative_oracle_strength_preserves_family_overrides() {
        let cases = [
            (
                ProbeFamily::ErrorPath,
                oracle("exact", OracleKind::ExactErrorVariant, OracleStrength::Weak),
                OracleStrength::Strong,
            ),
            (
                ProbeFamily::ErrorPath,
                oracle("broad", OracleKind::BroadError, OracleStrength::Weak),
                OracleStrength::Weak,
            ),
            (
                ProbeFamily::ErrorPath,
                oracle("smoke", OracleKind::SmokeOnly, OracleStrength::Strong),
                OracleStrength::Smoke,
            ),
            (
                ProbeFamily::ErrorPath,
                oracle("snapshot", OracleKind::Snapshot, OracleStrength::Medium),
                OracleStrength::Medium,
            ),
            (
                ProbeFamily::ReturnValue,
                oracle("exact", OracleKind::ExactValue, OracleStrength::Weak),
                OracleStrength::Strong,
            ),
            (
                ProbeFamily::Predicate,
                oracle("snapshot", OracleKind::Snapshot, OracleStrength::Medium),
                OracleStrength::Medium,
            ),
            (
                ProbeFamily::FieldConstruction,
                oracle("smoke", OracleKind::SmokeOnly, OracleStrength::Strong),
                OracleStrength::Smoke,
            ),
            (
                ProbeFamily::MatchArm,
                oracle("unknown", OracleKind::Unknown, OracleStrength::Strong),
                OracleStrength::Unknown,
            ),
            (
                ProbeFamily::SideEffect,
                oracle("mock", OracleKind::MockExpectation, OracleStrength::Medium),
                OracleStrength::Medium,
            ),
            (
                ProbeFamily::SideEffect,
                oracle(
                    "exact",
                    OracleKind::WholeObjectEquality,
                    OracleStrength::Weak,
                ),
                OracleStrength::Strong,
            ),
            (
                ProbeFamily::CallDeletion,
                oracle("rel", OracleKind::RelationalCheck, OracleStrength::Weak),
                OracleStrength::Weak,
            ),
            (
                ProbeFamily::CallDeletion,
                oracle("smoke", OracleKind::SmokeOnly, OracleStrength::Strong),
                OracleStrength::Smoke,
            ),
            (
                ProbeFamily::SideEffect,
                oracle(
                    "exact_error",
                    OracleKind::ExactErrorVariant,
                    OracleStrength::Strong,
                ),
                OracleStrength::Medium,
            ),
            (
                ProbeFamily::SideEffect,
                oracle("snapshot", OracleKind::Snapshot, OracleStrength::Weak),
                OracleStrength::Weak,
            ),
            (
                ProbeFamily::SideEffect,
                oracle("unknown", OracleKind::Unknown, OracleStrength::Strong),
                OracleStrength::Unknown,
            ),
            (
                ProbeFamily::StaticUnknown,
                oracle("exact", OracleKind::ExactValue, OracleStrength::Strong),
                OracleStrength::Unknown,
            ),
        ];

        for (family, assertion, expected) in cases {
            assert_eq!(
                probe_relative_oracle_strength(&family, &assertion),
                expected
            );
        }
    }

    fn probe(family: ProbeFamily, expression: &str) -> Probe {
        Probe {
            id: ProbeId("probe:test".to_string()),
            location: SourceLocation::new("src/lib.rs", 1, 1),
            owner: None,
            family,
            delta: DeltaKind::Value,
            before: None,
            after: None,
            expression: expression.to_string(),
            expected_sinks: Vec::new(),
            required_oracles: Vec::new(),
        }
    }

    fn test_with_assertions(name: &str, assertions: Vec<OracleFact>) -> TestSummary {
        TestSummary {
            name: name.to_string(),
            file: PathBuf::from("tests/value.rs"),
            start_line: 1,
            end_line: 3,
            body: "score();".to_string(),
            calls: Vec::new(),
            assertions,
            literals: Vec::new(),
            attrs: Vec::new(),
        }
    }

    fn oracle(text: &str, kind: OracleKind, strength: OracleStrength) -> OracleFact {
        OracleFact {
            line: 2,
            text: text.to_string(),
            kind,
            strength,
            observed_tokens: extract_identifier_tokens(text),
        }
    }

    // --- RIPR-SPEC-0093 arm-blind downgrade ---

    /// A MatchArm probe whose expression has no extractable tokens (e.g. `None`
    /// is filtered) and whose single related test has an ExactValue oracle for a
    /// DIFFERENT arm must emit weakly_exposed with observation_unverified.
    #[test]
    fn match_arm_probe_without_token_match_downgrades_discriminate_to_weak() {
        // probe expression "None => 0," — None is filtered, 0 is not alpha
        let probe = probe(ProbeFamily::MatchArm, "None => 0,");
        let test = test_with_assertions(
            "some_arm_returns_incremented_value",
            vec![oracle(
                "assert_eq!(reason(Some(5)), 6);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(observe.state, StageState::Yes, "observe must still fire");
        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "discriminate must be downgraded to Weak (observation_unverified)"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "summary must name the reason: got `{}`",
            discriminate.summary
        );
    }

    /// A MatchArm probe whose expression DOES have a token that appears in the
    /// assertion text (token_match) must stay exposed (StageState::Yes).
    #[test]
    fn match_arm_probe_with_token_match_keeps_discriminate_yes() {
        // probe expression "Status::Idle => 0," — Idle and Status are extractable
        let probe = probe(ProbeFamily::MatchArm, "Status::Idle => 0,");
        let test = test_with_assertions(
            "idle_arm_returns_zero",
            vec![oracle(
                "assert_eq!(classify(Status::Idle), 0);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(observe.state, StageState::Yes);
        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "token_match on Idle must keep discriminate Yes (no over-correction)"
        );
    }

    /// A ReturnValue probe whose single related test has a family-matching assertion
    /// but NO token referencing the changed expression must downgrade to Weak.
    /// This inverts the former bug-locking test
    /// `non_match_arm_probe_family_match_only_keeps_discriminate_yes`.
    #[test]
    fn return_value_family_match_only_without_token_downgrades_discriminate_to_weak() {
        // "value + 1" — tokens: ["value"] (len 5). Assertion "assert_eq!(compute(), 42);"
        // has no occurrence of "value", so has_token_match=false.
        let probe = probe(ProbeFamily::ReturnValue, "value + 1");
        let test = test_with_assertions(
            "returns_incremented",
            vec![oracle(
                "assert_eq!(compute(), 42);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "ReturnValue probe with no token_match must downgrade to Weak (observation_unverified)"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "summary must name the reason: got `{}`",
            discriminate.summary
        );
    }

    /// A ReturnValue probe whose assertion text CONTAINS a token from the probe
    /// expression must stay exposed (StageState::Yes) — no over-correction.
    #[test]
    fn return_value_with_token_match_keeps_discriminate_yes() {
        // "score + 1" — tokens: ["score"] (len 5). Assertion contains "score".
        let probe = probe(ProbeFamily::ReturnValue, "score + 1");
        let test = test_with_assertions(
            "score_incremented",
            vec![oracle(
                "assert_eq!(score(), 6);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "ReturnValue probe with token_match must stay Yes (no over-correction)"
        );
    }

    /// A FieldConstruction probe whose single assertion has a dot (family_match)
    /// but no token referencing the specific changed field must downgrade to Weak.
    #[test]
    fn field_construction_family_match_only_without_token_downgrades_to_weak() {
        // "priority: 3" — tokens: ["priority"] (len 8). Assertion "assert_eq!(item.id, 3);"
        // does not contain "priority".
        let probe = probe(ProbeFamily::FieldConstruction, "priority: 3");
        let test = test_with_assertions(
            "item_has_id",
            vec![oracle(
                "assert_eq!(item.id, 3);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "FieldConstruction probe with no token_match must downgrade to Weak"
        );
    }

    /// A FieldConstruction probe whose assertion references the exact changed field
    /// must stay exposed (StageState::Yes).
    #[test]
    fn field_construction_with_token_match_keeps_discriminate_yes() {
        // "priority: 3" — tokens: ["priority"]. Assertion "assert_eq!(item.priority, 3);"
        // contains "priority".
        let probe = probe(ProbeFamily::FieldConstruction, "priority: 3");
        let test = test_with_assertions(
            "item_has_priority",
            vec![oracle(
                "assert_eq!(item.priority, 3);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "FieldConstruction probe with token_match on priority must stay Yes"
        );
    }

    /// A SideEffect probe whose single PLAIN assertion has neither a token
    /// referencing the changed effect NOR an effect-observer kind (no mock,
    /// snapshot, or whole-object) must emit observation_unverified. This is the
    /// genuinely-blind case: the assertion only fired via the single-assertion
    /// escape hatch.
    #[test]
    fn side_effect_plain_assertion_without_token_or_observer_emits_observation_unverified() {
        // "send_notification(user_id)" — tokens: ["send", "notification", "user"].
        // Assertion "assert!(ran);" contains none of those, and is not a mock,
        // snapshot, or whole-object observer.
        let probe = probe(ProbeFamily::SideEffect, "send_notification(user_id)");
        let test = test_with_assertions(
            "ran",
            vec![oracle(
                "assert!(ran);",
                OracleKind::Unknown,
                OracleStrength::Unknown,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "SideEffect probe with no token and no effect observer must downgrade to Weak"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "plain non-observing assertion must emit observation_unverified: got `{}`",
            discriminate.summary
        );
    }

    /// REGRESSION LOCK (#1216 second-pass): a SideEffect probe whose single
    /// matched assertion is a genuine MOCK EXPECTATION that kind-matches the seam
    /// but shares NO token with the probe expression must NOT emit
    /// observation_unverified. The mock observes the effect; downgrading it to
    /// observation_unverified would be a false weakening. (It may still be Weak
    /// via the Medium-strength path, but never via observation_unverified.)
    #[test]
    fn side_effect_mock_observer_without_token_clears_observation_unverified() {
        // "send_notification(user_id)" — tokens: ["send", "notification", "user"].
        // Assertion "mock.verify();" shares no token but is a MockExpectation,
        // i.e. a genuine effect observer.
        let probe = probe(ProbeFamily::SideEffect, "send_notification(user_id)");
        let test = test_with_assertions(
            "notification_checked",
            vec![oracle(
                "mock.verify();",
                OracleKind::MockExpectation,
                OracleStrength::Medium,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "a genuine mock observer must clear observation_unverified even without a token: got `{}`",
            discriminate.summary
        );
    }

    /// REGRESSION LOCK (#1216 second-pass): a CallDeletion probe whose single
    /// matched assertion is a whole-object equality (a genuine effect observer)
    /// sharing no token must NOT emit observation_unverified. Whole-object
    /// equality captures the resulting persisted state, so it observes the
    /// effect even without naming the changed call token.
    #[test]
    fn call_deletion_whole_object_observer_without_token_clears_observation_unverified() {
        // "persist_audit(record)" — tokens: ["persist", "audit", "record"].
        // Assertion "assert_eq!(store, expected);" shares no token but is a
        // WholeObjectEquality effect observer (Strong).
        let probe = probe(ProbeFamily::CallDeletion, "persist_audit(record)");
        let test = test_with_assertions(
            "store_matches_expected",
            vec![oracle(
                "assert_eq!(store, expected);",
                OracleKind::WholeObjectEquality,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "a whole-object effect observer must clear observation_unverified even without a token: got `{}`",
            discriminate.summary
        );
    }

    /// A VALUE family (ReturnValue) must NOT treat a mock/whole-object as an
    /// observation confirmation — only a token_match confirms value families.
    /// This guards against the effect-family relaxation leaking into value
    /// families (the point of #1200/#1216: an ExactValue/whole-object oracle
    /// does not kind-match a value seam's specific sub-expression).
    #[test]
    fn return_value_whole_object_without_token_still_emits_observation_unverified() {
        // "base * SCALE" — tokens: ["base", "SCALE"]. Assertion
        // "assert_eq!(result, expected);" is WholeObjectEquality but shares no
        // token; for a VALUE family this must NOT clear observation_unverified.
        let probe = probe(ProbeFamily::ReturnValue, "base * SCALE");
        let test = test_with_assertions(
            "result_matches_expected",
            vec![oracle(
                "assert_eq!(result, expected);",
                OracleKind::WholeObjectEquality,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "ReturnValue (value family) with no token must stay observation_unverified"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "value family must not be cleared by an effect-observer kind: got `{}`",
            discriminate.summary
        );
    }

    /// A SideEffect probe whose assertion references a specific token from the
    /// changed expression must not be downgraded by observation_unverified.
    #[test]
    fn side_effect_with_token_match_keeps_discriminate_not_unverified() {
        // "emit_payment_event(tx)" — tokens: ["emit_payment_event", "tx"] but
        // only "emit_payment_event" (len > 3, well, len 17) would match.
        // Assertion "mock.expect_emit_payment_event();" contains "emit_payment_event".
        let probe = probe(ProbeFamily::SideEffect, "emit_payment_event(tx)");
        let test = test_with_assertions(
            "payment_event_emitted",
            vec![oracle(
                "mock.expect_emit_payment_event();",
                OracleKind::MockExpectation,
                OracleStrength::Medium,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        // MockExpectation yields OracleStrength::Medium → StageState::Weak via
        // the existing Medium oracle path, NOT via observation_unverified.
        // The key invariant: observation_unverified must NOT fire when there IS
        // a token_match — so the summary must not contain "observation_unverified".
        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "token-matched SideEffect must not emit observation_unverified: got `{}`",
            discriminate.summary
        );
    }

    /// A CallDeletion probe whose single assertion fires family_match via
    /// `text.contains("assert")` but contains no token from the changed call
    /// expression must downgrade to Weak.
    #[test]
    fn call_deletion_family_match_only_without_token_downgrades_to_weak() {
        // "log_audit_event(record)" — tokens: ["audit", "event", "record"] (all len > 3).
        // Assertion "assert!(result.is_ok());" does not contain any of those.
        let probe = probe(ProbeFamily::CallDeletion, "log_audit_event(record)");
        let test = test_with_assertions(
            "result_ok",
            vec![oracle(
                "assert!(result.is_ok());",
                OracleKind::BroadError,
                OracleStrength::Weak,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "CallDeletion probe with no token_match must downgrade to Weak"
        );
    }

    /// A CallDeletion probe whose assertion text contains the full call token
    /// must not be downgraded by observation_unverified.
    #[test]
    fn call_deletion_with_token_match_does_not_emit_observation_unverified() {
        // "log_audit_event(record)" — tokens: ["log_audit_event", "record"].
        // Assertion "assert!(log_audit_event_was_called);" contains
        // "log_audit_event" (the full call token).
        let probe = probe(ProbeFamily::CallDeletion, "log_audit_event(record)");
        let test = test_with_assertions(
            "audit_event_logged",
            vec![oracle(
                "assert!(log_audit_event_was_called);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "token-matched CallDeletion must not emit observation_unverified: got `{}`",
            discriminate.summary
        );
    }

    /// MatchArm: type-blind token match — `Mode::Warm` assertion must NOT clear
    /// observation_unverified for a `Mode::Frozen` probe (Part B regression lock).
    #[test]
    fn match_arm_sibling_qualifier_does_not_clear_observation_unverified() {
        // probe expression "Mode::Frozen => -1," — tokens: ["Mode", "Frozen"].
        // Assertion "assert_eq!(classify(Mode::Warm), 1);" contains "Mode" (len 4)
        // but NOT "Frozen" (the variant token). With variant-scoped token_match,
        // "Mode" alone must not clear observation_unverified.
        let probe = probe(ProbeFamily::MatchArm, "Mode::Frozen => -1,");
        let test = test_with_assertions(
            "warm_arm_returns_one",
            vec![oracle(
                "assert_eq!(classify(Mode::Warm), 1);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "Mode::Warm assertion must not confirm Mode::Frozen arm (sibling-qualifier hole)"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "summary must name the reason: got `{}`",
            discriminate.summary
        );
    }

    /// MatchArm: assertion containing the specific VARIANT token confirms the arm.
    #[test]
    fn match_arm_variant_token_match_keeps_discriminate_yes() {
        // probe expression "Mode::Frozen => -1," — variant "Frozen" appears in assertion.
        let probe = probe(ProbeFamily::MatchArm, "Mode::Frozen => -1,");
        let test = test_with_assertions(
            "frozen_arm_returns_minus_one",
            vec![oracle(
                "assert_eq!(classify(Mode::Frozen), -1);",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "Frozen variant in assertion must confirm observation (no over-correction)"
        );
    }

    // --- Predicate must NOT be affected; ErrorPath now requires token/variant confirmation ---

    /// Predicate probes do not require token confirmation and must not be
    /// affected by the observation_unverified logic.
    #[test]
    fn predicate_probe_family_match_only_keeps_discriminate_yes() {
        let probe = probe(ProbeFamily::Predicate, "x > 0");
        let test = test_with_assertions(
            "check_positive",
            vec![oracle(
                "assert!(value >= 3);",
                OracleKind::RelationalCheck,
                OracleStrength::Weak,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        // RelationalCheck → OracleStrength::Weak → StageState::Weak, but NOT
        // via observation_unverified.
        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "Predicate probe must not emit observation_unverified: got `{}`",
            discriminate.summary
        );
    }

    // --- RIPR-SPEC-0107: ErrorPath now requires variant/token confirmation ---

    /// RIPR-SPEC-0107 Control A (REPRO): an ErrorPath probe with ONLY a broad
    /// `is_err()` oracle and a sibling `ExactValue` result (no variant-pinning
    /// oracle) must downgrade to `weakly_exposed` via `observation_unverified`.
    /// This is the fake-clean being fixed: the sibling oracle cannot confirm the
    /// changed error variant is specifically observed.
    #[test]
    fn error_path_broad_oracle_only_downgrades_discriminate_to_weak() {
        let probe = probe(ProbeFamily::ErrorPath, "Err(AuthError::RevokedToken)");
        let test = test_with_assertions(
            "revoked_token_fails",
            vec![oracle(
                "assert!(result.is_err());",
                OracleKind::BroadError,
                OracleStrength::Weak,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "ErrorPath probe with only a broad is_err() oracle must downgrade to Weak (observation_unverified)"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "broad is_err() must emit observation_unverified for ErrorPath: got `{}`",
            discriminate.summary
        );
    }

    /// RIPR-SPEC-0107 Control A continued: an ErrorPath probe with a sibling
    /// `ExactValue` oracle (no variant token in assertion) must also downgrade.
    /// An `assert_eq!(validate_or_default(""), "guest")` oracle credits the
    /// happy-path return value, not the error variant — it must NOT promote
    /// the error_path seam to `exposed`.
    #[test]
    fn error_path_sibling_exact_value_oracle_downgrades_discriminate_to_weak() {
        let probe = probe(ProbeFamily::ErrorPath, "Err(ParseError::TooLong(len))");
        let test = test_with_assertions(
            "default_value_returned",
            vec![oracle(
                "assert_eq!(validate_or_default(\"\"), \"guest\");",
                OracleKind::ExactValue,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Weak,
            "ErrorPath probe with a sibling ExactValue oracle (no variant token) must downgrade to Weak"
        );
        assert!(
            discriminate.summary.contains("observation_unverified"),
            "sibling ExactValue oracle must emit observation_unverified for ErrorPath: got `{}`",
            discriminate.summary
        );
    }

    /// RIPR-SPEC-0107 Control B (MUST-NOT-OVER-CORRECT): an ErrorPath probe
    /// backed by a real variant-pinning oracle (`assert_eq!(err, ParseError::TooLong(12))`)
    /// must STAY `exposed`. The RIPR-SPEC-0106/#1252 variant-credit path sets
    /// `has_token_match=true` for a genuine `ExactErrorVariant` oracle whose
    /// text contains the probe's specific variant token, clearing
    /// `observation_unverified`.
    #[test]
    fn error_path_exact_variant_oracle_keeps_discriminate_yes() {
        // Probe: Err(ParseError::TooLong(len)) — variant token "TooLong".
        // Assertion: assert_eq!(err, ParseError::TooLong(12)) — contains "TooLong".
        let probe = probe(ProbeFamily::ErrorPath, "Err(ParseError::TooLong(len))");
        let test = test_with_assertions(
            "too_long_error_pinned",
            vec![oracle(
                "assert_eq!(err, ParseError::TooLong(12));",
                OracleKind::ExactErrorVariant,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "ErrorPath probe with a genuine variant-pinning ExactErrorVariant oracle must stay exposed (no over-correction)"
        );
        assert!(
            !discriminate.summary.contains("observation_unverified"),
            "variant-confirmed oracle must NOT emit observation_unverified: got `{}`",
            discriminate.summary
        );
    }

    /// RIPR-SPEC-0107 Control B continued: `matches!(err, ParseError::TooLong(_))`
    /// also pins the variant token and must keep the seam `exposed`.
    #[test]
    fn error_path_matches_variant_oracle_keeps_discriminate_yes() {
        let probe = probe(ProbeFamily::ErrorPath, "Err(ParseError::TooLong(len))");
        let test = test_with_assertions(
            "too_long_error_matches",
            vec![oracle(
                "assert!(matches!(err, ParseError::TooLong(_)));",
                OracleKind::ExactErrorVariant,
                OracleStrength::Strong,
            )],
        );
        let (_observe, discriminate, _related) =
            reveal_evidence(&probe, &[(&test, RelationReason::DirectOwnerCall)]);

        assert_eq!(
            discriminate.state,
            StageState::Yes,
            "ErrorPath probe with a matches! variant oracle must stay exposed"
        );
    }

    /// RIPR-SPEC-0107 Control C (CROSS-SURFACE / IS-EFFECT-FAMILY guard):
    /// `is_effect_family` must return false for `ErrorPath`, ensuring that a
    /// mock/snapshot cannot clear `observation_unverified` for an error seam.
    /// Only a genuine variant-pinning oracle may confirm it.
    #[test]
    fn error_path_is_not_effect_family() {
        assert!(
            !is_effect_family(&ProbeFamily::ErrorPath),
            "ErrorPath must not be classified as an effect family (mocks must not clear observation_unverified)"
        );
    }
}