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
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
use super::config::LspAnalysisConfig;
use super::gap_artifacts::{
    GapArtifactKind, GapArtifactRejection, GapArtifactValidationContext, validate_gap_artifact,
    validate_workspace_gap_artifact_report,
};
use super::state::{AnalysisSnapshot, RefreshMetadata};
use super::uri::file_uri_for_path;
use crate::analysis::ClassifiedSeam;
use crate::analysis::inventory_classified_seams_at_with_config;
use crate::analysis::seams::SeamGripClass;
use crate::app::check_workspace_with_config;
use crate::config::{ConfigSeverity, SeverityConfig};
use crate::domain::{Finding, LanguageId, LanguageStatus, RelatedTest};
use crate::output::gap_decision_ledger::{
    DEFAULT_GAP_DECISION_LEDGER_OUT, GapRecord, projection_eligible,
};
use crate::output::next_step::reconcile_next_step;
use crate::output::preview_actionability::{
    preview_actionability_for, preview_actionability_json_value,
};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use tower_lsp_server::ls_types::{
    Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, Location, NumberOrString,
    Position, Range, Uri,
};

const MAX_DIAGNOSTIC_RANGE_WIDTH: u32 = 120;

pub struct DiagnosticBatch {
    pub uri: Uri,
    pub diagnostics: Vec<Diagnostic>,
}

pub(super) struct WorkspaceDiagnostics {
    pub(super) snapshot: AnalysisSnapshot,
    pub(super) batches: Vec<DiagnosticBatch>,
}

pub(super) struct DiagnosticRefreshPlan {
    pub(super) publish_batches: Vec<DiagnosticBatch>,
    pub(super) clear_uris: Vec<Uri>,
    pub(super) current_uris: BTreeSet<Uri>,
}

pub(super) fn diagnostic_refresh_plan(
    previous_uris: &BTreeSet<Uri>,
    batches: Vec<DiagnosticBatch>,
) -> DiagnosticRefreshPlan {
    let current_uris = batches
        .iter()
        .map(|batch| batch.uri.clone())
        .collect::<BTreeSet<_>>();
    let clear_uris = previous_uris
        .difference(&current_uris)
        .cloned()
        .collect::<Vec<_>>();
    DiagnosticRefreshPlan {
        publish_batches: batches,
        clear_uris,
        current_uris,
    }
}

pub(super) fn take_all_uris(uris: &mut BTreeSet<Uri>) -> Vec<Uri> {
    let cleared = uris.iter().cloned().collect::<Vec<_>>();
    uris.clear();
    cleared
}

pub fn workspace_diagnostic_batches(root: &Path) -> Result<Vec<DiagnosticBatch>, String> {
    workspace_diagnostic_batches_with_config(root, &LspAnalysisConfig::default())
}

pub(super) fn workspace_diagnostic_batches_with_config(
    root: &Path,
    config: &LspAnalysisConfig,
) -> Result<Vec<DiagnosticBatch>, String> {
    Ok(workspace_diagnostics_with_config(root, config, false)?.batches)
}

/// Run workspace diagnostics.
///
/// When `defer_seam_inventory` is `true` (the default on interactive
/// `did_open`/`did_save` refreshes), the expensive full-repo seam inventory
/// (`inventory_classified_seams_at_with_config`) is skipped and the snapshot
/// carries `seams_deferred = true` with `run_status = "seams_deferred"`.
/// Diff-scoped findings are always produced — they are fast and complete.
///
/// When `defer_seam_inventory` is `false` (the explicit
/// `ripr.refreshDiagnostics` path), the seam inventory runs as before and the
/// snapshot transitions to `full` (or `limited`/`stale`/`cache_limited` per
/// existing rules) with seam diagnostics present.
pub(super) fn workspace_diagnostics_with_config(
    root: &Path,
    config: &LspAnalysisConfig,
    defer_seam_inventory: bool,
) -> Result<WorkspaceDiagnostics, String> {
    let input = config.check_input(root);
    let output = check_workspace_with_config(input, config.repo_config())
        .map_err(|err| format!("workspace analysis failed: {err}"))?;
    let root = output.root;
    let base = output.base;
    let mode = output.mode;
    let findings = output.findings;

    // Validate gap artifacts first so we can determine run status before
    // assembling diagnostics. Run status governs severity downgrade/suppression
    // policy: finding WARNINGs become INFORMATION and gap-record diagnostics are
    // suppressed entirely when the run is not "full" (stale/cache_limited/limited).
    // This surfaces the limited state via `ripr.collectWorkspaceStatus`, not
    // per-file spam. See RIPR-SPEC-0076 diagnostics policy.
    let gap_artifact_report =
        validate_workspace_gap_artifact_report(&root, config.repo_config().languages().enabled());
    let run_status = snapshot_run_status(
        &findings,
        &gap_artifact_report.rejections,
        defer_seam_inventory,
    );
    let is_full_run = run_status == "full";

    let mut grouped = BTreeMap::<Uri, Vec<Diagnostic>>::new();
    for finding in &findings {
        let path = absolute_finding_path(&root, finding);
        let uri = file_uri_for_path(&path)?;
        let mut diagnostic =
            diagnostic_for_finding_with_config(&root, finding, config.repo_config().severity());
        // Policy: clamp advisory findings to INFORMATION (never WARNING).
        // Also downgrade WARNING to INFORMATION when run is not "full".
        if diagnostic.severity == Some(DiagnosticSeverity::WARNING)
            && (finding_is_advisory(finding) || !is_full_run)
        {
            diagnostic.severity = Some(DiagnosticSeverity::INFORMATION);
        }
        grouped.entry(uri).or_default().push(diagnostic);
    }

    // Repo seam evidence diagnostics. Enabled by built-in defaults for the
    // saved-workspace editor model; explicit LSP options or repo policy can
    // still disable it for quieter or larger workspaces.
    //
    // Performance: `inventory_classified_seams_at_with_config` walks ALL
    // production Rust files — 336s cold / 31s warm on this repo — so it
    // MUST NOT run on the interactive did_open/did_save path. When
    // `defer_seam_inventory` is true the entire block is skipped and the
    // snapshot is marked `seams_deferred`. The explicit
    // `ripr.refreshDiagnostics` command sets `defer_seam_inventory = false`
    // to compute seams on demand (RIPR-SPEC-0105).
    //
    // Reliability: a seam-walk failure is downgraded to "no seam
    // diagnostics this refresh", not a hard failure. The opt-in
    // feature must not take down baseline Finding diagnostics if
    // some unrelated repo file confuses the walker. Caught by
    // chatgpt-codex on PR #241.
    //
    // Seam diagnostics severity policy: structural grip-class signals,
    // not gap-record repair packets — the WARNING/INFORMATION mapping
    // is owned by SeverityConfig. When run is not full, seam WARNINGs
    // downgrade to INFORMATION. The exception is documented here.
    let classified_seams = if !defer_seam_inventory
        && config.enable_seam_diagnostics
        && config
            .repo_config()
            .languages()
            .enabled()
            .contains(&LanguageId::Rust)
    {
        match inventory_classified_seams_at_with_config(&root, config.repo_config()) {
            Ok((seams, _)) => {
                seams
                    .into_iter()
                    .filter(|entry| {
                        // Drop entries that won't produce a published
                        // diagnostic so `is_consistent` keeps counting
                        // the snapshot accurately. URI-resolution
                        // failures are silent here on purpose: they
                        // are operational noise, not analysis errors.
                        if diagnostic_severity_for_grip_class_with_config(
                            entry.class,
                            config.repo_config().severity(),
                        )
                        .is_none()
                        {
                            return false;
                        }
                        let path = absolute_seam_path(&root, &entry.seam);
                        let Ok(uri) = file_uri_for_path(&path) else {
                            return false;
                        };
                        if let Some(mut diagnostic) = diagnostic_for_classified_seam_with_config(
                            &root,
                            entry,
                            config.repo_config().severity(),
                        ) {
                            // Policy: limited/stale run downgrades seam WARNINGs to INFORMATION.
                            if !is_full_run
                                && diagnostic.severity == Some(DiagnosticSeverity::WARNING)
                            {
                                diagnostic.severity = Some(DiagnosticSeverity::INFORMATION);
                            }
                            grouped.entry(uri).or_default().push(diagnostic);
                            true
                        } else {
                            false
                        }
                    })
                    .collect()
            }
            Err(err) => {
                eprintln!("ripr lsp: seam diagnostics skipped this refresh: {err}");
                Vec::new()
            }
        }
    } else {
        Vec::new()
    };

    // Policy: gap-record diagnostics are suppressed entirely when run is not
    // "full" (stale/cache_limited/limited). The limited state is surfaced by
    // `ripr.collectWorkspaceStatus`, not per-file spam.
    if is_full_run {
        append_gap_record_diagnostics(
            &root,
            config.repo_config().languages().enabled(),
            &mut grouped,
        );
    }

    let diagnostics_by_uri = grouped.clone();
    let batches = grouped
        .into_iter()
        .map(|(uri, diagnostics)| DiagnosticBatch { uri, diagnostics })
        .collect();
    let snapshot = AnalysisSnapshot {
        root,
        base,
        mode,
        refresh: RefreshMetadata::generated_now(),
        findings,
        classified_seams,
        gap_artifacts: gap_artifact_report.artifacts,
        gap_artifact_rejections: gap_artifact_report.rejections,
        diagnostics_by_uri,
        seams_deferred: defer_seam_inventory,
    };
    Ok(WorkspaceDiagnostics { snapshot, batches })
}

/// Compute the run status from findings, gap-artifact rejections, and the
/// seam-deferral flag. This replicates the logic of
/// `backend::workspace_status_run_status` but operates directly on the raw
/// ingredients so diagnostics.rs does not need to import from backend.rs
/// (keeping the module boundary clean).
///
/// Returns `"full"`, `"stale"`, `"cache_limited"`, `"limited"`, or
/// `"seams_deferred"`. `"seams_deferred"` is returned when
/// `defer_seam_inventory` is `true` and no other limitation applies; it is
/// a member of the `limited` family for severity-downgrade policy purposes.
fn snapshot_run_status(
    findings: &[Finding],
    rejections: &[GapArtifactRejection],
    defer_seam_inventory: bool,
) -> &'static str {
    if rejections
        .iter()
        .any(|r| matches!(r, GapArtifactRejection::StaleArtifact))
    {
        return "stale";
    }
    if !rejections.is_empty() {
        return "cache_limited";
    }
    let has_static_limit = findings.iter().any(|f| f.static_limit_kind.is_some());
    if has_static_limit {
        return "limited";
    }
    if defer_seam_inventory {
        return "seams_deferred";
    }
    "full"
}

/// Test-only re-export of `snapshot_run_status` so RIPR-SPEC-0105 control 4
/// can verify the limited-policy wiring without going through the full workspace
/// analysis stack. Gated behind `#[cfg(test)]` so it never leaks to production.
#[cfg(test)]
pub(super) fn snapshot_run_status_for_test(
    findings: &[Finding],
    rejections: &[GapArtifactRejection],
    defer_seam_inventory: bool,
) -> &'static str {
    snapshot_run_status(findings, rejections, defer_seam_inventory)
}

fn append_gap_record_diagnostics(
    root: &Path,
    enabled_languages: &[LanguageId],
    grouped: &mut BTreeMap<Uri, Vec<Diagnostic>>,
) {
    let ledger_path = root.join(DEFAULT_GAP_DECISION_LEDGER_OUT);
    let contents = match fs::read_to_string(&ledger_path) {
        Ok(contents) => contents,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
        Err(err) => {
            eprintln!(
                "ripr lsp: gap diagnostics skipped: read {} failed: {err}",
                ledger_path.display()
            );
            return;
        }
    };
    let artifact = match serde_json::from_str::<serde_json::Value>(&contents) {
        Ok(artifact) => artifact,
        Err(err) => {
            eprintln!(
                "ripr lsp: gap diagnostics skipped: parse {} failed: {err}",
                ledger_path.display()
            );
            return;
        }
    };
    let context = GapArtifactValidationContext {
        root,
        enabled_languages,
    };
    match validate_gap_artifact(&artifact, &context) {
        Ok(validated) if validated.kind == GapArtifactKind::GapDecisionLedger => {}
        Ok(_) => {
            eprintln!(
                "ripr lsp: gap diagnostics skipped: {} is not a gap decision ledger",
                ledger_path.display()
            );
            return;
        }
        Err(rejection) => {
            eprintln!(
                "ripr lsp: gap diagnostics skipped: {} rejected as {}",
                ledger_path.display(),
                rejection.as_str()
            );
            return;
        }
    }
    let records = match crate::output::gap_decision_ledger::parse_gap_records_json(&contents) {
        Ok(records) => records,
        Err(err) => {
            eprintln!(
                "ripr lsp: gap diagnostics skipped: parse {} failed: {err}",
                ledger_path.display()
            );
            return;
        }
    };
    for record in &records {
        let Some((uri, diagnostic)) = diagnostic_for_gap_record(root, &ledger_path, record) else {
            continue;
        };
        grouped.entry(uri).or_default().push(diagnostic);
    }
}

fn diagnostic_for_gap_record(
    root: &Path,
    ledger_path: &Path,
    record: &GapRecord,
) -> Option<(Uri, Diagnostic)> {
    if !projection_eligible(record, "lsp_diagnostic") {
        return None;
    }
    let anchor = record.anchor.as_ref()?;
    let file = anchor.file.as_ref()?.trim();
    if file.is_empty() {
        return None;
    }
    let line = anchor.line?;
    if line == 0 {
        return None;
    }
    let path = absolute_gap_anchor_path(root, Path::new(file));
    let uri = file_uri_for_path(&path).ok()?;
    let line_index = line.saturating_sub(1) as u32;
    let diagnostic = Diagnostic {
        range: Range {
            start: Position {
                line: line_index,
                character: 0,
            },
            end: Position {
                line: line_index,
                character: MAX_DIAGNOSTIC_RANGE_WIDTH,
            },
        },
        severity: Some(gap_record_diagnostic_severity(record)),
        code: Some(NumberOrString::String(format!(
            "ripr-gap-{}",
            record.kind.replace('_', "-")
        ))),
        code_description: None,
        source: Some("ripr".to_string()),
        message: gap_record_diagnostic_message(record),
        related_information: None,
        tags: None,
        data: Some(gap_record_diagnostic_data(ledger_path, record)),
    };
    Some((uri, diagnostic))
}

fn absolute_gap_anchor_path(root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

fn display_lsp_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// A finding is advisory when it carries a static limit or a preview language
/// status. Advisory findings must never emit WARNING — they lack a complete
/// repair packet by definition. Clamp to INFORMATION instead.
fn finding_is_advisory(finding: &Finding) -> bool {
    finding.static_limit_kind.is_some() || finding.language_status == Some(LanguageStatus::Preview)
}

/// A gap record has a complete repair packet when it is repairable, carries
/// at least one verification command, and has a receipt command.
/// WARNING is only appropriate when the packet is complete and actionable.
fn gap_record_has_complete_packet(record: &GapRecord) -> bool {
    record.repairability == "repairable"
        && !record.verification_commands.is_empty()
        && record.receipt_command.is_some()
}

/// A gap record is advisory when it is from a preview language or carries a
/// static limit kind. Advisory gap records must not emit WARNING regardless of
/// repair-packet completeness.
fn gap_record_is_advisory(record: &GapRecord) -> bool {
    record.language_status == "preview" || record.static_limit_kind.is_some()
}

/// Severity policy: WARNING only when the gap record has a complete repair
/// packet AND is not advisory. All other cases → INFORMATION.
///
/// This enforces the hard rule: no WARNING without a complete repair packet.
/// A complete packet requires `repairability == "repairable"`,
/// non-empty `verification_commands`, and `receipt_command.is_some()`.
/// Advisory records (preview language or static_limit_kind present) are
/// clamped to INFORMATION even when the packet looks complete.
fn gap_record_diagnostic_severity(record: &GapRecord) -> DiagnosticSeverity {
    if gap_record_has_complete_packet(record) && !gap_record_is_advisory(record) {
        DiagnosticSeverity::WARNING
    } else {
        DiagnosticSeverity::INFORMATION
    }
}

fn gap_record_diagnostic_message(record: &GapRecord) -> String {
    let kind = non_empty(&record.kind).unwrap_or("Unknown");
    let route = record
        .repair_route
        .as_ref()
        .and_then(|route| non_empty(&route.route_kind))
        .unwrap_or("InspectGap");
    let mut message = format!("ripr gap: {kind}; repair route: {route}");
    if let Some(route) = &record.repair_route {
        if let Some(changed) = route.changed_behavior.as_deref().and_then(non_empty) {
            message.push_str(&format!("; changed behavior: {changed}"));
        }
        if let Some(assertion) = route.assertion_shape.as_deref().and_then(non_empty) {
            message.push_str(&format!("; suggested check: {assertion}"));
        }
    }
    if record.language_status == "preview" {
        message.push_str("; preview advisory evidence");
    }
    message
}

fn gap_record_diagnostic_data(ledger_path: &Path, record: &GapRecord) -> serde_json::Value {
    serde_json::json!({
        "schema_version": "0.1",
        "source": "gap_decision_ledger",
        "gap_ledger": display_lsp_path(ledger_path),
        "gap_id": record.gap_id,
        "canonical_gap_id": record.canonical_gap_id,
        "gap_kind": record.kind,
        "language": record.language,
        "language_status": record.language_status,
        "scope": record.scope,
        "evidence_class": record.evidence_class,
        "gap_state": record.gap_state,
        "policy_state": record.policy_state,
        "repairability": record.repairability,
        "static_limit_kind": record.static_limit_kind,
        "static_limit_detail": record.static_limit_detail,
        "static_limits": record.static_limits,
        "repair_route": record.repair_route,
        "anchor": record.anchor,
        "evidence_ids": record.evidence_ids,
        "verification_commands": record.verification_commands,
        "regeneration_commands": record.regeneration_commands,
        "receipt_command": record.receipt_command,
        "receipt": record.receipt,
        "authority_boundary": record.authority_boundary,
    })
}

fn non_empty(value: &str) -> Option<&str> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed)
    }
}

/// Per-class severity for seam diagnostics. WARNING for the headline-
/// eligible classes (the agent should act); INFORMATION for `Opaque`
/// (visible but advisory). `StronglyGripped`, `Intentional`, and
/// `Suppressed` produce no diagnostic — `diagnostic_for_classified_seam`
/// returns `None` for those.
pub(super) fn diagnostic_severity_for_grip_class(
    class: SeamGripClass,
) -> Option<DiagnosticSeverity> {
    diagnostic_severity_for_grip_class_with_config(class, &SeverityConfig::default())
}

pub(super) fn diagnostic_severity_for_grip_class_with_config(
    class: SeamGripClass,
    config: &SeverityConfig,
) -> Option<DiagnosticSeverity> {
    lsp_severity(config.for_seam(class))
}

/// Build the LSP `Diagnostic` for a single classified seam, or `None`
/// if the class is not surfacable (strongly gripped / intentional /
/// suppressed). Diagnostic codes are prefixed with `ripr-seam-` so
/// editor consumers can filter by code without parsing severity.
///
/// `_root` is reserved for future range resolution: today seams do
/// not carry a column, so we anchor the range to the full seam line
/// (start char 0 to `MAX_DIAGNOSTIC_RANGE_WIDTH`). That way the
/// squiggle always covers the seam origin even for deeply indented
/// expressions — caught by chatgpt-codex on PR #241. When seams gain
/// a stored column, this function can read the source via `_root` to
/// produce a tighter range.
#[cfg(test)]
pub(super) fn diagnostic_for_classified_seam(
    _root: &Path,
    entry: &ClassifiedSeam,
) -> Option<Diagnostic> {
    diagnostic_for_classified_seam_with_config(_root, entry, &SeverityConfig::default())
}

pub(super) fn diagnostic_for_classified_seam_with_config(
    _root: &Path,
    entry: &ClassifiedSeam,
    config: &SeverityConfig,
) -> Option<Diagnostic> {
    let severity = diagnostic_severity_for_grip_class_with_config(entry.class, config)?;
    let seam = &entry.seam;
    let evidence = &entry.evidence;
    let line = seam.display_line().saturating_sub(1) as u32;
    let range = Range {
        start: Position { line, character: 0 },
        end: Position {
            line,
            character: MAX_DIAGNOSTIC_RANGE_WIDTH,
        },
    };
    Some(Diagnostic {
        range,
        severity: Some(severity),
        code: Some(NumberOrString::String(format!(
            "ripr-seam-{}",
            entry.class.as_str().replace('_', "-")
        ))),
        code_description: None,
        source: Some("ripr".to_string()),
        message: lsp_seam_message(entry),
        related_information: None,
        tags: None,
        data: Some(serde_json::json!({
            "schema_version": "0.1",
            "seam_id": seam.id().as_str(),
            "seam_kind": seam.kind().as_str(),
            "grip_class": entry.class.as_str(),
            "headline_eligible": entry.class.is_headline_eligible(),
            "owner": seam.owner(),
            "expected_sink": seam.expected_sink().as_str(),
            "evidence": {
                "reach": evidence.reach.state.as_str(),
                "activate": evidence.activate.state.as_str(),
                "propagate": evidence.propagate.state.as_str(),
                "observe": evidence.observe.state.as_str(),
                "discriminate": evidence.discriminate.state.as_str(),
            },
        })),
    })
}

fn lsp_seam_message(entry: &ClassifiedSeam) -> String {
    let seam = &entry.seam;
    let head = match entry.class {
        SeamGripClass::Opaque => "Opaque static evidence",
        SeamGripClass::Ungripped => "No detected test grip",
        SeamGripClass::WeaklyGripped => "Weakly gripped behavioral seam",
        SeamGripClass::ReachableUnrevealed => "Test reaches seam but does not reveal it",
        SeamGripClass::ActivationUnknown => "Activation evidence is unclear",
        SeamGripClass::PropagationUnknown => "Propagation to sink is unclear",
        SeamGripClass::ObservationUnknown => "Sink observation is unclear",
        SeamGripClass::DiscriminationUnknown => "Oracle specificity is unclear",
        // Filtered earlier; included for exhaustiveness.
        SeamGripClass::StronglyGripped => "Strongly gripped",
        SeamGripClass::Intentional => "Intentional low-grip",
        SeamGripClass::Suppressed => "Suppressed",
    };
    format!(
        "{} ({}): {}",
        head,
        seam.kind().as_str(),
        seam.expression()
            .lines()
            .next()
            .unwrap_or(seam.expression())
    )
}

fn absolute_seam_path(root: &Path, seam: &crate::analysis::seams::RepoSeam) -> PathBuf {
    let path = seam.file();
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

#[cfg(test)]
pub(super) fn diagnostic_for_finding(root: &Path, finding: &Finding) -> Diagnostic {
    diagnostic_for_finding_with_config(root, finding, &SeverityConfig::default())
}

pub(super) fn diagnostic_for_finding_with_config(
    root: &Path,
    finding: &Finding,
    config: &SeverityConfig,
) -> Diagnostic {
    let mut data = serde_json::json!({
        "schema_version": "0.1",
        "finding_id": finding.id.as_str(),
        "probe_id": finding.probe.id.to_string(),
        "classification": finding.class.as_str(),
        "probe_family": finding.probe.family.as_str(),
        "confidence": finding.confidence,
        "source_range": {
            "file": finding.probe.location.file.display().to_string(),
            "line": finding.probe.location.line,
            "column": finding.probe.location.column,
        },
    });
    if let Some(obj) = data.as_object_mut() {
        if let Some(language) = &finding.language {
            obj.insert(
                "language".to_string(),
                serde_json::Value::String(language.as_str().to_string()),
            );
        }
        if let Some(gap) = &finding.canonical_gap {
            obj.insert(
                "canonical_gap_id".to_string(),
                serde_json::Value::String(gap.id.clone()),
            );
        }
        if let Some(status) = &finding.language_status {
            obj.insert(
                "language_status".to_string(),
                serde_json::Value::String(status.as_str().to_string()),
            );
        }
        if let Some(owner_kind) = &finding.owner_kind {
            obj.insert(
                "owner_kind".to_string(),
                serde_json::Value::String(owner_kind.as_str().to_string()),
            );
        }
        if let Some(static_limit_kind) = &finding.static_limit_kind {
            obj.insert(
                "static_limit_kind".to_string(),
                serde_json::Value::String(static_limit_kind.as_str().to_string()),
            );
        }
        if let Some(actionability) = preview_actionability_for(finding) {
            obj.insert(
                "preview_actionability".to_string(),
                preview_actionability_json_value(&actionability),
            );
        }
    }
    Diagnostic {
        range: diagnostic_range_for_finding(finding),
        severity: lsp_severity(config.for_exposure(&finding.class)),
        code: Some(NumberOrString::String(finding.class.as_str().to_string())),
        code_description: None,
        source: Some("ripr".to_string()),
        message: lsp_message(finding),
        related_information: related_information_for_finding(root, finding),
        tags: None,
        data: Some(data),
    }
}

fn diagnostic_range_for_finding(finding: &Finding) -> Range {
    let line = finding.probe.location.line.saturating_sub(1) as u32;
    let start_character = finding.probe.location.column.saturating_sub(1) as u32;
    let width = expression_lsp_width(&finding.probe.expression).min(MAX_DIAGNOSTIC_RANGE_WIDTH);
    Range {
        start: Position {
            line,
            character: start_character,
        },
        end: Position {
            line,
            character: start_character.saturating_add(width),
        },
    }
}

fn expression_lsp_width(expression: &str) -> u32 {
    expression
        .chars()
        .map(|character| character.len_utf16() as u32)
        .sum::<u32>()
        .max(1)
}

fn related_information_for_finding(
    root: &Path,
    finding: &Finding,
) -> Option<Vec<DiagnosticRelatedInformation>> {
    let related = finding
        .related_tests
        .iter()
        .filter_map(|test| related_information_for_test(root, test))
        .collect::<Vec<_>>();
    if related.is_empty() {
        None
    } else {
        Some(related)
    }
}

fn related_information_for_test(
    root: &Path,
    test: &RelatedTest,
) -> Option<DiagnosticRelatedInformation> {
    let path = absolute_related_test_path(root, test);
    let uri = file_uri_for_path(&path).ok()?;
    let line = test.line.saturating_sub(1) as u32;
    Some(DiagnosticRelatedInformation {
        location: Location {
            uri,
            range: Range {
                start: Position { line, character: 0 },
                end: Position {
                    line,
                    character: 120,
                },
            },
        },
        message: related_test_message(test),
    })
}

fn related_test_message(test: &RelatedTest) -> String {
    let strength = test.oracle_strength.as_str();
    match &test.oracle {
        Some(oracle) => format!(
            "Related test `{}` has {strength} oracle: {oracle}",
            test.name
        ),
        None => format!("Related test `{}` has {strength} oracle", test.name),
    }
}

#[cfg(test)]
pub(super) fn diagnostic_severity_for_class(
    class: &crate::domain::ExposureClass,
) -> DiagnosticSeverity {
    lsp_severity(SeverityConfig::default().for_exposure(class))
        .unwrap_or(DiagnosticSeverity::INFORMATION)
}

fn lsp_severity(severity: ConfigSeverity) -> Option<DiagnosticSeverity> {
    match severity {
        ConfigSeverity::Off => None,
        ConfigSeverity::Info | ConfigSeverity::Note => Some(DiagnosticSeverity::INFORMATION),
        ConfigSeverity::Warning => Some(DiagnosticSeverity::WARNING),
    }
}

fn lsp_message(finding: &Finding) -> String {
    let reconciled = reconcile_next_step(finding);
    let base = if reconciled.is_empty() {
        format!("{} static RIPR exposure", finding.class.as_str())
    } else {
        reconciled
    };
    if finding
        .language_status
        .as_ref()
        .is_some_and(|status| status.as_str() == "preview")
    {
        let language = finding
            .language
            .as_ref()
            .map(|language| language.as_str())
            .unwrap_or("preview-language");
        let mut message = format!("{language} preview evidence (syntax-first, advisory): {base}");
        if let Some(static_limit_kind) = &finding.static_limit_kind {
            message.push_str(&format!(" Static limit: {}.", static_limit_kind.as_str()));
        }
        return message;
    }
    base
}

fn absolute_finding_path(root: &Path, finding: &Finding) -> PathBuf {
    if finding.probe.location.file.is_absolute() {
        finding.probe.location.file.clone()
    } else {
        root.join(&finding.probe.location.file)
    }
}

fn absolute_related_test_path(root: &Path, test: &RelatedTest) -> PathBuf {
    if test.file.is_absolute() {
        test.file.clone()
    } else {
        root.join(&test.file)
    }
}

#[cfg(test)]
mod seam_diagnostic_tests {
    use super::*;
    use crate::analysis::seams::{
        ExpectedSink, RepoSeam, RequiredDiscriminator, SeamGripClass, SeamKind,
    };
    use crate::analysis::test_grip_evidence::TestGripEvidence;
    use crate::domain::{Confidence, StageEvidence, StageState};
    use crate::output::gap_decision_ledger::{GapAnchor, GapRepairRoute, ProjectionEligibility};

    fn stage(state: StageState) -> StageEvidence {
        StageEvidence::new(state, Confidence::Medium, "test stage")
    }

    fn classified(class: SeamGripClass) -> ClassifiedSeam {
        let seam = RepoSeam::new(
            "src/pricing.rs",
            "pricing::discounted_total",
            SeamKind::PredicateBoundary,
            42,
            88,
            "amount >= discount_threshold",
            RequiredDiscriminator::BoundaryValue {
                description: "amount >= discount_threshold".to_string(),
            },
            ExpectedSink::ReturnValue,
        );
        let evidence = TestGripEvidence {
            seam_id: seam.id().clone(),
            related_tests: Vec::new(),
            reach: stage(StageState::Yes),
            activate: stage(StageState::Yes),
            propagate: stage(StageState::Yes),
            observe: stage(StageState::Yes),
            discriminate: stage(StageState::Weak),
            observed_values: Vec::new(),
            missing_discriminators: Vec::new(),
        };
        ClassifiedSeam {
            seam,
            evidence,
            class,
        }
    }

    #[test]
    fn weakly_gripped_seam_emits_warning_with_stable_code() -> Result<(), String> {
        let entry = classified(SeamGripClass::WeaklyGripped);
        let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
            .ok_or_else(|| "expected diagnostic for weakly_gripped".to_string())?;
        if diag.severity != Some(DiagnosticSeverity::WARNING) {
            return Err(format!("expected WARNING, got {:?}", diag.severity));
        }
        match &diag.code {
            Some(NumberOrString::String(code)) if code == "ripr-seam-weakly-gripped" => Ok(()),
            other => Err(format!("expected ripr-seam-weakly-gripped, got {other:?}")),
        }
    }

    #[test]
    fn ungripped_and_reachable_unrevealed_emit_warning() -> Result<(), String> {
        for class in [SeamGripClass::Ungripped, SeamGripClass::ReachableUnrevealed] {
            let entry = classified(class);
            let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
                .ok_or_else(|| format!("expected diagnostic for {}", class.as_str()))?;
            if diag.severity != Some(DiagnosticSeverity::WARNING) {
                return Err(format!(
                    "expected WARNING for {}, got {:?}",
                    class.as_str(),
                    diag.severity
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn unknown_classes_emit_information() -> Result<(), String> {
        for class in [
            SeamGripClass::ActivationUnknown,
            SeamGripClass::PropagationUnknown,
            SeamGripClass::ObservationUnknown,
            SeamGripClass::DiscriminationUnknown,
        ] {
            let entry = classified(class);
            let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
                .ok_or_else(|| format!("expected diagnostic for {}", class.as_str()))?;
            if diag.severity != Some(DiagnosticSeverity::INFORMATION) {
                return Err(format!(
                    "expected INFORMATION for {}, got {:?}",
                    class.as_str(),
                    diag.severity
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn opaque_emits_information_severity() -> Result<(), String> {
        let entry = classified(SeamGripClass::Opaque);
        let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
            .ok_or_else(|| "expected diagnostic for opaque".to_string())?;
        if diag.severity != Some(DiagnosticSeverity::INFORMATION) {
            return Err(format!("expected INFORMATION, got {:?}", diag.severity));
        }
        Ok(())
    }

    #[test]
    fn configured_seam_severity_can_disable_a_class() -> Result<(), String> {
        let config =
            crate::config::tests_only_parse("[severity.seams]\nweakly_gripped = \"off\"\n")?;
        let entry = classified(SeamGripClass::WeaklyGripped);
        let diagnostic = diagnostic_for_classified_seam_with_config(
            Path::new("/repo"),
            &entry,
            config.severity(),
        );
        if diagnostic.is_some() {
            return Err("configured off severity should suppress seam diagnostic".to_string());
        }
        Ok(())
    }

    #[test]
    fn strongly_gripped_emits_no_diagnostic() {
        let entry = classified(SeamGripClass::StronglyGripped);
        assert!(diagnostic_for_classified_seam(Path::new("/repo"), &entry).is_none());
    }

    #[test]
    fn intentional_and_suppressed_emit_no_diagnostic() {
        for class in [SeamGripClass::Intentional, SeamGripClass::Suppressed] {
            let entry = classified(class);
            assert!(
                diagnostic_for_classified_seam(Path::new("/repo"), &entry).is_none(),
                "{} should produce no diagnostic",
                class.as_str()
            );
        }
    }

    #[test]
    fn diagnostic_data_field_carries_seam_id_and_grip_class() -> Result<(), String> {
        let entry = classified(SeamGripClass::WeaklyGripped);
        let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
            .ok_or_else(|| "expected diagnostic".to_string())?;
        let data = diag
            .data
            .as_ref()
            .ok_or_else(|| "missing data".to_string())?;
        let seam_id = data
            .get("seam_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "missing seam_id".to_string())?;
        if seam_id != entry.seam.id().as_str() {
            return Err(format!("seam_id mismatch: {seam_id}"));
        }
        let grip_class = data
            .get("grip_class")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "missing grip_class".to_string())?;
        if grip_class != "weakly_gripped" {
            return Err(format!("grip_class mismatch: {grip_class}"));
        }
        Ok(())
    }

    #[test]
    fn gap_record_diagnostic_carries_shared_repair_payload() -> Result<(), String> {
        let record = gap_record(true);
        let (_, diagnostic) = diagnostic_for_gap_record(
            Path::new("/repo"),
            Path::new("/repo/target/ripr/reports/gap-decision-ledger.json"),
            &record,
        )
        .ok_or_else(|| "expected gap diagnostic".to_string())?;

        if diagnostic.severity != Some(DiagnosticSeverity::WARNING) {
            return Err(format!(
                "expected warning severity, got {:?}",
                diagnostic.severity
            ));
        }
        match &diagnostic.code {
            Some(NumberOrString::String(code)) if code == "ripr-gap-MissingBoundaryAssertion" => {}
            other => return Err(format!("unexpected diagnostic code: {other:?}")),
        }
        if !diagnostic
            .message
            .contains("repair route: AddBoundaryAssertion")
            || !diagnostic.message.contains("amount >= threshold")
            || diagnostic.message.contains("confidence")
        {
            return Err(format!(
                "unexpected gap diagnostic message: {}",
                diagnostic.message
            ));
        }
        let data = diagnostic
            .data
            .as_ref()
            .ok_or_else(|| "missing diagnostic data".to_string())?;
        assert_eq!(data["source"], "gap_decision_ledger");
        assert_eq!(data["gap_id"], "gap:pr:pricing:threshold-boundary");
        assert_eq!(data["gap_kind"], "MissingBoundaryAssertion");
        assert_eq!(data["repair_route"]["route_kind"], "AddBoundaryAssertion");
        assert_eq!(
            data["verification_commands"][0],
            "cargo xtask fixtures boundary_gap"
        );
        Ok(())
    }

    #[test]
    fn gap_record_diagnostic_requires_projection_eligibility_and_anchor() {
        let mut record = gap_record(false);
        assert!(
            diagnostic_for_gap_record(Path::new("/repo"), Path::new("ledger.json"), &record)
                .is_none()
        );

        record.projection_eligibility.insert(
            "lsp_diagnostic".to_string(),
            ProjectionEligibility {
                eligible: true,
                reason: "local_file_scope".to_string(),
            },
        );
        record.anchor = None;
        assert!(
            diagnostic_for_gap_record(Path::new("/repo"), Path::new("ledger.json"), &record)
                .is_none()
        );
    }

    #[test]
    fn gap_record_diagnostic_names_preview_inspection_route() -> Result<(), String> {
        let mut record = gap_record(true);
        record.repairability = "inspect_only".to_string();
        record.language_status = "preview".to_string();
        record.repair_route = None;

        let (_, diagnostic) =
            diagnostic_for_gap_record(Path::new("/repo"), Path::new("ledger.json"), &record)
                .ok_or_else(|| "expected gap diagnostic".to_string())?;

        if diagnostic.severity != Some(DiagnosticSeverity::INFORMATION) {
            return Err(format!(
                "expected information severity, got {:?}",
                diagnostic.severity
            ));
        }
        if !diagnostic.message.contains("repair route: InspectGap")
            || !diagnostic.message.contains("preview advisory evidence")
        {
            return Err(format!(
                "unexpected preview gap diagnostic message: {}",
                diagnostic.message
            ));
        }
        Ok(())
    }

    #[test]
    fn append_gap_record_diagnostics_reads_default_ledger() -> Result<(), String> {
        let root = temp_gap_root()?;
        let ledger_path = root.join(DEFAULT_GAP_DECISION_LEDGER_OUT);
        let contents = gap_ledger_json(vec![gap_record(true)]).to_string();
        fs::write(&ledger_path, contents)
            .map_err(|err| format!("write {} failed: {err}", ledger_path.display()))?;

        let mut grouped = std::collections::BTreeMap::new();
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);

        let diagnostic_count: usize = grouped.values().map(Vec::len).sum();
        if diagnostic_count != 1 {
            return Err(format!(
                "expected one gap diagnostic, got {diagnostic_count}"
            ));
        }
        let uri = grouped
            .keys()
            .next()
            .ok_or_else(|| "missing diagnostic URI".to_string())?
            .as_str()
            .to_string();
        if !uri.ends_with("/src/pricing.rs") {
            return Err(format!("unexpected diagnostic URI: {uri}"));
        }

        fs::remove_dir_all(&root)
            .map_err(|err| format!("remove temp root {} failed: {err}", root.display()))?;
        Ok(())
    }

    #[test]
    fn append_gap_record_diagnostics_fails_closed_for_invalid_artifacts() -> Result<(), String> {
        let root = temp_gap_root()?;
        let ledger_path = root.join(DEFAULT_GAP_DECISION_LEDGER_OUT);

        let mut stale = gap_ledger_json(vec![gap_record(true)]);
        stale["status"] = serde_json::json!("stale");
        fs::write(&ledger_path, stale.to_string())
            .map_err(|err| format!("write stale ledger failed: {err}"))?;
        let mut grouped = std::collections::BTreeMap::new();
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "stale gap artifact must not publish diagnostics"
        );

        fs::write(&ledger_path, "{")
            .map_err(|err| format!("write malformed ledger failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "malformed gap artifact must not publish diagnostics"
        );

        let first_action = serde_json::json!({
            "schema_version": "0.1",
            "tool": "ripr",
            "kind": "first_useful_action",
            "root": ".",
            "status": "actionable",
            "selected": {
                "seam_id": "seam:pricing",
                "path": "src/pricing.rs"
            },
            "target": {
                "file": "tests/pricing.rs",
                "related_test": "tests/pricing.rs::handles_threshold"
            },
            "commands": {
                "verify": "ripr agent verify --root . --json",
                "receipt": "ripr agent receipt --root . --json"
            }
        });
        fs::write(&ledger_path, first_action.to_string())
            .map_err(|err| format!("write wrong-kind ledger failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "non-ledger gap artifact must not publish diagnostics"
        );

        let mut wrong_root = gap_ledger_json(vec![gap_record(true)]);
        wrong_root["root"] = serde_json::json!("/other/workspace");
        fs::write(&ledger_path, wrong_root.to_string())
            .map_err(|err| format!("write wrong-root ledger failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "wrong-root gap artifact must not publish diagnostics"
        );

        let mut disabled_record = gap_record(true);
        disabled_record.language = "python".to_string();
        disabled_record.language_status = "preview".to_string();
        let disabled = gap_ledger_json(vec![disabled_record]);
        fs::write(&ledger_path, disabled.to_string())
            .map_err(|err| format!("write disabled-language ledger failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "disabled preview-language gap artifact must not publish diagnostics"
        );

        fs::write(&ledger_path, "{not json")
            .map_err(|err| format!("write malformed ledger failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "malformed gap artifact must not publish diagnostics"
        );

        let first_useful_action = serde_json::json!({
            "schema_version": "0.1",
            "kind": "first_useful_action",
            "root": ".",
            "canonical_gap_id": "gap:rust:first-useful-action",
            "language": "rust",
            "language_status": "stable",
        });
        fs::write(&ledger_path, first_useful_action.to_string())
            .map_err(|err| format!("write non-ledger artifact failed: {err}"))?;
        append_gap_record_diagnostics(&root, &[LanguageId::Rust], &mut grouped);
        assert!(
            grouped.is_empty(),
            "non-ledger gap artifact must not publish ledger diagnostics"
        );

        fs::remove_dir_all(&root)
            .map_err(|err| format!("remove temp root {} failed: {err}", root.display()))?;
        Ok(())
    }

    #[test]
    fn diagnostic_message_names_seam_kind_and_expression() -> Result<(), String> {
        let entry = classified(SeamGripClass::WeaklyGripped);
        let diag = diagnostic_for_classified_seam(Path::new("/repo"), &entry)
            .ok_or_else(|| "expected diagnostic".to_string())?;
        if !diag.message.contains("predicate_boundary") {
            return Err(format!("message missing kind: {}", diag.message));
        }
        if !diag.message.contains("amount >= discount_threshold") {
            return Err(format!("message missing expression: {}", diag.message));
        }
        Ok(())
    }

    fn gap_record(lsp_eligible: bool) -> GapRecord {
        let mut projection_eligibility = BTreeMap::new();
        projection_eligibility.insert(
            "lsp_diagnostic".to_string(),
            ProjectionEligibility {
                eligible: lsp_eligible,
                reason: "local_file_scope".to_string(),
            },
        );
        GapRecord {
            gap_id: "gap:pr:pricing:threshold-boundary".to_string(),
            canonical_gap_id: "gap:rust:pricing:threshold-boundary".to_string(),
            kind: "MissingBoundaryAssertion".to_string(),
            language: "rust".to_string(),
            language_status: "stable".to_string(),
            scope: "pr_local".to_string(),
            evidence_class: "presentation_text".to_string(),
            gap_state: "actionable".to_string(),
            policy_state: "new".to_string(),
            repairability: "repairable".to_string(),
            repair_route: Some(GapRepairRoute {
                route_kind: "AddBoundaryAssertion".to_string(),
                target_file: Some("tests/pricing.rs".to_string()),
                target_line: Some(33),
                related_test: Some("tests/pricing.rs::discount_threshold".to_string()),
                assertion_shape: Some("assert_eq!(price(threshold), expected)".to_string()),
                missing_discriminator: Some("amount == threshold".to_string()),
                changed_behavior: Some("amount >= threshold".to_string()),
                stop_conditions: vec!["Stop if the target owner moved.".to_string()],
            }),
            static_limit_kind: None,
            static_limit_detail: None,
            static_limits: Vec::new(),
            anchor: Some(GapAnchor {
                file: Some("src/pricing.rs".to_string()),
                line: Some(42),
                owner: Some("pricing::discounted_total".to_string()),
                dedupe_fingerprint: Some("gap:rust:pricing:threshold-boundary".to_string()),
            }),
            evidence_ids: vec!["evidence:pricing".to_string()],
            projection_eligibility,
            verification_commands: vec!["cargo xtask fixtures boundary_gap".to_string()],
            receipt_command: Some(
                "ripr outcome --before target/ripr/workflow/before.json --after target/ripr/workflow/after.json --out target/ripr/receipts/pricing.json".to_string(),
            ),
            regeneration_commands: Vec::new(),
            receipt: None,
            safe_gate_predicate: None,
            authority_boundary: "advisory".to_string(),
        }
    }

    fn gap_ledger_json(records: Vec<GapRecord>) -> serde_json::Value {
        serde_json::json!({
            "schema_version": "0.1",
            "tool": "ripr",
            "kind": "gap_decision_ledger",
            "status": "advisory",
            "root": ".",
            "records": records,
        })
    }

    fn temp_gap_root() -> Result<PathBuf, String> {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|err| format!("system clock before UNIX_EPOCH: {err}"))?
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "ripr-lsp-gap-diagnostics-{}-{stamp}",
            std::process::id()
        ));
        fs::create_dir_all(root.join("target/ripr/reports"))
            .map_err(|err| format!("create temp root {} failed: {err}", root.display()))?;
        Ok(root)
    }

    #[test]
    fn absolute_related_test_path_joins_repo_root_for_relative_paths() {
        let test = RelatedTest {
            name: "tests::pricing::handles_discount".to_string(),
            file: PathBuf::from("tests/pricing.rs"),
            line: 33,
            oracle: None,
            oracle_kind: crate::domain::OracleKind::ExactValue,
            oracle_strength: crate::domain::OracleStrength::Weak,
            relation_reason: None,
            relation_confidence: None,
        };

        let path = absolute_related_test_path(Path::new("/repo"), &test);
        assert_eq!(path, Path::new("/repo/tests/pricing.rs"));
    }

    #[test]
    fn absolute_related_test_path_keeps_absolute_paths() {
        let test = RelatedTest {
            name: "tests::pricing::handles_discount".to_string(),
            file: PathBuf::from("/tmp/workspace/tests/pricing.rs"),
            line: 33,
            oracle: None,
            oracle_kind: crate::domain::OracleKind::ExactValue,
            oracle_strength: crate::domain::OracleStrength::Weak,
            relation_reason: None,
            relation_confidence: None,
        };

        let path = absolute_related_test_path(Path::new("/repo"), &test);
        assert_eq!(path, Path::new("/tmp/workspace/tests/pricing.rs"));
    }
}

/// Reject-list tests for the LSP diagnostics severity policy (RIPR-SPEC-0076).
///
/// The hard rule: no WARNING (or higher) may be emitted for a finding or gap
/// record that lacks a complete repair packet. Seam diagnostics are exempt —
/// they carry structural grip-class signals, not repair packets (see comment
/// on `gap_record_diagnostic_severity`).
///
/// These tests are the behavioral proof: each asserts the correct
/// severity or suppression outcome for the named policy condition.
#[cfg(test)]
mod diagnostic_policy_tests {
    use super::*;
    use crate::domain::{
        ActivationEvidence, Confidence, DeltaKind, ExposureClass, LanguageStatus, Probe,
        ProbeFamily, ProbeId, RevealEvidence, RiprEvidence, SourceLocation, StageEvidence,
        StageState, StaticLimitKind,
    };
    use crate::output::gap_decision_ledger::{GapAnchor, GapRepairRoute, ProjectionEligibility};

    fn policy_finding() -> Finding {
        Finding {
            id: "probe:pricing:42:predicate".to_string(),
            canonical_gap: None,
            probe: Probe {
                id: ProbeId("probe:pricing:42:predicate".to_string()),
                location: SourceLocation {
                    file: std::path::PathBuf::from("src/pricing.rs"),
                    line: 42,
                    column: 1,
                },
                owner: None,
                family: ProbeFamily::Predicate,
                delta: DeltaKind::Control,
                before: None,
                after: None,
                expression: "amount >= threshold".to_string(),
                expected_sinks: Vec::new(),
                required_oracles: Vec::new(),
            },
            class: ExposureClass::WeaklyExposed,
            ripr: RiprEvidence {
                reach: StageEvidence::new(StageState::Yes, Confidence::High, "reached"),
                infect: StageEvidence::new(StageState::Yes, Confidence::High, "infected"),
                propagate: StageEvidence::new(StageState::Yes, Confidence::Medium, "propagated"),
                reveal: RevealEvidence {
                    observe: StageEvidence::new(StageState::Weak, Confidence::Medium, "observed"),
                    discriminate: StageEvidence::new(
                        StageState::Weak,
                        Confidence::Medium,
                        "weak discriminator",
                    ),
                },
            },
            confidence: 0.75,
            evidence: Vec::new(),
            missing: Vec::new(),
            flow_sinks: Vec::new(),
            activation: ActivationEvidence::default(),
            stop_reasons: Vec::new(),
            related_tests: Vec::new(),
            recommended_next_step: None,
            language: None,
            language_status: None,
            owner_kind: None,
            static_limit_kind: None,
            changed_sink: None,
            observed_sink: None,
            oracle_alignment: None,
            alignment_reason: None,
        }
    }

    fn complete_gap_record() -> GapRecord {
        let mut projection_eligibility = BTreeMap::new();
        projection_eligibility.insert(
            "lsp_diagnostic".to_string(),
            ProjectionEligibility {
                eligible: true,
                reason: "local_file_scope".to_string(),
            },
        );
        GapRecord {
            gap_id: "gap:pr:pricing:policy-test".to_string(),
            canonical_gap_id: "gap:rust:pricing:policy-test".to_string(),
            kind: "MissingBoundaryAssertion".to_string(),
            language: "rust".to_string(),
            language_status: "stable".to_string(),
            scope: "pr_local".to_string(),
            evidence_class: "predicate_boundary".to_string(),
            gap_state: "actionable".to_string(),
            policy_state: "new".to_string(),
            repairability: "repairable".to_string(),
            repair_route: Some(GapRepairRoute {
                route_kind: "AddBoundaryAssertion".to_string(),
                target_file: Some("tests/pricing.rs".to_string()),
                target_line: Some(33),
                related_test: Some("tests/pricing.rs::discount_threshold".to_string()),
                assertion_shape: Some("assert_eq!(price(threshold), expected)".to_string()),
                missing_discriminator: None,
                changed_behavior: Some("amount >= threshold".to_string()),
                stop_conditions: Vec::new(),
            }),
            static_limit_kind: None,
            static_limit_detail: None,
            static_limits: Vec::new(),
            anchor: Some(GapAnchor {
                file: Some("src/pricing.rs".to_string()),
                line: Some(42),
                owner: Some("pricing::discounted_total".to_string()),
                dedupe_fingerprint: Some("gap:rust:pricing:policy-test".to_string()),
            }),
            evidence_ids: Vec::new(),
            projection_eligibility,
            verification_commands: vec!["cargo xtask fixtures boundary_gap".to_string()],
            receipt_command: Some(
                "ripr outcome --before before.json --after after.json --out receipt.json"
                    .to_string(),
            ),
            regeneration_commands: Vec::new(),
            receipt: None,
            safe_gate_predicate: None,
            authority_boundary: "advisory".to_string(),
        }
    }

    // Test 1: WeaklyExposed + static_limit_kind=Some → advisory → INFORMATION (never WARNING).
    #[test]
    fn no_warning_for_finding_with_static_limit() -> Result<(), String> {
        let mut finding = policy_finding();
        finding.class = ExposureClass::WeaklyExposed;
        finding.static_limit_kind = Some(StaticLimitKind::DynamicDispatch);

        if !finding_is_advisory(&finding) {
            return Err("expected finding_is_advisory=true for static_limit_kind".to_string());
        }

        // Simulate the workspace assembly policy: get base severity then clamp if advisory.
        let config = SeverityConfig::default();
        let base_severity = lsp_severity(config.for_exposure(&finding.class));
        // The base for WeaklyExposed is WARNING by default config.
        if base_severity != Some(DiagnosticSeverity::WARNING) {
            return Err(format!(
                "expected base severity to be WARNING (to validate the clamp), got {base_severity:?}"
            ));
        }
        // Policy clamp: advisory → INFORMATION.
        let clamped = if finding_is_advisory(&finding) {
            Some(DiagnosticSeverity::INFORMATION)
        } else {
            base_severity
        };
        if clamped != Some(DiagnosticSeverity::INFORMATION) {
            return Err(format!(
                "expected clamped severity=INFORMATION, got {clamped:?}"
            ));
        }
        Ok(())
    }

    // Test 2: WeaklyExposed + language_status=Preview → advisory → INFORMATION (never WARNING).
    #[test]
    fn no_warning_for_preview_finding() -> Result<(), String> {
        let mut finding = policy_finding();
        finding.class = ExposureClass::WeaklyExposed;
        finding.language_status = Some(LanguageStatus::Preview);

        if !finding_is_advisory(&finding) {
            return Err(
                "expected finding_is_advisory=true for preview language_status".to_string(),
            );
        }

        let config = SeverityConfig::default();
        let base_severity = lsp_severity(config.for_exposure(&finding.class));
        let clamped = if finding_is_advisory(&finding) {
            Some(DiagnosticSeverity::INFORMATION)
        } else {
            base_severity
        };
        if clamped != Some(DiagnosticSeverity::INFORMATION) {
            return Err(format!(
                "expected INFORMATION for preview finding, got {clamped:?}"
            ));
        }
        Ok(())
    }

    // Test 3: complete packet (repairable + verification_commands + receipt_command) → WARNING;
    //         missing verify or receipt → INFORMATION.
    #[test]
    fn warning_only_when_gap_record_has_complete_packet() -> Result<(), String> {
        // Complete packet → WARNING.
        let complete = complete_gap_record();
        let severity = gap_record_diagnostic_severity(&complete);
        if severity != DiagnosticSeverity::WARNING {
            return Err(format!(
                "expected WARNING for complete packet, got {severity:?}"
            ));
        }

        // Missing verification_commands → INFORMATION.
        let mut no_verify = complete.clone();
        no_verify.verification_commands = Vec::new();
        let severity = gap_record_diagnostic_severity(&no_verify);
        if severity != DiagnosticSeverity::INFORMATION {
            return Err(format!(
                "expected INFORMATION when verification_commands empty, got {severity:?}"
            ));
        }

        // Missing receipt_command → INFORMATION.
        let mut no_receipt = complete.clone();
        no_receipt.receipt_command = None;
        let severity = gap_record_diagnostic_severity(&no_receipt);
        if severity != DiagnosticSeverity::INFORMATION {
            return Err(format!(
                "expected INFORMATION when receipt_command missing, got {severity:?}"
            ));
        }

        // Not repairable → INFORMATION.
        let mut not_repairable = complete.clone();
        not_repairable.repairability = "inspect_only".to_string();
        let severity = gap_record_diagnostic_severity(&not_repairable);
        if severity != DiagnosticSeverity::INFORMATION {
            return Err(format!(
                "expected INFORMATION when not repairable, got {severity:?}"
            ));
        }

        Ok(())
    }

    // Test 4: complete packet but language_status="preview" → advisory → INFORMATION.
    #[test]
    fn no_warning_for_preview_gap_record() -> Result<(), String> {
        let mut record = complete_gap_record();
        record.language_status = "preview".to_string();

        if !gap_record_is_advisory(&record) {
            return Err(
                "expected gap_record_is_advisory=true for language_status=preview".to_string(),
            );
        }
        let severity = gap_record_diagnostic_severity(&record);
        if severity != DiagnosticSeverity::INFORMATION {
            return Err(format!(
                "expected INFORMATION for preview gap record, got {severity:?}"
            ));
        }
        Ok(())
    }

    // Test 5: complete packet but static_limit_kind=Some → advisory → INFORMATION.
    #[test]
    fn no_warning_for_static_limit_gap_record() -> Result<(), String> {
        let mut record = complete_gap_record();
        record.static_limit_kind = Some("dynamic_dispatch".to_string());

        if !gap_record_is_advisory(&record) {
            return Err(
                "expected gap_record_is_advisory=true for static_limit_kind present".to_string(),
            );
        }
        let severity = gap_record_diagnostic_severity(&record);
        if severity != DiagnosticSeverity::INFORMATION {
            return Err(format!(
                "expected INFORMATION for static-limit gap record, got {severity:?}"
            ));
        }
        Ok(())
    }

    // Test 6: snapshot with static_limit finding (run_status != "full") → finding WARNING
    //         would be downgraded to INFORMATION.
    //
    // Asserts: snapshot_run_status returns "limited" when a finding carries
    // static_limit_kind, and the workspace assembly downgrades WARNING→INFORMATION.
    // The assembly logic is: if !is_full_run && severity==WARNING → INFORMATION.
    #[test]
    fn limited_run_downgrades_finding_warnings() -> Result<(), String> {
        let mut finding = policy_finding();
        finding.static_limit_kind = Some(StaticLimitKind::MissingImportGraph);

        // Confirm run status is "limited" when finding has a static limit.
        let run_status = snapshot_run_status(&[finding.clone()], &[], false);
        if run_status != "limited" {
            return Err(format!(
                "expected run_status=limited for finding with static_limit_kind, got {run_status}"
            ));
        }

        let is_full_run = run_status == "full";

        // Simulate the workspace assembly downgrade: get base severity, apply
        // limited-run downgrade.
        let config = SeverityConfig::default();
        // Use a non-advisory finding to isolate the limited-run downgrade from
        // the advisory clamp. Remove static_limit_kind for the severity check.
        let mut non_advisory = policy_finding();
        non_advisory.class = ExposureClass::WeaklyExposed;
        let base_severity = lsp_severity(config.for_exposure(&non_advisory.class));
        if base_severity != Some(DiagnosticSeverity::WARNING) {
            return Err(format!(
                "expected base severity WARNING for WeaklyExposed (to prove downgrade), got {base_severity:?}"
            ));
        }
        let final_severity = if !is_full_run && base_severity == Some(DiagnosticSeverity::WARNING) {
            Some(DiagnosticSeverity::INFORMATION)
        } else {
            base_severity
        };
        if final_severity != Some(DiagnosticSeverity::INFORMATION) {
            return Err(format!(
                "expected INFORMATION after limited-run downgrade, got {final_severity:?}"
            ));
        }
        Ok(())
    }

    // Test 7: stale/limited snapshot → gap-record diagnostics suppressed entirely.
    //
    // Asserts: snapshot_run_status returns "stale" for a StaleArtifact rejection,
    // and "cache_limited" for other rejections, both of which are not "full".
    // When !is_full_run, the workspace assembly skips gap-record diagnostics.
    #[test]
    fn stale_run_suppresses_gap_record_diagnostics() -> Result<(), String> {
        // StaleArtifact rejection → run_status "stale" → not full → suppress gap records.
        let stale_rejections = vec![GapArtifactRejection::StaleArtifact];
        let run_status = snapshot_run_status(&[], &stale_rejections, false);
        if run_status != "stale" {
            return Err(format!(
                "expected run_status=stale for StaleArtifact rejection, got {run_status}"
            ));
        }
        if run_status == "full" {
            return Err("stale run must not be treated as full".to_string());
        }

        // cache_limited rejection → also not full → suppress gap records.
        let cache_rejections = vec![GapArtifactRejection::WrongRoot("other-root".to_string())];
        let run_status = snapshot_run_status(&[], &cache_rejections, false);
        if run_status != "cache_limited" {
            return Err(format!(
                "expected run_status=cache_limited for non-stale rejection, got {run_status}"
            ));
        }
        if run_status == "full" {
            return Err("cache_limited run must not be treated as full".to_string());
        }

        // Confirm the suppression decision: gap records are only emitted when is_full_run.
        // Here we verify the boolean gate directly.
        let would_emit = run_status == "full";
        if would_emit {
            return Err("gap records must not be emitted for non-full run".to_string());
        }
        Ok(())
    }
}

/// PARITY TEST (#1209): LSP diagnostic surface must route `recommended_next_step`
/// through `reconcile_next_step` — a complete TypeScript repair packet must NOT
/// emit the blocked-state disclosure string, and a blocked packet MUST still
/// emit it.
///
/// `lsp_message` is private, so this test must live inside the diagnostics module
/// where it has direct access.
#[cfg(test)]
mod lsp_next_step_parity_tests {
    use super::lsp_message;
    use crate::domain::{
        ActivationEvidence, Confidence, DeltaKind, ExposureClass, Finding, LanguageId,
        LanguageStatus, MissingDiscriminatorFact, OracleKind, OracleStrength, OwnerKind, Probe,
        ProbeFamily, ProbeId, RelatedTest, RevealEvidence, RiprEvidence, SourceLocation,
        StageEvidence, StageState, SymbolId,
    };
    use std::path::PathBuf;

    fn complete_ts_finding() -> Finding {
        Finding {
            id: "probe:src_discount.ts:typescript_preview:2396aec1".to_string(),
            canonical_gap: None,
            probe: Probe {
                id: ProbeId("probe:src_discount.ts:typescript_preview:2396aec1".to_string()),
                location: SourceLocation::new("src/discount.ts", 2, 1),
                owner: Some(SymbolId(
                    "typescript:src/discount.ts::applyDiscount".to_string(),
                )),
                family: ProbeFamily::Predicate,
                delta: DeltaKind::Control,
                before: None,
                after: Some("if (amount >= threshold) {".to_string()),
                expression: "if (amount >= threshold) {".to_string(),
                expected_sinks: Vec::new(),
                required_oracles: Vec::new(),
            },
            class: ExposureClass::WeaklyExposed,
            ripr: RiprEvidence {
                reach: StageEvidence::new(StageState::Yes, Confidence::Low, "1 related test"),
                infect: StageEvidence::new(
                    StageState::Unknown,
                    Confidence::Low,
                    "TypeScript preview adapter does not yet model infection.",
                ),
                propagate: StageEvidence::new(
                    StageState::Unknown,
                    Confidence::Low,
                    "TypeScript preview adapter does not yet model propagation.",
                ),
                reveal: RevealEvidence {
                    observe: StageEvidence::new(StageState::Weak, Confidence::Low, "weak oracle"),
                    discriminate: StageEvidence::new(
                        StageState::Weak,
                        Confidence::Low,
                        "weak discriminator",
                    ),
                },
            },
            confidence: 0.4,
            evidence: vec![
                "owner: applyDiscount".to_string(),
                "gap_state: advisory".to_string(),
                "actionability_category: incomplete_repair_packet".to_string(),
                "why_not_actionable: TypeScript preview has owner, related-test, oracle, and probe evidence but lacks a complete repair packet contract".to_string(),
                "repair_route: project canonical TypeScript repair packet fields only after verify, receipt, evidence refs, and edit boundaries are available".to_string(),
                "evidence_needed_to_promote: canonical gap identity, repair kind, target test shape, related observer, verify command, receipt command, raw evidence refs, and edit constraints".to_string(),
                "raw_evidence_ref: leg=rust_seam;file=src/discount.ts;line=2;kind=typescript_preview_probe;source_id=probe:src_discount.ts:typescript_preview:2396aec1;owner=applyDiscount".to_string(),
                "typescript_package_root: .".to_string(),
                "typescript_workspace_root: .".to_string(),
                "typescript_framework_hint: jest".to_string(),
                "typescript_runner_hint: npm".to_string(),
                "typescript_package_confidence: high".to_string(),
                "typescript_verify_command: jest tests/discount.test.ts".to_string(),
                "typescript_oracle_observed: applyDiscount(100, 100)".to_string(),
                "typescript_oracle_expected: 50".to_string(),
                "typescript_oracle_confidence: high".to_string(),
                "typescript_oracle_evidence_ref: tests/discount.test.ts:3".to_string(),
                "missing_discriminator: amount == threshold".to_string(),
            ],
            missing: Vec::new(),
            flow_sinks: Vec::new(),
            activation: ActivationEvidence {
                observed_values: Vec::new(),
                missing_discriminators: vec![MissingDiscriminatorFact {
                    value: "amount == threshold".to_string(),
                    reason: "changed TypeScript equality-boundary at line 2 lacks a concrete preview discriminator".to_string(),
                    flow_sink: None,
                }],
            },
            stop_reasons: Vec::new(),
            related_tests: vec![RelatedTest {
                name: "applyDiscount applies discount when amount meets threshold".to_string(),
                file: PathBuf::from("tests/discount.test.ts"),
                line: 3,
                oracle_strength: OracleStrength::Weak,
                oracle_kind: OracleKind::RelationalCheck,
                oracle: Some("expect(result).toBeGreaterThan(50)".to_string()),
                relation_reason: None,
                relation_confidence: None,
            }],
            recommended_next_step: Some(
                "TypeScript preview advisory: add or strengthen a focused assertion for missing discriminator `amount == threshold`; no actionable repair packet is emitted until verify, receipt, and edit-boundary fields are available.".to_string(),
            ),
            language: Some(LanguageId::TypeScript),
            language_status: Some(LanguageStatus::Preview),
            owner_kind: Some(OwnerKind::Function),
            static_limit_kind: None,
            changed_sink: None,
            observed_sink: None,
            oracle_alignment: None,
            alignment_reason: None,
        }
    }

    fn incomplete_ts_finding() -> Finding {
        let mut f = complete_ts_finding();
        f.evidence
            .retain(|l| !l.starts_with("typescript_verify_command:"));
        f.recommended_next_step = Some(
            "TypeScript preview advisory: add or strengthen a focused assertion; no actionable repair packet is emitted until verify, receipt, and edit-boundary fields are available.".to_string(),
        );
        f
    }

    /// PARITY: complete packet → LSP diagnostic message must NOT contain the
    /// blocked-state disclosure string (the contradiction that #1209 fixes).
    #[test]
    fn lsp_diagnostic_complete_packet_strips_blocked_tail() {
        let finding = complete_ts_finding();
        let message = lsp_message(&finding);
        assert!(
            message.contains("the repair packet is complete and delegatable (advisory)"),
            "LSP diagnostic must contain reconciled next-step for complete packet; got: {message}"
        );
        assert!(
            !message.contains("no actionable repair packet is emitted until"),
            "LSP diagnostic must NOT contain blocked-case tail for complete packet; got: {message}"
        );
    }

    /// PARITY: blocked packet → LSP diagnostic message must STILL contain the
    /// blocked-state disclosure (fail-closed: real disclosures must not be silenced).
    #[test]
    fn lsp_diagnostic_blocked_packet_preserves_disclosure() {
        let finding = incomplete_ts_finding();
        let message = lsp_message(&finding);
        assert!(
            message.contains("no actionable repair packet is emitted"),
            "LSP diagnostic must preserve blocked-case disclosure for incomplete packet; got: {message}"
        );
        assert!(
            !message.contains("the repair packet is complete and delegatable"),
            "LSP diagnostic must NOT say actionable for blocked packet; got: {message}"
        );
    }
}