i-self 0.4.3

Personal developer-companion CLI: scans your repos, indexes code semantically, watches your activity, and moves AI-agent sessions between tools (Claude Code, Aider, Goose, OpenAI Codex CLI, Continue.dev, OpenCode).
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
#![allow(dead_code)]

use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum VulnError {
    #[error("Failed to read: {0}")]
    ReadError(#[from] std::io::Error),
    #[error("Failed to parse: {0}")]
    ParseError(#[from] toml::de::Error),
    #[error("Network error: {0}")]
    NetworkError(String),
    #[error("API error: {0}")]
    ApiError(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Vulnerability {
    pub id: String,
    pub package: String,
    pub severity: Severity,
    pub title: String,
    pub description: String,
    pub url: String,
    pub patched_in: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

impl Severity {
    pub fn from_string(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "low" => Severity::Low,
            "medium" | "moderate" => Severity::Medium,
            "high" => Severity::High,
            "critical" => Severity::Critical,
            _ => Severity::Low,
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            Severity::Low => "LOW",
            Severity::Medium => "MEDIUM",
            Severity::High => "HIGH",
            Severity::Critical => "CRITICAL",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dependency {
    pub name: String,
    pub version: String,
    pub ecosystem: Ecosystem,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Ecosystem {
    Npm,
    Cargo,
    Pip,
    Go,
    Maven,
    NuGet,
}

impl Ecosystem {
    pub fn from_lockfile(path: &PathBuf) -> Option<Self> {
        let name = path.file_name()?.to_str()?;
        match name {
            "package-lock.json" => Some(Ecosystem::Npm),
            "Cargo.lock" => Some(Ecosystem::Cargo),
            "Pipfile.lock" | "requirements.txt" => Some(Ecosystem::Pip),
            "go.sum" | "go.mod" => Some(Ecosystem::Go),
            "pom.xml" => Some(Ecosystem::Maven),
            "packages.lock.json" | "packages.config" => Some(Ecosystem::NuGet),
            _ => None,
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Ecosystem::Npm => "npm",
            Ecosystem::Cargo => "cargo",
            Ecosystem::Pip => "pip",
            Ecosystem::Go => "go",
            Ecosystem::Maven => "maven",
            Ecosystem::NuGet => "nuget",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VulnScanResult {
    pub ecosystem: Ecosystem,
    pub dependencies: Vec<Dependency>,
    pub vulnerabilities: Vec<Vulnerability>,
    /// Per-package OSV lookup failures. A non-empty list means the scan is
    /// **incomplete** — some packages were never checked. The summary surfaces
    /// this so a "0 vulns" result with errors doesn't get a green checkmark.
    #[serde(default)]
    pub scan_errors: Vec<String>,
    pub scanned_at: i64,
}

impl VulnScanResult {
    pub fn critical_count(&self) -> usize {
        self.vulnerabilities.iter()
            .filter(|v| v.severity == Severity::Critical)
            .count()
    }

    pub fn high_count(&self) -> usize {
        self.vulnerabilities.iter()
            .filter(|v| v.severity == Severity::High)
            .count()
    }

    pub fn has_vulnerabilities(&self) -> bool {
        !self.vulnerabilities.is_empty()
    }

    /// True iff every dependency was successfully checked against OSV.
    pub fn is_complete(&self) -> bool {
        self.scan_errors.is_empty()
    }

    pub fn summary(&self) -> String {
        let total = self.vulnerabilities.len();
        let err_count = self.scan_errors.len();
        let err_suffix = if err_count > 0 {
            format!(
                " ⚠️ {} lookup{} FAILED — scan is INCOMPLETE",
                err_count,
                if err_count == 1 { "" } else { "s" }
            )
        } else {
            String::new()
        };

        if total == 0 {
            return if err_count == 0 {
                "No vulnerabilities found ✅".to_string()
            } else {
                format!("No vulnerabilities found in successful lookups{}", err_suffix)
            };
        }

        let critical = self.critical_count();
        let high = self.high_count();
        format!(
            "Found {} vulnerabilities ({} critical, {} high){}",
            total, critical, high, err_suffix
        )
    }
}

pub struct VulnScanner {
    client: reqwest::Client,
}

impl VulnScanner {
    pub fn new() -> Self {
        Self {
            client: reqwest::Client::new(),
        }
    }

    pub async fn scan_project(&self, project_path: &PathBuf) -> Result<VulnScanResult, VulnError> {
        let lockfiles = self.find_lockfiles(project_path)?;

        let mut all_vulns = Vec::new();
        let mut all_deps = Vec::new();
        let mut all_errors: Vec<String> = Vec::new();
        let mut ecosystem = Ecosystem::Npm;

        for lockfile in lockfiles {
            if let Some(eco) = Ecosystem::from_lockfile(&lockfile) {
                ecosystem = eco;
                let (deps, vulns, errors) = self.scan_lockfile(&lockfile, eco).await?;
                all_deps.extend(deps);
                all_vulns.extend(vulns);
                all_errors.extend(errors);
            }
        }

        Ok(VulnScanResult {
            ecosystem,
            dependencies: all_deps,
            vulnerabilities: all_vulns,
            scan_errors: all_errors,
            scanned_at: chrono::Utc::now().timestamp(),
        })
    }

    fn find_lockfiles(&self, project_path: &PathBuf) -> Result<Vec<PathBuf>, VulnError> {
        let mut lockfiles = Vec::new();
        // Order matters when a project has both a high-fidelity lockfile and
        // a low-fidelity manifest (e.g. go.sum AND go.mod, or Pipfile.lock AND
        // requirements.txt). Prefer the lockfile.
        let lock_names = [
            "package-lock.json",
            "Cargo.lock",
            "Pipfile.lock",
            "requirements.txt",
            "go.sum",
            "go.mod",
            "pom.xml",
            "packages.lock.json",
            "packages.config",
            "Gemfile.lock",
        ];

        for name in &lock_names {
            let path = project_path.join(name);
            if path.exists() {
                lockfiles.push(path);
            }
        }

        Ok(lockfiles)
    }

    async fn scan_lockfile(
        &self,
        lockfile: &PathBuf,
        ecosystem: Ecosystem,
    ) -> Result<(Vec<Dependency>, Vec<Vulnerability>, Vec<String>), VulnError> {
        let content = std::fs::read_to_string(lockfile)?;
        let name = lockfile
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");

        let deps = match (ecosystem, name) {
            (Ecosystem::Cargo, _) => parse_cargo_lock(&content)?,
            (Ecosystem::Npm, _) => parse_package_lock(&content),
            (Ecosystem::Pip, "Pipfile.lock") => parse_pipfile_lock(&content),
            (Ecosystem::Pip, "requirements.txt") => parse_requirements_txt(&content),
            (Ecosystem::Go, "go.sum") => parse_go_sum(&content),
            (Ecosystem::Go, "go.mod") => parse_go_mod(&content),
            (Ecosystem::Maven, _) => parse_pom_xml(&content),
            (Ecosystem::NuGet, "packages.lock.json") => parse_packages_lock_json(&content),
            (Ecosystem::NuGet, "packages.config") => parse_packages_config(&content),
            // Unknown filename for a known ecosystem — give up cleanly.
            _ => return Ok((Vec::new(), Vec::new(), Vec::new())),
        };
        self.check_deps(&deps, ecosystem.name()).await
    }

    /// Look every dep up against OSV, collecting both vulnerabilities AND
    /// per-package errors. The errors are surfaced in `VulnScanResult.scan_errors`
    /// so the user sees that "no vulnerabilities found" came with caveats.
    async fn check_deps(
        &self,
        deps: &[Dependency],
        ecosystem: &str,
    ) -> Result<(Vec<Dependency>, Vec<Vulnerability>, Vec<String>), VulnError> {
        let mut vulns = Vec::new();
        let mut errors = Vec::new();
        for dep in deps {
            match self.check_osv(&dep.name, &dep.version, ecosystem).await {
                Ok(found) => vulns.extend(found),
                Err(e) => errors.push(format!("{}@{}: {}", dep.name, dep.version, e)),
            }
        }
        Ok((deps.to_vec(), vulns, errors))
    }

    async fn check_osv(&self, package: &str, version: &str, ecosystem: &str) -> Result<Vec<Vulnerability>, VulnError> {
        let query = serde_json::json!({
            "package": {
                "name": package,
                "ecosystem": osv_ecosystem_label(ecosystem)
            },
            "version": version
        });

        let response = self.client
            .post("https://api.osv.dev/v1/query")
            .json(&query)
            .send()
            .await
            .map_err(|e| VulnError::NetworkError(e.to_string()))?;

        let status = response.status();
        if !status.is_success() {
            // Previously we swallowed this with `Ok(Vec::new())` — a clean
            // "no vulns" answer despite the upstream call having failed. Now
            // we surface the failure so the user knows the scan is incomplete.
            let body = response.text().await.unwrap_or_default();
            return Err(VulnError::ApiError(format!(
                "OSV {} for {}@{}: {}",
                status,
                package,
                version,
                body.chars().take(200).collect::<String>()
            )));
        }

        let result: serde_json::Value = response.json().await
            .map_err(|e| VulnError::NetworkError(format!("JSON parse error: {}", e)))?;

        let mut vulns = Vec::new();

        if let Some(vulns_arr) = result.get("vulns").and_then(|v| v.as_array()) {
            for vuln in vulns_arr {
                vulns.push(Vulnerability {
                    id: vuln.get("id").and_then(|i| i.as_str()).unwrap_or("unknown").to_string(),
                    package: package.to_string(),
                    severity: extract_severity(vuln),
                    title: vuln.get("summary").and_then(|s| s.as_str()).unwrap_or("No title").to_string(),
                    description: vuln.get("details").and_then(|d| d.as_str()).unwrap_or("").to_string(),
                    url: vuln.get("id").and_then(|i| i.as_str()).map(|id| format!("https://osv.dev/vulnerability/{}", id)).unwrap_or_default(),
                    patched_in: vuln.get("fixed_version").and_then(|v| v.as_str()).map(|s| s.to_string()),
                });
            }
        }

        Ok(vulns)
    }

    pub async fn quick_check(&self, package: &str, version: &str, ecosystem: Ecosystem) -> Result<Vec<Vulnerability>, VulnError> {
        let eco_name = ecosystem.name();
        self.check_osv(package, version, eco_name).await
    }
}

impl Default for VulnScanner {
    fn default() -> Self {
        Self::new()
    }
}

/// Pull a meaningful severity off an OSV vuln record.
///
/// Resolution order:
/// 1. `database_specific.severity` — string label (e.g. GHSA records carry
///    "MODERATE" / "HIGH" / "CRITICAL"). Fastest, most reliable when present.
/// 2. `severity[].score` parsed as CVSS v3 — compute the base score and bucket.
/// 3. `Severity::Low` as a last resort. The previous implementation always
///    landed here because it read `severity[].type` (a CVSS algorithm tag like
///    `CVSS_V3`) and ran it through `Severity::from_string`, which fell through
///    to Low for everything.
fn extract_severity(vuln: &serde_json::Value) -> Severity {
    if let Some(label) = vuln
        .get("database_specific")
        .and_then(|d| d.get("severity"))
        .and_then(|s| s.as_str())
    {
        let parsed = Severity::from_string(label);
        // `from_string` returns Low for unknown labels; only trust it if the
        // label was actually one we recognize.
        if parsed != Severity::Low || matches!(label.to_lowercase().as_str(), "low") {
            return parsed;
        }
    }

    if let Some(arr) = vuln.get("severity").and_then(|s| s.as_array()) {
        for entry in arr {
            let ty = entry.get("type").and_then(|t| t.as_str()).unwrap_or("");
            if ty == "CVSS_V3" || ty == "CVSS_V31" {
                if let Some(vec) = entry.get("score").and_then(|s| s.as_str()) {
                    if let Some(score) = cvss_v3_base_score(vec) {
                        return cvss_score_to_severity(score);
                    }
                }
            }
        }
    }

    Severity::Low
}

/// Bucket a CVSS v3 base score into the project's coarse severity enum.
/// Cutoffs match the official CVSS v3 qualitative ratings:
/// 0.0 None, 0.1–3.9 Low, 4.0–6.9 Medium, 7.0–8.9 High, 9.0–10.0 Critical.
fn cvss_score_to_severity(score: f32) -> Severity {
    if score >= 9.0 {
        Severity::Critical
    } else if score >= 7.0 {
        Severity::High
    } else if score >= 4.0 {
        Severity::Medium
    } else {
        Severity::Low
    }
}

/// Compute the CVSS v3 base score from a vector string like
/// `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H`.
/// Returns `None` if the vector is malformed or not v3.
///
/// Implementation of the formulas in the CVSS v3.1 spec, section 7.1
/// (https://www.first.org/cvss/v3.1/specification-document). The roundUp
/// helper uses the integer-arithmetic form from the spec to avoid the
/// classic "9.0000001 → 9.1" floating-point error.
fn cvss_v3_base_score(vector: &str) -> Option<f32> {
    let mut parts = std::collections::HashMap::new();
    for piece in vector.split('/') {
        if let Some((k, v)) = piece.split_once(':') {
            parts.insert(k, v);
        }
    }

    if !parts.get("CVSS").map(|v| v.starts_with("3.")).unwrap_or(false) {
        return None;
    }

    let av = match *parts.get("AV")? {
        "N" => 0.85,
        "A" => 0.62,
        "L" => 0.55,
        "P" => 0.20,
        _ => return None,
    };
    let ac = match *parts.get("AC")? {
        "L" => 0.77,
        "H" => 0.44,
        _ => return None,
    };
    let ui = match *parts.get("UI")? {
        "N" => 0.85,
        "R" => 0.62,
        _ => return None,
    };
    let scope_changed = match *parts.get("S")? {
        "U" => false,
        "C" => true,
        _ => return None,
    };
    let pr = match *parts.get("PR")? {
        "N" => 0.85,
        "L" => if scope_changed { 0.68 } else { 0.62 },
        "H" => if scope_changed { 0.50 } else { 0.27 },
        _ => return None,
    };
    let cia = |s: &str| -> Option<f32> {
        match s {
            "N" => Some(0.0),
            "L" => Some(0.22),
            "H" => Some(0.56),
            _ => None,
        }
    };
    let c = cia(parts.get("C")?)?;
    let i = cia(parts.get("I")?)?;
    let a = cia(parts.get("A")?)?;

    let iss = 1.0 - ((1.0 - c) * (1.0 - i) * (1.0 - a));
    let impact = if scope_changed {
        7.52 * (iss - 0.029) - 3.25 * (iss - 0.02).powi(15)
    } else {
        6.42 * iss
    };
    if impact <= 0.0 {
        return Some(0.0);
    }

    let exploitability = 8.22 * av * ac * pr * ui;
    let raw = if scope_changed {
        (1.08 * (impact + exploitability)).min(10.0)
    } else {
        (impact + exploitability).min(10.0)
    };

    Some(cvss_round_up(raw))
}

/// CVSS v3.1 spec roundUp1: smallest multiple of 0.1 ≥ x.
/// Implemented in integer arithmetic to dodge FP drift, exactly as the spec
/// recommends.
fn cvss_round_up(x: f32) -> f32 {
    let int_input = (x * 100_000.0).round() as i64;
    if int_input % 10_000 == 0 {
        int_input as f32 / 100_000.0
    } else {
        ((int_input / 10_000) + 1) as f32 / 10.0
    }
}

/// Map an internal ecosystem string to the label OSV expects in `package.ecosystem`.
/// OSV is case-sensitive: `crates.io`, `npm`, `PyPI`, `Go`, `Maven`, `NuGet`,
/// `RubyGems`. https://ossf.github.io/osv-schema/#affectedpackage-field
fn osv_ecosystem_label(ecosystem: &str) -> &'static str {
    match ecosystem {
        "cargo" => "crates.io",
        "npm" => "npm",
        "pip" => "PyPI",
        "go" => "Go",
        "maven" => "Maven",
        "nuget" => "NuGet",
        "rubygems" | "gem" => "RubyGems",
        _ => "npm",
    }
}

/// Parse a Cargo.lock file. Cargo.lock is TOML with a top-level `package`
/// array; each entry has `name` and `version`. The previous string-slicing
/// approach used `as_ptr() as usize` as a byte offset (UB) and silently
/// produced garbage; this delegates to a real TOML parser.
fn parse_cargo_lock(content: &str) -> Result<Vec<Dependency>, VulnError> {
    #[derive(Deserialize)]
    struct CargoLock {
        #[serde(default)]
        package: Vec<CargoLockPackage>,
    }
    #[derive(Deserialize)]
    struct CargoLockPackage {
        name: String,
        version: String,
    }

    let parsed: CargoLock = toml::from_str(content)?;
    Ok(parsed
        .package
        .into_iter()
        .map(|p| Dependency {
            name: p.name,
            version: p.version,
            ecosystem: Ecosystem::Cargo,
        })
        .collect())
}

/// Parse a package-lock.json file. Supports lockfileVersion 1 (`dependencies`
/// recursive tree) and 2/3 (`packages` flat map keyed by node_modules path).
/// The previous parser scanned for lines containing both `"name"` and
/// `"version"`, which never happens in a real lockfile, so it always returned
/// an empty list — silent zero-vuln "scans" of any npm project.
fn parse_package_lock(content: &str) -> Vec<Dependency> {
    let json: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let mut out = Vec::new();

    // v2/v3: `packages` is { "node_modules/foo": { "version": "1.2.3" }, ... }.
    // The empty key "" is the root project — skip it.
    if let Some(packages) = json.get("packages").and_then(|p| p.as_object()) {
        for (path, info) in packages {
            if path.is_empty() {
                continue;
            }
            let name = path
                .rsplit("node_modules/")
                .next()
                .unwrap_or(path)
                .to_string();
            if name.is_empty() {
                continue;
            }
            let version = info
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            if version.is_empty() {
                continue;
            }
            out.push(Dependency {
                name,
                version: version.to_string(),
                ecosystem: Ecosystem::Npm,
            });
        }
        return out;
    }

    // v1: `dependencies` is { "foo": { "version": "1.2.3", "dependencies": { ... } } }.
    if let Some(deps) = json.get("dependencies").and_then(|d| d.as_object()) {
        walk_v1_deps(deps, &mut out);
    }
    out
}

/// Parse a `Pipfile.lock` (pipenv). Schema: a JSON object with `default` and
/// `develop` sections, each mapping `<package> -> {"version": "==1.2.3", ...}`.
/// We strip the leading `==` because OSV expects bare versions.
fn parse_pipfile_lock(content: &str) -> Vec<Dependency> {
    let json: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let mut out = Vec::new();
    for section in ["default", "develop"] {
        let pkgs = match json.get(section).and_then(|v| v.as_object()) {
            Some(p) => p,
            None => continue,
        };
        for (name, info) in pkgs {
            let v = info
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim_start_matches("==")
                .trim_start_matches('=');
            if v.is_empty() {
                continue;
            }
            out.push(Dependency {
                name: name.clone(),
                version: v.to_string(),
                ecosystem: Ecosystem::Pip,
            });
        }
    }
    out
}

/// Parse a `requirements.txt`. PEP 508 is a maze; we cover the 95% case:
/// `<package>==<version>` (and `~=` / `>=` if there's no `==`). Comments
/// and editable installs are skipped. This is a degraded fallback when no
/// real lockfile is present — pinned versions only.
fn parse_requirements_txt(content: &str) -> Vec<Dependency> {
    let mut out = Vec::new();
    for raw_line in content.lines() {
        let line = raw_line.split('#').next().unwrap_or("").trim();
        if line.is_empty() || line.starts_with("-e ") || line.starts_with("--") {
            continue;
        }
        // Find the FIRST occurrence of `==`, `~=`, `>=`, or `>`. We only
        // record dependencies pinned to a specific version because OSV
        // queries need a single `version` field.
        let (sep, len) = if let Some(i) = line.find("==") {
            (i, 2)
        } else if let Some(i) = line.find("~=") {
            (i, 2)
        } else if let Some(i) = line.find(">=") {
            (i, 2)
        } else {
            continue;
        };
        let name = line[..sep]
            .trim()
            .split(|c: char| c.is_whitespace() || c == '[')
            .next()
            .unwrap_or("")
            .to_string();
        let version_part = line[sep + len..]
            .split(|c: char| c == ',' || c == ';' || c.is_whitespace())
            .next()
            .unwrap_or("")
            .trim();
        if name.is_empty() || version_part.is_empty() {
            continue;
        }
        out.push(Dependency {
            name,
            version: version_part.to_string(),
            ecosystem: Ecosystem::Pip,
        });
    }
    out
}

/// Parse a `go.sum`. Each line is `<module> <version>[/go.mod] <hash>`.
/// We pick distinct (module, version) pairs and drop `/go.mod` synthetic
/// entries (which are hash-of-go.mod-file lines, not separate modules).
fn parse_go_sum(content: &str) -> Vec<Dependency> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for line in content.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 2 {
            continue;
        }
        let name = parts[0];
        let version = parts[1].trim_end_matches("/go.mod");
        if version.is_empty() || version.contains("h1:") {
            continue;
        }
        let key = format!("{}@{}", name, version);
        if seen.insert(key) {
            out.push(Dependency {
                name: name.to_string(),
                version: version.to_string(),
                ecosystem: Ecosystem::Go,
            });
        }
    }
    out
}

/// Parse a `go.mod`. Recognizes single-line `require <mod> <version>` and
/// the multi-line `require ( ... )` block form. Replace directives are
/// honored — if `replace foo => bar v1.2.3` appears, foo points at bar's
/// version. Indirect dependencies (marked `// indirect`) are included
/// because they too can be vulnerable.
fn parse_go_mod(content: &str) -> Vec<Dependency> {
    let mut deps: std::collections::HashMap<String, String> =
        std::collections::HashMap::new();
    let mut in_require = false;
    let mut in_replace = false;

    for raw in content.lines() {
        let line = raw.split("//").next().unwrap_or("").trim();
        if line.is_empty() {
            continue;
        }
        if line == "require (" {
            in_require = true;
            continue;
        }
        if line == "replace (" {
            in_replace = true;
            continue;
        }
        if line == ")" {
            in_require = false;
            in_replace = false;
            continue;
        }

        if let Some(rest) = line.strip_prefix("require ") {
            let parts: Vec<&str> = rest.split_whitespace().collect();
            if parts.len() >= 2 {
                deps.insert(parts[0].to_string(), parts[1].to_string());
            }
        } else if in_require {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                deps.insert(parts[0].to_string(), parts[1].to_string());
            }
        } else if let Some(rest) = line.strip_prefix("replace ") {
            apply_replace(rest, &mut deps);
        } else if in_replace {
            apply_replace(line, &mut deps);
        }
    }

    deps.into_iter()
        .map(|(name, version)| Dependency {
            name,
            version,
            ecosystem: Ecosystem::Go,
        })
        .collect()
}

fn apply_replace(rest: &str, deps: &mut std::collections::HashMap<String, String>) {
    // `<old> [<old-version>] => <new> <new-version>`
    let arrow = match rest.find("=>") {
        Some(i) => i,
        None => return,
    };
    let lhs = rest[..arrow].trim();
    let rhs = rest[arrow + 2..].trim();
    let lhs_parts: Vec<&str> = lhs.split_whitespace().collect();
    let rhs_parts: Vec<&str> = rhs.split_whitespace().collect();
    if lhs_parts.is_empty() || rhs_parts.len() < 2 {
        return;
    }
    deps.insert(lhs_parts[0].to_string(), rhs_parts[1].to_string());
}

/// Parse a Maven `pom.xml`. We extract direct `<dependency>` blocks under
/// any parent (`<dependencies>`, `<dependencyManagement>`). Property
/// substitution (`${some.version}`) is resolved against `<properties>`.
/// Transitive dependencies are NOT discovered — Maven resolves those at
/// build time. For full coverage the user should run `mvn dependency:tree`
/// and feed the output through a separate pipeline.
///
/// Tag matching is regex-based on substrings; we don't pull in a real XML
/// parser dep. Real Maven projects nest deeply, but the relevant
/// `<groupId>/<artifactId>/<version>` triple appears as adjacent siblings
/// inside one `<dependency>` so a flat scan suffices.
fn parse_pom_xml(content: &str) -> Vec<Dependency> {
    let properties = collect_pom_properties(content);
    let mut out = Vec::new();
    let bytes = content.as_bytes();
    let mut cursor = 0usize;
    while let Some(start_rel) = content[cursor..].find("<dependency>") {
        let start = cursor + start_rel + "<dependency>".len();
        let end_rel = match content[start..].find("</dependency>") {
            Some(i) => i,
            None => break,
        };
        let block = &content[start..start + end_rel];
        cursor = start + end_rel + "</dependency>".len();

        let group = take_xml_text(block, "groupId").unwrap_or_default();
        let artifact = take_xml_text(block, "artifactId").unwrap_or_default();
        let version_raw = take_xml_text(block, "version").unwrap_or_default();
        let version = resolve_pom_property(&version_raw, &properties);
        if artifact.is_empty() || version.is_empty() {
            continue;
        }
        let name = if group.is_empty() {
            artifact
        } else {
            format!("{}:{}", group, artifact)
        };
        out.push(Dependency {
            name,
            version,
            ecosystem: Ecosystem::Maven,
        });
    }
    let _ = bytes; // suppress unused — we walk via str
    out
}

fn collect_pom_properties(content: &str) -> std::collections::HashMap<String, String> {
    let mut props = std::collections::HashMap::new();
    let block_start = match content.find("<properties>") {
        Some(i) => i + "<properties>".len(),
        None => return props,
    };
    let block_end = content[block_start..]
        .find("</properties>")
        .map(|i| block_start + i)
        .unwrap_or(content.len());
    let block = &content[block_start..block_end];
    // <name>value</name>
    let mut cursor = 0usize;
    while let Some(open_rel) = block[cursor..].find('<') {
        let open = cursor + open_rel + 1;
        let close_rel = match block[open..].find('>') {
            Some(i) => i,
            None => break,
        };
        let tag = &block[open..open + close_rel];
        if tag.starts_with('/') {
            cursor = open + close_rel;
            continue;
        }
        let value_start = open + close_rel + 1;
        let close_tag = format!("</{}>", tag);
        let value_end_rel = match block[value_start..].find(&close_tag) {
            Some(i) => i,
            None => {
                cursor = value_start;
                continue;
            }
        };
        let value = block[value_start..value_start + value_end_rel].trim();
        if !tag.contains(' ') {
            props.insert(tag.to_string(), value.to_string());
        }
        cursor = value_start + value_end_rel + close_tag.len();
    }
    props
}

fn resolve_pom_property(
    raw: &str,
    props: &std::collections::HashMap<String, String>,
) -> String {
    let trimmed = raw.trim();
    if let Some(name) = trimmed.strip_prefix("${").and_then(|s| s.strip_suffix('}')) {
        if let Some(v) = props.get(name) {
            return v.clone();
        }
    }
    trimmed.to_string()
}

fn take_xml_text(block: &str, tag: &str) -> Option<String> {
    let open = format!("<{}>", tag);
    let close = format!("</{}>", tag);
    let s = block.find(&open)? + open.len();
    let e = block[s..].find(&close)?;
    Some(block[s..s + e].trim().to_string())
}

/// Parse a `packages.lock.json` (NuGet "lock file" introduced in 2018).
/// Schema:
///
/// ```json
/// {"version":1, "dependencies": {"net6.0": {
///   "Newtonsoft.Json": {"type":"Direct","resolved":"13.0.1","contentHash":"..."},
///   ...
/// }}}
/// ```
fn parse_packages_lock_json(content: &str) -> Vec<Dependency> {
    let json: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    let frameworks = match json.get("dependencies").and_then(|d| d.as_object()) {
        Some(o) => o,
        None => return out,
    };
    for (_framework, pkgs) in frameworks {
        let pkgs = match pkgs.as_object() {
            Some(o) => o,
            None => continue,
        };
        for (name, info) in pkgs {
            let version = info
                .get("resolved")
                .and_then(|r| r.as_str())
                .unwrap_or("");
            if version.is_empty() {
                continue;
            }
            // Same package can be resolved per-framework — dedupe.
            let key = format!("{}@{}", name, version);
            if seen.insert(key) {
                out.push(Dependency {
                    name: name.clone(),
                    version: version.to_string(),
                    ecosystem: Ecosystem::NuGet,
                });
            }
        }
    }
    out
}

/// Parse a legacy `packages.config` (pre-PackageReference NuGet).
/// Schema: `<packages><package id="..." version="..." /></packages>`.
fn parse_packages_config(content: &str) -> Vec<Dependency> {
    let mut out = Vec::new();
    let mut cursor = 0usize;
    while let Some(start_rel) = content[cursor..].find("<package ") {
        let start = cursor + start_rel;
        let end_rel = match content[start..].find("/>") {
            Some(i) => i,
            None => break,
        };
        let tag = &content[start..start + end_rel];
        cursor = start + end_rel + 2;
        let id = attr_value(tag, "id");
        let version = attr_value(tag, "version");
        if let (Some(id), Some(v)) = (id, version) {
            out.push(Dependency {
                name: id,
                version: v,
                ecosystem: Ecosystem::NuGet,
            });
        }
    }
    out
}

/// Extract `name="value"` from an XML attribute string.
fn attr_value(tag: &str, name: &str) -> Option<String> {
    let key = format!("{}=\"", name);
    let s = tag.find(&key)? + key.len();
    let e = tag[s..].find('"')?;
    Some(tag[s..s + e].to_string())
}

fn walk_v1_deps(map: &serde_json::Map<String, serde_json::Value>, out: &mut Vec<Dependency>) {
    for (name, info) in map {
        let version = info
            .get("version")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !version.is_empty() {
            out.push(Dependency {
                name: name.clone(),
                version: version.to_string(),
                ecosystem: Ecosystem::Npm,
            });
        }
        if let Some(nested) = info.get("dependencies").and_then(|d| d.as_object()) {
            walk_v1_deps(nested, out);
        }
    }
}

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

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Low < Severity::Medium);
        assert!(Severity::Medium < Severity::High);
        assert!(Severity::High < Severity::Critical);
    }

    #[test]
    fn test_severity_from_string() {
        assert_eq!(Severity::from_string("critical"), Severity::Critical);
        assert_eq!(Severity::from_string("HIGH"), Severity::High);
        assert_eq!(Severity::from_string("moderate"), Severity::Medium);
        assert_eq!(Severity::from_string("unknown"), Severity::Low);
    }

    #[test]
    fn test_severity_label() {
        assert_eq!(Severity::Critical.label(), "CRITICAL");
        assert_eq!(Severity::Low.label(), "LOW");
    }

    #[test]
    fn test_ecosystem_from_lockfile() {
        assert_eq!(Ecosystem::from_lockfile(&PathBuf::from("Cargo.lock")), Some(Ecosystem::Cargo));
        assert_eq!(Ecosystem::from_lockfile(&PathBuf::from("package-lock.json")), Some(Ecosystem::Npm));
        assert_eq!(Ecosystem::from_lockfile(&PathBuf::from("random.txt")), None);
    }

    #[test]
    fn test_vuln_scan_result_summary() {
        let result = VulnScanResult {
            ecosystem: Ecosystem::Cargo,
            dependencies: vec![],
            vulnerabilities: vec![],
            scan_errors: vec![],
            scanned_at: 0,
        };
        assert_eq!(result.summary(), "No vulnerabilities found ✅");
        assert!(result.is_complete());

        let result = VulnScanResult {
            ecosystem: Ecosystem::Cargo,
            dependencies: vec![],
            vulnerabilities: vec![
                Vulnerability {
                    id: "1".to_string(),
                    package: "test".to_string(),
                    severity: Severity::Critical,
                    title: "Test".to_string(),
                    description: "".to_string(),
                    url: "".to_string(),
                    patched_in: None,
                },
                Vulnerability {
                    id: "2".to_string(),
                    package: "test".to_string(),
                    severity: Severity::High,
                    title: "Test".to_string(),
                    description: "".to_string(),
                    url: "".to_string(),
                    patched_in: None,
                },
            ],
            scan_errors: vec![],
            scanned_at: 0,
        };
        assert_eq!(result.summary(), "Found 2 vulnerabilities (1 critical, 1 high)");
    }

    #[test]
    fn summary_flags_partial_scans_with_warning() {
        // Errors but no vulns — must NOT show ✅, must say INCOMPLETE.
        let mut result = VulnScanResult {
            ecosystem: Ecosystem::Cargo,
            dependencies: vec![],
            vulnerabilities: vec![],
            scan_errors: vec!["foo@1.0: 503".to_string()],
            scanned_at: 0,
        };
        assert!(!result.is_complete());
        let s = result.summary();
        assert!(!s.contains(''), "got: {}", s);
        assert!(s.contains("INCOMPLETE"), "got: {}", s);
        assert!(s.contains("FAILED"), "got: {}", s);

        // Errors AND vulns — both surfaced.
        result.vulnerabilities.push(Vulnerability {
            id: "x".into(),
            package: "p".into(),
            severity: Severity::Critical,
            title: "t".into(),
            description: "".into(),
            url: "".into(),
            patched_in: None,
        });
        let s = result.summary();
        assert!(s.contains("Found 1 vulnerabilities"), "got: {}", s);
        assert!(s.contains("INCOMPLETE"), "got: {}", s);
    }

    #[test]
    fn extract_severity_prefers_database_specific_label() {
        let v = serde_json::json!({
            "database_specific": { "severity": "HIGH" },
            "severity": [{ "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N" }]
        });
        // CVSS vector above is 0.0, but database_specific says HIGH — that wins.
        assert_eq!(extract_severity(&v), Severity::High);
    }

    #[test]
    fn extract_severity_falls_back_to_cvss() {
        let v = serde_json::json!({
            "severity": [{
                "type": "CVSS_V3",
                "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
            }]
        });
        // 9.8 → Critical
        assert_eq!(extract_severity(&v), Severity::Critical);
    }

    #[test]
    fn extract_severity_handles_missing_data() {
        let v = serde_json::json!({});
        assert_eq!(extract_severity(&v), Severity::Low);
    }

    #[test]
    fn extract_severity_ignores_unknown_label_falls_through() {
        let v = serde_json::json!({
            "database_specific": { "severity": "WHATEVER" },
            "severity": [{
                "type": "CVSS_V3",
                "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
            }]
        });
        // Unknown label should NOT short-circuit to Low — CVSS is Critical.
        assert_eq!(extract_severity(&v), Severity::Critical);
    }

    #[test]
    fn cvss_score_to_severity_buckets() {
        assert_eq!(cvss_score_to_severity(0.0), Severity::Low);
        assert_eq!(cvss_score_to_severity(3.9), Severity::Low);
        assert_eq!(cvss_score_to_severity(4.0), Severity::Medium);
        assert_eq!(cvss_score_to_severity(6.9), Severity::Medium);
        assert_eq!(cvss_score_to_severity(7.0), Severity::High);
        assert_eq!(cvss_score_to_severity(8.9), Severity::High);
        assert_eq!(cvss_score_to_severity(9.0), Severity::Critical);
        assert_eq!(cvss_score_to_severity(10.0), Severity::Critical);
    }

    fn approx_eq(a: f32, b: f32) -> bool {
        (a - b).abs() < 0.05
    }

    #[test]
    fn cvss_v3_base_score_known_vectors() {
        // CVE-2020-XXXX style worst-case: full network exploit with full impact.
        let s = cvss_v3_base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H").unwrap();
        assert!(approx_eq(s, 9.8), "got {}", s);

        // Network, low integrity impact only.
        let s = cvss_v3_base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N").unwrap();
        assert!(approx_eq(s, 5.3), "got {}", s);

        // Scope-changed, full impact — pushes above 10 cap and over 9.8.
        let s = cvss_v3_base_score("CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H").unwrap();
        assert!(s >= 9.0 && s <= 10.0, "got {}", s);

        // No impact at all → 0.0
        let s = cvss_v3_base_score("CVSS:3.1/AV:L/AC:H/PR:H/UI:R/S:U/C:N/I:N/A:N").unwrap();
        assert!(approx_eq(s, 0.0), "got {}", s);
    }

    #[test]
    fn cvss_v3_rejects_v2_and_garbage() {
        // CVSS v2 vector — different format, should be rejected.
        assert!(cvss_v3_base_score("AV:N/AC:L/Au:N/C:P/I:P/A:P").is_none());
        // Pure garbage.
        assert!(cvss_v3_base_score("not a vector").is_none());
        // Missing required field (no AV).
        assert!(cvss_v3_base_score("CVSS:3.1/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H").is_none());
    }

    #[test]
    fn cvss_round_up_avoids_fp_drift() {
        // 7.0 should stay 7.0 even if the unrounded value is 6.99999...
        assert!(approx_eq(cvss_round_up(6.9999999), 7.0));
        assert!(approx_eq(cvss_round_up(7.0), 7.0));
        // 7.01 rounds up to 7.1
        assert!(approx_eq(cvss_round_up(7.01), 7.1));
    }

    #[test]
    fn parse_cargo_lock_extracts_packages() {
        let lock = r#"
version = 3

[[package]]
name = "anyhow"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abcd"

[[package]]
name = "tokio"
version = "1.35.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
"#;
        let deps = parse_cargo_lock(lock).expect("parses");
        assert_eq!(deps.len(), 2);
        assert!(deps.iter().any(|d| d.name == "anyhow" && d.version == "1.0.79"));
        assert!(deps.iter().any(|d| d.name == "tokio" && d.version == "1.35.1"));
    }

    #[test]
    fn parse_cargo_lock_handles_empty() {
        let deps = parse_cargo_lock("version = 3\n").expect("parses");
        assert!(deps.is_empty());
    }

    #[test]
    fn parse_cargo_lock_rejects_garbage() {
        // The old parser silently produced garbage; the new one should error.
        assert!(parse_cargo_lock("[[ not toml ::").is_err());
    }

    #[test]
    fn parse_package_lock_v3_extracts_packages() {
        let lock = r#"
{
  "name": "myapp",
  "lockfileVersion": 3,
  "packages": {
    "": { "name": "myapp", "version": "1.0.0" },
    "node_modules/lodash": { "version": "4.17.21" },
    "node_modules/express": { "version": "4.18.2" },
    "node_modules/express/node_modules/qs": { "version": "6.11.0" }
  }
}
"#;
        let deps = parse_package_lock(lock);
        // Three real entries; root "" is skipped.
        assert_eq!(deps.len(), 3, "got {:?}", deps);
        assert!(deps.iter().any(|d| d.name == "lodash" && d.version == "4.17.21"));
        assert!(deps.iter().any(|d| d.name == "qs" && d.version == "6.11.0"));
    }

    #[test]
    fn parse_package_lock_v1_walks_recursive_dependencies() {
        let lock = r#"
{
  "lockfileVersion": 1,
  "dependencies": {
    "lodash": {
      "version": "4.17.21"
    },
    "express": {
      "version": "4.18.2",
      "dependencies": {
        "qs": { "version": "6.11.0" }
      }
    }
  }
}
"#;
        let deps = parse_package_lock(lock);
        assert_eq!(deps.len(), 3);
        assert!(deps.iter().any(|d| d.name == "qs" && d.version == "6.11.0"));
    }

    #[test]
    fn parse_package_lock_handles_invalid_json() {
        assert!(parse_package_lock("not json").is_empty());
    }

    #[test]
    fn osv_ecosystem_labels() {
        assert_eq!(osv_ecosystem_label("cargo"), "crates.io");
        assert_eq!(osv_ecosystem_label("pip"), "PyPI");
        assert_eq!(osv_ecosystem_label("npm"), "npm");
        assert_eq!(osv_ecosystem_label("nuget"), "NuGet");
    }

    /// Hits the real OSV API (https://api.osv.dev). `#[ignore]` so the default
    /// suite stays offline; opt in with `cargo test -- --ignored osv_live_query`.
    /// Uses lodash 4.17.20, which has well-known prototype-pollution CVEs that
    /// have been in OSV's index for years. If this test starts failing, OSV's
    /// schema or API URL has likely changed.
    #[test]
    fn parse_pipfile_lock_extracts_default_and_dev() {
        let lock = r#"
        {
          "_meta": {"hash": {"sha256": "..."}},
          "default": {
            "requests": {"version": "==2.31.0", "hashes": []},
            "urllib3": {"version": "==2.0.7"}
          },
          "develop": {
            "pytest": {"version": "==7.4.0"}
          }
        }
        "#;
        let deps = parse_pipfile_lock(lock);
        assert_eq!(deps.len(), 3);
        assert!(deps.iter().any(|d| d.name == "requests" && d.version == "2.31.0"));
        assert!(deps.iter().any(|d| d.name == "pytest" && d.version == "7.4.0"));
        assert!(deps.iter().all(|d| d.ecosystem == Ecosystem::Pip));
    }

    #[test]
    fn parse_requirements_txt_handles_pins_and_comments() {
        let req = "requests==2.31.0  # http client\n\
                   urllib3>=2.0.7\n\
                   # comment-only line\n\
                   pytest~=7.4.0\n\
                   -e ./local-package\n\
                   --extra-index-url https://example.com\n\
                   numpy\n"; // unpinned — ignored
        let deps = parse_requirements_txt(req);
        assert_eq!(deps.len(), 3);
        assert!(deps.iter().any(|d| d.name == "requests" && d.version == "2.31.0"));
        assert!(deps.iter().any(|d| d.name == "urllib3" && d.version == "2.0.7"));
        assert!(deps.iter().any(|d| d.name == "pytest" && d.version == "7.4.0"));
        assert!(!deps.iter().any(|d| d.name == "numpy"));
    }

    #[test]
    fn parse_go_sum_dedupes_module_and_gomod_lines() {
        let sum = "github.com/foo/bar v1.2.3 h1:abc=\n\
                   github.com/foo/bar v1.2.3/go.mod h1:xyz=\n\
                   golang.org/x/net v0.10.0 h1:def=\n\
                   golang.org/x/net v0.10.0/go.mod h1:ghi=\n";
        let deps = parse_go_sum(sum);
        assert_eq!(deps.len(), 2);
        assert!(deps.iter().any(|d| d.name == "github.com/foo/bar" && d.version == "v1.2.3"));
    }

    #[test]
    fn parse_go_mod_handles_block_form_and_replace() {
        let m = r#"
module example.com/myapp

go 1.21

require github.com/single v0.1.0

require (
    github.com/foo/bar v1.2.3
    golang.org/x/net v0.10.0 // indirect
)

replace github.com/foo/bar => github.com/myfork/bar v9.9.9
        "#;
        let deps = parse_go_mod(m);
        let foo = deps.iter().find(|d| d.name == "github.com/foo/bar").unwrap();
        assert_eq!(foo.version, "v9.9.9", "replace directive should override version");
        assert!(deps.iter().any(|d| d.name == "github.com/single" && d.version == "v0.1.0"));
        assert!(deps.iter().any(|d| d.name == "golang.org/x/net" && d.version == "v0.10.0"));
    }

    #[test]
    fn parse_pom_xml_resolves_property_substitution() {
        let pom = r#"<?xml version="1.0"?>
<project>
  <properties>
    <jackson.version>2.15.2</jackson.version>
    <slf4j.version>1.7.36</slf4j.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
  </dependencies>
</project>"#;
        let deps = parse_pom_xml(pom);
        assert_eq!(deps.len(), 3);
        let jackson = deps.iter().find(|d| d.name.contains("jackson-databind")).unwrap();
        assert_eq!(jackson.version, "2.15.2");
        assert!(deps.iter().any(|d| d.name == "commons-lang:commons-lang" && d.version == "2.6"));
    }

    #[test]
    fn parse_packages_lock_json_dedupes_across_frameworks() {
        let lock = r#"{
          "version": 1,
          "dependencies": {
            "net6.0": {
              "Newtonsoft.Json": {"type": "Direct", "resolved": "13.0.1"},
              "Serilog": {"type": "Direct", "resolved": "2.12.0"}
            },
            "net7.0": {
              "Newtonsoft.Json": {"type": "Direct", "resolved": "13.0.1"}
            }
          }
        }"#;
        let deps = parse_packages_lock_json(lock);
        assert_eq!(deps.len(), 2, "duplicates across frameworks should collapse");
        assert!(deps.iter().any(|d| d.name == "Newtonsoft.Json" && d.version == "13.0.1"));
    }

    #[test]
    fn parse_packages_config_legacy_format() {
        let cfg = r#"<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.4.4" targetFramework="net48" />
  <package id="Newtonsoft.Json" version="12.0.3" targetFramework="net48" />
</packages>"#;
        let deps = parse_packages_config(cfg);
        assert_eq!(deps.len(), 2);
        assert!(deps.iter().any(|d| d.name == "Newtonsoft.Json" && d.version == "12.0.3"));
        assert!(deps.iter().all(|d| d.ecosystem == Ecosystem::NuGet));
    }

    #[test]
    fn from_lockfile_recognizes_new_filenames() {
        assert_eq!(
            Ecosystem::from_lockfile(&PathBuf::from("requirements.txt")),
            Some(Ecosystem::Pip)
        );
        assert_eq!(
            Ecosystem::from_lockfile(&PathBuf::from("go.mod")),
            Some(Ecosystem::Go)
        );
        assert_eq!(
            Ecosystem::from_lockfile(&PathBuf::from("packages.lock.json")),
            Some(Ecosystem::NuGet)
        );
        assert_eq!(
            Ecosystem::from_lockfile(&PathBuf::from("pom.xml")),
            Some(Ecosystem::Maven)
        );
    }

    #[tokio::test]
    #[ignore]
    async fn osv_live_query_known_vulnerable_package() {
        let scanner = VulnScanner::new();
        let vulns = scanner
            .quick_check("lodash", "4.17.20", Ecosystem::Npm)
            .await
            .expect("OSV query failed");
        assert!(
            !vulns.is_empty(),
            "expected lodash@4.17.20 to have at least one OSV vulnerability"
        );
        // Basic sanity: every returned vuln has a non-empty ID and points at osv.dev.
        for v in &vulns {
            assert!(!v.id.is_empty(), "vuln has empty id: {:?}", v);
            assert!(
                v.url.is_empty() || v.url.contains("osv.dev"),
                "url should reference osv.dev: {}",
                v.url
            );
            assert_eq!(v.package, "lodash");
        }
        // Lodash 4.17.20 has well-known prototype-pollution CVEs rated High
        // (e.g. CVE-2020-8203) — if the severity extractor regressed to "all
        // Low" again, this catches it. Pre-fix, every returned vuln was Low.
        let any_non_low = vulns.iter().any(|v| v.severity != Severity::Low);
        assert!(
            any_non_low,
            "all vulns parsed as Low — severity extractor likely regressed; got: {:?}",
            vulns.iter().map(|v| (&v.id, v.severity)).collect::<Vec<_>>()
        );
    }

    /// Same OSV path for a Cargo crate, exercising the `crates.io` label.
    /// time 0.1.45 had RUSTSEC-2020-0071 (a long-standing Cargo advisory).
    #[tokio::test]
    #[ignore]
    async fn osv_live_query_known_vulnerable_cargo_crate() {
        let scanner = VulnScanner::new();
        let vulns = scanner
            .quick_check("time", "0.1.45", Ecosystem::Cargo)
            .await
            .expect("OSV query failed");
        assert!(
            !vulns.is_empty(),
            "expected `time` 0.1.45 to have at least one OSV vulnerability \
             (test will fail if OSV stops indexing it; see RUSTSEC-2020-0071)"
        );
    }
}