deps-core 1.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
//! Lock file parsing abstractions.
//!
//! Provides generic types and traits for parsing lock files across different
//! package ecosystems (Cargo.lock, package-lock.json, poetry.lock, etc.).
//!
//! Lock files contain resolved dependency versions, allowing instant display
//! without network requests to registries.

use crate::error::{DepsError, Result};
use crate::fs_probe;
use dashmap::DashMap;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime};
use tower_lsp_server::ls_types::Uri;

/// Maximum depth to search for workspace root lock file.
const MAX_WORKSPACE_DEPTH: usize = 5;

/// Maximum lock file size [`read_lockfile_content`] reads before parsing.
///
/// Deliberately a separate, larger constant than [`crate::mtime_cache::MAX_CACHED_FILE_BYTES`]
/// — that cap is scoped to small config files (`.cargo/config.toml`, `.npmrc`, typically a
/// few KB), while a lock file records every transitively resolved package across an entire
/// dependency graph, and a large npm monorepo `package-lock.json` can legitimately run well
/// past 8 MiB. 32 MiB matches [`crate::cache`]'s `MAX_RESPONSE_BYTES` order of magnitude —
/// generous for any realistic lock file while still bounding the read against a
/// maliciously large one discovered by an unauthenticated ancestor walk over a cloned
/// repository (CWE-400).
pub const MAX_LOCKFILE_BYTES: u64 = 32 * 1024 * 1024;

/// Reads a lock file's contents, wrapping any I/O failure into a [`DepsError::ParseError`]
/// tagged with the ecosystem's `file_type` label and the file's path.
///
/// Every `LockFileProvider::parse_lockfile` implementation reads its lock file the same
/// way; this shares that boilerplate and keeps the error message format consistent
/// across ecosystems.
///
/// Bounded by [`MAX_LOCKFILE_BYTES`] via [`fs_probe::read_to_string_capped`] — a lock file
/// is discovered by an unauthenticated ancestor walk ([`locate_lockfile_for_manifest`]) over
/// a possibly hostile cloned repository, so nothing here may assume it is reasonably sized
/// or a regular file before reading it in full (CWE-400). The whole stat-then-read sequence
/// runs as one unit on the blocking-thread pool via [`tokio::task::spawn_blocking`], not on
/// the calling tokio worker thread: both steps are synchronous I/O with no `.await` of their
/// own, and every `LockFileProvider::parse_lockfile` call site sits on the LSP request path,
/// where a worker thread blocked on a `stat` or an 8+ MiB read — or indefinitely, on a FIFO —
/// would violate the project's non-blocking-handler rule (#963).
///
/// # Errors
///
/// Returns [`DepsError::ParseError`] if the file cannot be read (e.g. missing, not a
/// regular file, unreadable, invalid UTF-8), exceeds [`MAX_LOCKFILE_BYTES`], or the
/// blocking read task panicked.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::read_lockfile_content;
/// use std::path::Path;
///
/// # async fn example() -> deps_core::error::Result<()> {
/// let content = read_lockfile_content(Path::new("Cargo.lock"), "Cargo.lock").await?;
/// println!("{} bytes read", content.len());
/// # Ok(())
/// # }
/// ```
#[tracing::instrument(skip_all, fields(path = %path.display(), file_type = %file_type), level = "debug")]
pub async fn read_lockfile_content(path: &Path, file_type: &str) -> Result<String> {
    let to_parse_error = |e: std::io::Error| DepsError::ParseError {
        file_type: format!("{file_type} at {}", path.display()),
        source: Box::new(e),
    };
    let oversized_error = || {
        to_parse_error(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("exceeds {MAX_LOCKFILE_BYTES} byte size cap"),
        ))
    };

    // Entered inside the closure below so the `path`/`file_type` fields this function's
    // `#[tracing::instrument]` attaches to its span still show up on events logged from the
    // blocking pool — a span is not implicitly active on whatever thread `spawn_blocking`
    // happens to run its closure on.
    let span = tracing::Span::current();
    let path_buf = path.to_path_buf();
    let read_result = tokio::task::spawn_blocking(move || {
        let _entered = span.enter();
        // Cheap `stat` pre-filter (mirrors `MtimeFileCache::get_or_parse`): rejects a
        // non-regular file (FIFO, socket, directory — reading one of those can block
        // indefinitely) and an obviously oversized file before it is ever opened. The
        // capped read below still enforces the size bound on the read itself regardless
        // of what this reports, closing the same TOCTOU gap (CWE-367) a stat-only check
        // alone would leave open (e.g. a symlink swapped to a FIFO, or the file growing,
        // between this stat and the read).
        if let Ok(metadata) = fs_probe::metadata(&path_buf) {
            if !metadata.is_file() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "not a regular file",
                ));
            }
            if metadata.len() > MAX_LOCKFILE_BYTES {
                tracing::warn!(
                    path = %path_buf.display(),
                    len = metadata.len(),
                    cap = MAX_LOCKFILE_BYTES,
                    "lock file exceeds size cap; not reading"
                );
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("exceeds {MAX_LOCKFILE_BYTES} byte size cap"),
                ));
            }
        }

        fs_probe::read_to_string_capped(&path_buf, MAX_LOCKFILE_BYTES)
    })
    .await
    .map_err(|e| to_parse_error(std::io::Error::other(e)))?;

    match read_result.map_err(to_parse_error)? {
        Some(content) => Ok(content),
        None => {
            tracing::warn!(
                path = %path.display(),
                cap = MAX_LOCKFILE_BYTES,
                "lock file exceeds size cap during read; not reading"
            );
            Err(oversized_error())
        }
    }
}

/// Reads a lock file via [`read_lockfile_content`] and runs `parse` on the blocking-thread
/// pool, returning the parsed result.
///
/// Every `LockFileProvider::parse_lockfile` implementation reads its lock file's content and
/// then parses it; this shares that second half of the boilerplate too. The parse step is
/// CPU-bound work over content bounded by the same [`MAX_LOCKFILE_BYTES`] cap as the read
/// (a `Cargo.lock`/`package-lock.json`/... TOML, JSON, or YAML document up to 32 MiB), so —
/// like the read itself — it must never run on the calling tokio worker thread: every
/// `LockFileProvider::parse_lockfile` call site sits on the LSP request path, where a worker
/// thread blocked on parsing a multi-megabyte document would violate the project's
/// non-blocking-handler rule.
///
/// # Errors
///
/// Returns whatever [`read_lockfile_content`] returns for a read failure, whatever `parse`
/// itself returns for a malformed document, or a [`DepsError::ParseError`] if the blocking
/// parse task panics or is cancelled.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::{read_and_parse_lockfile, ResolvedPackages};
/// use std::path::Path;
///
/// # async fn example() -> deps_core::error::Result<()> {
/// let packages: ResolvedPackages = read_and_parse_lockfile(
///     Path::new("Cargo.lock"),
///     "Cargo.lock",
///     |content| Ok(ResolvedPackages::new()), // real parsers inspect `content`
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
#[tracing::instrument(skip_all, fields(path = %path.display(), file_type = %file_type), level = "debug")]
pub async fn read_and_parse_lockfile<T, F>(path: &Path, file_type: &str, parse: F) -> Result<T>
where
    F: FnOnce(String) -> Result<T> + Send + 'static,
    T: Send + 'static,
{
    let content = read_lockfile_content(path, file_type).await?;

    tokio::task::spawn_blocking(move || parse(content))
        .await
        .map_err(|e| DepsError::ParseError {
            file_type: format!("{file_type} at {}", path.display()),
            source: Box::new(std::io::Error::other(e)),
        })?
}

/// Generic lock file locator.
///
/// Searches for lock files in the following order:
/// 1. Same directory as the manifest
/// 2. Parent directories (up to MAX_WORKSPACE_DEPTH levels) for workspace root
///
/// Each candidate is checked with [`fs_probe::is_file`], not a plain existence check — a
/// FIFO or socket happening to sit at a lock file's conventional name must never be
/// returned as "found", since [`read_lockfile_content`] opening one would block
/// indefinitely.
///
/// This function is ecosystem-agnostic and works with any lock file name.
///
/// # Arguments
///
/// * `manifest_uri` - URI of the manifest file
/// * `lockfile_names` - List of possible lock file names to search for
///
/// # Returns
///
/// Path to the first found lock file, or None if not found.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::locate_lockfile_for_manifest;
/// use tower_lsp_server::ls_types::Uri;
///
/// let manifest_uri = Uri::from_file_path("/path/to/Cargo.toml").unwrap();
/// let lockfile_names = &["Cargo.lock"];
///
/// if let Some(path) = locate_lockfile_for_manifest(&manifest_uri, lockfile_names) {
///     println!("Found lock file at: {}", path.display());
/// }
/// ```
pub fn locate_lockfile_for_manifest(
    manifest_uri: &Uri,
    lockfile_names: &[&str],
) -> Option<PathBuf> {
    let manifest_path = manifest_uri.to_file_path()?;
    let manifest_dir = manifest_path.parent()?;

    // Reuse single PathBuf to avoid allocations in loops
    let mut lock_path = manifest_dir.to_path_buf();

    // Try same directory as manifest
    for &name in lockfile_names {
        lock_path.push(name);
        if fs_probe::is_file(&lock_path) {
            tracing::debug!("Found {} at: {}", name, lock_path.display());
            return Some(lock_path);
        }
        lock_path.pop();
    }

    // Search up the directory tree for workspace root
    let Some(mut current_dir) = manifest_dir.parent() else {
        tracing::debug!("No lock file found for: {:?}", manifest_uri);
        return None;
    };

    for depth in 0..MAX_WORKSPACE_DEPTH {
        lock_path.clear();
        lock_path.push(current_dir);

        for &name in lockfile_names {
            lock_path.push(name);
            if fs_probe::is_file(&lock_path) {
                tracing::debug!(
                    "Found workspace {} at depth {}: {}",
                    name,
                    depth + 1,
                    lock_path.display()
                );
                return Some(lock_path);
            }
            lock_path.pop();
        }

        match current_dir.parent() {
            Some(parent) => current_dir = parent,
            None => break,
        }
    }

    tracing::debug!("No lock file found for: {:?}", manifest_uri);
    None
}

/// Resolved package information from a lock file.
///
/// Contains the exact version and source information for a dependency
/// as resolved by the package manager.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPackage {
    /// Package name
    pub name: String,
    /// Resolved version (exact version from lock file)
    pub version: String,
    /// Source information (registry URL, git commit, path)
    pub source: ResolvedSource,
    /// Dependencies of this package (for dependency tree analysis)
    pub dependencies: Vec<String>,
}

impl ResolvedPackage {
    /// Constructs a `ResolvedPackage` from its three required fields, with
    /// [`Self::dependencies`] left empty — chain [`Self::with_dependencies`] to attach them.
    ///
    /// Needed because [`Self`] is `#[non_exhaustive]`: a struct literal only works inside
    /// this crate, so every other crate must go through this constructor instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lockfile::{ResolvedPackage, ResolvedSource};
    ///
    /// let package = ResolvedPackage::new(
    ///     "serde".to_string(),
    ///     "1.0.195".to_string(),
    ///     ResolvedSource::Registry {
    ///         url: "https://github.com/rust-lang/crates.io-index".into(),
    ///         checksum: "abc123".into(),
    ///     },
    /// );
    /// assert!(package.dependencies.is_empty());
    /// ```
    #[must_use]
    pub fn new(name: String, version: String, source: ResolvedSource) -> Self {
        Self {
            name,
            version,
            source,
            dependencies: Vec::new(),
        }
    }

    /// Attaches this package's own dependencies. See [`Self::dependencies`].
    #[must_use]
    pub fn with_dependencies(mut self, dependencies: Vec<String>) -> Self {
        self.dependencies = dependencies;
        self
    }
}

/// Source of a resolved dependency.
///
/// Indicates where the package was downloaded from or how it was resolved.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedSource {
    /// From a registry with optional checksum
    Registry {
        /// Registry URL
        url: String,
        /// Checksum/integrity hash
        checksum: String,
    },
    /// From git with commit hash
    Git {
        /// Git repository URL
        url: String,
        /// Commit SHA or tag
        rev: String,
    },
    /// From local file system
    Path {
        /// Relative or absolute path
        path: String,
    },
}

/// Collection of resolved packages from a lock file.
///
/// Supports multiple versions per package name, returning the highest
/// semver version through public API methods.
///
/// # Examples
///
/// ```
/// use deps_core::lockfile::{ResolvedPackages, ResolvedPackage, ResolvedSource};
///
/// let mut packages = ResolvedPackages::new();
/// packages.insert(
///     ResolvedPackage::new(
///         "serde".into(),
///         "1.0.195".into(),
///         ResolvedSource::Registry {
///             url: "https://github.com/rust-lang/crates.io-index".into(),
///             checksum: "abc123".into(),
///         },
///     )
///     .with_dependencies(vec!["serde_derive".into()]),
/// );
///
/// assert_eq!(packages.version("serde"), Some("1.0.195"));
/// assert_eq!(packages.len(), 1);
/// ```
#[derive(Debug, Default, Clone)]
pub struct ResolvedPackages {
    packages: HashMap<String, Vec<ResolvedPackage>>,
}

/// Orders two version strings, preferring a valid semver parse over a non-parseable one and
/// falling back to a lexicographic compare when both (or neither) parse.
///
/// Shared by [`best_package`] and the per-occurrence candidate selection in
/// [`crate::lsp_helpers::resolve_in_use_version`] (issue #649) so a lock file entry with a
/// non-semver version string is never ordered by two diverging policies depending on which
/// caller is asking.
pub(crate) fn compare_lockfile_versions(a: &str, b: &str) -> std::cmp::Ordering {
    match (semver::Version::parse(a), semver::Version::parse(b)) {
        (Ok(va), Ok(vb)) => va.cmp(&vb),
        (Ok(_), Err(_)) => std::cmp::Ordering::Greater,
        (Err(_), Ok(_)) => std::cmp::Ordering::Less,
        (Err(_), Err(_)) => a.cmp(b),
    }
}

/// Returns the package with the highest semver version from a slice.
fn best_package(packages: &[ResolvedPackage]) -> Option<&ResolvedPackage> {
    packages
        .iter()
        .max_by(|a, b| compare_lockfile_versions(&a.version, &b.version))
}

impl ResolvedPackages {
    /// Creates a new empty collection.
    pub fn new() -> Self {
        Self {
            packages: HashMap::new(),
        }
    }

    /// Inserts a resolved package, storing all versions per name.
    pub fn insert(&mut self, package: ResolvedPackage) {
        self.packages
            .entry(package.name.clone())
            .or_default()
            .push(package);
    }

    /// Gets the resolved package with the highest semver version.
    pub fn get(&self, name: &str) -> Option<&ResolvedPackage> {
        self.packages.get(name).and_then(|v| best_package(v))
    }

    /// Gets the highest resolved version string for a package.
    pub fn version(&self, name: &str) -> Option<&str> {
        self.get(name).map(|p| p.version.as_str())
    }

    /// Returns all stored versions for a package.
    pub fn all(&self, name: &str) -> Option<&[ResolvedPackage]> {
        self.packages.get(name).map(|v| v.as_slice())
    }

    /// Returns an iterator yielding every stored version for each unique package name,
    /// unlike [`Self::iter`] which collapses each name down to `best_package`'s single
    /// pick.
    ///
    /// The building block for per-occurrence lock-file resolution (issue #649): a caller
    /// disambiguating two manifest occurrences of the same resolved package name (e.g. a
    /// Cargo `package = "..."` rename pinning an older major alongside a plain dependency
    /// on the current major) needs every retained version for that name, not just the one
    /// [`Self::iter`]/[`Self::into_map`] would collapse it to.
    pub fn iter_all(&self) -> impl Iterator<Item = (&String, &[ResolvedPackage])> {
        self.packages
            .iter()
            .map(|(name, versions)| (name, versions.as_slice()))
    }

    /// Returns the number of unique package names.
    pub fn len(&self) -> usize {
        self.packages.len()
    }

    /// Returns true if there are no resolved packages.
    pub fn is_empty(&self) -> bool {
        self.packages.is_empty()
    }

    /// Returns an iterator yielding the best version per unique package name.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ResolvedPackage)> {
        self.packages.keys().filter_map(|name| {
            self.packages
                .get(name)
                .and_then(|v| best_package(v).map(|p| (name, p)))
        })
    }

    /// Converts into a HashMap with the best version per package name.
    pub fn into_map(self) -> HashMap<String, ResolvedPackage> {
        self.packages
            .into_iter()
            .filter_map(|(name, versions)| best_package(&versions).cloned().map(|p| (name, p)))
            .collect()
    }
}

/// Lock file provider trait for ecosystem-specific implementations.
///
/// Implementations parse lock files for a specific package ecosystem
/// (Cargo.lock, package-lock.json, etc.) and extract resolved versions.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::{LockFileProvider, ResolvedPackages};
/// use std::path::{Path, PathBuf};
/// use tower_lsp_server::ls_types::Uri;
///
/// struct MyLockParser;
///
/// impl LockFileProvider for MyLockParser {
///     fn locate_lockfile(&self, manifest_uri: &Uri) -> Option<PathBuf> {
///         let manifest_path = manifest_uri.to_file_path()?;
///         let lock_path = manifest_path.with_file_name("my.lock");
///         lock_path.exists().then_some(lock_path)
///     }
///
///     fn parse_lockfile<'a>(&'a self, lockfile_path: &'a Path) -> std::pin::Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<ResolvedPackages>> + Send + 'a>> {
///         Box::pin(async move {
///             // Parse lock file format and extract packages
///             Ok(ResolvedPackages::new())
///         })
///     }
/// }
/// ```
pub trait LockFileProvider: Send + Sync {
    /// Locates the lock file for a given manifest URI.
    ///
    /// Returns `None` if:
    /// - Lock file doesn't exist
    /// - Manifest path cannot be determined from URI
    /// - Workspace root search fails
    ///
    /// # Arguments
    ///
    /// * `manifest_uri` - URI of the manifest file (Cargo.toml, package.json, etc.)
    ///
    /// # Returns
    ///
    /// Path to lock file if found
    fn locate_lockfile(&self, manifest_uri: &Uri) -> Option<PathBuf>;

    /// Parses a lock file and extracts resolved packages.
    ///
    /// # Arguments
    ///
    /// * `lockfile_path` - Path to the lock file
    ///
    /// # Returns
    ///
    /// ResolvedPackages on success, error if parse fails
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - File cannot be read
    /// - File format is invalid
    /// - Required fields are missing
    fn parse_lockfile<'a>(
        &'a self,
        lockfile_path: &'a Path,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>>;
}

/// Upper bound on a [`LockFileCache`]'s entry count.
///
/// Matches [`crate::mtime_cache::DEFAULT_MAX_CACHED_FILES`] — the same generous bound for
/// any realistic workspace's set of *distinct* lock files. Without a cap, a long-running
/// server session that opens many workspaces over time (or one pointed at a monorepo with
/// many independently-locked sub-projects) would grow this cache unboundedly, since entries
/// previously survived even a `textDocument/didClose` (#962).
///
/// Bounds this cache's worst-case retained content at `DEFAULT_MAX_CACHED_LOCKFILES *
/// MAX_LOCKFILE_BYTES` (256 * 32 MiB = 8 GiB of raw lock file content, before accounting for
/// parsed [`ResolvedPackages`] overhead) — generous headroom rather than a tight budget,
/// since a byte-accounted eviction policy (like [`crate::cache::HttpCache`]'s) is more
/// precision than this entry-count-keyed cache needs.
pub const DEFAULT_MAX_CACHED_LOCKFILES: usize = 256;

/// Cached lock file entry with staleness detection.
struct CachedLockFile {
    packages: ResolvedPackages,
    modified_at: SystemTime,
    /// When this entry was last parsed *or* served from a cache hit — the recency key
    /// [`LockFileCache::evict_oldest`] evicts by once the cache is at capacity. Refreshed on
    /// every access (not only on (re)parse), so eviction is genuinely LRU rather than
    /// FIFO-by-parse-time — otherwise a stable, frequently-read lock file would look oldest
    /// and get evicted first, while one that keeps changing (and reparsing) would never age
    /// out.
    parsed_at: Instant,
}

/// Cache for parsed lock files with automatic staleness detection.
///
/// Caches parsed lock file contents and checks file modification time
/// to avoid re-parsing unchanged files. Thread-safe for concurrent access.
///
/// Bounded by a capacity ([`DEFAULT_MAX_CACHED_LOCKFILES`] by default, via [`Self::new`]; a
/// custom bound via [`Self::with_capacity`]): once full, inserting a new key evicts the
/// least-recently-used entry first, keyed by `CachedLockFile::parsed_at`, which is
/// refreshed on every cache hit as well as every (re)parse (#962).
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::LockFileCache;
/// use std::path::Path;
///
/// # async fn example() -> deps_core::error::Result<()> {
/// let cache = LockFileCache::new();
/// // First call parses the file
/// // Second call returns cached result if file hasn't changed
/// # Ok(())
/// # }
/// ```
pub struct LockFileCache {
    entries: DashMap<PathBuf, CachedLockFile>,
    capacity: usize,
}

impl LockFileCache {
    /// Creates a new empty lock file cache, capped at [`DEFAULT_MAX_CACHED_LOCKFILES`]
    /// entries.
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_MAX_CACHED_LOCKFILES)
    }

    /// Creates a new empty lock file cache, capped at `capacity` entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lockfile::LockFileCache;
    ///
    /// let cache = LockFileCache::with_capacity(64);
    /// assert!(cache.is_empty());
    /// ```
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: DashMap::new(),
            capacity,
        }
    }

    /// Evicts the least-recently-used entry, making room for one new insert.
    ///
    /// A full scan of `entries` by [`CachedLockFile::parsed_at`] — acceptable at this
    /// cache's scale (bounded by `capacity`, [`DEFAULT_MAX_CACHED_LOCKFILES`] by default),
    /// unlike [`crate::osv`]'s cache, which is sized an order of magnitude larger and batches
    /// its eviction accordingly. Logs at `warn` when eviction actually runs, mirroring
    /// [`crate::mtime_cache::MtimeFileCache`]'s own at-capacity warning.
    fn evict_oldest(&self) {
        let oldest = self
            .entries
            .iter()
            .min_by_key(|entry| entry.parsed_at)
            .map(|entry| entry.key().clone());
        if let Some(key) = oldest {
            tracing::warn!(
                path = %key.display(),
                capacity = self.capacity,
                "lock file cache capacity reached; evicting least-recently-used entry"
            );
            self.entries.remove(&key);
        }
    }

    /// Gets parsed packages from cache or parses the lock file.
    ///
    /// Checks file modification time to detect changes. If the file
    /// has been modified since last parse, re-parses it. Otherwise,
    /// returns the cached result.
    ///
    /// # Arguments
    ///
    /// * `provider` - Lock file provider implementation
    /// * `lockfile_path` - Path to the lock file
    ///
    /// # Returns
    ///
    /// Resolved packages on success
    ///
    /// # Errors
    ///
    /// Returns error if file cannot be read or parsed
    pub async fn get_or_parse(
        &self,
        provider: &dyn LockFileProvider,
        lockfile_path: &Path,
    ) -> Result<ResolvedPackages> {
        // Extract owned data from the cache entry before awaiting: the DashMap shard
        // `Ref` returned by `entries.get` must not be held across `.await`, or a
        // concurrent access to the same key blocks for the duration (#350, same hazard
        // class as #333).
        let cached = self
            .entries
            .get(lockfile_path)
            .map(|entry| (entry.modified_at, entry.packages.clone()));

        // Check cache first
        if let Some((cached_modified_at, cached_packages)) = cached
            && let Ok(metadata) = tokio::fs::metadata(lockfile_path).await
            && let Ok(mtime) = metadata.modified()
            && mtime <= cached_modified_at
        {
            tracing::debug!("Lock file cache hit: {}", lockfile_path.display());
            // Refresh the recency marker on a hit too, not only on (re)parse: otherwise
            // eviction is FIFO-by-parse-time rather than LRU, evicting a stable,
            // frequently-read lock file before one that keeps changing and reparsing.
            if let Some(mut entry) = self.entries.get_mut(lockfile_path) {
                entry.parsed_at = Instant::now();
            }
            return Ok(cached_packages);
        }

        // Cache miss - parse and store.
        //
        // Stat the file *before* parsing and use that pre-parse mtime as the cache
        // key's freshness marker. If we stat'd after `parse_lockfile` instead, a
        // concurrent rewrite landing mid-parse would let us store content read from
        // the old version of the file under the new version's mtime, making the
        // entry look fresh when it is actually stale (#359).
        tracing::debug!("Lock file cache miss: {}", lockfile_path.display());
        let metadata = tokio::fs::metadata(lockfile_path).await?;
        let modified_at = metadata.modified()?;

        let packages = provider.parse_lockfile(lockfile_path).await?;

        if !self.entries.contains_key(lockfile_path) && self.entries.len() >= self.capacity {
            self.evict_oldest();
        }
        self.entries.insert(
            lockfile_path.to_path_buf(),
            CachedLockFile {
                packages: packages.clone(),
                modified_at,
                parsed_at: Instant::now(),
            },
        );

        Ok(packages)
    }

    /// Invalidates cached entry for a lock file.
    ///
    /// Forces next access to re-parse the file. Use when you know
    /// the file has changed but modification time might not reflect it.
    pub fn invalidate(&self, lockfile_path: &Path) {
        self.entries.remove(lockfile_path);
    }

    /// Returns the number of cached lock files.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

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

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

    #[tokio::test]
    async fn test_read_lockfile_content_success() {
        // Held per `fs_probe::snapshot_guard`'s doc: `read_lockfile_content` transitively
        // touches fs_probe, and this test runs in the same binary as other modules' (e.g.
        // `mtime_cache`'s) diffing tests.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        std::fs::write(&lock_path, "version = 4").unwrap();

        let content = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap();

        assert_eq!(content, "version = 4");
    }

    /// An oversized lock file must be rejected by the capped read rather than read into
    /// memory in full (CWE-400) — `read_lockfile_content` previously had no size gate at
    /// all (#607). Uses a sparse file (`set_len`, all-zero bytes, valid UTF-8) so the test
    /// does not need to write `MAX_LOCKFILE_BYTES` of real content to disk — `unwrap_err()`
    /// panics outright if the cap is not actually applied, since a sparse file's all-NUL
    /// content is otherwise perfectly valid `String` content for the success path to return.
    #[tokio::test]
    async fn test_read_lockfile_content_rejects_oversized_file() {
        // See the comment in `test_read_lockfile_content_success` on why this guard is
        // needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        let file = std::fs::File::create(&lock_path).unwrap();
        file.set_len(MAX_LOCKFILE_BYTES + 1).unwrap();

        let err = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap_err();

        match err {
            DepsError::ParseError { file_type, .. } => {
                assert_eq!(file_type, format!("Cargo.lock at {}", lock_path.display()));
            }
            other => panic!("Expected ParseError, got: {other:?}"),
        }
    }

    /// A non-regular file (a directory here, portable across platforms unlike a FIFO) at
    /// the lock file path must be rejected by the `is_file` stat pre-filter, not handed to
    /// `File::open`/`read_to_string_capped` — the same class of hazard `fs_probe::is_file`'s
    /// own doc warns about (a FIFO would block the read indefinitely).
    #[tokio::test]
    async fn test_read_lockfile_content_rejects_non_regular_file() {
        // See the comment in `test_read_lockfile_content_success` on why this guard is
        // needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        std::fs::create_dir(&lock_path).unwrap();

        let err = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap_err();

        match err {
            DepsError::ParseError { file_type, .. } => {
                assert_eq!(file_type, format!("Cargo.lock at {}", lock_path.display()));
            }
            other => panic!("Expected ParseError, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_read_lockfile_content_missing_file_wraps_error() {
        // See the comment in `test_read_lockfile_content_success` on why this guard is
        // needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");

        let err = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap_err();

        match err {
            DepsError::ParseError { file_type, .. } => {
                assert_eq!(file_type, format!("Cargo.lock at {}", lock_path.display()));
            }
            other => panic!("Expected ParseError, got: {other:?}"),
        }
    }

    /// The `spawn_blocking` `JoinError`→`DepsError::ParseError` mapping is issue #723's core
    /// concern (a panicking/blocking parse must not silently misbehave or unwind the caller),
    /// but had zero executable coverage — only the `no_run` doctest, which never runs. A
    /// panicking `parse` closure must surface as `Err(DepsError::ParseError)`, labeled the
    /// same way as every other `read_and_parse_lockfile` failure (`"{file_type} at {path}"`),
    /// with the panic message preserved in `source` (tokio's `JoinError: Display` carries it).
    #[tokio::test]
    async fn test_read_and_parse_lockfile_panic_in_parse_becomes_parse_error() {
        // See the comment in `test_read_lockfile_content_success` on why this guard is
        // needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        std::fs::write(&lock_path, "version = 4").unwrap();

        let err = read_and_parse_lockfile(&lock_path, "Cargo.lock", |_content| -> Result<()> {
            panic!("boom")
        })
        .await
        .unwrap_err();

        match err {
            DepsError::ParseError { file_type, source } => {
                assert_eq!(file_type, format!("Cargo.lock at {}", lock_path.display()));
                assert!(
                    source.to_string().contains("boom"),
                    "panic message should be preserved in the error source, got: {source}"
                );
            }
            other => panic!("Expected ParseError, got: {other:?}"),
        }
    }

    /// Proves `parse` actually runs off the calling (async) thread via `spawn_blocking`, not
    /// merely that the return type happens to line up — the whole point of the fix is that
    /// CPU-bound parsing no longer executes on the tokio worker driving the LSP request.
    #[tokio::test]
    async fn test_read_and_parse_lockfile_runs_parse_off_calling_thread() {
        // See the comment in `test_read_lockfile_content_success` on why this guard is
        // needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        std::fs::write(&lock_path, "version = 4").unwrap();

        let calling_thread = std::thread::current().id();

        let content = read_and_parse_lockfile(&lock_path, "Cargo.lock", move |content| {
            assert_ne!(
                std::thread::current().id(),
                calling_thread,
                "parse must run on the blocking pool, not the calling thread"
            );
            Ok(content)
        })
        .await
        .unwrap();

        assert_eq!(content, "version = 4");
    }

    #[test]
    fn test_resolved_packages_new() {
        let packages = ResolvedPackages::new();
        assert!(packages.is_empty());
        assert_eq!(packages.len(), 0);
    }

    #[test]
    fn test_resolved_packages_insert_and_get() {
        let mut packages = ResolvedPackages::new();

        let pkg = ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "https://github.com/rust-lang/crates.io-index".into(),
                checksum: "abc123".into(),
            },
            dependencies: vec!["serde_derive".into()],
        };

        packages.insert(pkg);

        assert_eq!(packages.len(), 1);
        assert!(!packages.is_empty());
        assert_eq!(packages.version("serde"), Some("1.0.195"));

        let retrieved = packages.get("serde");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "serde");
        assert_eq!(retrieved.unwrap().dependencies.len(), 1);
    }

    #[test]
    fn test_resolved_packages_get_nonexistent() {
        let packages = ResolvedPackages::new();
        assert_eq!(packages.get("nonexistent"), None);
        assert_eq!(packages.version("nonexistent"), None);
    }

    #[test]
    fn test_resolved_packages_replace() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "old".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "new".into(),
            },
            dependencies: vec![],
        });

        // Both versions stored, but len counts unique names
        assert_eq!(packages.len(), 1);
        assert_eq!(packages.version("serde"), Some("1.0.195"));
        // Both versions accessible via get_all
        assert_eq!(packages.all("serde").unwrap().len(), 2);
    }

    #[test]
    fn test_resolved_packages_multiple_versions() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "0.9.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "b".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "2.0.0-beta.1".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "c".into(),
            },
            dependencies: vec![],
        });

        assert_eq!(packages.len(), 1);
        assert_eq!(packages.version("serde"), Some("2.0.0-beta.1"));
        assert_eq!(packages.all("serde").unwrap().len(), 3);
    }

    #[test]
    fn test_resolved_packages_non_semver_fallback() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "weird".into(),
            version: "abc".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "weird".into(),
            version: "xyz".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        // Falls back to string comparison: "xyz" > "abc"
        assert_eq!(packages.version("weird"), Some("xyz"));
    }

    #[test]
    fn test_resolved_packages_semver_preferred_over_non_semver() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "mixed".into(),
            version: "not-a-version".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "mixed".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        // Parseable semver is preferred over non-parseable
        assert_eq!(packages.version("mixed"), Some("1.0.0"));
    }

    #[test]
    fn test_resolved_source_equality() {
        let source1 = ResolvedSource::Registry {
            url: "https://test.com".into(),
            checksum: "abc".into(),
        };
        let source2 = ResolvedSource::Registry {
            url: "https://test.com".into(),
            checksum: "abc".into(),
        };
        let source3 = ResolvedSource::Git {
            url: "https://github.com/test".into(),
            rev: "abc123".into(),
        };

        assert_eq!(source1, source2);
        assert_ne!(source1, source3);
    }

    #[test]
    fn test_resolved_packages_iter() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "tokio".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "b".into(),
            },
            dependencies: vec![],
        });

        let count = packages.iter().count();
        assert_eq!(count, 2);

        let names: Vec<_> = packages.iter().map(|(name, _)| name.as_str()).collect();
        assert!(names.contains(&"serde"));
        assert!(names.contains(&"tokio"));
    }

    #[test]
    fn test_resolved_packages_into_map() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        let map = packages.into_map();
        assert_eq!(map.len(), 1);
        assert!(map.contains_key("serde"));
    }

    #[test]
    fn test_lockfile_cache_new() {
        let cache = LockFileCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert_eq!(
            cache.capacity, DEFAULT_MAX_CACHED_LOCKFILES,
            "new() must use the documented default capacity"
        );
    }

    #[test]
    fn test_lockfile_cache_invalidate() {
        let cache = LockFileCache::new();
        let test_path = PathBuf::from("/test/Cargo.lock");

        cache.entries.insert(
            test_path.clone(),
            CachedLockFile {
                packages: ResolvedPackages::new(),
                modified_at: SystemTime::now(),
                parsed_at: Instant::now(),
            },
        );

        assert_eq!(cache.len(), 1);

        cache.invalidate(&test_path);
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_lockfile_cache_with_capacity() {
        let cache = LockFileCache::with_capacity(64);
        assert_eq!(cache.capacity, 64);
        assert!(cache.is_empty());
    }

    /// #962 regression: a [`LockFileCache`] at capacity must evict the least-recently-parsed
    /// entry before inserting a new key, never grow past its configured bound.
    #[tokio::test]
    async fn test_get_or_parse_evicts_oldest_entry_at_capacity() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_a = temp_dir.path().join("a.lock");
        let lock_b = temp_dir.path().join("b.lock");
        let lock_c = temp_dir.path().join("c.lock");
        std::fs::write(&lock_a, "a").unwrap();
        std::fs::write(&lock_b, "b").unwrap();
        std::fs::write(&lock_c, "c").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::with_capacity(2);

        cache.get_or_parse(&provider, &lock_a).await.unwrap();
        cache.get_or_parse(&provider, &lock_b).await.unwrap();
        assert_eq!(
            cache.len(),
            2,
            "cache should hold exactly `capacity` entries"
        );

        // `a` is now the oldest by `parsed_at`; inserting a third distinct key must evict
        // it rather than growing the cache past its capacity.
        cache.get_or_parse(&provider, &lock_c).await.unwrap();
        assert_eq!(
            cache.len(),
            2,
            "cache must not grow past its configured capacity"
        );
        assert!(
            cache.entries.contains_key(&lock_b),
            "the more recently parsed entry must survive eviction"
        );
        assert!(
            cache.entries.contains_key(&lock_c),
            "the newly inserted entry must be present"
        );
        assert!(
            !cache.entries.contains_key(&lock_a),
            "the least-recently-parsed entry must have been evicted"
        );

        // Re-fetching the evicted `a` must trigger a fresh parse, not a cache hit.
        let parses_before = provider.parse_count();
        cache.get_or_parse(&provider, &lock_a).await.unwrap();
        assert_eq!(
            provider.parse_count(),
            parses_before + 1,
            "an evicted entry must be re-parsed on next access"
        );
    }

    /// A repeat `get_or_parse` for an already-cached key at capacity must not trigger
    /// eviction — the cache-hit path returns before `entries.insert` is ever reached.
    #[tokio::test]
    async fn test_get_or_parse_cache_hit_at_capacity_does_not_evict() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_a = temp_dir.path().join("a.lock");
        let lock_b = temp_dir.path().join("b.lock");
        std::fs::write(&lock_a, "a").unwrap();
        std::fs::write(&lock_b, "b").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::with_capacity(2);

        cache.get_or_parse(&provider, &lock_a).await.unwrap();
        cache.get_or_parse(&provider, &lock_b).await.unwrap();

        // Re-fetch `a` (unchanged mtime): a cache hit, must not evict `b`.
        cache.get_or_parse(&provider, &lock_a).await.unwrap();
        assert_eq!(cache.len(), 2);
        assert!(cache.entries.contains_key(&lock_a));
        assert!(cache.entries.contains_key(&lock_b));
    }

    #[test]
    fn test_locate_lockfile_for_manifest_same_directory() {
        // Held per `fs_probe::snapshot_guard`'s doc: `locate_lockfile_for_manifest`
        // transitively touches fs_probe (via `fs_probe::is_file`), and this test runs in the
        // same binary as other modules' (e.g. `mtime_cache`'s) diffing tests.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("Cargo.toml");
        let lock_path = temp_dir.path().join("Cargo.lock");

        std::fs::write(&manifest_path, "[package]\nname = \"test\"").unwrap();
        std::fs::write(&lock_path, "version = 4").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), lock_path);
    }

    #[test]
    fn test_locate_lockfile_for_manifest_workspace_root() {
        // See the comment in `test_locate_lockfile_for_manifest_same_directory` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let workspace_lock = temp_dir.path().join("Cargo.lock");
        let member_dir = temp_dir.path().join("crates").join("member");
        std::fs::create_dir_all(&member_dir).unwrap();
        let member_manifest = member_dir.join("Cargo.toml");

        std::fs::write(&workspace_lock, "version = 4").unwrap();
        std::fs::write(&member_manifest, "[package]\nname = \"member\"").unwrap();

        let manifest_uri = Uri::from_file_path(&member_manifest).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), workspace_lock);
    }

    /// A directory named `Cargo.lock` (portable stand-in for a FIFO, which
    /// `std::fs::exists`-style checks would also wrongly treat as "found") must not be
    /// returned as a located lock file — `fs_probe::is_file` rejects anything but a
    /// regular file, unlike the plain `Path::exists()` this locator used before the fix.
    #[test]
    fn test_locate_lockfile_for_manifest_skips_non_regular_file() {
        // See the comment in `test_locate_lockfile_for_manifest_same_directory` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("Cargo.toml");
        let lock_path = temp_dir.path().join("Cargo.lock");

        std::fs::write(&manifest_path, "[package]\nname = \"test\"").unwrap();
        std::fs::create_dir(&lock_path).unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(
            located.is_none(),
            "a directory at the lock file path must not be treated as a found lock file"
        );
    }

    #[test]
    fn test_locate_lockfile_for_manifest_not_found() {
        // See the comment in `test_locate_lockfile_for_manifest_same_directory` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("Cargo.toml");
        std::fs::write(&manifest_path, "[package]\nname = \"test\"").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_none());
    }

    #[test]
    fn test_locate_lockfile_for_manifest_multiple_names() {
        // See the comment in `test_locate_lockfile_for_manifest_same_directory` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("pyproject.toml");
        let uv_lock = temp_dir.path().join("uv.lock");

        std::fs::write(&manifest_path, "[project]\nname = \"test\"").unwrap();
        std::fs::write(&uv_lock, "version = 1").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        // poetry.lock doesn't exist, but uv.lock does - should find uv.lock
        let located = locate_lockfile_for_manifest(&manifest_uri, &["poetry.lock", "uv.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), uv_lock);
    }

    /// Stub [`LockFileProvider`] that counts `parse_lockfile` invocations and returns
    /// a package whose version is the lock file's trimmed content, so tests can
    /// observe both call count and which content was actually parsed.
    struct CountingLockFileProvider {
        parse_count: std::sync::atomic::AtomicUsize,
    }

    impl CountingLockFileProvider {
        fn new() -> Self {
            Self {
                parse_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn parse_count(&self) -> usize {
            self.parse_count.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    impl LockFileProvider for CountingLockFileProvider {
        fn locate_lockfile(&self, _manifest_uri: &Uri) -> Option<PathBuf> {
            None
        }

        fn parse_lockfile<'a>(
            &'a self,
            lockfile_path: &'a Path,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>,
        > {
            Box::pin(async move {
                self.parse_count
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let content = read_lockfile_content(lockfile_path, "test.lock").await?;

                let mut packages = ResolvedPackages::new();
                packages.insert(ResolvedPackage {
                    name: "test-package".into(),
                    version: content.trim().to_string(),
                    source: ResolvedSource::Path { path: ".".into() },
                    dependencies: vec![],
                });
                Ok(packages)
            })
        }
    }

    #[tokio::test]
    async fn test_get_or_parse_cache_hit_does_not_reparse() {
        // Held per `fs_probe::snapshot_guard`'s doc: the stub provider's `parse_lockfile`
        // calls `read_lockfile_content`, which transitively touches fs_probe.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(provider.parse_count(), 1, "second call should hit cache");
        assert_eq!(first.version("test-package"), Some("1.0.0"));
        assert_eq!(second.version("test-package"), Some("1.0.0"));
    }

    /// A lock file that does not exist (never cached, or deleted since) must surface as an
    /// `Err`, not panic or silently return empty/stale data — `get_or_parse` has no dedicated
    /// missing-file branch of its own; its cache-miss path's `tokio::fs::metadata` stat simply
    /// propagates the failure via `?`.
    #[tokio::test]
    async fn test_get_or_parse_missing_file_returns_error() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("does-not-exist.lock");

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let err = cache.get_or_parse(&provider, &lock_path).await.unwrap_err();

        assert!(
            matches!(err, DepsError::Io(_)),
            "expected an Io error for a missing lock file, got: {err:?}"
        );
        assert_eq!(
            provider.parse_count(),
            0,
            "parse_lockfile must not be called when the file cannot be stat'd"
        );
    }

    /// A cached entry whose backing file has since been deleted must not be served as a
    /// stale-but-valid cache hit: the freshness check's stat fails, falls through to the
    /// cache-miss path, and that path's own stat also fails, surfacing as `Err` rather than
    /// resurrecting the old cached packages.
    #[tokio::test]
    async fn test_get_or_parse_cached_entry_with_deleted_file_returns_error() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.version("test-package"), Some("1.0.0"));

        std::fs::remove_file(&lock_path).unwrap();

        let err = cache.get_or_parse(&provider, &lock_path).await.unwrap_err();

        assert!(
            matches!(err, DepsError::Io(_)),
            "expected an Io error once the cached file is deleted, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn test_get_or_parse_reparses_when_mtime_advances() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.version("test-package"), Some("1.0.0"));

        std::fs::write(&lock_path, "2.0.0").unwrap();
        // Explicitly bump mtime into the future rather than relying on filesystem
        // mtime resolution (coarse on some platforms) to observe the change.
        let future_mtime = SystemTime::now() + std::time::Duration::from_secs(5);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lock_path)
            .unwrap()
            .set_modified(future_mtime)
            .unwrap();

        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(
            provider.parse_count(),
            2,
            "stale mtime should trigger reparse"
        );
        assert_eq!(second.version("test-package"), Some("2.0.0"));
    }

    /// Documents intentional behavior, not a bug: if a lock file's mtime moves *backward*
    /// relative to what is cached (clock skew, a restored backup, a `git checkout` touching
    /// an older tree), `get_or_parse`'s freshness check (`mtime <= cached_modified_at`) treats
    /// it as still fresh and serves the cached (now content-stale) packages rather than
    /// re-parsing. This mirrors the removed `is_lockfile_stale` default's own behavior for a
    /// `last_modified` timestamp set to the future, so the semantics are unchanged by its
    /// removal — this test exists only so the choice stays covered and visible.
    #[tokio::test]
    async fn test_get_or_parse_cache_hit_when_mtime_moves_backward() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.version("test-package"), Some("1.0.0"));

        std::fs::write(&lock_path, "2.0.0").unwrap();
        let past_mtime = SystemTime::now() - std::time::Duration::from_secs(3600);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lock_path)
            .unwrap()
            .set_modified(past_mtime)
            .unwrap();

        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(
            provider.parse_count(),
            1,
            "a backward-moving mtime must still be treated as a cache hit"
        );
        assert_eq!(
            second.version("test-package"),
            Some("1.0.0"),
            "cached (pre-rewrite) content should be served, not the new on-disk content"
        );
    }

    /// Stub [`LockFileProvider`] that simulates a concurrent writer racing the parse:
    /// each `parse_lockfile` call reads the file's *current* content first, then — as
    /// a side effect before returning — rewrites the file to `"2.0.0"` and bumps its
    /// mtime into the future, then returns packages parsed from the content it read
    /// *before* that rewrite. This reproduces the only await point between the
    /// `get_or_parse` stat and cache insert, entirely under test control.
    struct RewritingDuringParseProvider {
        parse_count: std::sync::atomic::AtomicUsize,
    }

    impl RewritingDuringParseProvider {
        fn new() -> Self {
            Self {
                parse_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn parse_count(&self) -> usize {
            self.parse_count.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    impl LockFileProvider for RewritingDuringParseProvider {
        fn locate_lockfile(&self, _manifest_uri: &Uri) -> Option<PathBuf> {
            None
        }

        fn parse_lockfile<'a>(
            &'a self,
            lockfile_path: &'a Path,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>,
        > {
            Box::pin(async move {
                self.parse_count
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let content = read_lockfile_content(lockfile_path, "test.lock").await?;

                // Simulate a writer rewriting the lock file mid-parse.
                std::fs::write(lockfile_path, "2.0.0").unwrap();
                let future_mtime = SystemTime::now() + std::time::Duration::from_secs(5);
                std::fs::OpenOptions::new()
                    .write(true)
                    .open(lockfile_path)
                    .unwrap()
                    .set_modified(future_mtime)
                    .unwrap();

                let mut packages = ResolvedPackages::new();
                packages.insert(ResolvedPackage {
                    name: "test-package".into(),
                    version: content.trim().to_string(),
                    source: ResolvedSource::Path { path: ".".into() },
                    dependencies: vec![],
                });
                Ok(packages)
            })
        }
    }

    /// Regression test for #359: discriminates the stat-before-parse fix from the
    /// original stat-after-parse ordering.
    ///
    /// With the fix, `get_or_parse` stats the file *before* calling `parse_lockfile`,
    /// so the cached `modified_at` reflects the pre-rewrite mtime tied to the
    /// `"1.0.0"` content actually parsed. A second call then sees the file's mtime is
    /// newer than the cached one, so it re-parses and observes `"2.0.0"`.
    ///
    /// On the pre-fix ordering (stat after parse), the post-parse stat would pick up
    /// the mtime bump this same call just made, storing the *new* mtime alongside the
    /// *old* (`"1.0.0"`) content. The second call would then incorrectly hit cache and
    /// return stale `"1.0.0"` content without re-parsing — exactly the bug #359
    /// describes. This test would have failed on that code.
    #[tokio::test]
    async fn test_get_or_parse_detects_rewrite_during_parse() {
        // See the comment in `test_get_or_parse_cache_hit_does_not_reparse` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard_async().await;
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = RewritingDuringParseProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.version("test-package"), Some("1.0.0"));

        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(
            provider.parse_count(),
            2,
            "rewrite during first parse must be detected and trigger a reparse"
        );
        assert_eq!(second.version("test-package"), Some("2.0.0"));
    }

    #[test]
    fn test_locate_lockfile_for_manifest_first_match_wins() {
        // See the comment in `test_locate_lockfile_for_manifest_same_directory` on why this
        // guard is needed here.
        let _guard = fs_probe::snapshot_guard();
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("pyproject.toml");
        let poetry_lock = temp_dir.path().join("poetry.lock");
        let uv_lock = temp_dir.path().join("uv.lock");

        std::fs::write(&manifest_path, "[project]\nname = \"test\"").unwrap();
        std::fs::write(&poetry_lock, "# poetry lock").unwrap();
        std::fs::write(&uv_lock, "version = 1").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        // Both exist, poetry.lock should be found first (listed first)
        let located = locate_lockfile_for_manifest(&manifest_uri, &["poetry.lock", "uv.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), poetry_lock);
    }
}