deps-cli 2.0.0

CLI for running deps-lsp's dependency-health checks in CI, pre-commit, and shell workflows
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
//! `CheckReport`/`CheckFinding`/`Category`/`FailOnPolicy` and the classification
//! orchestrator that assembles one manifest's [`deps_core::VersionData`].
//!
//! It then calls its ecosystem's [`deps_core::Ecosystem::generate_diagnostics`] — the
//! identical call `deps-lsp`'s `handlers/diagnostics.rs` makes.
//!
//! Every outdated/yanked/vulnerable/unsatisfiable/deprecated verdict is decided by
//! [`deps_engine::classify`] or by `generate_diagnostics` itself; nothing in this module
//! re-derives a verdict from raw registry/lockfile/OSV data (spec 062 FR-005). `Category`
//! stays in this crate rather than `deps_core` per `specs/062-cli-check-mode/plan.md`'s
//! `[NEEDS CLARIFICATION: O-4]` marker — see that doc before moving it.

use deps_core::diagnostic::{Diagnostic, Severity};
use deps_core::lsp_helpers::{
    DEPRECATED_DIAGNOSTIC_CODE, LICENSE_POLICY_VIOLATION_DIAGNOSTIC_CODE,
    UNSATISFIABLE_DIAGNOSTIC_CODE, redact_name_for_diagnostic, redact_requirement_for_diagnostic,
};
use deps_core::osv::{OsvClient, ScanOutcome, VulnKeys, VulnSeverity, VulnerabilityMap};
use deps_core::policy_config::PolicyConfig;
use deps_core::position::Range;
use deps_core::{Dependency, Ecosystem, EcosystemId, HttpCache};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Every non-`deps-core` diagnostic code constant in the workspace, mirrored here as
/// literals rather than importing `deps-github-actions`/`deps-gitlab-ci` directly (both are
/// optional, feature-gated dependencies of `deps-engine`; importing their constants
/// unconditionally would break a `--no-default-features --features cargo`-style build, and
/// `#[cfg]`-gating each match arm was judged not worth the complexity for three stable
/// strings). **This list must stay exhaustive** — issue C3 (spec 062 review) was exactly one
/// ecosystem-owned code (`UNRESOLVED_HOST_DIAGNOSTIC_CODE`) missing from it, which silently
/// misclassified an informational notice as `Category::Vulnerable`. Before trusting
/// [`classify`]'s fallback again, re-run
/// `grep -rn 'pub const.*_DIAGNOSTIC_CODE.*: &str' crates/*/src/lib.rs crates/*/src/ecosystem.rs`
/// across the workspace and add anything new here.
const GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE: &str = "mutable-ref-pin";
/// See [`GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE`]'s doc.
const GITLAB_CI_MUTABLE_REF_PIN_CODE: &str = "gitlab-ci-mutable-ref-pin";
/// `deps_gitlab_ci::UNRESOLVED_HOST_DIAGNOSTIC_CODE` — an informational notice (INFORMATION
/// severity, never a vulnerability), emitted unconditionally whenever GitLab CI's
/// `registries.gitlab_instance_host` is unset/invalid. See
/// [`GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE`]'s doc for why this is a literal.
const GITLAB_CI_UNRESOLVED_HOST_CODE: &str = "unresolved-gitlab-host";
/// `deps_github_actions::SHA_COMMENT_MISMATCH_DIAGNOSTIC_CODE` — a supply-chain hygiene
/// warning, not a vulnerability. See [`GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE`]'s doc for why this
/// is a literal.
const GITHUB_ACTIONS_SHA_COMMENT_MISMATCH_CODE: &str = "sha-comment-mismatch";

/// A category a [`CheckFinding`] can be classified into — the seven `--fail-on` tokens FR-009
/// defines, plus [`Category::Other`].
///
/// `Other` covers a `generate_diagnostics` finding that matches none of the seven (an
/// "Unknown package", a collapsed registry-lookup failure, or a workspace-registry/
/// offline/dependency-count notice). It is never selectable via `--fail-on`
/// (`#[value(skip)]`) and never matched by [`FailOnPolicy`] — it exists purely so
/// [`CheckFinding`] stays a 1:1 mapping of every diagnostic `generate_diagnostics` produced,
/// per spec 062 `tasks.md` T020, rather than silently dropping findings this crate cannot
/// classify.
///
/// `Serialize`/`Deserialize` (#1626, manual impls below [`Self::as_str`]) produce/accept the
/// exact same tokens as [`Self::as_str`] — used directly as
/// `crate::format::json::FindingDocument::category` and as the
/// `crate::format::json::ReportDocument::summary` map key, so the JSON wire format never
/// stringly-types this closed set.
///
/// # Examples
///
/// ```
/// use deps_cli::report::Category;
///
/// assert_eq!(Category::MutableRefPin.as_str(), "mutable-ref");
/// assert_eq!(Category::License.as_str(), "license");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, clap::ValueEnum)]
pub enum Category {
    /// A newer version is published for a dependency's declared requirement.
    Outdated,
    /// The in-use (or only-satisfying) version has been yanked/retracted.
    Yanked,
    /// A known OSV advisory affects the in-use version.
    Vulnerable,
    /// No published version satisfies the declared requirement.
    Unsatisfiable,
    /// Pinned to a mutable ref (tag/branch) instead of a commit SHA (GitHub Actions/GitLab
    /// CI).
    #[value(name = "mutable-ref")]
    MutableRefPin,
    /// The resolved license violates the configured allow/deny policy.
    License,
    /// The registry reports the package itself as deprecated/abandoned.
    Deprecated,
    /// A `generate_diagnostics` finding that does not map to any category above.
    #[value(skip)]
    Other,
}

impl Category {
    /// The FR-009 wire token for this category (`table`/`json` output and `--fail-on`).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Outdated => "outdated",
            Self::Yanked => "yanked",
            Self::Vulnerable => "vulnerable",
            Self::Unsatisfiable => "unsatisfiable",
            Self::MutableRefPin => "mutable-ref",
            Self::License => "license",
            Self::Deprecated => "deprecated",
            Self::Other => "other",
        }
    }

    /// A one-line human-readable description, longer than [`Self::as_str`]'s wire token —
    /// used as SARIF rule metadata (`crate::format::sarif`) for a rule that only has
    /// category-level granularity (no finer diagnostic code). Deliberately close in wording
    /// to each variant's own doc comment above (both describe the same category, and SARIF's
    /// `shortDescription` is meant to read like ordinary documentation prose) rather than a
    /// genuinely distinct text written just to avoid the overlap.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_cli::report::Category;
    ///
    /// assert_eq!(
    ///     Category::Vulnerable.description(),
    ///     "A known security advisory affects the in-use version."
    /// );
    /// assert_eq!(
    ///     Category::License.description(),
    ///     "The resolved license violates the configured allow/deny policy."
    /// );
    /// ```
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::Outdated => {
                "A newer version is published for the dependency's declared requirement."
            }
            Self::Yanked => "The in-use version has been yanked or retracted from the registry.",
            Self::Vulnerable => "A known security advisory affects the in-use version.",
            Self::Unsatisfiable => "No published version satisfies the declared requirement.",
            Self::MutableRefPin => {
                "Pinned to a mutable ref (tag or branch) instead of a commit SHA."
            }
            Self::License => "The resolved license violates the configured allow/deny policy.",
            Self::Deprecated => {
                "The registry reports the package itself as deprecated or abandoned."
            }
            Self::Other => "A finding that does not map to any of the other categories.",
        }
    }
}

impl std::fmt::Display for Category {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

// Manual `Serialize`/`Deserialize` (#1626), not `#[derive(Serialize)]` +
// `#[serde(rename_all = ...)]`: the derived unit-variant `Serialize` impl
// (`serialize_unit_variant`) was empirically reproduced to make
// `insta::assert_json_snapshot!` panic ("cannot serialize maps without string keys to JSON")
// when this type was used as a raw `BTreeMap` key. `ReportDocument::summary` now serializes
// through its own `serialize_with` (`serialize_summary_lexicographically`) instead of relying
// on this impl for its keys, but this `serialize_str` impl is kept so `Category` still reads
// as a plain string in every other context (the `FindingDocument::category` field, and
// `summary`'s `Deserialize` side).
impl serde::Serialize for Category {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> serde::Deserialize<'de> for Category {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let token = String::deserialize(deserializer)?;
        match token.as_str() {
            "outdated" => Ok(Self::Outdated),
            "yanked" => Ok(Self::Yanked),
            "vulnerable" => Ok(Self::Vulnerable),
            "unsatisfiable" => Ok(Self::Unsatisfiable),
            "mutable-ref" => Ok(Self::MutableRefPin),
            "license" => Ok(Self::License),
            "deprecated" => Ok(Self::Deprecated),
            "other" => Ok(Self::Other),
            other => Err(serde::de::Error::unknown_variant(
                other,
                &[
                    "outdated",
                    "yanked",
                    "vulnerable",
                    "unsatisfiable",
                    "mutable-ref",
                    "license",
                    "deprecated",
                    "other",
                ],
            )),
        }
    }
}

/// One reported issue, derived 1:1 from a [`Diagnostic`] `generate_diagnostics` produced.
#[derive(Debug, Clone)]
pub struct CheckFinding {
    /// Which ecosystem's manifest this finding came from.
    pub ecosystem: EcosystemId,
    /// Path to the manifest, relative to the walked root when discovered by [`crate::walk`].
    /// Passed through `crate::sanitize::sanitize_path_for_display` (#1299) at `to_finding`
    /// construction time, so a raw ANSI escape byte or bidi-override character embedded in
    /// the walked path never reaches the table or JSON sink unescaped. Every other
    /// `deps-cli` warning sink sanitizes at its own construction boundary the same way — see
    /// that module's doc.
    pub manifest_path: PathBuf,
    /// The dependency's declared name, when a manifest occurrence's range matched the
    /// diagnostic's own range. `None` for a document-level finding not anchored to one
    /// dependency (e.g. an offline/dependency-count notice). Passed through
    /// [`deps_core::lsp_helpers::redact_name_for_diagnostic`] (#1242, #1246), so this is
    /// never the raw manifest value.
    pub dependency_name: Option<String>,
    /// The dependency's declared version requirement, when known. Passed through
    /// [`deps_core::lsp_helpers::redact_requirement_for_diagnostic`] (#1258, #1300), so this
    /// is never the raw manifest value either.
    pub requirement: Option<String>,
    /// The classified category (see [`Category`]).
    pub category: Category,
    /// The diagnostic's own `code`, when it carried a string one (spec 062 review S3,
    /// issue #1075): a vulnerability diagnostic's code is an OSV advisory id
    /// (`RUSTSEC-...`/`GHSA-...`), finer-grained than [`Self::category`]; the workspace's
    /// other stable diagnostic-code constants (`UNSATISFIABLE_DIAGNOSTIC_CODE`, etc.) are
    /// 1:1 with a category, so carrying them here changes nothing beyond echoing
    /// `category`. `None` when `classify` fell back to matching the diagnostic's message
    /// text instead of its code (`Outdated`/`Yanked`/`Other`).
    pub code: Option<String>,
    /// The advisory's own `https://osv.dev/vulnerability/{id}` page, when [`Self::code`] is
    /// an OSV advisory id — sourced from the diagnostic's `code_description.href` (already
    /// `Uri`-parsed and validated by `deps_core::lsp_helpers::diagnostics::
    /// push_vulnerability_diagnostics` before it ever reaches a `Diagnostic`), not
    /// re-derived from `code` — the authoritative URL OSV itself gave us, rather than a
    /// second, redundant formula that could drift from it. `None` whenever `code_description`
    /// is absent (every non-advisory finding, and the rare case where OSV's own `url` failed
    /// `Uri` parsing upstream).
    pub advisory_url: Option<String>,
    /// The OSV-derived severity bucket for [`Self::code`], when it names an advisory this
    /// manifest's OSV scan actually fetched (issue #1077 C2) — looked up by advisory id from
    /// the same scan results `generate_diagnostics` consumed, not re-derived from
    /// [`Self::severity`] (the three-bucket [`Severity`] `code` already collapsed into is too
    /// coarse to recover a CVSS-style grade from). `None` for every non-advisory finding, and
    /// for an advisory `code` this run's scan did not itself fetch (e.g. a stale `code` from a
    /// formatter that does not source it from a live scan).
    pub advisory_severity: Option<VulnSeverity>,
    /// The diagnostic's severity.
    pub severity: Severity,
    /// The diagnostic's range within the manifest.
    pub range: Range,
    /// The diagnostic's human-readable message.
    pub message: String,
}

/// The full result of one `check` invocation.
#[derive(Debug, Clone, Default)]
pub struct CheckReport {
    /// Every finding produced across every walked manifest.
    pub findings: Vec<CheckFinding>,
}

impl CheckReport {
    /// Per-category finding counts, derived from [`Self::findings`] rather than kept as
    /// separately mutated state (spec 062 tasks.md T020).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_cli::report::{Category, CheckFinding, CheckReport};
    /// use deps_core::EcosystemId;
    /// use deps_core::diagnostic::Severity;
    /// use deps_core::position::Range;
    /// use std::path::PathBuf;
    ///
    /// let report = CheckReport {
    ///     findings: vec![CheckFinding {
    ///         ecosystem: EcosystemId::Cargo,
    ///         manifest_path: PathBuf::from("Cargo.toml"),
    ///         dependency_name: Some("serde".to_string()),
    ///         requirement: Some("1.0".to_string()),
    ///         category: Category::Outdated,
    ///         code: None,
    ///         advisory_url: None,
    ///         advisory_severity: None,
    ///         severity: Severity::Hint,
    ///         range: Range::default(),
    ///         message: "Newer version available: 1.1".to_string(),
    ///     }],
    /// };
    /// assert_eq!(report.summary().get(&Category::Outdated), Some(&1));
    /// ```
    #[must_use]
    pub fn summary(&self) -> BTreeMap<Category, usize> {
        let mut counts = BTreeMap::new();
        for finding in &self.findings {
            *counts.entry(finding.category).or_insert(0_usize) += 1;
        }
        counts
    }
}

/// The set of categories that turn at least one matching [`CheckFinding`] into a
/// process-exit-1 policy violation (FR-009/FR-010).
#[derive(Debug, Clone)]
pub struct FailOnPolicy {
    categories: Vec<Category>,
}

impl FailOnPolicy {
    /// Builds a policy from an explicit category list.
    #[must_use]
    pub const fn new(categories: Vec<Category>) -> Self {
        Self { categories }
    }

    /// The default policy (FR-010): `vulnerable,yanked,unsatisfiable` — the categories that
    /// represent a broken or unsafe build, as opposed to advisory-only categories.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_cli::report::{Category, FailOnPolicy};
    ///
    /// let policy = FailOnPolicy::default_categories();
    /// assert!(policy.categories().contains(&Category::Vulnerable));
    /// assert!(!policy.categories().contains(&Category::Outdated));
    /// ```
    #[must_use]
    pub fn default_categories() -> Self {
        Self::new(vec![
            Category::Vulnerable,
            Category::Yanked,
            Category::Unsatisfiable,
        ])
    }

    /// The categories this policy fails on.
    #[must_use]
    pub fn categories(&self) -> &[Category] {
        &self.categories
    }

    /// Whether any finding in `findings` matches this policy.
    #[must_use]
    pub fn matches(&self, findings: &[CheckFinding]) -> bool {
        findings
            .iter()
            .any(|finding| self.categories.contains(&finding.category))
    }
}

impl Default for FailOnPolicy {
    fn default() -> Self {
        Self::default_categories()
    }
}

/// Runtime handles and resolved policy shared across every manifest a `check` run classifies.
///
/// Built once in `main.rs` (or by an integration test) and passed by reference to
/// [`check_manifest`] for every discovered manifest.
#[derive(Clone)]
pub struct CheckContext {
    /// Shared HTTP cache for registry requests.
    pub cache: Arc<HttpCache>,
    /// Shared OSV.dev vulnerability scan client.
    pub osv: Arc<OsvClient>,
    /// Shared deps.dev client for GOSSIP cooldown findings (spec 074) — always constructed,
    /// regardless of `policy.gossip.enabled`; see `deps-cli::main::RuntimeHandles::deps_dev`'s
    /// doc for why. [`crate::analyze::analyze_manifest`] passes it through as
    /// `Option<&Arc<DepsDevClient>>`, `None` when GOSSIP is disabled.
    pub deps_dev: Arc<deps_core::DepsDevClient>,
    /// Shared lock-file cache, keyed by resolved lockfile path.
    pub lockfile_cache: Arc<deps_core::lockfile::LockFileCache>,
    /// The resolved policy configuration for this run.
    pub policy: PolicyConfig,
}

/// Error running [`check_manifest`] for one manifest.
#[derive(Debug, thiserror::Error)]
pub enum CheckError {
    /// The manifest content could not be parsed by its ecosystem's parser.
    #[error("failed to parse {path}: {source}")]
    Parse {
        /// The manifest path that failed to parse.
        path: PathBuf,
        /// The underlying parse error.
        #[source]
        source: deps_core::DepsError,
    },
    /// `manifest_path` could not be represented as a file URI (e.g. a malformed or
    /// non-representable path on this platform).
    #[error("could not build a file URI for {path}")]
    InvalidPath {
        /// The manifest path that could not be converted.
        path: PathBuf,
    },
}

/// The result of classifying one manifest.
#[derive(Debug, Clone)]
pub struct ManifestCheckResult {
    /// Every finding produced for this manifest.
    pub findings: Vec<CheckFinding>,
    /// Whether at least one dependency's *version* registry fetch failed while not offline
    /// (FR-012) — the caller uses this to decide between exit 1 (policy violation over an
    /// otherwise complete report) and exit 2 (an incomplete report because a registry was
    /// unreachable).
    ///
    /// Deliberately does **not** cover a tier-3 license-source timeout (Dart/Swift/Gradle/
    /// Deno) — see [`Self::license_fetch_incomplete`] — a Maven Central outage while the
    /// version registry itself is fully reachable is a different failure with a different
    /// remediation (issue #1133 code-review finding #1), and conflating the two would mislead
    /// a caller inspecting this field into diagnosing the wrong system.
    pub registry_unreachable: bool,
    /// Whether at least one dependency's tier-3 license fetch (Dart/Swift/Gradle/Deno) timed
    /// out while not offline (issue #1133 code-review finding #1) — kept separate from
    /// [`Self::registry_unreachable`] since the two name genuinely different subsystems (the
    /// license source vs. the version registry), even though both feed the same exit-2
    /// "incomplete report" signal in `main.rs`. See
    /// `deps_engine::classify::license::TierThreeLicenseFetch::timed_out`'s doc for exactly
    /// which failure modes this can (and cannot) detect.
    pub license_fetch_incomplete: bool,
}

/// Classifies one already-routed manifest.
///
/// Parses it, resolves in-use/lockfile versions, fetches latest registry versions, runs an
/// OSV scan (when enabled and not offline), and calls the ecosystem's own
/// `generate_diagnostics` — then converts each returned [`Diagnostic`] into a
/// [`CheckFinding`].
///
/// Every verdict decision (outdated/yanked/vulnerable/unsatisfiable/deprecated/license) is
/// made by [`deps_engine::classify`] or by `generate_diagnostics` itself; this function only
/// assembles their inputs and converts their output (spec 062 FR-005).
///
/// # Errors
///
/// Returns [`CheckError::InvalidPath`] if `manifest_path` cannot be represented as a file
/// URI, or [`CheckError::Parse`] if `content` fails to parse as this ecosystem's manifest
/// format.
pub async fn check_manifest(
    ecosystem: &Arc<dyn Ecosystem>,
    manifest_path: &Path,
    display_path: &Path,
    content: &str,
    ctx: &CheckContext,
) -> Result<ManifestCheckResult, CheckError> {
    let analysis = crate::analyze::analyze_manifest(
        ecosystem,
        manifest_path,
        content,
        ctx,
        crate::analyze::AnalysisScope::all(),
    )
    .await?;
    let formatter = ecosystem.formatter();

    let severities = ctx.policy.diagnostics.to_severities();
    let diagnostics = ecosystem
        .generate_diagnostics(
            analysis.parse_result.as_ref(),
            analysis.version_data(),
            &analysis.uri,
            ctx.policy.freshness.to_freshness(),
            severities,
        )
        .await;

    let dep_index = DependencyIndex::build(analysis.parse_result.as_ref());
    // TODO(#1726): mark advisories matched only through a sibling release tag in the report.
    let advisory_severities = advisory_severity_index(analysis.vulnerabilities.as_ref());
    // Same per-occurrence key `vulnerabilities` was built under, so a shared advisory id
    // across two dependencies can never resolve to the wrong one's severity (issue #1077 review #4).
    let vuln_keys = deps_core::osv::vulnerability_keys(
        analysis.parse_result.as_ref(),
        &analysis.resolved_versions,
        Some(&analysis.resolved_version_candidates),
        formatter,
        analysis.ecosystem_id,
    );
    let findings = diagnostics
        .into_iter()
        .map(|diagnostic| {
            to_finding(
                analysis.ecosystem_id,
                display_path,
                &dep_index,
                formatter,
                diagnostic,
                &advisory_severities,
                &vuln_keys,
                &analysis.cached_versions,
            )
        })
        .collect();
    Ok(ManifestCheckResult {
        findings,
        registry_unreachable: analysis.registry_unreachable,
        license_fetch_incomplete: analysis.license_fetch_incomplete,
    })
}

/// Indexes every dependency occurrence by its name range and (separately) its version
/// range, so a diagnostic anchored at either can be traced back to the declaration that
/// produced it (see [`to_finding`]).
///
/// Two separate maps (M6, spec 062 review) rather than one shared `HashMap<Range, _>`: a
/// single map risks one dependency's name-range entry silently overwriting a *different*
/// dependency's version-range entry if the two ranges ever coincide, misattributing
/// `dependency_name`. Keeping the two lookups apart makes that impossible regardless of
/// range values, not just unlikely in practice.
struct DependencyIndex<'a> {
    by_name_range: HashMap<Range, &'a dyn Dependency>,
    by_version_range: HashMap<Range, &'a dyn Dependency>,
}

impl<'a> DependencyIndex<'a> {
    fn build(parse_result: &'a dyn deps_core::ParseResult) -> Self {
        let mut by_name_range = HashMap::new();
        let mut by_version_range = HashMap::new();
        for dep in parse_result.dependencies() {
            if !dep.name_range_is_synthetic() {
                by_name_range.insert(dep.name_range(), dep);
            }
            if let Some(version_range) = dep.version_range() {
                by_version_range.insert(version_range, dep);
            }
        }
        Self {
            by_name_range,
            by_version_range,
        }
    }

    /// Looks up the dependency a diagnostic's `range` is anchored to, preferring a
    /// name-range match (diagnostics anchored at `resolved.version_range` still resolve via
    /// the version-range map when no name-range entry matches the same coordinates).
    fn lookup(&self, range: Range) -> Option<&'a dyn Dependency> {
        self.by_name_range
            .get(&range)
            .or_else(|| self.by_version_range.get(&range))
            .copied()
    }
}

/// Indexes every advisory this manifest's OSV scan fetched, keyed by (the [`VulnerabilityMap`]
/// key identifying the specific dependency occurrence, advisory id) rather than by advisory id
/// alone (issue #1077 review #4), so [`to_finding`] can attach a
/// [`CheckFinding::advisory_severity`] without re-deriving a grade from the coarser
/// [`Severity`] a `Diagnostic` carries.
///
/// A bare `HashMap<String, VulnSeverity>` keyed only by advisory id would let one dependency's
/// severity silently overwrite another's (unspecified `HashMap` iteration order) whenever two
/// dependencies in this manifest shared an advisory id — OSV can legitimately report one id
/// against several different packages in the same record. [`to_finding`] looks its own
/// dependency occurrence's key up via [`deps_core::osv::vulnerability_keys`] — the same
/// function `vulnerabilities` itself was keyed under — so this can never drift out of sync
/// with how the scan actually mapped occurrences to results.
///
/// `None` `vulnerabilities` (scan disabled, or offline) yields an empty index, same as a
/// (key, id) pair this index has no entry for — both resolve to
/// `CheckFinding::advisory_severity: None`.
fn advisory_severity_index(
    vulnerabilities: Option<&VulnerabilityMap>,
) -> HashMap<(deps_core::osv::VulnKey, String), VulnSeverity> {
    let mut index = HashMap::new();
    let Some(vulnerabilities) = vulnerabilities else {
        return index;
    };
    for (dependency_key, outcome) in vulnerabilities {
        if let ScanOutcome::Vulnerable(dv) = outcome {
            for advisory in dv.advisories.items() {
                index.insert(
                    (dependency_key.clone(), advisory.id.clone()),
                    advisory.severity,
                );
            }
        }
    }
    index
}

/// Converts one `generate_diagnostics` [`Diagnostic`] into a [`CheckFinding`], classifying
/// its [`Category`] (see [`classify`]) and, when its range matches a manifest occurrence
/// (from [`DependencyIndex`]), its `dependency_name`/`requirement`. `advisory_severities` and
/// `vuln_keys` together resolve [`CheckFinding::advisory_severity`] — see
/// [`advisory_severity_index`].
#[allow(
    clippy::too_many_arguments,
    reason = "internal (non-pub) call-site-controlled classification/attribution inputs; \
              grouping into a struct would only move, not reduce, the single production \
              call site's churn"
)]
fn to_finding(
    ecosystem: EcosystemId,
    display_path: &Path,
    dep_index: &DependencyIndex<'_>,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
    diagnostic: Diagnostic,
    advisory_severities: &HashMap<(deps_core::osv::VulnKey, String), VulnSeverity>,
    vuln_keys: &VulnKeys,
    cached_versions: &HashMap<deps_core::PackageName, deps_core::lsp_helpers::PackageVersions>,
) -> CheckFinding {
    let category = classify(&diagnostic, formatter);
    let dep = dep_index.lookup(diagnostic.range);
    let code = diagnostic.code().map(str::to_string);
    let advisory_url = diagnostic
        .code_description
        .as_ref()
        .map(|code_description| code_description.href.as_str().to_string());
    let advisory_severity = code.as_deref().zip(dep).and_then(|(code, dep)| {
        // Deliberately narrower than resolve_scan_outcome: None on synthetic ranges, no further fallback.
        if dep.name_range_is_synthetic() {
            return None;
        }
        let dependency_key = deps_core::osv::vuln_key_for(dep, Some(vuln_keys), formatter);
        advisory_severities
            .get(&(dependency_key, code.to_string()))
            .copied()
    });
    // Spec 074 FR-005: attribute an `Outdated` finding to an active GOSSIP cooldown when it
    // is the sole reason a newer version was excluded from being "latest" — matched by the
    // occurrence's own (pre-redaction) `PackageName`, never `CheckFinding::dependency_name`
    // (already redacted by this point, and not guaranteed to equal `cached_versions`'s raw
    // key). No `deps-core` change: this only reads the additive
    // `PackageVersions::gossip_excluded_version` field `deps-engine`'s fetch already set.
    let mut message = diagnostic.message().to_string();
    if category == Category::Outdated
        && let Some(dep) = dep
        && cached_versions
            .get(dep.name())
            .is_some_and(|v| v.gossip_excluded_version.is_some())
    {
        message.push_str(
            " (a newer version was excluded from this pick by an active GOSSIP cooldown finding)",
        );
    }
    CheckFinding {
        ecosystem,
        manifest_path: crate::sanitize::sanitize_path_for_display(display_path),
        dependency_name: dep.map(|d| redact_name_for_diagnostic(d.name())),
        requirement: dep
            .and_then(Dependency::version_requirement)
            .map(redact_requirement_for_diagnostic),
        category,
        code,
        advisory_url,
        advisory_severity,
        severity: diagnostic.severity.unwrap_or(Severity::Warning),
        range: diagnostic.range,
        message,
    }
}

/// Classifies a `generate_diagnostics` [`Diagnostic`] into a [`Category`].
///
/// Diagnostics that carry one of the workspace's known non-advisory codes (the three
/// `deps-core` sentinels, the two mutable-ref-pin codes, or GitLab CI's
/// [`GITLAB_CI_UNRESOLVED_HOST_CODE`] notice) classify directly from `code`. A vulnerability
/// advisory id (an OSV id such as `RUSTSEC-...`/`GHSA-...`) is the only other free-form `code`
/// value `generate_diagnostics_from_cache` ever sets, so any `Some(code)` that matches none of
/// the known non-advisory codes classifies as [`Category::Vulnerable`] — this fallback is
/// sound only as long as the known-code list above stays exhaustive (see that list's own doc
/// for the regression this already caused once). An outdated diagnostic carries no code but
/// always starts with the fixed prefix `apply_outdated_rule` uses; a yanked diagnostic carries
/// no code either, but always contains `formatter.yanked_message()` verbatim — the same text
/// it was built from. The advisory-overflow summary line ("+N more advisories") also carries
/// no code but always ends with that fixed suffix, and is still [`Category::Vulnerable`].
/// Anything else (unknown-package, collapsed fetch-failure, blocked-registry,
/// offline/dependency-count notices) classifies as [`Category::Other`].
fn classify(
    diagnostic: &Diagnostic,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> Category {
    if let Some(code) = diagnostic.code() {
        return match code {
            UNSATISFIABLE_DIAGNOSTIC_CODE => Category::Unsatisfiable,
            LICENSE_POLICY_VIOLATION_DIAGNOSTIC_CODE => Category::License,
            DEPRECATED_DIAGNOSTIC_CODE => Category::Deprecated,
            GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE | GITLAB_CI_MUTABLE_REF_PIN_CODE => {
                Category::MutableRefPin
            }
            GITLAB_CI_UNRESOLVED_HOST_CODE | GITHUB_ACTIONS_SHA_COMMENT_MISMATCH_CODE => {
                Category::Other
            }
            _ => Category::Vulnerable,
        };
    }
    if diagnostic.message().starts_with("Newer version available") {
        return Category::Outdated;
    }
    if diagnostic.message().contains(formatter.yanked_message()) {
        return Category::Yanked;
    }
    // The advisory-overflow summary line carries no code but is still a vulnerability finding
    // (M1, spec 062 review) — else a manifest over `ADVISORY_DISPLAY_CAP` reports it as `Other`.
    if diagnostic.message().ends_with("more advisories") {
        return Category::Vulnerable;
    }
    Category::Other
}

/// Builds a file URI from a filesystem path, without any path-existence check. Returns
/// `None` when `path` cannot be represented as a file URI at all — `Url::from_file_path`
/// requires an absolute path (this function already joins a relative one onto the current
/// directory first) and, on Windows, a disk (`C:`) or UNC (`\\`) prefix; UNC paths
/// themselves are supported, just not any other Windows path prefix shape. The caller
/// surfaces a `None` here as [`CheckError::InvalidPath`] rather than fabricating a
/// synthetic, unusable URI.
pub(crate) fn path_to_uri(path: &Path) -> Option<url::Url> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    };
    url::Url::from_file_path(&absolute).ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use deps_core::PackageName;

    fn finding(category: Category) -> CheckFinding {
        CheckFinding {
            ecosystem: EcosystemId::Cargo,
            manifest_path: PathBuf::from("Cargo.toml"),
            dependency_name: Some("serde".to_string()),
            requirement: Some("1.0".to_string()),
            category,
            code: None,
            advisory_url: None,
            advisory_severity: None,
            severity: Severity::Warning,
            range: Range::default(),
            message: "test".to_string(),
        }
    }

    #[test]
    fn test_category_as_str_matches_fr009_tokens() {
        assert_eq!(Category::Outdated.as_str(), "outdated");
        assert_eq!(Category::Yanked.as_str(), "yanked");
        assert_eq!(Category::Vulnerable.as_str(), "vulnerable");
        assert_eq!(Category::Unsatisfiable.as_str(), "unsatisfiable");
        assert_eq!(Category::MutableRefPin.as_str(), "mutable-ref");
        assert_eq!(Category::License.as_str(), "license");
        assert_eq!(Category::Deprecated.as_str(), "deprecated");
        assert_eq!(Category::Other.as_str(), "other");
    }

    /// #1626: `Serialize` must emit the same tokens as [`Category::as_str`], byte-identical
    /// (quoted JSON strings), for every variant — including `MutableRefPin`'s explicit rename.
    #[test]
    fn test_category_serialize_matches_as_str_tokens() {
        for category in [
            Category::Outdated,
            Category::Yanked,
            Category::Vulnerable,
            Category::Unsatisfiable,
            Category::MutableRefPin,
            Category::License,
            Category::Deprecated,
            Category::Other,
        ] {
            let json = serde_json::to_string(&category).expect("Category must serialize");
            assert_eq!(json, format!("\"{}\"", category.as_str()));
            let parsed: Category = serde_json::from_str(&json).expect("must round-trip");
            assert_eq!(parsed, category);
        }
    }

    /// #1626 tester gap 1: an unrecognized `category` token must be a hard deserialize error
    /// (the `unknown_variant` arm of `Category`'s manual `Deserialize` impl above), not
    /// silently accepted or defaulted to [`Category::Other`].
    #[test]
    fn test_category_deserialize_rejects_unknown_token() {
        let result: Result<Category, _> = serde_json::from_str("\"not-a-real-category\"");
        assert!(result.is_err());
    }

    #[test]
    fn test_fail_on_policy_default_categories() {
        let policy = FailOnPolicy::default_categories();
        assert!(policy.matches(&[finding(Category::Vulnerable)]));
        assert!(policy.matches(&[finding(Category::Yanked)]));
        assert!(policy.matches(&[finding(Category::Unsatisfiable)]));
        assert!(!policy.matches(&[finding(Category::Outdated)]));
        assert!(!policy.matches(&[finding(Category::License)]));
        assert!(!policy.matches(&[finding(Category::Deprecated)]));
        assert!(!policy.matches(&[finding(Category::MutableRefPin)]));
        assert!(!policy.matches(&[finding(Category::Other)]));
    }

    #[test]
    fn test_fail_on_policy_custom_categories() {
        let policy = FailOnPolicy::new(vec![Category::License]);
        assert!(policy.matches(&[finding(Category::License)]));
        assert!(!policy.matches(&[finding(Category::Vulnerable)]));
    }

    #[test]
    fn test_fail_on_policy_empty_findings_never_matches() {
        assert!(!FailOnPolicy::default_categories().matches(&[]));
    }

    #[test]
    fn test_check_report_summary_counts_per_category() {
        let report = CheckReport {
            findings: vec![
                finding(Category::Outdated),
                finding(Category::Outdated),
                finding(Category::Vulnerable),
            ],
        };
        let summary = report.summary();
        assert_eq!(summary.get(&Category::Outdated), Some(&2));
        assert_eq!(summary.get(&Category::Vulnerable), Some(&1));
        assert_eq!(summary.get(&Category::License), None);
    }

    #[test]
    fn test_check_report_summary_empty_for_no_findings() {
        let report = CheckReport::default();
        assert!(report.summary().is_empty());
    }

    const STUB_FORMATTER: deps_core::test_util::StubFormatter =
        deps_core::test_util::StubFormatter::new().with_package_url_prefix("");

    fn diagnostic_with(code: Option<&str>, message: &str) -> Diagnostic {
        let diagnostic =
            Diagnostic::new(Range::default(), message).with_severity(Severity::Warning);
        match code {
            Some(code) => diagnostic.with_code(code),
            None => diagnostic,
        }
    }

    #[test]
    fn test_classify_unsatisfiable_by_code() {
        let d = diagnostic_with(Some(UNSATISFIABLE_DIAGNOSTIC_CODE), "no matching version");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Unsatisfiable);
    }

    #[test]
    fn test_classify_license_by_code() {
        let d = diagnostic_with(
            Some(LICENSE_POLICY_VIOLATION_DIAGNOSTIC_CODE),
            "GPL-3.0 denied",
        );
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::License);
    }

    #[test]
    fn test_classify_deprecated_by_code() {
        let d = diagnostic_with(Some(DEPRECATED_DIAGNOSTIC_CODE), "package deprecated");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Deprecated);
    }

    #[test]
    fn test_classify_mutable_ref_pin_by_code() {
        let d = diagnostic_with(Some(GITHUB_ACTIONS_MUTABLE_REF_PIN_CODE), "pinned to a tag");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::MutableRefPin);
        let d = diagnostic_with(Some(GITLAB_CI_MUTABLE_REF_PIN_CODE), "pinned to a tag");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::MutableRefPin);
    }

    #[test]
    fn test_classify_sha_comment_mismatch_is_other() {
        let d = diagnostic_with(
            Some(GITHUB_ACTIONS_SHA_COMMENT_MISMATCH_CODE),
            "SHA is not the commit of the tag in the comment",
        );
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Other);
    }

    #[test]
    fn test_classify_advisory_code_is_vulnerable() {
        let d = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Vulnerable);
    }

    #[test]
    fn test_classify_outdated_by_message_prefix() {
        let d = diagnostic_with(None, "Newer version available: 2.0.0");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Outdated);
    }

    #[test]
    fn test_classify_yanked_by_formatter_message() {
        let d = diagnostic_with(None, "This version has been yanked (1.0.0)");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Yanked);
    }

    #[test]
    fn test_classify_unknown_package_is_other() {
        let d = diagnostic_with(None, "Unknown package 'left-pad'");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Other);
    }

    /// Regression test for M1 (spec 062 review): the trailing "+N more advisories" overflow
    /// summary carries no code but is still a vulnerability finding, not `Other`.
    #[test]
    fn test_classify_advisory_overflow_summary_is_vulnerable() {
        let d = diagnostic_with(None, "+5 more advisories");
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Vulnerable);
    }

    /// Regression test for C3 (spec 062 review): GitLab CI's `unresolved-gitlab-host` notice
    /// is informational (INFORMATION severity, never a vulnerability) and must not fall
    /// through to the advisory-id fallback.
    #[test]
    fn test_classify_gitlab_unresolved_host_is_other_not_vulnerable() {
        let d = diagnostic_with(
            Some(GITLAB_CI_UNRESOLVED_HOST_CODE),
            "registries.gitlab_instance_host is unset; skipping component/project host resolution",
        );
        assert_eq!(classify(&d, &STUB_FORMATTER), Category::Other);
    }

    /// A single-dependency parse result whose one dependency ("dep-0") sits at
    /// `Range::default()` (`deps_core::test_util::StubDependency::name_range` always
    /// returns it) — matching `diagnostic_with`'s own hardcoded `range: Range::default()`
    /// (both the same `deps_core::position::Range` `DependencyIndex` is keyed on), so
    /// `DependencyIndex::lookup` resolves it for tests that need a real, non-`None`
    /// dependency occurrence.
    fn dep_index_with_one_dependency() -> Box<dyn deps_core::ParseResult> {
        deps_core::test_util::stub_parse_result_with_dependencies(1)
    }

    fn empty_dep_index() -> Box<dyn deps_core::ParseResult> {
        deps_core::test_util::stub_parse_result_with_dependencies(0)
    }

    /// A single-dependency [`deps_core::Dependency`]/[`deps_core::ParseResult`] fixture whose
    /// name (and, for the #1258/#1300 requirement-redaction tests, requirement) is
    /// caller-controlled — unlike [`dep_index_with_one_dependency`]'s fixed `dep-0`, needed
    /// to exercise `to_finding`'s `dependency_name`/`requirement` redaction (#1242, #1246,
    /// #1258, #1300) with attacker-controlled manifest values.
    struct NamedFixtureDep {
        name: PackageName,
        requirement: Option<deps_core::VersionReq>,
    }

    impl deps_core::Dependency for NamedFixtureDep {
        fn name(&self) -> &PackageName {
            &self.name
        }
        fn name_range(&self) -> Range {
            Range::default()
        }
        fn version_requirement(&self) -> Option<&deps_core::VersionReq> {
            self.requirement.as_ref()
        }
        fn version_range(&self) -> Option<Range> {
            None
        }
        fn source(&self) -> deps_core::parser::DependencySource {
            deps_core::parser::DependencySource::Registry
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    struct NamedFixtureParseResult {
        dep: NamedFixtureDep,
        uri: url::Url,
    }

    impl deps_core::ParseResult for NamedFixtureParseResult {
        fn dependencies(&self) -> Vec<&dyn deps_core::Dependency> {
            vec![&self.dep]
        }
        fn workspace_root(&self) -> Option<&Path> {
            None
        }
        fn uri(&self) -> &url::Url {
            &self.uri
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    fn dep_index_with_named_dependency(name: &str) -> Box<dyn deps_core::ParseResult> {
        Box::new(NamedFixtureParseResult {
            dep: NamedFixtureDep {
                name: PackageName::new(name),
                requirement: None,
            },
            uri: "file:///project/manifest.toml".parse().expect("valid URI"),
        })
    }

    /// Like [`dep_index_with_named_dependency`], but also setting the dependency's
    /// requirement — needed by the #1258/#1300 requirement-redaction regression tests.
    fn dep_index_with_named_dependency_and_requirement(
        name: &str,
        requirement: &str,
    ) -> Box<dyn deps_core::ParseResult> {
        Box::new(NamedFixtureParseResult {
            dep: NamedFixtureDep {
                name: PackageName::new(name),
                requirement: Some(deps_core::VersionReq::new(requirement)),
            },
            uri: "file:///project/manifest.toml".parse().expect("valid URI"),
        })
    }

    /// Regression test (issue #1077 tester must-fix #2): every other SARIF test hand-builds a
    /// `CheckFinding` with `code` pre-set, bypassing the real `Diagnostic.code ->
    /// CheckFinding.code` extraction this covers.
    #[test]
    fn test_to_finding_extracts_string_code_from_diagnostic() {
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );
        assert_eq!(finding.code.as_deref(), Some("RUSTSEC-2024-0001"));
    }

    #[test]
    fn test_to_finding_code_is_none_without_a_diagnostic_code() {
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 2.0.0");
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );
        assert!(finding.code.is_none());
    }

    /// Spec 074 FR-005: an `Outdated` finding whose dependency has a
    /// `gossip_excluded_version` in `cached_versions` is attributed to GOSSIP in its message.
    #[test]
    fn test_to_finding_attributes_outdated_to_gossip_when_excluded() {
        let parse_result = dep_index_with_named_dependency("serde");
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 1.0.0");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            PackageName::new("serde"),
            deps_core::lsp_helpers::PackageVersions::latest_only("1.0.0")
                .with_gossip_excluded_version(deps_core::ConcreteVersion::new("2.0.0")),
        );
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &cached_versions,
        );
        assert_eq!(finding.category, Category::Outdated);
        assert!(
            finding.message.contains("GOSSIP"),
            "message must attribute the exclusion to GOSSIP: {:?}",
            finding.message
        );
    }

    /// The same dependency with no `gossip_excluded_version` set must not gain the
    /// attribution suffix.
    #[test]
    fn test_to_finding_does_not_attribute_when_no_gossip_exclusion() {
        let parse_result = dep_index_with_named_dependency("serde");
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 1.0.0");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            PackageName::new("serde"),
            deps_core::lsp_helpers::PackageVersions::latest_only("1.0.0"),
        );
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &cached_versions,
        );
        assert_eq!(finding.category, Category::Outdated);
        assert!(!finding.message.contains("GOSSIP"));
    }

    #[test]
    fn test_to_finding_extracts_advisory_url_from_code_description() {
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let href: url::Url = "https://osv.dev/vulnerability/RUSTSEC-2024-0001"
            .parse()
            .expect("valid URL");
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary")
            .with_code_description(deps_core::diagnostic::CodeDescription::new(href));
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );
        assert_eq!(
            finding.advisory_url.as_deref(),
            Some("https://osv.dev/vulnerability/RUSTSEC-2024-0001")
        );
    }

    #[test]
    fn test_to_finding_advisory_url_is_none_without_code_description() {
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");
        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );
        assert!(finding.advisory_url.is_none());
    }

    /// #1242/#1246: `to_finding`'s `dependency_name` field is a second leak path,
    /// independent of the diagnostic's own `message` — the fix at `report.rs`'s
    /// `dependency_name` construction must redact it too.
    #[test]
    fn test_to_finding_redacts_credential_shaped_dependency_name() {
        let parse_result = dep_index_with_named_dependency(
            "https://svcacct:glpat-AAAABBBBCCCCDDDD@gitlab.corp/g/p",
        );
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Unknown package");

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );

        let name = finding
            .dependency_name
            .expect("range matched the dependency");
        assert!(name.contains("***@"));
        assert!(!name.contains("glpat-AAAABBBBCCCCDDDD"));
    }

    /// #1242/#1246 (critic S3 follow-up): unlike a test that builds a [`CheckFinding`] by
    /// hand and assigns an already-redacted `dependency_name`, this drives the real
    /// `to_finding` -> [`crate::format::sarif::to_sarif`] pipeline end to end, so it actually
    /// fails if `to_finding`'s redaction at `dependency_name` construction is ever reverted —
    /// the SARIF fingerprint's percent-encoding otherwise preserves a credential verbatim
    /// (trivially reversible), and GitHub code scanning persists it in alert history beyond
    /// the manifest's own lifetime.
    #[test]
    fn test_to_sarif_fingerprint_never_carries_a_credential_through_to_finding() {
        let parse_result = dep_index_with_named_dependency(
            "https://svcacct:glpat-AAAABBBBCCCCDDDD@gitlab.corp/g/p",
        );
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Unknown package");

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );

        let sarif = crate::format::sarif::to_sarif(&CheckReport {
            findings: vec![finding],
        });
        let fp = sarif.runs[0].results.as_ref().expect("one result")[0]
            .partial_fingerprints
            .as_ref()
            .expect("fingerprint set")
            .get("depsCli/v1")
            .expect("depsCli/v1 fingerprint key")
            .clone();

        assert!(
            !fp.contains("glpat-AAAABBBBCCCCDDDD"),
            "token leaked (raw or percent-encoded, since `-` is never percent-escaped): {fp}"
        );
        let decoded = urlencoding::decode(&fp).expect("fingerprint is valid percent-encoding");
        assert!(
            decoded.contains("***@gitlab.corp"),
            "expected the redacted '***@host' marker, got: {decoded}"
        );
    }

    /// Regression test for #1299: `to_finding`'s `manifest_path` construction must strip a
    /// raw ANSI escape byte and a bidi-override character before the finding is built, not
    /// leave that to each sink. Drives the real `to_finding` -> `format::table::render` /
    /// `format::json::to_document` pipelines end to end (mirrors
    /// `test_to_sarif_fingerprint_never_carries_a_credential_through_to_finding`'s rationale
    /// for #1242/#1246) so it actually fails if the sanitization at construction time is ever
    /// reverted, while asserting the legitimate `src`/`Cargo.toml` path segments still show
    /// up in both sinks.
    #[test]
    fn test_to_finding_sanitizes_manifest_path_ansi_and_bidi() {
        let malicious_path = Path::new("src/\u{202E}\x1Bsneaky/Cargo.toml");
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 2.0.0");

        let finding = to_finding(
            EcosystemId::Cargo,
            malicious_path,
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );

        let sanitized = finding.manifest_path.to_string_lossy().into_owned();
        assert!(
            !sanitized.contains('\u{202E}'),
            "bidi override survived sanitization: {sanitized:?}"
        );
        assert!(
            !sanitized.contains('\x1B'),
            "raw ANSI escape byte survived sanitization: {sanitized:?}"
        );
        assert!(sanitized.contains("src"), "legitimate path info lost");
        assert!(
            sanitized.contains("Cargo.toml"),
            "legitimate path info lost"
        );

        let report = CheckReport {
            findings: vec![finding],
        };

        let table = crate::format::table::render(&report);
        assert!(
            !table.contains('\u{202E}'),
            "bidi override reached table output"
        );
        assert!(
            !table.contains('\x1B'),
            "raw ANSI escape byte reached table output"
        );

        let json = crate::format::json::to_document(&report);
        let manifest_path_json = &json.findings[0].manifest_path;
        assert!(
            !manifest_path_json.contains('\u{202E}'),
            "bidi override reached JSON output"
        );
        assert!(
            !manifest_path_json.contains('\x1B'),
            "raw ANSI escape byte reached JSON output"
        );
        assert!(manifest_path_json.contains("Cargo.toml"));
    }

    /// Regression test for #1258/#1300: `to_finding`'s `requirement` construction must redact
    /// a credential-shaped requirement string, mirroring
    /// `test_to_finding_redacts_credential_shaped_dependency_name`'s coverage of the sibling
    /// `dependency_name` field.
    #[test]
    fn test_to_finding_redacts_credential_shaped_requirement() {
        let parse_result = dep_index_with_named_dependency_and_requirement(
            "some-pkg",
            "https://svcacct:hunter2@gitlab.corp/g/p.git",
        );
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 2.0.0");

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );

        let requirement = finding.requirement.expect("range matched the dependency");
        assert!(requirement.contains("***@"));
        assert!(!requirement.contains("hunter2"));
    }

    /// Regression test for #1258: the requirement's own leak class (raw ANSI escape / bidi
    /// override in `requirement`, reaching `format::json::to_document` — `requirement` has no
    /// table or SARIF sink) must come out sanitized. Mirrors
    /// `test_to_finding_sanitizes_manifest_path_ansi_and_bidi`'s payload and rationale for
    /// the sibling `manifest_path` field. Supersedes #1301's near-identical
    /// `test_json_output_never_carries_raw_bidi_or_ansi_through_requirement` /
    /// `test_to_finding_sanitizes_bidi_and_ansi_in_requirement` (dropped at the #1299/#1300
    /// rebase to avoid shipping two tests for the same regression): this one additionally
    /// targets the exact `requirement` field rather than the whole serialized JSON blob, and
    /// asserts the legitimate `^1.0` prefix survives, not just that the bad chars are gone.
    #[test]
    fn test_to_finding_sanitizes_ansi_and_bidi_in_requirement_json_sink() {
        let parse_result =
            dep_index_with_named_dependency_and_requirement("some-pkg", "^1.0\u{202E}\x1B[31m");
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(None, "Newer version available: 2.0.0");

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &VulnKeys::default(),
            &HashMap::new(),
        );

        let report = CheckReport {
            findings: vec![finding],
        };
        let json = crate::format::json::to_document(&report);
        let requirement_json = json.findings[0]
            .requirement
            .as_deref()
            .expect("range matched the dependency");

        assert!(
            !requirement_json.contains('\u{202E}'),
            "bidi override reached JSON output"
        );
        assert!(
            !requirement_json.contains('\x1B'),
            "raw ANSI escape byte reached JSON output"
        );
        assert!(
            requirement_json.starts_with("^1.0"),
            "legitimate requirement info lost"
        );
    }

    #[test]
    fn test_to_finding_resolves_advisory_severity_from_index() {
        let parse_result = dep_index_with_one_dependency();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");

        let vuln_keys = deps_core::osv::vulnerability_keys(
            parse_result.as_ref(),
            &HashMap::new(),
            None,
            &STUB_FORMATTER,
            EcosystemId::Cargo,
        );
        let mut severities = HashMap::new();
        severities.insert(
            (
                deps_core::test_util::vuln_key("dep-0"),
                "RUSTSEC-2024-0001".to_string(),
            ),
            VulnSeverity::Critical,
        );

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &severities,
            &vuln_keys,
            &HashMap::new(),
        );
        assert_eq!(finding.advisory_severity, Some(VulnSeverity::Critical));
    }

    #[test]
    fn test_to_finding_advisory_severity_is_none_for_an_unindexed_code() {
        let parse_result = dep_index_with_one_dependency();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");
        let vuln_keys = deps_core::osv::vulnerability_keys(
            parse_result.as_ref(),
            &HashMap::new(),
            None,
            &STUB_FORMATTER,
            EcosystemId::Cargo,
        );

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &HashMap::new(),
            &vuln_keys,
            &HashMap::new(),
        );
        assert!(finding.advisory_severity.is_none());
    }

    /// Regression test for issue #1077 review #4: no matching dependency occurrence at all
    /// (an empty `dep_index`/`vuln_keys`, e.g. a document-level diagnostic) must resolve to
    /// `None`, not panic.
    #[test]
    fn test_to_finding_advisory_severity_is_none_without_a_matched_dependency() {
        let parse_result = empty_dep_index();
        let dep_index = DependencyIndex::build(parse_result.as_ref());
        let diagnostic = diagnostic_with(Some("RUSTSEC-2024-0001"), "advisory summary");
        let mut severities = HashMap::new();
        severities.insert(
            (
                deps_core::test_util::vuln_key("dep-0"),
                "RUSTSEC-2024-0001".to_string(),
            ),
            VulnSeverity::Critical,
        );

        let finding = to_finding(
            EcosystemId::Cargo,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostic,
            &severities,
            &VulnKeys::default(),
            &HashMap::new(),
        );
        assert!(finding.advisory_severity.is_none());
    }

    #[test]
    fn test_advisory_severity_index_collects_from_vulnerable_outcomes() {
        use deps_core::osv::{Advisory, Capped, DependencyVulnerabilities};
        use std::sync::Arc;

        let advisory = Advisory::new(
            "RUSTSEC-2024-0001".to_string(),
            "2024-01-01T00:00:00Z".to_string(),
            VulnSeverity::High,
        )
        .expect("valid osv id");
        let dv = DependencyVulnerabilities::new(Capped::new(vec![Arc::new(advisory)], 1));
        let mut map: VulnerabilityMap = HashMap::new();
        map.insert(
            deps_core::test_util::vuln_key("serde"),
            ScanOutcome::Vulnerable(dv),
        );

        let index = advisory_severity_index(Some(&map));
        assert_eq!(
            index.get(&(
                deps_core::test_util::vuln_key("serde"),
                "RUSTSEC-2024-0001".to_string()
            )),
            Some(&VulnSeverity::High)
        );
    }

    /// Regression test for issue #1077 review #4: two different dependencies whose OSV
    /// records legitimately share one advisory id must not let one silently overwrite the
    /// other's severity bucket.
    #[test]
    fn test_advisory_severity_index_does_not_collide_across_dependencies_sharing_an_advisory_id() {
        use deps_core::osv::{Advisory, Capped, DependencyVulnerabilities};
        use std::sync::Arc;

        let advisory_for = |severity: VulnSeverity| {
            Arc::new(
                Advisory::new(
                    "GHSA-shared-id".to_string(),
                    "2024-01-01T00:00:00Z".to_string(),
                    severity,
                )
                .expect("valid osv id"),
            )
        };
        let mut map: VulnerabilityMap = HashMap::new();
        map.insert(
            deps_core::test_util::vuln_key("package-a"),
            ScanOutcome::Vulnerable(DependencyVulnerabilities::new(Capped::new(
                vec![advisory_for(VulnSeverity::Critical)],
                1,
            ))),
        );
        map.insert(
            deps_core::test_util::vuln_key("package-b"),
            ScanOutcome::Vulnerable(DependencyVulnerabilities::new(Capped::new(
                vec![advisory_for(VulnSeverity::Low)],
                1,
            ))),
        );

        let index = advisory_severity_index(Some(&map));
        assert_eq!(
            index.get(&(
                deps_core::test_util::vuln_key("package-a"),
                "GHSA-shared-id".to_string()
            )),
            Some(&VulnSeverity::Critical)
        );
        assert_eq!(
            index.get(&(
                deps_core::test_util::vuln_key("package-b"),
                "GHSA-shared-id".to_string()
            )),
            Some(&VulnSeverity::Low)
        );
    }

    #[test]
    fn test_advisory_severity_index_empty_without_vulnerabilities() {
        assert!(advisory_severity_index(None).is_empty());
    }

    /// Spec 075 SC-007/FR-006: `ManifestAnalysis::version_data()` finally wires live GOSSIP
    /// prefetch data into `check`'s diagnostic generation (`version_data()` never called
    /// `with_gossip_prefetch` before this field existed) — an `Outdated` dependency with an
    /// active GOSSIP cooldown finding for its exact `latest` renders the GOSSIP-attributed
    /// message, not the unattributed local-heuristic one, through the same
    /// `ecosystem.generate_diagnostics`/`generate_diagnostics_from_cache` path `check_manifest`
    /// uses — and that message survives unchanged into the `to_finding`-produced
    /// [`CheckFinding`].
    #[test]
    fn test_check_pipeline_surfaces_gossip_cooldown_wording_via_version_data() {
        use crate::analyze::ManifestAnalysis;
        use deps_core::position::{Position, Range as PosRange};
        use deps_core::test_util::stub_gossip_findings;
        use deps_core::{Dependency, GossipCooldown, GossipRiskLevel, PublishTime};
        use std::any::Any;
        use std::collections::HashSet;

        struct FixtureDep {
            name: PackageName,
            version_req: deps_core::VersionReq,
            version_range: PosRange,
        }
        impl Dependency for FixtureDep {
            fn name(&self) -> &PackageName {
                &self.name
            }
            fn name_range(&self) -> PosRange {
                PosRange::new(Position::new(0, 0), Position::new(0, 5))
            }
            fn version_requirement(&self) -> Option<&deps_core::VersionReq> {
                Some(&self.version_req)
            }
            fn version_range(&self) -> Option<PosRange> {
                Some(self.version_range)
            }
            fn source(&self) -> deps_core::parser::DependencySource {
                deps_core::parser::DependencySource::Registry
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        struct FixtureParseResult {
            dep: FixtureDep,
            uri: url::Url,
        }
        impl deps_core::ParseResult for FixtureParseResult {
            fn dependencies(&self) -> Vec<&dyn Dependency> {
                vec![&self.dep]
            }
            fn workspace_root(&self) -> Option<&Path> {
                None
            }
            fn uri(&self) -> &url::Url {
                &self.uri
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        let uri: url::Url = "file:///project/Cargo.toml".parse().expect("valid URI");
        let parse_result: Box<dyn deps_core::ParseResult> = Box::new(FixtureParseResult {
            dep: FixtureDep {
                name: PackageName::new("serde"),
                version_req: deps_core::VersionReq::new("1.0"),
                version_range: PosRange::new(Position::new(0, 10), Position::new(0, 20)),
            },
            uri: uri.clone(),
        });

        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            PackageName::new("serde"),
            deps_core::lsp_helpers::PackageVersions::latest_only("2.0.0"),
        );

        let mut gossip_findings = HashMap::new();
        gossip_findings.insert(
            PackageName::new("serde"),
            stub_gossip_findings(
                "2.0.0",
                Some(GossipCooldown::new(
                    PublishTime::from_unix_secs(PublishTime::now().as_unix_secs() + 1_000),
                    GossipRiskLevel::High,
                )),
            ),
        );

        let analysis = ManifestAnalysis {
            parse_result,
            uri: uri.clone(),
            now: PublishTime::now(),
            ecosystem_id: EcosystemId::Cargo,
            cached_versions: cached_versions.clone(),
            resolved_versions: HashMap::new(),
            resolved_version_candidates: HashMap::new(),
            outcomes: deps_core::lsp_helpers::DependencyOutcomes::new(),
            vulnerabilities: None,
            latest_status: None,
            fallback_status: None,
            cooldown_fallback_view: None,
            gossip_findings,
            licenses: HashMap::new(),
            license_policy: deps_core::licenses::LicensePolicy::default(),
            license_source: deps_core::LicenseSource::default(),
            network: deps_core::NetworkMode::Online,
            fetch_failed: HashSet::new(),
            registry_unreachable: false,
            license_fetch_incomplete: false,
        };

        let diagnostics = deps_core::lsp_helpers::generate_diagnostics_from_cache(
            analysis.parse_result.as_ref(),
            analysis.version_data(),
            &STUB_FORMATTER,
            &uri,
            deps_core::FreshnessSettings::default(),
            deps_core::lsp_helpers::DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
        assert!(
            diagnostics[0].message().contains("deps.dev/GOSSIP"),
            "check's diagnostic generation must consult live GOSSIP prefetch data: {}",
            diagnostics[0].message()
        );

        let dep_index = DependencyIndex::build(analysis.parse_result.as_ref());
        let finding = to_finding(
            analysis.ecosystem_id,
            Path::new("Cargo.toml"),
            &dep_index,
            &STUB_FORMATTER,
            diagnostics.into_iter().next().expect("one diagnostic"),
            &HashMap::new(),
            &VulnKeys::default(),
            &cached_versions,
        );
        assert_eq!(finding.category, Category::Outdated);
        assert!(
            finding.message.contains("deps.dev/GOSSIP"),
            "the GOSSIP wording must survive into the SARIF finding: {}",
            finding.message
        );
    }
}