deps-core 2.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
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
use dashmap::DashMap;
use std::sync::Arc;

use crate::{Ecosystem, EcosystemId};

/// Registry for all available ecosystems.
///
/// This registry manages ecosystem implementations and provides fast lookup
/// by ecosystem ID or manifest filename. It's designed for thread-safe
/// concurrent access using DashMap.
///
/// # Examples
///
/// ```no_run
/// use deps_core::EcosystemRegistry;
/// use std::sync::Arc;
///
/// let registry = EcosystemRegistry::new();
///
/// // Register ecosystems (would be actual implementations)
/// // registry.register(Arc::new(CargoEcosystem::new(cache.clone())));
/// // registry.register(Arc::new(NpmEcosystem::new(cache.clone())));
///
/// // Look up by filename
/// if let Some(ecosystem) = registry.for_filename("Cargo.toml") {
///     println!("Found ecosystem: {}", ecosystem.display_name());
/// }
///
/// // List all registered ecosystems
/// for id in registry.ecosystem_ids() {
///     println!("Registered: {}", id);
/// }
/// ```
pub struct EcosystemRegistry {
    /// Map from ecosystem ID to implementation
    ecosystems: DashMap<EcosystemId, Arc<dyn Ecosystem>>,
    /// Map from filename to ecosystem ID (for fast lookup)
    filename_map: DashMap<&'static str, EcosystemId>,
    /// Map from lowercased file extension (e.g. ".csproj") to ecosystem ID.
    ///
    /// Consulted only when an exact `filename_map` lookup misses. Kept as a
    /// separate `DashMap` rather than folded into `filename_map` so extension
    /// routing cannot silently shadow an exact filename. Two ecosystems
    /// claiming the same extension is a configuration error caught by a
    /// `debug_assert!` in [`register`](EcosystemRegistry::register) — in a
    /// release build (or if the assertion is otherwise skipped) `DashMap::insert`
    /// silently last-write-wins, so the outcome is registration-order-dependent,
    /// not deterministic.
    extension_map: DashMap<&'static str, EcosystemId>,
    /// Map from a basename pattern (e.g. `"requirements*.txt"`) to
    /// `(prefix, suffix, ecosystem_id)`, split on the pattern's single `*` at
    /// [`register`](EcosystemRegistry::register) time. Consulted between the
    /// exact-filename and extension stages in
    /// [`for_filename`](EcosystemRegistry::for_filename), using
    /// most-specific-wins selection over all matches for determinism
    /// regardless of `DashMap` iteration order.
    patterns: DashMap<&'static str, (&'static str, &'static str, EcosystemId)>,
}

impl EcosystemRegistry {
    /// Create a new empty registry
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// assert_eq!(registry.ecosystem_ids().len(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            ecosystems: DashMap::new(),
            filename_map: DashMap::new(),
            extension_map: DashMap::new(),
            patterns: DashMap::new(),
        }
    }

    /// Register an ecosystem implementation
    ///
    /// This method registers the ecosystem and creates filename mappings
    /// for all manifest filenames declared by the ecosystem.
    ///
    /// # Arguments
    ///
    /// * `ecosystem` - Arc-wrapped ecosystem implementation
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    /// use std::sync::Arc;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(Arc::new(CargoEcosystem::new(cache)));
    /// ```
    pub fn register(&self, ecosystem: Arc<dyn Ecosystem>) {
        let id = ecosystem.ecosystem_id();

        for filename in ecosystem.manifest_filenames() {
            self.filename_map.insert(*filename, id);
        }

        // Fallback for unbounded basenames, e.g. *.csproj
        for extension in ecosystem.manifest_extensions() {
            debug_assert!(
                self.extension_map
                    .get(extension)
                    .is_none_or(|owner| *owner == id),
                "extension {extension:?} already claimed by ecosystem {:?}, cannot also assign it to {id:?}",
                self.extension_map.get(extension).map(|o| *o),
            );
            self.extension_map.insert(*extension, id);
        }

        // e.g. `requirements*.txt`
        for &pattern in ecosystem.manifest_patterns() {
            let Some((prefix, suffix)) = pattern.split_once('*') else {
                debug_assert!(
                    false,
                    "manifest pattern {pattern:?} must contain exactly one '*'"
                );
                continue;
            };
            debug_assert!(
                !prefix.is_empty() || !suffix.is_empty(),
                "manifest pattern {pattern:?} must not be a bare '*', which would claim every file"
            );
            debug_assert!(
                !suffix.contains('*'),
                "manifest pattern {pattern:?} must contain exactly one '*'"
            );
            debug_assert!(
                self.patterns
                    .iter()
                    .all(|e| e.value().2 == id || *e.key() == pattern),
                "pattern {pattern:?} would introduce a second ecosystem ({id:?}) into the \
                 single-owner pattern set; the most-specific-wins selection in \
                 for_filename assumes all patterns belong to one ecosystem"
            );
            self.patterns.insert(pattern, (prefix, suffix, id));
        }

        self.ecosystems.insert(id, ecosystem);
    }

    /// Get ecosystem by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Ecosystem identifier
    ///
    /// # Returns
    ///
    /// * `Some(Arc<dyn Ecosystem>)` - Registered ecosystem
    /// * `None` - No ecosystem registered with this ID
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::{EcosystemId, EcosystemRegistry};
    ///
    /// let registry = EcosystemRegistry::new();
    /// if let Some(ecosystem) = registry.get(EcosystemId::Cargo) {
    ///     println!("Found: {}", ecosystem.display_name());
    /// }
    /// ```
    pub fn get(&self, id: EcosystemId) -> Option<Arc<dyn Ecosystem>> {
        self.ecosystems.get(&id).map(|e| Arc::clone(&e))
    }

    /// Get ecosystem for a filename
    ///
    /// Lookup is two-stage: an exact, case-sensitive match against
    /// registered manifest filenames (e.g. `"Cargo.toml"`) is tried first;
    /// if that misses, the filename's extension is matched case-insensitively
    /// against registered [`Ecosystem::manifest_extensions`]. This asymmetry
    /// is deliberate — exact filenames are canonical and case-sensitive on
    /// Unix filesystems, while extensions on unbounded basenames (e.g.
    /// `*.csproj`) come from MSBuild/Windows projects that commonly vary
    /// case (`MyApp.CSPROJ`). So `MyApp.CSPROJ` routes via the extension
    /// fallback, but `packages.Config` does **not** match the exact-name
    /// entry for `packages.config`.
    ///
    /// # Arguments
    ///
    /// * `filename` - Manifest filename (e.g., "Cargo.toml", "package.json")
    ///
    /// # Returns
    ///
    /// * `Some(Arc<dyn Ecosystem>)` - Ecosystem handling this filename
    /// * `None` - No ecosystem handles this filename
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// if let Some(ecosystem) = registry.for_filename("Cargo.toml") {
    ///     println!("Cargo.toml handled by: {}", ecosystem.display_name());
    /// }
    /// ```
    pub fn for_filename(&self, filename: &str) -> Option<Arc<dyn Ecosystem>> {
        if let Some(id) = self.filename_map.get(filename) {
            return self.get(*id);
        }

        if let Some(id) = self.match_pattern(filename) {
            return self.get(id);
        }

        // Avoid the rsplit_once/format! allocation below when no ecosystem has registered
        // an extension (extension routing is only used by nuget today) — this runs on
        // every exact-match miss, including every did_open/did_change via for_uri.
        if self.extension_map.is_empty() {
            return None;
        }

        let (_, extension) = filename.rsplit_once('.')?;
        let lowercased = format!(".{}", extension.to_lowercase());
        let id = self.extension_map.get(lowercased.as_str())?;
        self.get(*id)
    }

    /// Matches `filename` against registered [`Ecosystem::manifest_patterns`],
    /// case-sensitively, returning the ecosystem id of the most specific
    /// match (greatest `prefix.len() + suffix.len()`, ties broken by pattern
    /// string ascending) rather than the first `DashMap` hit — so the result
    /// is deterministic regardless of map iteration order.
    fn match_pattern(&self, filename: &str) -> Option<EcosystemId> {
        if self.patterns.is_empty() {
            return None;
        }

        let mut best: Option<(usize, &'static str, EcosystemId)> = None; // (specificity, pattern, id)
        for e in self.patterns.iter() {
            let (prefix, suffix, id) = *e.value();
            if prefix_suffix_matches(filename, prefix, suffix) {
                let score = prefix.len() + suffix.len();
                let pattern = *e.key();
                if best.is_none_or(|(s, p, _)| (score, pattern) > (s, p)) {
                    best = Some((score, pattern, id));
                }
            }
        }

        best.map(|(_, _, id)| id)
    }

    /// Get ecosystem from URI
    ///
    /// Extracts the filename from the URI path and looks up the ecosystem.
    ///
    /// A bare-basename [`Ecosystem::manifest_filenames`] match and a
    /// [`Ecosystem::manifest_directory_patterns`] match are both attempted, and when they
    /// disagree — one registered ecosystem's basename rule and a *different* registered
    /// ecosystem's directory-and-suffix rule both match the same path — the directory
    /// pattern wins (issue #706 review finding, CRITICAL): it carries strictly more
    /// path-specific signal than a bare basename that (by design, see
    /// [`Ecosystem::manifest_filenames`]) matches anywhere in the tree. Concretely: GitHub
    /// Actions' `action.yml`/`action.yaml` basename match and GitLab CI's
    /// `.gitlab/ci/*.yml` directory pattern would otherwise silently race on
    /// `.gitlab/ci/action.yml`, with the basename match winning purely because it was
    /// checked first — routing a real GitLab CI file to the wrong ecosystem with no error.
    /// When only one of the two matches, or both agree on the same ecosystem, that
    /// ecosystem is returned as before.
    ///
    /// # Arguments
    ///
    /// * `uri` - Document URI (file:///path/to/Cargo.toml)
    ///
    /// # Returns
    ///
    /// * `Some(Arc<dyn Ecosystem>)` - Ecosystem handling this file
    /// * `None` - No ecosystem handles this file type or URI parsing failed
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    /// use url::Url;
    ///
    /// let registry = EcosystemRegistry::new();
    /// let uri = Url::from_file_path("/home/user/project/Cargo.toml").unwrap();
    ///
    /// if let Some(ecosystem) = registry.for_uri(&uri) {
    ///     println!("File handled by: {}", ecosystem.display_name());
    /// }
    /// ```
    pub fn for_uri(&self, uri: &url::Url) -> Option<Arc<dyn Ecosystem>> {
        let path = uri.path();
        let filename = path.rsplit('/').next()?;
        let by_filename = self.for_filename(filename);
        let by_directory = self.get_for_directory_pattern(path, filename);
        match (by_filename, by_directory) {
            (Some(by_filename), Some(by_directory))
                if by_filename.ecosystem_id() != by_directory.ecosystem_id() =>
            {
                Some(by_directory)
            }
            (Some(by_filename), _) => Some(by_filename),
            (None, by_directory) => by_directory,
        }
    }

    /// Matches a file whose containing directory path (tail) and file suffix are
    /// declared by an ecosystem's
    /// [`manifest_directory_patterns`](Ecosystem::manifest_directory_patterns) — e.g.
    /// Python's single-segment `requirements/base.txt` layout, or GitHub Actions'
    /// multi-segment `.github/workflows/ci.yml` layout, where the basename alone
    /// carries no ecosystem signal. This needs the full path, not just the basename,
    /// so unlike [`manifest_patterns`](Ecosystem::manifest_patterns) it is consulted
    /// only from [`for_uri`](Self::for_uri), never from
    /// [`for_filename`](Self::for_filename). Mirrors
    /// [`for_lockfile`](Self::for_lockfile)'s linear scan rather than
    /// building a dedicated map — the pattern count per ecosystem is tiny.
    ///
    /// The scan is `DashMap`-iteration-order-dependent when two ecosystems' *directory*
    /// patterns could both match the same path; today's registered directory patterns
    /// (PyPI's `requirements`, GitHub Actions' `.github/workflows`, GitLab CI's
    /// `.gitlab/ci`) are disjoint from each other, so this is deterministic in practice,
    /// but a future ecosystem introducing an overlapping *directory* pattern would need
    /// its own disambiguation, not silent first-match-wins.
    ///
    /// A directory pattern from one ecosystem racing a *basename*
    /// [`manifest_filenames`](Ecosystem::manifest_filenames) entry from a different
    /// ecosystem (e.g. GitLab CI's `.gitlab/ci/*.yml` directory
    /// pattern vs. GitHub Actions' `action.yml` basename, both matching
    /// `.gitlab/ci/action.yml`) is a separate, resolved case — this function alone cannot
    /// see the basename side of that conflict; [`for_uri`](Self::for_uri) resolves
    /// it deterministically by preferring the more path-specific directory-pattern match.
    fn get_for_directory_pattern(&self, path: &str, filename: &str) -> Option<Arc<dyn Ecosystem>> {
        for entry in self.ecosystems.iter() {
            let ecosystem = entry.value();
            let matches =
                ecosystem
                    .manifest_directory_patterns()
                    .iter()
                    .any(|(dir_pattern, suffix)| {
                        directory_pattern_matches(path, filename, dir_pattern, suffix)
                    });
            if matches {
                return Some(Arc::clone(ecosystem));
            }
        }
        None
    }

    /// Get all registered ecosystem IDs
    ///
    /// Returns a vector of all ecosystem IDs currently registered.
    /// This is useful for debugging and listing available ecosystems.
    ///
    /// # Returns
    ///
    /// Vector of ecosystem IDs
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(cargo_ecosystem);
    /// // registry.register(npm_ecosystem);
    ///
    /// for id in registry.ecosystem_ids() {
    ///     println!("Registered ecosystem: {}", id);
    /// }
    /// ```
    pub fn ecosystem_ids(&self) -> Vec<EcosystemId> {
        self.ecosystems.iter().map(|e| *e.key()).collect()
    }

    /// Get ecosystem for a lock file name
    ///
    /// An entry in [`Ecosystem::lockfile_filenames`] is either an exact name
    /// (`"Cargo.lock"`) or a single-`*`-wildcard pattern
    /// (`"packages.*.lock.json"`, NuGet's per-project lock files) — the same
    /// prefix/suffix scheme [`Ecosystem::manifest_patterns`] uses, applied
    /// here via a linear scan (mirroring `get_for_directory_pattern`'s own linear scan)
    /// rather than a dedicated map, since the pattern count per ecosystem is tiny.
    ///
    /// # Arguments
    ///
    /// * `filename` - Lock file name (e.g., "Cargo.lock", "package-lock.json")
    ///
    /// # Returns
    ///
    /// * `Some(Arc<dyn Ecosystem>)` - Ecosystem using this lock file
    /// * `None` - No ecosystem uses this lock file
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(cargo_ecosystem);
    ///
    /// if let Some(ecosystem) = registry.for_lockfile("Cargo.lock") {
    ///     println!("Cargo.lock handled by: {}", ecosystem.display_name());
    /// }
    /// ```
    pub fn for_lockfile(&self, filename: &str) -> Option<Arc<dyn Ecosystem>> {
        for entry in self.ecosystems.iter() {
            let ecosystem = entry.value();
            let matches = ecosystem
                .lockfile_filenames()
                .iter()
                .any(|pattern| lockfile_pattern_matches(pattern, filename));
            if matches {
                return Some(Arc::clone(ecosystem));
            }
        }
        None
    }

    /// Get all lock file patterns for file watching
    ///
    /// Returns glob patterns (e.g., "**/Cargo.lock") for all registered ecosystems.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(cargo_ecosystem);
    /// // registry.register(npm_ecosystem);
    ///
    /// let patterns = registry.all_lockfile_patterns();
    /// for pattern in patterns {
    ///     println!("Watching pattern: {}", pattern);
    /// }
    /// ```
    pub fn all_lockfile_patterns(&self) -> Vec<String> {
        let mut patterns = Vec::new();
        for entry in self.ecosystems.iter() {
            let ecosystem = entry.value();
            for filename in ecosystem.lockfile_filenames() {
                patterns.push(format!("**/{}", filename));
            }
        }
        patterns
    }

    /// Get *every* ecosystem matching a [`Ecosystem::watched_config_filenames`] entry —
    /// mirrors [`Self::for_lockfile`]'s exact/single-`*`-wildcard matching, but scanning the
    /// *config* list instead of the lockfile one, and returning all matches rather than the
    /// first: more than one ecosystem can watch the same config filename (e.g. both npm and
    /// Deno resolve `.npmrc`), and a single-winner lookup would leave the other silently
    /// unreparsed on save (#1232).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(npm_ecosystem);
    ///
    /// for ecosystem in registry.for_watched_config(".npmrc") {
    ///     println!(".npmrc handled by: {}", ecosystem.display_name());
    /// }
    /// ```
    pub fn for_watched_config(&self, filename: &str) -> Vec<Arc<dyn Ecosystem>> {
        let mut matched = Vec::new();
        for entry in self.ecosystems.iter() {
            let ecosystem = entry.value();
            let matches = ecosystem
                .watched_config_filenames()
                .iter()
                .any(|pattern| lockfile_pattern_matches(pattern, filename));
            if matches {
                matched.push(Arc::clone(ecosystem));
            }
        }
        matched
    }

    /// Get all [`Ecosystem::watched_config_filenames`] glob patterns for file watching —
    /// mirrors [`Self::all_lockfile_patterns`], scanning the *config* list instead.
    ///
    /// Deduplicated (issue #1232 M1): more than one ecosystem can watch the same config
    /// filename (e.g. both npm and Deno resolve `.npmrc`), and without a dedup here the same
    /// `**/.npmrc` pattern would be registered as two separate
    /// `tower_lsp_server::ls_types::FileSystemWatcher`s with the LSP client, doubling every
    /// `didChangeWatchedFiles` event (and the reparse work it triggers) for a single save.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use deps_core::EcosystemRegistry;
    ///
    /// let registry = EcosystemRegistry::new();
    /// // registry.register(npm_ecosystem);
    ///
    /// let patterns = registry.all_watched_config_patterns();
    /// for pattern in patterns {
    ///     println!("Watching pattern: {}", pattern);
    /// }
    /// ```
    pub fn all_watched_config_patterns(&self) -> Vec<String> {
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut patterns: Vec<String> = Vec::new();
        for entry in self.ecosystems.iter() {
            let ecosystem = entry.value();
            for filename in ecosystem.watched_config_filenames() {
                let pattern = format!("**/{filename}");
                if seen.insert(pattern.clone()) {
                    patterns.push(pattern);
                }
            }
        }
        patterns
    }
}

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

/// Matches a lock file `filename` against one [`Ecosystem::lockfile_filenames`] entry: an
/// exact name, or — for a NuGet-style `packages.*.lock.json` entry — a single-`*`
/// prefix/suffix pattern, the same scheme [`EcosystemRegistry::register`] uses to split
/// `manifest_patterns` (S2, #451 follow-up).
fn lockfile_pattern_matches(pattern: &str, filename: &str) -> bool {
    match pattern.split_once('*') {
        Some((prefix, suffix)) => prefix_suffix_matches(filename, prefix, suffix),
        None => pattern == filename,
    }
}

/// Core single-`*`-wildcard glob check shared by every basename-pattern matcher in this
/// module: `filename` matches when it is at least as long as `prefix` and `suffix`
/// combined, starts with `prefix`, and ends with `suffix`.
fn prefix_suffix_matches(filename: &str, prefix: &str, suffix: &str) -> bool {
    filename.len() >= prefix.len() + suffix.len()
        && filename.starts_with(prefix)
        && filename.ends_with(suffix)
}

/// Whether `filename`'s containing directory path, relative to any ancestor, ends
/// exactly at `dir_pattern` on a `/`-segment boundary, and `filename` itself ends
/// with `suffix`.
///
/// `dir_pattern` may be a single segment (PyPI's `"requirements"`, matching any
/// `.../requirements/base.txt`) or multiple segments joined by `/` (GitHub Actions'
/// `".github/workflows"`, matching any `.../.github/workflows/ci.yml`) — the
/// single-segment case is just the multi-segment rule applied to a one-element path,
/// so both share this one matcher rather than PyPI keeping a separate
/// immediate-parent-only check.
///
/// `path` is the full URI path (e.g. `/home/user/project/.github/workflows/ci.yml`);
/// `filename` is its basename, passed separately so the caller (which already split
/// it off) does not force a second basename computation here.
fn directory_pattern_matches(path: &str, filename: &str, dir_pattern: &str, suffix: &str) -> bool {
    if !filename.ends_with(suffix) {
        return false;
    }
    let Some(dir_path) = path.strip_suffix(filename) else {
        return false;
    };
    let dir_path = dir_path.trim_end_matches('/');
    #[expect(
        clippy::indexing_slicing,
        reason = "n comes from checked_sub and is matched separately from the Some(0) arm, so \
                  1 <= n <= dir_path.len(), making n - 1 a valid index into dir_path"
    )]
    match dir_path.len().checked_sub(dir_pattern.len()) {
        Some(0) => dir_path == dir_pattern,
        Some(n) => dir_path.ends_with(dir_pattern) && dir_path.as_bytes()[n - 1] == b'/',
        None => false,
    }
}

/// Whether `filename` matches a raw [`Ecosystem::manifest_patterns`] entry (e.g.
/// `"requirements*.txt"`).
///
/// Applies the same single-`*`-wildcard semantics
/// [`EcosystemRegistry::register`]/[`EcosystemRegistry::for_filename`] use
/// internally — but as a stateless, registry-free check.
///
/// Exposed so an ecosystem can ask "would my own `manifest_patterns` have matched this
/// basename?" independently of an `EcosystemRegistry` instance — e.g. to gate a
/// [`Ecosystem::manifest_directory_patterns`]-only match more strictly than a primary
/// basename match (#452 S6): a file routed to an ecosystem purely by directory-name
/// convention carries far weaker "this really is a manifest" evidence than one that
/// also matches a basename pattern.
///
/// Returns `false` for a malformed `pattern` (no `*`, or more than one) rather than
/// panicking — callers pass a `&'static str` they authored themselves, so this is a
/// defensive fallback, not an expected runtime path.
///
/// # Examples
///
/// ```
/// use deps_core::ecosystem_registry::manifest_pattern_matches;
///
/// assert!(manifest_pattern_matches("requirements-dev.txt", "requirements*.txt"));
/// assert!(!manifest_pattern_matches("base.txt", "requirements*.txt"));
/// ```
#[must_use]
pub fn manifest_pattern_matches(filename: &str, pattern: &str) -> bool {
    match pattern.split_once('*') {
        Some((prefix, suffix)) if !suffix.contains('*') => {
            prefix_suffix_matches(filename, prefix, suffix)
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::any::Any;
    #[cfg(feature = "lsp-responses")]
    use tower_lsp_server::ls_types::Position;

    #[cfg(feature = "lsp-responses")]
    use crate::completion::Completions;
    use crate::test_util::StubFormatter;
    use crate::{ParseResult, Registry, lsp_helpers::EcosystemFormatter};

    struct MockEcosystem {
        id: &'static str,
        ecosystem: EcosystemId,
        display_name: &'static str,
        filenames: &'static [&'static str],
        lockfiles: &'static [&'static str],
        watched_configs: &'static [&'static str],
    }

    impl crate::ecosystem::private::Sealed for MockEcosystem {}

    impl Ecosystem for MockEcosystem {
        // Routing tests below assert on `self.id`, an arbitrary test label (e.g. "test",
        // "exact") that is not always a real `EcosystemId` variant, so `id()` stays an
        // explicit override rather than deriving from `ecosystem_id()`.
        fn id(&self) -> &'static str {
            self.id
        }

        fn ecosystem_id(&self) -> crate::EcosystemId {
            self.ecosystem
        }

        fn display_name(&self) -> &'static str {
            self.display_name
        }

        fn manifest_filenames(&self) -> &[&'static str] {
            self.filenames
        }

        fn lockfile_filenames(&self) -> &[&'static str] {
            self.lockfiles
        }

        fn watched_config_filenames(&self) -> &[&'static str] {
            self.watched_configs
        }

        fn parse_manifest<'a>(
            &'a self,
            _content: &'a str,
            _uri: &'a url::Url,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Box<dyn ParseResult>>> {
            Box::pin(async move { unimplemented!() })
        }

        fn registry(&self) -> Arc<dyn Registry> {
            unimplemented!()
        }

        fn formatter(&self) -> &dyn EcosystemFormatter {
            &StubFormatter::DEFAULT
        }

        #[cfg(feature = "lsp-responses")]
        fn generate_completions<'a>(
            &'a self,
            _parse_result: &'a dyn ParseResult,
            _position: Position,
            _content: &'a str,
            _freshness: crate::FreshnessSettings,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            Box::pin(async move { Completions::default() })
        }

        #[cfg(feature = "lsp-responses")]
        fn complete_version<'a>(
            &'a self,
            _request: crate::completion::CompletionRequest<'a>,
            _package_name: crate::PackageName,
            _prefix: String,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            unimplemented!()
        }

        fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
            unimplemented!()
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    // Unbounded-basename extension routing, mirrors NuGet's *.csproj
    struct MockExtEcosystem {
        id: &'static str,
        ecosystem: EcosystemId,
        filenames: &'static [&'static str],
        extensions: &'static [&'static str],
    }

    impl crate::ecosystem::private::Sealed for MockExtEcosystem {}

    impl Ecosystem for MockExtEcosystem {
        fn id(&self) -> &'static str {
            self.id
        }

        fn ecosystem_id(&self) -> crate::EcosystemId {
            self.ecosystem
        }

        fn display_name(&self) -> &'static str {
            self.id
        }

        fn manifest_filenames(&self) -> &[&'static str] {
            self.filenames
        }

        fn manifest_extensions(&self) -> &[&'static str] {
            self.extensions
        }

        fn parse_manifest<'a>(
            &'a self,
            _content: &'a str,
            _uri: &'a url::Url,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Box<dyn ParseResult>>> {
            Box::pin(async move { unimplemented!() })
        }

        fn registry(&self) -> Arc<dyn Registry> {
            unimplemented!()
        }

        fn formatter(&self) -> &dyn EcosystemFormatter {
            &StubFormatter::DEFAULT
        }

        #[cfg(feature = "lsp-responses")]
        fn generate_completions<'a>(
            &'a self,
            _parse_result: &'a dyn ParseResult,
            _position: Position,
            _content: &'a str,
            _freshness: crate::FreshnessSettings,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            Box::pin(async move { Completions::default() })
        }

        #[cfg(feature = "lsp-responses")]
        fn complete_version<'a>(
            &'a self,
            _request: crate::completion::CompletionRequest<'a>,
            _package_name: crate::PackageName,
            _prefix: String,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            unimplemented!()
        }

        fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
            unimplemented!()
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    // Mock ecosystem with basename patterns (mirrors PyPI's `requirements*.txt`) and,
    // since issue #706's review, exact `manifest_filenames` too (mirrors GitHub Actions'
    // `action.yml`/`action.yaml` alongside another ecosystem's directory pattern).
    struct MockPatternEcosystem {
        id: &'static str,
        ecosystem: EcosystemId,
        filenames: &'static [&'static str],
        patterns: &'static [&'static str],
        dir_patterns: &'static [(&'static str, &'static str)],
    }

    impl crate::ecosystem::private::Sealed for MockPatternEcosystem {}

    impl Ecosystem for MockPatternEcosystem {
        fn id(&self) -> &'static str {
            self.id
        }

        fn ecosystem_id(&self) -> crate::EcosystemId {
            self.ecosystem
        }

        fn display_name(&self) -> &'static str {
            self.id
        }

        fn manifest_filenames(&self) -> &[&'static str] {
            self.filenames
        }

        fn manifest_patterns(&self) -> &[&'static str] {
            self.patterns
        }

        fn manifest_directory_patterns(&self) -> &[(&'static str, &'static str)] {
            self.dir_patterns
        }

        fn parse_manifest<'a>(
            &'a self,
            _content: &'a str,
            _uri: &'a url::Url,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Box<dyn ParseResult>>> {
            Box::pin(async move { unimplemented!() })
        }

        fn registry(&self) -> Arc<dyn Registry> {
            unimplemented!()
        }

        fn formatter(&self) -> &dyn EcosystemFormatter {
            &StubFormatter::DEFAULT
        }

        #[cfg(feature = "lsp-responses")]
        fn generate_completions<'a>(
            &'a self,
            _parse_result: &'a dyn ParseResult,
            _position: Position,
            _content: &'a str,
            _freshness: crate::FreshnessSettings,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            Box::pin(async move { Completions::default() })
        }

        #[cfg(feature = "lsp-responses")]
        fn complete_version<'a>(
            &'a self,
            _request: crate::completion::CompletionRequest<'a>,
            _package_name: crate::PackageName,
            _prefix: String,
        ) -> crate::ecosystem::BoxFuture<'a, Completions> {
            unimplemented!()
        }

        fn completion_insert_text(&self, _metadata: &dyn crate::Metadata) -> Option<String> {
            unimplemented!()
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    fn pypi_pattern_registry() -> EcosystemRegistry {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockPatternEcosystem {
            id: "pypi",
            ecosystem: EcosystemId::Pypi,
            filenames: &[],
            patterns: &[
                "requirements*.txt",
                "*-requirements.txt",
                "*.requirements.txt",
                "constraints*.txt",
            ],
            dir_patterns: &[("requirements", ".txt")],
        }));
        registry
    }

    /// D1 regression fixture: a multi-segment `manifest_directory_patterns` entry
    /// (`.github/workflows`), the shape a single-segment directory pattern like
    /// PyPI's `requirements` could never express.
    fn gha_pattern_registry() -> EcosystemRegistry {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockPatternEcosystem {
            id: "github-actions",
            ecosystem: EcosystemId::GithubActions,
            filenames: &[],
            patterns: &[],
            dir_patterns: &[
                (".github/workflows", ".yml"),
                (".github/workflows", ".yaml"),
            ],
        }));
        registry
    }

    #[test]
    fn test_for_uri_multi_segment_directory_pattern_matches_yml_and_yaml() {
        let registry = gha_pattern_registry();
        for path in [
            "/repo/.github/workflows/ci.yml",
            "/repo/.github/workflows/release.yaml",
        ] {
            let uri = crate::test_util::test_uri(path);
            assert_eq!(
                registry.for_uri(&uri).map(|e| e.id()),
                Some("github-actions"),
                "{path} should match the .github/workflows/*.y[a]ml directory pattern"
            );
        }
    }

    #[test]
    fn test_for_uri_multi_segment_directory_pattern_matches_nested_repo() {
        let registry = gha_pattern_registry();
        let uri = crate::test_util::test_uri("/home/user/a/b/.github/workflows/x.yml");
        assert_eq!(
            registry.for_uri(&uri).map(|e| e.id()),
            Some("github-actions"),
            "a repo nested under arbitrary ancestor directories should still match"
        );
    }

    #[test]
    fn test_for_uri_multi_segment_directory_pattern_rejects_partial_paths() {
        let registry = gha_pattern_registry();
        for path in [
            // Missing the `.github` segment entirely.
            "/repo/workflows/x.yml",
            // Missing the `workflows` segment.
            "/repo/.github/x.yml",
            // A directory that merely ends with the pattern as a substring, not on a
            // segment boundary — mirrors PyPI's `myrequirements` regression guard.
            "/repo/my.github/workflows/x.yml",
        ] {
            let uri = crate::test_util::test_uri(path);
            assert!(
                registry.for_uri(&uri).is_none(),
                "{path} should not match the .github/workflows/*.y[a]ml directory pattern"
            );
        }
    }

    /// CRITICAL regression fixture (issue #706 review): a bare-basename `manifest_filenames`
    /// entry from one ecosystem (`action.yml`/`action.yaml`, mirrors GitHub Actions'
    /// composite-action manifest support) and a directory-and-suffix `manifest_directory_patterns`
    /// entry from a *different* ecosystem (`.gitlab/ci/*.yml`, mirrors GitLab CI's
    /// split-pipeline layout) that can both match the same real path
    /// (`.gitlab/ci/action.yml`).
    fn basename_vs_directory_conflict_registry() -> EcosystemRegistry {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockPatternEcosystem {
            id: "github-actions",
            ecosystem: EcosystemId::GithubActions,
            filenames: &["action.yml", "action.yaml"],
            patterns: &[],
            dir_patterns: &[
                (".github/workflows", ".yml"),
                (".github/workflows", ".yaml"),
            ],
        }));
        registry.register(Arc::new(MockPatternEcosystem {
            id: "gitlab-ci",
            ecosystem: EcosystemId::GitlabCi,
            filenames: &[],
            patterns: &[],
            dir_patterns: &[(".gitlab/ci", ".yml"), (".gitlab/ci", ".yaml")],
        }));
        registry
    }

    #[test]
    fn test_for_uri_directory_pattern_wins_over_different_ecosystems_basename_match() {
        let registry = basename_vs_directory_conflict_registry();

        // The conflict: `action.yml` matches github-actions' basename rule AND sits in a
        // directory matching gitlab-ci's directory pattern. Before the fix,
        // `for_filename` was consulted first and always won, silently routing this
        // real GitLab CI file to the wrong ecosystem.
        let uri = crate::test_util::test_uri("/repo/.gitlab/ci/action.yml");
        assert_eq!(
            registry.for_uri(&uri).map(|e| e.id()),
            Some("gitlab-ci"),
            "a directory-pattern match from a different ecosystem must win over a bare \
             basename match"
        );

        // Non-conflicting cases must be unaffected by the precedence change.
        let root_action = crate::test_util::test_uri("/repo/action.yml");
        assert_eq!(
            registry.for_uri(&root_action).map(|e| e.id()),
            Some("github-actions"),
            "a root-level action.yml with no competing directory-pattern match must still \
             route by basename"
        );

        let nested_action =
            crate::test_util::test_uri("/repo/.github/actions/my-action/action.yml");
        assert_eq!(
            registry.for_uri(&nested_action).map(|e| e.id()),
            Some("github-actions"),
            "action.yml nested under .github/actions/<name>/ (no directory pattern \
             registered for that path) must still route by basename"
        );

        let workflow = crate::test_util::test_uri("/repo/.github/workflows/ci.yml");
        assert_eq!(
            registry.for_uri(&workflow).map(|e| e.id()),
            Some("github-actions"),
            "an ordinary workflow file (directory-pattern-only match, no basename match) \
             must be unaffected"
        );
    }

    #[test]
    fn test_for_filename_pattern_matches_requirements_variants() {
        let registry = pypi_pattern_registry();
        for name in [
            "requirements.txt",
            "requirements-dev.txt",
            "requirements.dev.txt",
            "requirements_test.txt",
            "dev-requirements.txt",
            "test.requirements.txt",
            "constraints.txt",
            "constraints-prod.txt",
        ] {
            assert_eq!(
                registry.for_filename(name).map(|e| e.id()),
                Some("pypi"),
                "{name} should match a PyPI pattern"
            );
        }
    }

    #[test]
    fn test_for_filename_pattern_does_not_match_unrelated_files() {
        let registry = pypi_pattern_registry();
        for name in [
            "notes.txt",
            "LICENSE.txt",
            "myrequirements.txt",
            "requirements.txt.bak",
            "Requirements.txt",
            "requirements",
        ] {
            assert!(
                registry.for_filename(name).is_none(),
                "{name} should not match any PyPI pattern"
            );
        }
    }

    #[test]
    fn test_for_filename_exact_name_wins_over_pattern() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockEcosystem {
            id: "exact",
            ecosystem: EcosystemId::Cargo,
            display_name: "Exact",
            filenames: &["requirements.txt"],
            lockfiles: &[],
            watched_configs: &[],
        }));
        registry.register(Arc::new(MockPatternEcosystem {
            id: "pattern",
            ecosystem: EcosystemId::Pypi,
            filenames: &[],
            patterns: &["requirements*.txt"],
            dir_patterns: &[],
        }));

        assert_eq!(
            registry.for_filename("requirements.txt").unwrap().id(),
            "exact"
        );
    }

    #[test]
    fn test_for_filename_pattern_wins_over_extension() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockExtEcosystem {
            id: "ext",
            ecosystem: EcosystemId::NuGet,
            filenames: &[],
            extensions: &[".txt"],
        }));
        registry.register(Arc::new(MockPatternEcosystem {
            id: "pattern",
            ecosystem: EcosystemId::Pypi,
            filenames: &[],
            patterns: &["requirements*.txt"],
            dir_patterns: &[],
        }));

        assert_eq!(
            registry.for_filename("requirements.txt").unwrap().id(),
            "pattern"
        );
    }

    #[test]
    fn test_for_filename_pattern_most_specific_wins_deterministically() {
        let registry = pypi_pattern_registry();
        // Matches both `requirements*.txt` (score 16) and `*.requirements.txt`
        // (score 17) — the longer, more specific pattern must win.
        assert_eq!(
            registry
                .for_filename("requirements.requirements.txt")
                .unwrap()
                .id(),
            "pypi"
        );
    }

    #[test]
    fn test_new_registry_is_empty() {
        let registry = EcosystemRegistry::new();
        assert_eq!(registry.ecosystem_ids().len(), 0);
    }

    #[test]
    fn test_register_ecosystem() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "test",
            ecosystem: EcosystemId::Cargo,
            display_name: "Test Ecosystem",
            filenames: &["test.toml"],
            lockfiles: &[],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        assert_eq!(registry.ecosystem_ids().len(), 1);
        assert!(registry.get(EcosystemId::Cargo).is_some());
    }

    #[test]
    fn test_get_by_id() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "test",
            ecosystem: EcosystemId::Cargo,
            display_name: "Test Ecosystem",
            filenames: &["test.toml"],
            lockfiles: &[],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let retrieved = registry.get(EcosystemId::Cargo).unwrap();
        assert_eq!(retrieved.id(), "test");
        assert_eq!(retrieved.display_name(), "Test Ecosystem");
    }

    #[test]
    fn test_get_by_filename() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "test",
            ecosystem: EcosystemId::Cargo,
            display_name: "Test Ecosystem",
            filenames: &["test.toml", "test.json"],
            lockfiles: &[],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let retrieved1 = registry.for_filename("test.toml").unwrap();
        assert_eq!(retrieved1.id(), "test");

        let retrieved2 = registry.for_filename("test.json").unwrap();
        assert_eq!(retrieved2.id(), "test");

        assert!(registry.for_filename("unknown.toml").is_none());
    }

    #[test]
    fn test_get_by_uri() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "test",
            ecosystem: EcosystemId::Cargo,
            display_name: "Test Ecosystem",
            filenames: &["test.toml"],
            lockfiles: &[],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let uri = crate::test_util::test_uri("/home/user/project/test.toml");
        let retrieved = registry.for_uri(&uri).unwrap();
        assert_eq!(retrieved.id(), "test");

        let unknown_uri = crate::test_util::test_uri("/home/user/project/unknown.toml");
        assert!(registry.for_uri(&unknown_uri).is_none());
    }

    #[test]
    fn test_for_uri_directory_pattern_matches_split_requirements_layout() {
        let registry = pypi_pattern_registry();
        for path in [
            "/home/user/project/requirements/base.txt",
            "/home/user/project/requirements/dev.txt",
            "/home/user/project/sub/requirements/prod.txt",
        ] {
            let uri = crate::test_util::test_uri(path);
            assert_eq!(
                registry.for_uri(&uri).map(|e| e.id()),
                Some("pypi"),
                "{path} should match the requirements/*.txt directory pattern"
            );
        }
    }

    #[test]
    fn test_for_uri_directory_pattern_requires_matching_directory_and_suffix() {
        let registry = pypi_pattern_registry();
        for path in [
            // Wrong directory name.
            "/home/user/project/reqs/base.txt",
            // Right directory, wrong suffix.
            "/home/user/project/requirements/base.cfg",
            // Bare `requirements.txt` at the top level is not a directory match
            // (it's already handled by the basename pattern stage).
            "/home/user/project/requirements.txt",
        ] {
            let uri = crate::test_util::test_uri(path);
            if path.ends_with("requirements.txt") {
                assert_eq!(registry.for_uri(&uri).map(|e| e.id()), Some("pypi"));
            } else {
                assert!(
                    registry.for_uri(&uri).is_none(),
                    "{path} should not match the requirements/*.txt directory pattern"
                );
            }
        }
    }

    #[test]
    fn test_for_uri_directory_pattern_requires_exact_directory_segment() {
        // Only a path segment that is *exactly* "requirements" counts — a
        // directory that merely contains that string as a substring must not
        // match (#452 S6 follow-up, confirmed by impl-critic).
        for path in [
            // The parent "directory" here is itself a file named
            // `requirements.txt`, not a directory literally named `requirements`.
            "/home/user/project/requirements.txt/base.txt",
            // "myrequirements" contains "requirements" as a substring but is not
            // an exact match.
            "/home/user/project/myrequirements/base.txt",
        ] {
            let uri = crate::test_util::test_uri(path);
            assert!(
                pypi_pattern_registry().for_uri(&uri).is_none(),
                "{path} should not match the requirements/*.txt directory pattern"
            );
        }
    }

    #[test]
    fn test_for_uri_basename_pattern_wins_over_directory_pattern() {
        // `requirements/dev-requirements.txt` matches the basename pattern stage
        // (`*-requirements.txt`) — the directory-pattern fallback must never be
        // reached, let alone override it.
        let registry = pypi_pattern_registry();
        let uri =
            crate::test_util::test_uri("/home/user/project/requirements/dev-requirements.txt");
        assert_eq!(registry.for_uri(&uri).map(|e| e.id()), Some("pypi"));
    }

    #[test]
    fn test_multiple_ecosystems() {
        let registry = EcosystemRegistry::new();

        let eco1 = Arc::new(MockEcosystem {
            id: "cargo",
            ecosystem: EcosystemId::Cargo,
            display_name: "Cargo",
            filenames: &["Cargo.toml"],
            lockfiles: &["Cargo.lock"],
            watched_configs: &[],
        });

        let eco2 = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &[],
        });

        registry.register(eco1);
        registry.register(eco2);

        assert_eq!(registry.ecosystem_ids().len(), 2);

        assert_eq!(registry.for_filename("Cargo.toml").unwrap().id(), "cargo");
        assert_eq!(registry.for_filename("package.json").unwrap().id(), "npm");
    }

    #[test]
    fn test_for_lockfile() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "cargo",
            ecosystem: EcosystemId::Cargo,
            display_name: "Cargo",
            filenames: &["Cargo.toml"],
            lockfiles: &["Cargo.lock"],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let retrieved = registry.for_lockfile("Cargo.lock").unwrap();
        assert_eq!(retrieved.id(), "cargo");
        assert_eq!(retrieved.display_name(), "Cargo");

        assert!(registry.for_lockfile("unknown.lock").is_none());
    }

    #[test]
    fn test_for_lockfile_multiple_lockfiles() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "pypi",
            ecosystem: EcosystemId::Pypi,
            display_name: "PyPI",
            filenames: &["pyproject.toml"],
            lockfiles: &["poetry.lock", "uv.lock"],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let retrieved1 = registry.for_lockfile("poetry.lock").unwrap();
        assert_eq!(retrieved1.id(), "pypi");

        let retrieved2 = registry.for_lockfile("uv.lock").unwrap();
        assert_eq!(retrieved2.id(), "pypi");
    }

    /// S2 regression (#451 follow-up): a single-`*`-wildcard `lockfile_filenames()` entry
    /// (NuGet's `"packages.*.lock.json"`, registered only so `all_lockfile_patterns()` sets
    /// up a file watcher) must actually route a real multi-project lock filename through
    /// `for_lockfile` — this is what `did_change_watched_files` calls to find the owning
    /// ecosystem for a changed lock file.
    #[test]
    fn test_for_lockfile_matches_wildcard_pattern() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "nuget",
            ecosystem: EcosystemId::NuGet,
            display_name: "NuGet",
            filenames: &["Directory.Packages.props"],
            lockfiles: &["packages.lock.json", "packages.*.lock.json"],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        assert_eq!(
            registry
                .for_lockfile("packages.App1.lock.json")
                .map(|e| e.id()),
            Some("nuget")
        );
        assert_eq!(
            registry.for_lockfile("packages.lock.json").map(|e| e.id()),
            Some("nuget")
        );
        assert!(registry.for_lockfile("other.lock.json").is_none());
        // Too short to contain both the prefix and the suffix.
        assert!(registry.for_lockfile("packages.lock").is_none());
    }

    #[test]
    fn test_all_lockfile_patterns_empty() {
        let registry = EcosystemRegistry::new();
        assert!(registry.all_lockfile_patterns().is_empty());
    }

    #[test]
    fn test_all_lockfile_patterns_single_ecosystem() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "cargo",
            ecosystem: EcosystemId::Cargo,
            display_name: "Cargo",
            filenames: &["Cargo.toml"],
            lockfiles: &["Cargo.lock"],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let patterns = registry.all_lockfile_patterns();
        assert_eq!(patterns.len(), 1);
        assert_eq!(patterns[0], "**/Cargo.lock");
    }

    #[test]
    fn test_all_lockfile_patterns_multiple_ecosystems() {
        let registry = EcosystemRegistry::new();

        let eco1 = Arc::new(MockEcosystem {
            id: "cargo",
            ecosystem: EcosystemId::Cargo,
            display_name: "Cargo",
            filenames: &["Cargo.toml"],
            lockfiles: &["Cargo.lock"],
            watched_configs: &[],
        });

        let eco2 = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &[],
        });

        let eco3 = Arc::new(MockEcosystem {
            id: "pypi",
            ecosystem: EcosystemId::Pypi,
            display_name: "PyPI",
            filenames: &["pyproject.toml"],
            lockfiles: &["poetry.lock", "uv.lock"],
            watched_configs: &[],
        });

        registry.register(eco1);
        registry.register(eco2);
        registry.register(eco3);

        let patterns = registry.all_lockfile_patterns();
        assert_eq!(patterns.len(), 4);
        assert!(patterns.contains(&"**/Cargo.lock".to_string()));
        assert!(patterns.contains(&"**/package-lock.json".to_string()));
        assert!(patterns.contains(&"**/poetry.lock".to_string()));
        assert!(patterns.contains(&"**/uv.lock".to_string()));
    }

    #[test]
    fn test_all_lockfile_patterns_no_lockfiles() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "test",
            ecosystem: EcosystemId::Cargo,
            display_name: "Test",
            filenames: &["test.toml"],
            lockfiles: &[],
            watched_configs: &[],
        });

        registry.register(ecosystem);

        let patterns = registry.all_lockfile_patterns();
        assert!(patterns.is_empty());
    }

    #[test]
    fn test_for_watched_config() {
        let registry = EcosystemRegistry::new();
        let npm = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &["pnpm-workspace.yaml", ".npmrc"],
        });

        registry.register(npm);

        let retrieved = registry.for_watched_config("pnpm-workspace.yaml");
        assert_eq!(retrieved.len(), 1);
        assert_eq!(retrieved[0].id(), "npm");
        let retrieved = registry.for_watched_config(".npmrc");
        assert_eq!(retrieved.len(), 1);
        assert_eq!(retrieved[0].id(), "npm");

        // A lockfile is not a watched config, and vice versa.
        assert!(registry.for_watched_config("package-lock.json").is_empty());
        assert!(registry.for_watched_config("unknown.yaml").is_empty());
    }

    #[test]
    fn test_for_watched_config_fans_out_to_all_matching_ecosystems() {
        // Regression test for #1232: more than one ecosystem can watch the same config
        // filename (npm and Deno both resolve `.npmrc`), so a single-winner lookup would
        // silently skip reparsing one of them on save.
        let registry = EcosystemRegistry::new();
        let npm = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &["pnpm-workspace.yaml", ".npmrc"],
        });
        let deno = Arc::new(MockEcosystem {
            id: "deno",
            ecosystem: EcosystemId::Deno,
            display_name: "Deno",
            filenames: &["deno.json", "deno.jsonc"],
            lockfiles: &[],
            watched_configs: &[".npmrc"],
        });

        registry.register(npm);
        registry.register(deno);

        let mut ids: Vec<&str> = registry
            .for_watched_config(".npmrc")
            .iter()
            .map(|e| e.id())
            .collect();
        ids.sort_unstable();
        assert_eq!(ids, ["deno", "npm"]);

        // pnpm-workspace.yaml is still npm-only.
        let retrieved = registry.for_watched_config("pnpm-workspace.yaml");
        assert_eq!(retrieved.len(), 1);
        assert_eq!(retrieved[0].id(), "npm");
    }

    #[test]
    fn test_all_watched_config_patterns() {
        let registry = EcosystemRegistry::new();
        let ecosystem = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &["pnpm-workspace.yaml", ".npmrc"],
        });

        registry.register(ecosystem);

        let patterns = registry.all_watched_config_patterns();
        assert_eq!(patterns.len(), 2);
        assert!(patterns.contains(&"**/pnpm-workspace.yaml".to_string()));
        assert!(patterns.contains(&"**/.npmrc".to_string()));

        // Lockfile patterns are a disjoint set, unaffected by watched-config registration.
        assert_eq!(
            registry.all_lockfile_patterns(),
            vec!["**/package-lock.json"]
        );
    }

    #[test]
    fn test_all_watched_config_patterns_empty() {
        let registry = EcosystemRegistry::new();
        assert!(registry.all_watched_config_patterns().is_empty());
    }

    #[test]
    fn test_all_watched_config_patterns_dedups_shared_filename() {
        // Regression test for #1232 M1: npm and Deno both watch `.npmrc`, and without a
        // dedup the pattern (and the LSP-client file watcher registered from it) would be
        // duplicated, doubling reparse work per save.
        let registry = EcosystemRegistry::new();
        let npm = Arc::new(MockEcosystem {
            id: "npm",
            ecosystem: EcosystemId::Npm,
            display_name: "npm",
            filenames: &["package.json"],
            lockfiles: &["package-lock.json"],
            watched_configs: &["pnpm-workspace.yaml", ".npmrc"],
        });
        let deno = Arc::new(MockEcosystem {
            id: "deno",
            ecosystem: EcosystemId::Deno,
            display_name: "Deno",
            filenames: &["deno.json", "deno.jsonc"],
            lockfiles: &[],
            watched_configs: &[".npmrc"],
        });

        registry.register(npm);
        registry.register(deno);

        let patterns = registry.all_watched_config_patterns();
        assert_eq!(
            patterns.iter().filter(|p| *p == "**/.npmrc").count(),
            1,
            "**/.npmrc must be registered only once: {patterns:?}"
        );
        assert!(patterns.contains(&"**/pnpm-workspace.yaml".to_string()));
    }

    #[test]
    fn test_for_filename_extension_fallback() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockExtEcosystem {
            id: "nuget",
            ecosystem: EcosystemId::NuGet,
            filenames: &["Directory.Packages.props"],
            extensions: &[".csproj", ".fsproj"],
        }));

        assert_eq!(registry.for_filename("MyApp.csproj").unwrap().id(), "nuget");
        assert_eq!(
            registry
                .for_filename("Directory.Packages.props")
                .unwrap()
                .id(),
            "nuget"
        );
        assert!(registry.for_filename("unrelated.txt").is_none());
    }

    #[test]
    fn test_for_filename_extension_fallback_case_insensitive() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockExtEcosystem {
            id: "nuget",
            ecosystem: EcosystemId::NuGet,
            filenames: &["Directory.Packages.props"],
            extensions: &[".csproj"],
        }));

        assert_eq!(registry.for_filename("MyApp.CSPROJ").unwrap().id(), "nuget");
    }

    #[test]
    fn test_for_filename_exact_match_case_sensitive_not_shadowed_by_extension() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockExtEcosystem {
            id: "nuget",
            ecosystem: EcosystemId::NuGet,
            filenames: &["packages.config"],
            extensions: &[],
        }));

        // Exact filenames stay case-sensitive: differently-cased basename does not match.
        assert!(registry.for_filename("packages.Config").is_none());
    }

    #[test]
    fn test_for_filename_no_extension_returns_none() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockExtEcosystem {
            id: "nuget",
            ecosystem: EcosystemId::NuGet,
            filenames: &[],
            extensions: &[".csproj"],
        }));

        assert!(registry.for_filename("README").is_none());
    }

    /// Registering a second ecosystem under the same [`EcosystemId`] replaces the first
    /// registration outright (`DashMap::insert`'s last-write-wins semantics), rather than
    /// somehow coexisting under distinct slots.
    #[test]
    fn test_register_same_ecosystem_id_replaces_first() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockEcosystem {
            id: "first",
            ecosystem: EcosystemId::Cargo,
            display_name: "First",
            filenames: &["first.toml"],
            lockfiles: &[],
            watched_configs: &[],
        }));
        registry.register(Arc::new(MockEcosystem {
            id: "second",
            ecosystem: EcosystemId::Cargo,
            display_name: "Second",
            filenames: &["second.toml"],
            lockfiles: &[],
            watched_configs: &[],
        }));

        assert_eq!(registry.ecosystem_ids(), vec![EcosystemId::Cargo]);
        assert_eq!(
            registry.get(EcosystemId::Cargo).unwrap().display_name(),
            "Second"
        );
    }

    /// Routing keys on `Ecosystem::ecosystem_id`, not `Ecosystem::id` — even when an
    /// implementor overrides `id()` to something that disagrees with `ecosystem_id()` (as
    /// `ecosystem::tests::StubEcosystem` does). Uses `MockEcosystem` here (`StubEcosystem`
    /// is private to its own module) with `id: "not-cargo"` deliberately mismatched against
    /// `ecosystem: EcosystemId::Cargo`.
    #[test]
    fn test_registry_routes_on_ecosystem_id_not_id() {
        let registry = EcosystemRegistry::new();
        registry.register(Arc::new(MockEcosystem {
            id: "not-cargo",
            ecosystem: EcosystemId::Cargo,
            display_name: "Mismatched",
            filenames: &[],
            lockfiles: &[],
            watched_configs: &[],
        }));

        let found = registry.get(EcosystemId::Cargo).unwrap();
        assert_eq!(found.id(), "not-cargo");
        assert_eq!(found.ecosystem_id(), EcosystemId::Cargo);
    }
}