oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
//! The workspace the planner reasons over: packages, their current versions, and
//! the intra-workspace edges between them.
//!
//! `discover` builds this by asking each package manager; nothing here reads a
//! manifest, so the cascade rules can be replayed against a recorded release
//! history.
//!
//! `String`, `Vec`, and friends come from `alloc` rather than the std prelude,
//! and the graph is a `BTreeMap` because `alloc` has no `HashMap` — see `plan`'s
//! module doc for what enforces that. Ordering is wanted independently: ADR-0012
//! checks the planner against `in/` + `out/` snapshot fixtures.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use semver::{Comparator, Op, Version, VersionReq};

use super::bounds::Bounds;

/// The registry namespace within which a package name is unique.
///
/// This is the identity axis, not the adapter axis. Discovery adapts per package
/// manager — pnpm and npm answer differently about the same directory — but npm,
/// pnpm, yarn, and bun packages all draw their names from one registry, so names
/// collide across those four and never across ecosystems.
///
/// Variant order sets [`PackageId`]'s sort order, which plans are compared by.
/// Reordering changes plan output.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Ecosystem {
    Npm,
    Cargo,
}

impl Ecosystem {
    #[must_use]
    pub const fn manifest_name(self) -> &'static str {
        match self {
            Self::Npm => "package.json",
            Self::Cargo => "Cargo.toml",
        }
    }

    /// Whether a range may be written with a [`RangeProtocol`] prefix. Cargo has
    /// no grammar for either one, and its `workspace = true` inheritance is a
    /// different mechanism that `cargo metadata` resolves to a plain range
    /// before oakum sees it.
    const fn has_range_protocols(self) -> bool {
        match self {
            Self::Npm => true,
            Self::Cargo => false,
        }
    }

    const fn has_target_tables(self) -> bool {
        match self {
            Self::Npm => false,
            Self::Cargo => true,
        }
    }
}

impl fmt::Display for Ecosystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Npm => "npm",
            Self::Cargo => "cargo",
        })
    }
}

/// What identifies a package inside a workspace.
///
/// The ecosystem is part of the identity because a polyglot repository can hold a
/// crate and an npm package under the same name. Keyed by name alone the two
/// would collapse into one node carrying both packages' edges, and a release of
/// either would cascade into the other's dependents.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PackageId {
    pub ecosystem: Ecosystem,
    pub name: String,
}

impl PackageId {
    #[must_use]
    pub fn new(ecosystem: Ecosystem, name: impl Into<String>) -> Self {
        Self {
            ecosystem,
            name: name.into(),
        }
    }
}

impl fmt::Display for PackageId {
    /// Carries the ecosystem, because a bare name is what makes a message
    /// ambiguous in the repositories this has to describe.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.name, self.ecosystem)
    }
}

/// The manifest section an edge was declared in, kept rather than reduced to
/// whether it cascades.
///
/// ADR-0008 decides which kinds are eligible, but the section survives into the
/// plan because `version` rewrites a range in the section it came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DependencyKind {
    Normal,
    Peer,
    Optional,
    Build,
    Development,
}

impl DependencyKind {
    /// The manifest section this kind is declared under, or `None` where the
    /// ecosystem has no such section — `Peer` and `Optional` are npm shapes,
    /// `Build` is a Cargo one.
    ///
    /// Cargo's optional dependencies are `optional = true` entries in
    /// `[dependencies]` rather than a section of their own, so a Cargo optional
    /// dependency is [`DependencyKind::Normal`].
    #[must_use]
    pub const fn section(self, ecosystem: Ecosystem) -> Option<&'static str> {
        match (ecosystem, self) {
            (Ecosystem::Npm | Ecosystem::Cargo, Self::Normal) => Some("dependencies"),
            (Ecosystem::Npm, Self::Peer) => Some("peerDependencies"),
            (Ecosystem::Npm, Self::Optional) => Some("optionalDependencies"),
            (Ecosystem::Npm, Self::Development) => Some("devDependencies"),
            (Ecosystem::Cargo, Self::Build) => Some("build-dependencies"),
            (Ecosystem::Cargo, Self::Development) => Some("dev-dependencies"),
            (Ecosystem::Npm, Self::Build) | (Ecosystem::Cargo, Self::Peer | Self::Optional) => None,
        }
    }

    /// Whether releasing the dependency can change what the dependent ships.
    ///
    /// `Build` is the three-way line in Cargo that no surveyed tool draws: a
    /// build script cannot see `[dependencies]` and needs `[build-dependencies]`
    /// to do its work, so a change there can change the compiled output.
    /// release-please merges all three kinds; knope does not handle
    /// `build-dependencies` at all (ADR-0008).
    ///
    /// False does not mean absent. Development edges stay in the graph and their
    /// ranges are rewritten whenever the dependent is released for some other
    /// reason — dropping them would leave stale ranges in published manifests.
    /// The graph is larger than the cascade set, and this is the only thing that
    /// separates them.
    #[must_use]
    pub const fn is_runtime(self) -> bool {
        match self {
            Self::Normal | Self::Peer | Self::Optional | Self::Build => true,
            Self::Development => false,
        }
    }
}

impl fmt::Display for DependencyKind {
    /// For the messages about a kind whose ecosystem has no section to name.
    /// Callers phrase around these rather than prefixing an article: `optional`
    /// is the one reachable kind that would need "an".
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Normal => "normal",
            Self::Peer => "peer",
            Self::Optional => "optional",
            Self::Build => "build",
            Self::Development => "development",
        })
    }
}

/// How far a `workspace:` protocol range follows the package it points at.
///
/// pnpm's publish-time rewrites are what make this a declaration rather than a
/// convention: for a dependency at `1.5.0`, `workspace:*` publishes as an exact
/// `1.5.0`, `workspace:~` as `~1.5.0`, and `workspace:^` as `^1.5.0`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tracking {
    /// `workspace:*`, and a bare `workspace:`, which pnpm treats as `workspace:*`.
    Exact,
    Tilde,
    Caret,
}

impl fmt::Display for Tracking {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Exact => "*",
            Self::Tilde => "~",
            Self::Caret => "^",
        })
    }
}

/// A prefix that replaces a range's bounds with a reference resolved at publish
/// time. Both are pnpm, yarn, and bun spellings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RangeProtocol {
    Workspace,
    Catalog,
}

impl fmt::Display for RangeProtocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Workspace => "workspace:",
            Self::Catalog => "catalog:",
        })
    }
}

/// The range a dependent declared for an intra-workspace dependency.
///
/// Two things are needed downstream and neither is recoverable from the other:
/// the bounds the published manifest imposes, which ADR-0010 gates the cascade
/// on, and the protocol prefix `version` has to write back.
///
/// Plain bounds are [`Bounds`]: Cargo text via [`Bounds::from_cargo_text`], npm
/// text via [`Bounds::from_npm_text`] (ADR-0026). Never parse npm strings with
/// `VersionReq` — bare `1.5.0` is a caret in Cargo and an exact pin in npm
/// (ADR-0018). Equality is ecosystem-aware for the same reason.
///
/// `workspace:` / `catalog:` arms also carry [`Bounds`]: after oakum peels the
/// protocol, the published range is still npm grammar on npm packages (including
/// `||`). Tracking forms expand at the tag version instead.
///
/// [`DeclaredRange::PathLinked`] is a Cargo path edge with no declared version:
/// there is nothing for ADR-0010's gate to compare, so the planner always
/// cascades (ADR-0026). [`Workspace::new`] refuses ecosystem/range pairings that
/// cannot appear in a real manifest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeclaredRange {
    /// A plain range: Cargo `^1.5.0` / `=1.5.0`, or npm bare / `||` / hyphen.
    /// npm rejects the workspace protocol outright with `EUNSUPPORTEDPROTOCOL`.
    Plain(Bounds),
    /// `workspace:` carrying its own bounds, as in `workspace:^1.5.0`. Publishes
    /// as those bounds alone, but the prefix has to survive a rewrite: without it
    /// the range resolves against the registry instead of the workspace member.
    Workspace(Bounds),
    /// A `workspace:` form whose bounds come from the dependency's version at
    /// publish time.
    WorkspaceTracking(Tracking),
    /// `catalog:` or `catalog:<name>`, carrying the bounds the catalog names.
    ///
    /// Discovery resolves it, since that is where `pnpm-workspace.yaml` can be
    /// read, and an entry it cannot resolve is an error naming the file rather
    /// than a range that passes: bumpy short-circuits its range check to `true`
    /// for every `catalog:` range while shipping the resolver it declines to
    /// call, which silently under-releases every catalog consumer (ADR-0010).
    /// `bounds` is mandatory to force that resolution, and a `*` here has to come
    /// from the catalog saying `*` rather than from a fallback.
    Catalog {
        /// `None` for the default catalog, which is written as a bare `catalog:`.
        name: Option<String>,
        bounds: Bounds,
    },
    /// Cargo path dependency with no `version` key (ADR-0026). Always cascades.
    PathLinked,
}

impl fmt::Display for DeclaredRange {
    /// Manifest protocol spelling. Catalog bounds are not part of the token
    /// (`catalog:` / `catalog:<name>`); print bounds separately when the
    /// ADR-0010 gate range is needed.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Plain(bounds) => write!(f, "{bounds}"),
            Self::Workspace(bounds) => write!(f, "workspace:{bounds}"),
            Self::WorkspaceTracking(tracking) => write!(f, "workspace:{tracking}"),
            Self::Catalog { name: None, .. } => f.write_str("catalog:"),
            Self::Catalog {
                name: Some(name), ..
            } => write!(f, "catalog:{name}"),
            Self::PathLinked => f.write_str("path-linked"),
        }
    }
}

impl DeclaredRange {
    /// The protocol prefix this range is written with, or `None` for a plain one
    /// or a path-linked edge.
    ///
    /// `version` rewrites through the same answer, so the mapping lives here
    /// rather than at its call site. Use [`DeclaredRange::is_path_linked`] before
    /// treating a no-protocol range as a plain `version` line.
    #[must_use]
    pub const fn protocol(&self) -> Option<RangeProtocol> {
        match self {
            Self::Workspace(_) | Self::WorkspaceTracking(_) => Some(RangeProtocol::Workspace),
            Self::Catalog { .. } => Some(RangeProtocol::Catalog),
            Self::Plain(_) | Self::PathLinked => None,
        }
    }

    #[must_use]
    pub const fn is_path_linked(&self) -> bool {
        matches!(self, Self::PathLinked)
    }

    fn expand_tracking(tracking: Tracking, version_at_last_tag: &Version) -> VersionReq {
        VersionReq {
            comparators: Vec::from([Comparator {
                op: match tracking {
                    Tracking::Exact => Op::Exact,
                    Tracking::Tilde => Op::Tilde,
                    Tracking::Caret => Op::Caret,
                },
                major: version_at_last_tag.major,
                minor: Some(version_at_last_tag.minor),
                patch: Some(version_at_last_tag.patch),
                // A prerelease dropped here publishes a pin on a version that was
                // never released.
                pre: version_at_last_tag.pre.clone(),
            }]),
        }
    }

    /// [`DeclaredRange::PathLinked`] never admits; ADR-0026 always cascades.
    ///
    /// `version_at_last_tag` is the version before the bump (ADR-0014): the new
    /// one would make every tracking form admit itself, so nothing cascades.
    /// A tracking form is expanded rather than read as `true`, bumpy's bug:
    /// pnpm publishes `workspace:*` as an exact version, the tightest pin.
    #[must_use]
    pub fn admits(&self, version_at_last_tag: &Version, candidate: &Version) -> bool {
        match self {
            Self::PathLinked => false,
            Self::Plain(bounds) | Self::Workspace(bounds) | Self::Catalog { bounds, .. } => {
                bounds.matches(candidate)
            }
            Self::WorkspaceTracking(tracking) => {
                Self::expand_tracking(*tracking, version_at_last_tag).matches(candidate)
            }
        }
    }

    /// `None` when the line must not change: `workspace:*`/`^`/`~` (pnpm
    /// expands at publish), `catalog:` (version lives in the catalog file), a
    /// blank npm range (any version, kept as written), or a path-only Cargo
    /// edge (no version key).
    ///
    /// Development edges use the same function. Rewriting is universal;
    /// [`DependencyKind::is_runtime`] gates bumping (ADR-0008).
    #[must_use]
    pub fn retargeted_text(&self, new: &Version) -> Option<String> {
        match self {
            Self::Plain(bounds) | Self::Workspace(bounds) if bounds.is_blank() => None,
            Self::Plain(bounds) => bounds.retargeted(new),
            Self::Workspace(bounds) => bounds
                .retargeted(new)
                .map(|range| alloc::format!("workspace:{range}")),
            Self::WorkspaceTracking(_) | Self::Catalog { .. } | Self::PathLinked => None,
        }
    }

    const fn fits_ecosystem(&self, ecosystem: Ecosystem) -> bool {
        matches!(
            (ecosystem, self),
            (
                Ecosystem::Cargo,
                Self::PathLinked | Self::Plain(Bounds::Cargo(_))
            ) | (
                Ecosystem::Npm,
                Self::Plain(Bounds::Npm { .. })
                    | Self::Workspace(Bounds::Npm { .. })
                    | Self::Catalog {
                        bounds: Bounds::Npm { .. },
                        ..
                    }
                    | Self::WorkspaceTracking(_)
            )
        )
    }
}

/// One intra-workspace edge.
///
/// Only intra-workspace edges belong in the graph. A dependency on a registry
/// package cannot be released by oakum, and carrying those edges would make every
/// traversal walk the whole transitive dependency set to reach the handful of
/// nodes that can move.
///
/// A manifest line is identified by the section this edge's kind maps to in the
/// dependent's ecosystem, the key it is written under, and the target table
/// holding it. `version` rewrites that line, and `Workspace::new` refuses a
/// repeat of those three, since one line cannot hold two ranges.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dependency {
    /// A package in the same ecosystem as the dependent, guaranteed for any
    /// `Dependency` reached through a [`Workspace`], which is where the check
    /// lives — [`Package`] can be built without it.
    pub on: PackageId,
    pub kind: DependencyKind,
    /// The manifest key this edge is written under, which equals `on.name` unless
    /// the dependent renamed it — Cargo's `alias = { package = "real" }`, npm's
    /// `"alias": "npm:real@^1.0.0"`. A renamed edge rewritten by name lands on
    /// the wrong entry, or on none.
    pub declared_as: String,
    /// Cargo's target predicate, as `cargo metadata` reports it — `cfg(windows)`
    /// for a `[target.'cfg(windows)'.dependencies]` entry, `None` for an
    /// unconditional one. Always `None` for npm, which has no equivalent.
    ///
    /// One package can be declared under one key in several target tables with a
    /// different range in each — see `docs/research/cargo-metadata-edge-shapes.md`.
    /// Without this they are indistinguishable, and a rewrite edits whichever
    /// table it finds first.
    pub target: Option<String>,
    pub range: DeclaredRange,
}

/// A member-named npm range the member's version does not satisfy: pnpm installs
/// it from the registry, though a stale pin meant as `workspace:` reads the same.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnlinkedDependency {
    pub on: String,
    /// The manifest key, which differs from `on` under an `npm:` alias.
    pub declared_as: String,
    pub kind: DependencyKind,
    pub range: DeclaredRange,
}

/// A Cargo registry, git, or out-of-workspace path dependency, kept outside the
/// graph. `cargo metadata`
/// reports a `workspace = true` entry exactly like a written-out one; only the
/// member manifest tells them apart.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExternalDependency {
    /// The real package name, as `Cargo.lock` lists it.
    pub name: String,
    /// The manifest (and `[workspace.dependencies]`) key; the alias under a rename.
    pub declared_as: String,
    pub kind: DependencyKind,
    /// Cargo's source id (`registry+…`, `git+…?branch=…`) as declared;
    /// `Cargo.lock` appends `#<commit>` to a git one. `None` for a path crate.
    pub source: Option<String>,
    /// `*` for a git dependency declared without a version.
    pub req: VersionReq,
    /// Written `workspace = true`.
    pub inherited: bool,
    pub declaration: Declaration,
}

/// How an external dependency is declared beyond its requirement and source,
/// as `cargo metadata` reports it after `workspace = true` inheritance.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Declaration {
    /// As [`Dependency::target`].
    pub target: Option<String>,
    /// The features asked for, without the defaults.
    pub features: BTreeSet<String>,
    pub default_features: bool,
    pub optional: bool,
    /// A path dependency's repository-relative directory, which `source`
    /// leaves out. `None` for a registry or git one, or a path outside the
    /// repository.
    pub path: Option<String>,
}

impl Default for Declaration {
    fn default() -> Self {
        Self {
            target: None,
            features: BTreeSet::new(),
            default_features: true,
            optional: false,
            path: None,
        }
    }
}

/// A path dependency on a crate outside the workspace, in no member's
/// directory, so a change there reaches the package declaring it (ADR-0039).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathCrate {
    pub name: String,
    /// Repository-relative, no trailing slash.
    pub dir: String,
    pub kind: DependencyKind,
}

/// When a package's dependency versions stop being re-resolvable, which is what
/// decides whether the range gate applies to it (ADR-0009).
///
/// Named for the mechanism rather than the effect, matching the config key.
/// "Delivery artifact" describes the consequence; a package resolving its
/// dependencies at build time is the fact that produces it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResolvesDependenciesAt {
    /// A consumer re-resolves at install time, so a dependency fix reaches it
    /// without a release. This is the case the range gate is correct for.
    Install,
    /// Dependencies are resolved once, at build time, and shipped inside the
    /// artifact. Nothing re-resolves afterward, so the range gate must not apply:
    /// a satisfied range means no bump, no bump means no tag, and the artifact
    /// users download keeps the version it was built against.
    Build(BuildResolution),
}

impl ResolvesDependenciesAt {
    /// Exhaustive, so a third variant is a compile error rather than a silent
    /// "not a delivery artifact" — the ADR-0009 under-release this type prevents.
    #[must_use]
    pub const fn is_build(self) -> bool {
        match self {
            Self::Build(_) => true,
            Self::Install => false,
        }
    }
}

/// Why a package was taken to resolve its dependencies at build time. ADR-0009
/// allows exactly these two routes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildResolution {
    /// The package manager reported a binary target: a `bin` target in
    /// `cargo metadata`, a `bin` field in npm. Derived from resolved targets and
    /// never from a `src/main.rs` on disk, which is what makes `autobins = false`
    /// and explicit `[[bin]]` entries come out right.
    BinaryTarget,
    /// `resolves-dependencies-at = "build"` in config. The one case that needs a
    /// declaration: a library that bundles its dependencies into its published
    /// output, and so ships them baked in without producing a binary.
    Declared,
}

/// A package as the planner sees it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Package {
    id: PackageId,
    version: Version,
    resolves_dependencies_at: ResolvesDependenciesAt,
    /// Whether a registry publish is allowed somewhere (ADR-0004 / ADR-0027).
    /// Derived from Cargo `publish` / npm `private`, never configured. Cargo
    /// allow-lists collapse to `true` in v0; retaining which registry is
    /// `okm-9sa`, and nothing needs it until a publish step exists.
    publishable: bool,
    dependencies: Vec<Dependency>,
    /// Empty for npm packages.
    external_dependencies: Vec<ExternalDependency>,
    /// Empty for Cargo packages.
    unlinked_dependencies: Vec<UnlinkedDependency>,
    /// `[package]` keys written `<key>.workspace = true`. Empty for npm packages.
    inherited_fields: BTreeSet<String>,
    /// Manifest keys of path dependencies written `workspace = true` under a
    /// runtime table. Empty for npm packages.
    inherited_path_dependencies: BTreeSet<String>,
    /// Empty for npm packages.
    path_crates: Vec<PathCrate>,
    /// Repository-relative directory (no trailing slash). Empty string is the
    /// repository root. Used for commit path fallback; plan math does not read it.
    manifest_dir: String,
    /// Ships a library its users depend on; discovery derives it from targets
    /// or entry points.
    ships_library: bool,
}

impl Package {
    #[must_use]
    pub fn new(
        id: PackageId,
        version: Version,
        resolves_dependencies_at: ResolvesDependenciesAt,
        publishable: bool,
        dependencies: Vec<Dependency>,
    ) -> Self {
        Self {
            id,
            version,
            resolves_dependencies_at,
            publishable,
            dependencies,
            external_dependencies: Vec::new(),
            unlinked_dependencies: Vec::new(),
            inherited_fields: BTreeSet::new(),
            inherited_path_dependencies: BTreeSet::new(),
            path_crates: Vec::new(),
            manifest_dir: String::new(),
            ships_library: false,
        }
    }

    #[must_use]
    pub const fn with_ships_library(mut self, ships: bool) -> Self {
        self.ships_library = ships;
        self
    }

    #[must_use]
    pub const fn ships_library(&self) -> bool {
        self.ships_library
    }

    #[must_use]
    pub fn with_path_crates(mut self, crates: Vec<PathCrate>) -> Self {
        self.path_crates = crates;
        self
    }

    #[must_use]
    pub fn with_external_dependencies(mut self, external: Vec<ExternalDependency>) -> Self {
        self.external_dependencies = external;
        self
    }

    #[must_use]
    pub fn with_unlinked_dependencies(mut self, unlinked: Vec<UnlinkedDependency>) -> Self {
        self.unlinked_dependencies = unlinked;
        self
    }

    #[must_use]
    pub fn with_inherited_fields(mut self, fields: BTreeSet<String>) -> Self {
        self.inherited_fields = fields;
        self
    }

    #[must_use]
    pub fn with_inherited_path_dependencies(mut self, keys: BTreeSet<String>) -> Self {
        self.inherited_path_dependencies = keys;
        self
    }

    /// Repository-relative package directory. Empty string is the repository root.
    #[must_use]
    pub fn with_manifest_dir(mut self, dir: impl Into<String>) -> Self {
        self.manifest_dir = dir.into();
        self
    }

    /// Config overlay for ADR-0009 bundled libraries (`resolves-dependencies-at = "build"`).
    /// A discovered binary target survives it: ADR-0040 reads the `bin`.
    #[must_use]
    pub fn with_resolves_dependencies_at(mut self, at: ResolvesDependenciesAt) -> Self {
        let binary = ResolvesDependenciesAt::Build(BuildResolution::BinaryTarget);
        let declared = ResolvesDependenciesAt::Build(BuildResolution::Declared);
        if !(at == declared && self.resolves_dependencies_at == binary) {
            self.resolves_dependencies_at = at;
        }
        self
    }

    /// Repository-relative directory. Empty string is the repository root.
    #[must_use]
    pub fn manifest_dir(&self) -> &str {
        &self.manifest_dir
    }

    /// `name` in this package's directory, repository-relative.
    #[must_use]
    pub fn file_path(&self, name: &str) -> String {
        in_dir(&self.manifest_dir, name)
    }

    /// This package's own `Cargo.toml` or `package.json`.
    #[must_use]
    pub fn manifest_path(&self) -> String {
        self.file_path(self.id.ecosystem.manifest_name())
    }

    #[must_use]
    pub const fn id(&self) -> &PackageId {
        &self.id
    }

    /// Working-tree manifest version, not the tagged version (ADR-0014).
    #[must_use]
    pub const fn version(&self) -> &Version {
        &self.version
    }

    #[must_use]
    pub const fn resolves_dependencies_at(&self) -> ResolvesDependenciesAt {
        self.resolves_dependencies_at
    }

    /// Registry publish allowed. Unrelated to whether oakum versions the package
    /// (ADR-0027: versioning unpublishable packages is opt-in preference).
    #[must_use]
    pub const fn publishable(&self) -> bool {
        self.publishable
    }

    /// Every declared intra-workspace edge, development edges included.
    #[must_use]
    pub fn dependencies(&self) -> &[Dependency] {
        &self.dependencies
    }

    /// The subset of [`Package::dependencies`] a release can cascade along.
    pub fn runtime_dependencies(&self) -> impl Iterator<Item = &Dependency> {
        self.dependencies.iter().filter(|d| d.kind.is_runtime())
    }

    /// Every declared dependency outside the workspace, development ones included.
    #[must_use]
    pub fn external_dependencies(&self) -> &[ExternalDependency] {
        &self.external_dependencies
    }

    #[must_use]
    pub fn unlinked_dependencies(&self) -> &[UnlinkedDependency] {
        &self.unlinked_dependencies
    }

    #[must_use]
    pub const fn inherited_fields(&self) -> &BTreeSet<String> {
        &self.inherited_fields
    }

    #[must_use]
    pub const fn inherited_path_dependencies(&self) -> &BTreeSet<String> {
        &self.inherited_path_dependencies
    }

    #[must_use]
    pub fn path_crates(&self) -> &[PathCrate] {
        &self.path_crates
    }
}

/// The packages in a repository and the edges between them.
///
/// [`Workspace::new`] is the only place the set is checked, so a [`Package`] or
/// [`Dependency`] reached through a `Workspace` has been through those checks and
/// one built directly has not. Construction refuses any cycle that names two or
/// more packages (every edge kind — ADR-0008). A package depending on itself is
/// allowed: Cargo accepts a path self-dev-dependency, and a self-edge cannot
/// cascade into another package — but it still appears in
/// [`Workspace::runtime_dependents`], so a naive walk can loop; callers need a
/// visited set (or must treat dependent == dependency as already seen).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Workspace {
    packages: BTreeMap<PackageId, Package>,
    /// Empty string is the repository root.
    cargo_workspace_root: Option<String>,
    /// The root `Cargo.toml` and `Cargo.lock` cargo reads when either is a
    /// link, resolved within the repository; `None` reads them in place.
    cargo_root_files: Option<(String, String)>,
    /// Empty is not a path, unlike the Cargo root.
    catalog_file: Option<String>,
    /// Where pnpm keeps `pnpm-lock.yaml` for these packages. Empty string is
    /// the repository root.
    pnpm_lock_dir: Option<String>,
    /// Every directory pnpm reports as a workspace project, the root and
    /// unversioned members included, repository-relative.
    pnpm_projects: Vec<String>,
}

impl Workspace {
    /// # Errors
    ///
    /// Returns [`WorkspaceError`] for a duplicate package, an empty set, or an
    /// edge that is any of the following:
    ///
    /// - onto a package in another ecosystem
    /// - declared under a section its ecosystem does not have
    /// - carrying a target predicate its ecosystem does not have
    /// - written with a range protocol its ecosystem does not have
    /// - carrying bounds (or a path-linked shape) its ecosystem cannot express
    /// - onto a package the workspace does not contain
    /// - a repeat of an existing `(section, key, target)`
    /// - part of a dependency cycle that names two or more packages
    ///
    /// Each is a discovery fault or a manifest mistake that under-cascades
    /// silently if let through: a dependent behind an unresolvable edge is
    /// reachable from no traversal at all, and an empty set makes "discovery
    /// found nothing" indistinguishable from "nothing to release" — never
    /// collapse "we didn't look" into "it's fine".
    ///
    /// The order of the edge checks is the order above, most fundamental first,
    /// so an edge breaking two rules reports the one that explains the other, and
    /// an edge that is itself unusable is reported before its interaction with
    /// any edge beside it. Cycle detection runs after every edge has passed those
    /// checks, so a broken line is never reported as a cycle.
    pub fn new(packages: impl IntoIterator<Item = Package>) -> Result<Self, WorkspaceError> {
        let mut map = BTreeMap::new();
        for package in packages {
            if let Some(existing) = map.insert(package.id.clone(), package) {
                return Err(WorkspaceError::DuplicatePackage { id: existing.id });
            }
        }

        if map.is_empty() {
            return Err(WorkspaceError::Empty);
        }

        for package in map.values() {
            let id = &package.id;
            let mut seen = BTreeSet::new();
            for dependency in &package.dependencies {
                if dependency.on.ecosystem != id.ecosystem {
                    return Err(WorkspaceError::CrossEcosystemDependency {
                        dependent: id.clone(),
                        dependency: dependency.on.clone(),
                    });
                }
                let Some(section) = dependency.kind.section(id.ecosystem) else {
                    return Err(WorkspaceError::KindNotInEcosystem {
                        dependent: id.clone(),
                        dependency: dependency.on.clone(),
                        kind: dependency.kind,
                    });
                };
                if let Some(target) = &dependency.target {
                    if !id.ecosystem.has_target_tables() {
                        return Err(WorkspaceError::TargetNotInEcosystem {
                            dependent: id.clone(),
                            dependency: dependency.on.clone(),
                            target: target.clone(),
                        });
                    }
                }
                if let Some(protocol) = dependency.range.protocol() {
                    if !id.ecosystem.has_range_protocols() {
                        return Err(WorkspaceError::RangeNotInEcosystem {
                            dependent: id.clone(),
                            dependency: dependency.on.clone(),
                            protocol,
                        });
                    }
                }
                if !dependency.range.fits_ecosystem(id.ecosystem) {
                    return Err(WorkspaceError::BoundsNotInEcosystem {
                        dependent: id.clone(),
                        dependency: dependency.on.clone(),
                    });
                }
                if !map.contains_key(&dependency.on) {
                    return Err(WorkspaceError::UnknownDependency {
                        dependent: id.clone(),
                        dependency: dependency.on.clone(),
                    });
                }
                // The manifest line, which the package it points at is no part
                // of: a key is unique within a section and target table whatever
                // it resolves to, so keying on the package would let two of them
                // share one line.
                if !seen.insert((section, &dependency.declared_as, &dependency.target)) {
                    return Err(WorkspaceError::DuplicateEdge {
                        dependent: id.clone(),
                        declared_as: dependency.declared_as.clone(),
                        section,
                        // The only way to reach this with a target set is a
                        // duplicate inside one target table, which is the case
                        // the bare section name describes wrongly.
                        target: dependency.target.clone(),
                    });
                }
            }
        }

        if let Some(path) = multi_package_cycle(&map) {
            return Err(WorkspaceError::Cycle { path });
        }

        Ok(Self {
            packages: map,
            cargo_workspace_root: None,
            cargo_root_files: None,
            catalog_file: None,
            pnpm_lock_dir: None,
            pnpm_projects: Vec::new(),
        })
    }

    /// The root `Cargo.toml` and `Cargo.lock`, repository-relative, as their
    /// links resolve.
    #[must_use]
    pub fn with_cargo_root_files(mut self, manifest: String, lock: String) -> Self {
        self.cargo_root_files = Some((manifest, lock));
        self
    }

    /// The root `Cargo.toml` and `Cargo.lock` a comparison reads,
    /// repository-relative: where a link at the root leads, else in place.
    #[must_use]
    pub fn cargo_root_files(&self) -> Option<(String, String)> {
        let root = self.cargo_workspace_root()?;
        Some(self.cargo_root_files.clone().unwrap_or_else(|| {
            (
                in_dir(root, Ecosystem::Cargo.manifest_name()),
                in_dir(root, "Cargo.lock"),
            )
        }))
    }

    /// Empty string is the repository root.
    #[must_use]
    pub fn with_cargo_workspace_root(mut self, dir: impl Into<String>) -> Self {
        self.cargo_workspace_root = Some(dir.into());
        self
    }

    #[must_use]
    pub fn with_catalog_file(mut self, path: impl Into<String>) -> Self {
        self.catalog_file = Some(path.into());
        self
    }

    /// Empty string is the repository root.
    #[must_use]
    pub fn with_pnpm_lock_dir(mut self, dir: impl Into<String>) -> Self {
        self.pnpm_lock_dir = Some(dir.into());
        self
    }

    #[must_use]
    pub fn with_pnpm_projects(mut self, dirs: Vec<String>) -> Self {
        self.pnpm_projects = dirs;
        self
    }

    #[must_use]
    pub fn pnpm_projects(&self) -> &[String] {
        &self.pnpm_projects
    }

    /// After a package rebuild. `None` on `other` clears the field.
    #[must_use]
    pub fn with_discovery_paths(mut self, other: &Self) -> Self {
        self.cargo_workspace_root
            .clone_from(&other.cargo_workspace_root);
        self.cargo_root_files.clone_from(&other.cargo_root_files);
        self.catalog_file.clone_from(&other.catalog_file);
        self.pnpm_lock_dir.clone_from(&other.pnpm_lock_dir);
        self.pnpm_projects.clone_from(&other.pnpm_projects);
        self
    }

    /// Empty string is the repository root.
    #[must_use]
    pub fn pnpm_lock_dir(&self) -> Option<&str> {
        self.pnpm_lock_dir.as_deref()
    }

    /// Empty string is the repository root.
    #[must_use]
    pub fn cargo_workspace_root(&self) -> Option<&str> {
        self.cargo_workspace_root.as_deref()
    }

    /// The Cargo workspace root's `Cargo.toml`, repository-relative.
    #[must_use]
    pub fn cargo_root_manifest(&self) -> Option<String> {
        self.cargo_workspace_root()
            .map(|root| in_dir(root, Ecosystem::Cargo.manifest_name()))
    }

    #[must_use]
    pub fn catalog_file(&self) -> Option<&str> {
        self.catalog_file.as_deref()
    }

    #[must_use]
    pub fn get(&self, id: &PackageId) -> Option<&Package> {
        self.packages.get(id)
    }

    /// Ordered by [`PackageId`], so a plan built from this workspace is
    /// reproducible.
    pub fn packages(&self) -> impl Iterator<Item = &Package> {
        self.packages.values()
    }

    /// Every package declaring an edge on `id`, paired with the edge itself.
    ///
    /// One item per edge, so a package appears more than once when it declares
    /// the same dependency under more than one section, key, or target table —
    /// `peerDependencies` plus `devDependencies` is the ordinary way to write an
    /// npm plugin. Callers that bump have to reach a package once however many
    /// edges led them there.
    pub fn dependents<'a, 'b>(
        &'a self,
        id: &'b PackageId,
    ) -> impl Iterator<Item = (&'a Package, &'a Dependency)> + use<'a, 'b> {
        self.packages.values().flat_map(move |package| {
            package
                .dependencies
                .iter()
                .filter(move |d| &d.on == id)
                .map(move |d| (package, d))
        })
    }

    /// The subset of [`Workspace::dependents`] a release can cascade along.
    pub fn runtime_dependents<'a, 'b>(
        &'a self,
        id: &'b PackageId,
    ) -> impl Iterator<Item = (&'a Package, &'a Dependency)> + use<'a, 'b> {
        self.dependents(id)
            .filter(|(_, dependency)| dependency.kind.is_runtime())
    }
}

/// A workspace that cannot be planned over, reported before any planning starts.
///
/// Messages name packages and manifest keys rather than files. Discovery holds
/// the paths and is where a location belongs in a message; by the time a
/// [`Package`] exists the path is deliberately gone, so nothing in the planner
/// can reach for it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WorkspaceError {
    Empty,
    DuplicatePackage {
        id: PackageId,
    },
    CrossEcosystemDependency {
        dependent: PackageId,
        dependency: PackageId,
    },
    KindNotInEcosystem {
        dependent: PackageId,
        dependency: PackageId,
        kind: DependencyKind,
    },
    TargetNotInEcosystem {
        dependent: PackageId,
        dependency: PackageId,
        target: String,
    },
    RangeNotInEcosystem {
        dependent: PackageId,
        dependency: PackageId,
        protocol: RangeProtocol,
    },
    /// Bounds or path-linked shape that cannot appear on this ecosystem
    /// (ADR-0026): e.g. [`DeclaredRange::PathLinked`] on npm, or
    /// [`Bounds::Npm`] on a Cargo plain.
    BoundsNotInEcosystem {
        dependent: PackageId,
        dependency: PackageId,
    },
    UnknownDependency {
        dependent: PackageId,
        dependency: PackageId,
    },
    DuplicateEdge {
        dependent: PackageId,
        declared_as: String,
        section: &'static str,
        target: Option<String>,
    },
    /// A dependency cycle naming two or more packages. `path` is the cycle
    /// walk with the first id repeated at the end (`a → b → a`).
    Cycle {
        path: Vec<PackageId>,
    },
}

impl fmt::Display for WorkspaceError {
    // Each variant needs its own wording; folding them into helpers obscures the
    // message that discovery surfaces.
    #[expect(clippy::too_many_lines)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str(
                "discovery reported no packages; a workspace file above the repository root can \
                 reparent the workspace, so check which root the package manager resolved",
            ),
            Self::DuplicatePackage { id } => {
                write!(f, "the workspace reports {id} more than once")
            }
            Self::CrossEcosystemDependency {
                dependent,
                dependency,
            } => write!(
                f,
                "{dependent} declares an edge on {dependency}, which no manifest can express"
            ),
            Self::KindNotInEcosystem {
                dependent,
                dependency,
                kind,
            } => {
                write!(
                    f,
                    "{dependent} declares {dependency} with kind {kind}, which {} has no section for",
                    dependent.ecosystem
                )?;
                // Cargo does have optional dependencies, so the bare message
                // reads as "unsupported" when the fault is a mis-mapped kind.
                if (dependent.ecosystem, kind) == (Ecosystem::Cargo, &DependencyKind::Optional) {
                    f.write_str(
                        "; Cargo declares optional dependencies as `optional = true` entries in \
                         [dependencies], which is the normal kind",
                    )?;
                }
                Ok(())
            }
            Self::TargetNotInEcosystem {
                dependent,
                dependency,
                target,
            } => write!(
                f,
                "{dependent} declares {dependency} under target `{target}`, which {} has no tables for",
                dependent.ecosystem
            ),
            Self::RangeNotInEcosystem {
                dependent,
                dependency,
                protocol,
            } => {
                write!(
                    f,
                    "{dependent} declares {dependency} with a `{protocol}` range, which {} has no \
                     protocol for",
                    dependent.ecosystem
                )?;
                // Cargo is the only ecosystem this variant can name today, so the
                // ecosystem half is pre-armed rather than live: a third one
                // without range protocols must not be handed Cargo's advice.
                if (dependent.ecosystem, protocol) == (Ecosystem::Cargo, &RangeProtocol::Workspace)
                {
                    f.write_str(
                        "; Cargo's `workspace = true` inheritance is a different mechanism and \
                         reaches the planner as a plain range",
                    )?;
                }
                Ok(())
            }
            Self::BoundsNotInEcosystem {
                dependent,
                dependency,
            } => write!(
                f,
                "{dependent} declares {dependency} with a range shape {} cannot express",
                dependent.ecosystem
            ),
            Self::UnknownDependency {
                dependent,
                dependency,
            } => write!(
                f,
                "{dependent} depends on {dependency}, which the workspace does not contain"
            ),
            Self::DuplicateEdge {
                dependent,
                declared_as,
                section,
                target,
            } => match target {
                Some(target) => write!(
                    f,
                    "{dependent} declares `{declared_as}` more than once in \
                     [target.'{target}'.{section}]"
                ),
                None => write!(
                    f,
                    "{dependent} declares `{declared_as}` more than once in {section}"
                ),
            },
            Self::Cycle { path } => {
                debug_assert!(
                    path.len() >= 3 && path.first() == path.last(),
                    "Cycle.path must be a closed multi-package walk"
                );
                f.write_str("found cycle in dependency graph: ")?;
                for (i, id) in path.iter().enumerate() {
                    if i > 0 {
                        f.write_str(" -> ")?;
                    }
                    write!(f, "{id}")?;
                }
                Ok(())
            }
        }
    }
}

/// Walks every edge (runtime and development). Returns a cycle path that names
/// two or more packages, with the start id repeated at the end. Self-edges alone
/// are ignored — Cargo accepts a path self-dev-dependency (ADR-0008).
fn multi_package_cycle(packages: &BTreeMap<PackageId, Package>) -> Option<Vec<PackageId>> {
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Color {
        White,
        Gray,
        Black,
    }

    fn visit(
        id: &PackageId,
        packages: &BTreeMap<PackageId, Package>,
        color: &mut BTreeMap<PackageId, Color>,
        path: &mut Vec<PackageId>,
    ) -> Option<Vec<PackageId>> {
        color.insert(id.clone(), Color::Gray);
        path.push(id.clone());

        if let Some(package) = packages.get(id) {
            for dependency in &package.dependencies {
                let next = &dependency.on;
                match color.get(next).copied().unwrap_or(Color::White) {
                    Color::Gray => {
                        let start = path
                            .iter()
                            .position(|step| step == next)
                            .expect("gray node must be on the DFS path");
                        // Self-edge: path[start..] is one node before the close.
                        if path.len() - start < 2 {
                            continue;
                        }
                        let mut cycle: Vec<PackageId> = path[start..].to_vec();
                        cycle.push(next.clone());
                        return Some(cycle);
                    }
                    Color::White => {
                        if let Some(cycle) = visit(next, packages, color, path) {
                            return Some(cycle);
                        }
                    }
                    Color::Black => {}
                }
            }
        }

        path.pop();
        color.insert(id.clone(), Color::Black);
        None
    }

    let mut color = BTreeMap::new();
    for id in packages.keys() {
        color.insert(id.clone(), Color::White);
    }

    let mut path = Vec::new();
    for id in packages.keys() {
        if color.get(id).copied() != Some(Color::White) {
            continue;
        }
        if let Some(cycle) = visit(id, packages, &mut color, &mut path) {
            return Some(cycle);
        }
    }
    None
}

impl core::error::Error for WorkspaceError {}

/// `name` under `dir`, joined with `/`; an empty `dir` is the repository root.
fn in_dir(dir: &str, name: &str) -> String {
    if dir.is_empty() {
        String::from(name)
    } else {
        alloc::format!("{dir}/{name}")
    }
}

// Held to `no_std` along with the rest of the module: `--all-targets` builds
// this through `crates/plan-no-std`, so a fixture reaching for `HashMap` or
// `Box` fails there rather than here.
#[cfg(test)]
mod tests {
    use alloc::format;
    use alloc::string::ToString;
    use alloc::vec;

    use super::*;

    fn cargo(name: &str) -> PackageId {
        PackageId::new(Ecosystem::Cargo, name)
    }

    fn npm(name: &str) -> PackageId {
        PackageId::new(Ecosystem::Npm, name)
    }

    fn req(text: &str) -> VersionReq {
        VersionReq::parse(text).expect("test range should parse")
    }

    fn plain_cargo(text: &str) -> DeclaredRange {
        DeclaredRange::Plain(Bounds::from_cargo_text(text).expect("test cargo range"))
    }

    fn plain_npm(text: &str) -> DeclaredRange {
        DeclaredRange::Plain(Bounds::from_npm_text(text).expect("test npm range"))
    }

    fn workspace_npm(text: &str) -> DeclaredRange {
        DeclaredRange::Workspace(Bounds::from_npm_text(text).expect("test npm range"))
    }

    fn catalog_npm(name: Option<&str>, text: &str) -> DeclaredRange {
        DeclaredRange::Catalog {
            name: name.map(str::to_string),
            bounds: Bounds::from_npm_text(text).expect("test npm range"),
        }
    }

    fn edge(on: PackageId, kind: DependencyKind) -> Dependency {
        let declared_as = on.name.clone();
        let range = match on.ecosystem {
            Ecosystem::Cargo => plain_cargo("^1.0.0"),
            Ecosystem::Npm => plain_npm("^1.0.0"),
        };
        Dependency {
            on,
            kind,
            declared_as,
            target: None,
            range,
        }
    }

    fn package(id: PackageId, dependencies: Vec<Dependency>) -> Package {
        Package::new(
            id,
            Version::new(1, 0, 0),
            ResolvesDependenciesAt::Install,
            true,
            dependencies,
        )
    }

    #[test]
    fn a_package_path_joins_its_directory_with_a_slash() {
        let root = package(cargo("core"), vec![]);
        let nested = package(npm("ui"), vec![]).with_manifest_dir("packages/ui");
        assert_eq!(root.manifest_path(), "Cargo.toml");
        assert_eq!(nested.manifest_path(), "packages/ui/package.json");
        assert_eq!(nested.file_path("CHANGELOG.md"), "packages/ui/CHANGELOG.md");

        let workspace = Workspace::new([root.clone()]).expect("workspace");
        assert_eq!(workspace.cargo_root_manifest(), None);
        for (dir, manifest) in [("", "Cargo.toml"), ("rust", "rust/Cargo.toml")] {
            let workspace = Workspace::new([root.clone()])
                .expect("workspace")
                .with_cargo_workspace_root(dir);
            assert_eq!(workspace.cargo_root_manifest().as_deref(), Some(manifest));
        }
    }

    #[test]
    fn a_duplicate_package_is_refused() {
        let error = Workspace::new([
            package(cargo("core"), vec![]),
            package(cargo("core"), vec![]),
        ])
        .expect_err("two packages under one id should not build a workspace");

        assert_eq!(
            error,
            WorkspaceError::DuplicatePackage { id: cargo("core") }
        );
        assert_eq!(
            error.to_string(),
            "the workspace reports core (cargo) more than once"
        );
    }

    /// Discovery returning nothing and a repository with nothing to release are
    /// different facts. pnpm reports the first as exit 0 with an empty list when
    /// a stray ancestor reparents the workspace, so the message has to name that.
    #[test]
    fn an_empty_workspace_is_refused_and_names_the_likely_cause() {
        let error = Workspace::new([]).expect_err("an empty workspace should be refused");

        assert_eq!(error, WorkspaceError::Empty);
        assert!(
            error.to_string().contains("reparent the workspace"),
            "message gives the reader nothing to check: {error}"
        );
    }

    #[test]
    fn discovery_paths_survive_a_package_rebuild() {
        let bare = Workspace::new([package(cargo("core"), vec![])]).expect("workspace");
        assert_eq!(bare.cargo_workspace_root(), None);
        assert_eq!(bare.catalog_file(), None);
        let original = bare
            .with_cargo_workspace_root("rust")
            .with_catalog_file("js/pnpm-workspace.yaml")
            .with_pnpm_lock_dir("js");
        let rebuilt = Workspace::new(original.packages().cloned())
            .expect("workspace")
            .with_discovery_paths(&original);
        assert_eq!(rebuilt.cargo_workspace_root(), Some("rust"));
        assert_eq!(rebuilt.catalog_file(), Some("js/pnpm-workspace.yaml"));
        assert_eq!(rebuilt.pnpm_lock_dir(), Some("js"));
    }

    /// An edge onto a package the workspace does not contain reaches nothing, so
    /// accepting it means a dependent that no traversal can find.
    #[test]
    fn an_edge_onto_a_package_outside_the_workspace_is_refused_by_name() {
        let error = Workspace::new([package(
            cargo("cli"),
            vec![edge(cargo("core"), DependencyKind::Normal)],
        )])
        .expect_err("an unresolvable edge should not build a workspace");

        // The whole rendered string, not that both names appear somewhere: the
        // message reads the same either way round, and one naming the two ends
        // backwards sends the reader to the wrong manifest.
        assert_eq!(
            error.to_string(),
            "cli (cargo) depends on core (cargo), which the workspace does not contain"
        );
        assert_eq!(
            error,
            WorkspaceError::UnknownDependency {
                dependent: cargo("cli"),
                dependency: cargo("core"),
            }
        );
    }

    /// See [`PackageId`]: keyed by name alone the two collapse into one node.
    #[test]
    fn one_name_in_two_ecosystems_is_two_packages() {
        let workspace = Workspace::new([
            package(cargo("oakum"), vec![]),
            package(npm("oakum"), vec![]),
        ])
        .expect("distinct ecosystems should not collide");

        assert_eq!(workspace.packages().count(), 2);
        // `is_some()` would hold whichever of the two came back.
        assert_eq!(
            workspace.get(&cargo("oakum")).map(Package::id),
            Some(&cargo("oakum"))
        );

        let cargo_only = Workspace::new([package(cargo("oakum"), vec![])]).expect("should build");
        assert!(cargo_only.get(&npm("oakum")).is_none());
    }

    /// The other half of that separation. Distinct ids stop the packages merging;
    /// only this stops an edge crossing between them.
    #[test]
    fn an_edge_across_ecosystems_is_refused() {
        let error = Workspace::new([
            package(cargo("core"), vec![]),
            package(
                npm("cli"),
                vec![edge(cargo("core"), DependencyKind::Normal)],
            ),
        ])
        .expect_err("a cross-ecosystem edge should be refused");

        assert_eq!(
            error.to_string(),
            "cli (npm) declares an edge on core (cargo), which no manifest can express"
        );
        assert_eq!(
            error,
            WorkspaceError::CrossEcosystemDependency {
                dependent: npm("cli"),
                dependency: cargo("core"),
            }
        );
    }

    /// Lookups have to match the whole id, not the name.
    #[test]
    fn dependents_does_not_match_across_ecosystems() {
        let workspace = Workspace::new([
            package(npm("shared"), vec![]),
            package(cargo("shared"), vec![]),
            package(
                cargo("cli"),
                vec![edge(cargo("shared"), DependencyKind::Normal)],
            ),
        ])
        .expect("workspace should build");

        let found: Vec<&PackageId> = workspace
            .dependents(&cargo("shared"))
            .map(|(package, _)| package.id())
            .collect();
        assert_eq!(found, vec![&cargo("cli")]);
        assert_eq!(workspace.dependents(&npm("shared")).count(), 0);
    }

    /// ADR-0008's separation, in both directions: the edge stays in the graph so
    /// its range is still rewritten, and out of the cascade set so it never bumps.
    #[test]
    fn a_development_edge_stays_in_the_graph_and_out_of_the_cascade_set() {
        let workspace = Workspace::new([
            package(cargo("config"), vec![]),
            package(
                cargo("cli"),
                vec![edge(cargo("config"), DependencyKind::Development)],
            ),
        ])
        .expect("a development edge should build a workspace");

        let cli = workspace.get(&cargo("cli")).expect("cli should be present");
        assert_eq!(cli.dependencies().len(), 1);
        assert_eq!(cli.runtime_dependencies().count(), 0);

        let dependents: Vec<&PackageId> = workspace
            .dependents(&cargo("config"))
            .map(|(package, _)| package.id())
            .collect();
        assert_eq!(dependents, vec![&cargo("cli")]);
        assert_eq!(workspace.runtime_dependents(&cargo("config")).count(), 0);
    }

    /// See [`DependencyKind::is_runtime`] for why `Build` is on the cascade side.
    #[test]
    fn every_kind_lands_on_the_side_adr_0008_puts_it() {
        for kind in [
            DependencyKind::Normal,
            DependencyKind::Peer,
            DependencyKind::Optional,
            DependencyKind::Build,
        ] {
            assert!(kind.is_runtime(), "{kind:?} should cascade");
        }
        assert!(!DependencyKind::Development.is_runtime());
    }

    /// The table `version` writes through. Three of the ten pairings are nothing;
    /// see [`DependencyKind::section`] for why Cargo has no optional section.
    #[test]
    fn every_kind_maps_to_the_section_its_ecosystem_writes() {
        use DependencyKind::{Build, Development, Normal, Optional, Peer};

        for (ecosystem, kind, section) in [
            (Ecosystem::Npm, Normal, Some("dependencies")),
            (Ecosystem::Npm, Peer, Some("peerDependencies")),
            (Ecosystem::Npm, Optional, Some("optionalDependencies")),
            (Ecosystem::Npm, Development, Some("devDependencies")),
            (Ecosystem::Npm, Build, None),
            (Ecosystem::Cargo, Normal, Some("dependencies")),
            (Ecosystem::Cargo, Build, Some("build-dependencies")),
            (Ecosystem::Cargo, Development, Some("dev-dependencies")),
            (Ecosystem::Cargo, Peer, None),
            (Ecosystem::Cargo, Optional, None),
        ] {
            assert_eq!(kind.section(ecosystem), section, "{ecosystem} {kind:?}");
        }
    }

    /// A kind its ecosystem has no section for would be written back nowhere.
    #[test]
    fn a_kind_the_ecosystem_has_no_section_for_is_refused() {
        let error = Workspace::new([
            package(cargo("core"), vec![]),
            package(
                cargo("cli"),
                vec![edge(cargo("core"), DependencyKind::Peer)],
            ),
        ])
        .expect_err("a Cargo peer dependency should be refused");

        assert_eq!(
            error.to_string(),
            "cli (cargo) declares core (cargo) with kind peer, which cargo has no section for"
        );
        assert_eq!(
            error,
            WorkspaceError::KindNotInEcosystem {
                dependent: cargo("cli"),
                dependency: cargo("core"),
                kind: DependencyKind::Peer,
            }
        );
    }

    /// Declaring a package as both a peer and a development dependency is the
    /// ordinary way to write an npm plugin, so a dependent arrives twice.
    #[test]
    fn a_package_declared_in_two_sections_yields_one_edge_each() {
        let workspace = Workspace::new([
            package(npm("host"), vec![]),
            package(
                npm("plugin"),
                vec![
                    edge(npm("host"), DependencyKind::Peer),
                    edge(npm("host"), DependencyKind::Development),
                ],
            ),
        ])
        .expect("two sections naming one dependency should build a workspace");

        let kinds: Vec<DependencyKind> = workspace
            .dependents(&npm("host"))
            .map(|(_, dependency)| dependency.kind)
            .collect();
        assert_eq!(
            kinds,
            vec![DependencyKind::Peer, DependencyKind::Development]
        );
        assert_eq!(workspace.runtime_dependents(&npm("host")).count(), 1);
    }

    /// Two entries under one key, one section, and one target table are two
    /// ranges for one manifest line, and whichever the gate reads decides whether
    /// the cascade fires.
    #[test]
    fn one_dependency_declared_twice_under_one_key_is_refused() {
        let mut tighter = edge(cargo("core"), DependencyKind::Normal);
        tighter.range = plain_cargo("=1.0.0");

        let error = Workspace::new([
            package(cargo("core"), vec![]),
            package(
                cargo("cli"),
                vec![edge(cargo("core"), DependencyKind::Normal), tighter],
            ),
        ])
        .expect_err("two ranges for one entry should be refused");

        assert_eq!(
            error.to_string(),
            "cli (cargo) declares `core` more than once in dependencies"
        );
        assert_eq!(
            error,
            WorkspaceError::DuplicateEdge {
                dependent: cargo("cli"),
                declared_as: "core".to_string(),
                section: "dependencies",
                target: None,
            }
        );
    }

    /// Two packages behind one key is a state no manifest can hold — the shape a
    /// broken alias resolver produces.
    #[test]
    fn two_packages_under_one_key_is_refused() {
        let mut collides = edge(cargo("utils"), DependencyKind::Normal);
        collides.declared_as = "shared".to_string();
        let mut first = edge(cargo("core"), DependencyKind::Normal);
        first.declared_as = "shared".to_string();

        let error = Workspace::new([
            package(cargo("core"), vec![]),
            package(cargo("utils"), vec![]),
            package(cargo("cli"), vec![first, collides]),
        ])
        .expect_err("one key naming two packages should be refused");

        assert_eq!(
            error,
            WorkspaceError::DuplicateEdge {
                dependent: cargo("cli"),
                declared_as: "shared".to_string(),
                section: "dependencies",
                target: None,
            }
        );
    }

    /// Two entries onto one package under different keys. Cargo builds this only
    /// while the aliased entry is an unenabled optional dependency, and npm
    /// aliases are ordinary separate keys — either way the uniqueness rule must
    /// not refuse it. See `docs/research/cargo-metadata-edge-shapes.md`.
    #[test]
    fn a_renamed_edge_alongside_the_plain_one_is_not_a_duplicate() {
        let mut renamed = edge(cargo("core"), DependencyKind::Normal);
        renamed.declared_as = "core_alias".to_string();

        let workspace = Workspace::new([
            package(cargo("core"), vec![]),
            package(
                cargo("cli"),
                vec![edge(cargo("core"), DependencyKind::Normal), renamed],
            ),
        ])
        .expect("a rename beside the plain entry should build a workspace");

        assert_eq!(workspace.dependents(&cargo("core")).count(), 2);
    }

    /// Verified against `cargo metadata`: one key under `cfg(unix)` and
    /// `cfg(windows)` reports two entries with different ranges, identical in
    /// every other field. Keying without the target refuses that legal manifest.
    #[test]
    fn one_key_in_two_target_tables_is_not_a_duplicate() {
        let mut unix = edge(cargo("core"), DependencyKind::Normal);
        unix.target = Some("cfg(unix)".to_string());
        let mut windows = edge(cargo("core"), DependencyKind::Normal);
        windows.target = Some("cfg(windows)".to_string());
        windows.range = plain_cargo("=1.0.0");

        let workspace = Workspace::new([
            package(cargo("core"), vec![]),
            package(cargo("cli"), vec![unix, windows]),
        ])
        .expect("two target tables should build a workspace");

        assert_eq!(workspace.runtime_dependents(&cargo("core")).count(), 2);
    }

    /// `workspace:` and `catalog:` are pnpm, yarn, and bun protocols. Accepting one
    /// on a Cargo package would have `version` write `workspace:^1.5.0` into a
    /// `Cargo.toml`, and `admits` expand it as though pnpm had rewritten it.
    #[test]
    fn a_range_protocol_the_ecosystem_does_not_have_is_refused() {
        // Cargo has workspace dependencies, so the `workspace:` message carries a
        // clause saying which mechanism is being refused.
        let inheritance = "; Cargo's `workspace = true` inheritance is a different \
                           mechanism and reaches the planner as a plain range";

        for (range, protocol, tail) in [
            (
                DeclaredRange::WorkspaceTracking(Tracking::Caret),
                RangeProtocol::Workspace,
                inheritance,
            ),
            (
                workspace_npm("^1.0.0"),
                RangeProtocol::Workspace,
                inheritance,
            ),
            (catalog_npm(None, "^1.0.0"), RangeProtocol::Catalog, ""),
        ] {
            let mut dependency = edge(cargo("core"), DependencyKind::Normal);
            dependency.range = range;

            let error = Workspace::new([
                package(cargo("core"), vec![]),
                package(cargo("cli"), vec![dependency]),
            ])
            .expect_err("a protocol range on a Cargo package should be refused");

            assert_eq!(
                error,
                WorkspaceError::RangeNotInEcosystem {
                    dependent: cargo("cli"),
                    dependency: cargo("core"),
                    protocol,
                }
            );
            // Named ends, not both names alone: swapped, the message sends
            // the reader to core's manifest when the bad range is in cli's.
            assert_eq!(
                error.to_string(),
                format!(
                    "cli (cargo) declares core (cargo) with a `{protocol}` range, \
                     which cargo has no protocol for{tail}"
                )
            );
        }

        // The pre-armed half of that guard, which `Workspace::new` cannot reach
        // while Cargo is the only ecosystem without range protocols.
        assert_eq!(
            WorkspaceError::RangeNotInEcosystem {
                dependent: npm("cli"),
                dependency: npm("core"),
                protocol: RangeProtocol::Workspace,
            }
            .to_string(),
            "cli (npm) declares core (npm) with a `workspace:` range, which npm has no protocol for"
        );

        // The same range on an npm package is the whole point of the variant.
        for range in [
            DeclaredRange::WorkspaceTracking(Tracking::Caret),
            workspace_npm("^1.0.0"),
            catalog_npm(None, "^1.0.0"),
            catalog_npm(Some("react18"), "^1.0.0 || ^2.0.0"),
        ] {
            Workspace::new([
                package(npm("core"), vec![]),
                package(npm("cli"), {
                    let mut d = edge(npm("core"), DependencyKind::Normal);
                    d.range = range;
                    vec![d]
                }),
            ])
            .expect("npm protocol / tracking ranges should build");
        }
    }

    /// Multi-package cycles refuse at construction (any edge kind). A self-edge
    /// alone is allowed: Cargo accepts `path = "."` under `[dev-dependencies]`.
    #[test]
    fn a_multi_package_cycle_is_refused_and_a_self_edge_is_not() {
        for kind in [DependencyKind::Normal, DependencyKind::Development] {
            Workspace::new([package(cargo("core"), vec![edge(cargo("core"), kind)])])
                .unwrap_or_else(|e| panic!("a {kind} self-edge should build: {e}"));
        }

        for kind in [DependencyKind::Normal, DependencyKind::Development] {
            let error = Workspace::new([
                package(cargo("a"), vec![edge(cargo("b"), kind)]),
                package(cargo("b"), vec![edge(cargo("a"), kind)]),
            ])
            .expect_err("a two-node cycle should refuse");
            match &error {
                WorkspaceError::Cycle { path } => {
                    assert!(path.len() >= 3, "{path:?}");
                    assert_eq!(path.first(), path.last());
                    let distinct: BTreeSet<_> = path.iter().collect();
                    assert_eq!(distinct.len(), 2);
                }
                other => panic!("expected Cycle, got {other:?}"),
            }
            assert!(
                error
                    .to_string()
                    .starts_with("found cycle in dependency graph: "),
                "{error}"
            );
        }

        // Self-edge still appears in runtime_dependents; callers must not loop.
        let workspace = Workspace::new([package(
            cargo("core"),
            vec![edge(cargo("core"), DependencyKind::Normal)],
        )])
        .expect("workspace should build");
        let reached: Vec<&PackageId> = workspace
            .runtime_dependents(&cargo("core"))
            .map(|(package, _)| package.id())
            .collect();
        assert_eq!(reached, vec![&cargo("core")]);
    }

    #[test]
    fn a_development_cycle_is_refused_like_a_runtime_one() {
        // release-please #2452 shape: two packages that only devDepend on each other.
        let error = Workspace::new([
            package(
                npm("eslint-plugin-treekeeper"),
                vec![edge(
                    npm("eslint-plugin-node-specifier"),
                    DependencyKind::Development,
                )],
            ),
            package(
                npm("eslint-plugin-node-specifier"),
                vec![edge(
                    npm("eslint-plugin-treekeeper"),
                    DependencyKind::Development,
                )],
            ),
        ])
        .expect_err("a development-only cycle should refuse");

        assert!(matches!(error, WorkspaceError::Cycle { .. }));
        let message = error.to_string();
        assert!(
            message.contains("eslint-plugin-treekeeper")
                && message.contains("eslint-plugin-node-specifier"),
            "{message}"
        );
    }

    #[test]
    fn a_three_node_cycle_names_every_package() {
        let error = Workspace::new([
            package(cargo("a"), vec![edge(cargo("b"), DependencyKind::Normal)]),
            package(cargo("b"), vec![edge(cargo("c"), DependencyKind::Build)]),
            package(
                cargo("c"),
                vec![edge(cargo("a"), DependencyKind::Development)],
            ),
        ])
        .expect_err("a three-node mixed-kind cycle should refuse");

        let WorkspaceError::Cycle { path } = error else {
            panic!("expected Cycle");
        };
        assert_eq!(path.len(), 4);
        assert_eq!(path.first(), path.last());
        let distinct: BTreeSet<_> = path.iter().cloned().collect();
        assert_eq!(
            distinct,
            BTreeSet::from([cargo("a"), cargo("b"), cargo("c")])
        );
    }

    #[test]
    fn an_unknown_dependency_is_reported_before_a_cycle() {
        let error = Workspace::new([
            package(
                cargo("a"),
                vec![
                    edge(cargo("b"), DependencyKind::Normal),
                    edge(cargo("absent"), DependencyKind::Normal),
                ],
            ),
            package(cargo("b"), vec![edge(cargo("a"), DependencyKind::Normal)]),
        ])
        .expect_err("unknown dependency should win over the a↔b cycle");

        assert_eq!(
            error,
            WorkspaceError::UnknownDependency {
                dependent: cargo("a"),
                dependency: cargo("absent"),
            }
        );
    }

    #[test]
    fn a_mixed_kind_two_node_cycle_is_refused() {
        let error = Workspace::new([
            package(cargo("a"), vec![edge(cargo("b"), DependencyKind::Normal)]),
            package(
                cargo("b"),
                vec![edge(cargo("a"), DependencyKind::Development)],
            ),
        ])
        .expect_err("runtime↔development between the same pair is still a cycle");

        assert!(matches!(error, WorkspaceError::Cycle { .. }));
    }

    #[test]
    fn a_self_edge_does_not_hide_a_multi_package_cycle() {
        let error = Workspace::new([
            package(
                cargo("a"),
                vec![
                    edge(cargo("a"), DependencyKind::Development),
                    edge(cargo("b"), DependencyKind::Normal),
                ],
            ),
            package(cargo("b"), vec![edge(cargo("a"), DependencyKind::Normal)]),
        ])
        .expect_err("self-edge plus a↔b must still refuse");

        let WorkspaceError::Cycle { path } = error else {
            panic!("expected Cycle");
        };
        let distinct: BTreeSet<_> = path.iter().collect();
        assert!(distinct.contains(&&cargo("a")) && distinct.contains(&&cargo("b")));
    }

    #[test]
    fn a_diamond_is_not_a_cycle() {
        Workspace::new([
            package(
                cargo("a"),
                vec![
                    edge(cargo("b"), DependencyKind::Normal),
                    edge(cargo("c"), DependencyKind::Normal),
                ],
            ),
            package(cargo("b"), vec![edge(cargo("d"), DependencyKind::Normal)]),
            package(cargo("c"), vec![edge(cargo("d"), DependencyKind::Normal)]),
            package(cargo("d"), vec![]),
        ])
        .expect("a diamond DAG should build");
    }

    /// An edge can break more than one rule at once, and the report has to be the
    /// fault that explains the others — otherwise the reader is sent to add a
    /// package that would still be rejected, or to a section that is not the
    /// problem.
    ///
    /// The duplicate pairing needs a *pair* of edges, not one edge with two
    /// faults: the duplicate check only runs on an edge whose key-mate already
    /// passed everything, so a fixture repeating one broken edge trips the other
    /// fault first and pins nothing.
    #[test]
    fn a_two_fault_edge_reports_the_fault_that_explains_the_other() {
        let keyed = |on: PackageId| {
            let mut dependency = edge(on, DependencyKind::Normal);
            dependency.declared_as = "shared".to_string();
            dependency
        };

        // Cross-ecosystem outranks no-such-section: an edge into another
        // ecosystem is not one a manifest could hold whatever section it names.
        assert!(matches!(
            Workspace::new([package(
                npm("cli"),
                vec![edge(cargo("core"), DependencyKind::Build)]
            )]),
            Err(WorkspaceError::CrossEcosystemDependency { .. })
        ));

        // No-such-section outranks unresolvable.
        assert!(matches!(
            Workspace::new([package(
                cargo("cli"),
                vec![edge(cargo("absent"), DependencyKind::Peer)]
            )]),
            Err(WorkspaceError::KindNotInEcosystem { .. })
        ));

        // Unresolvable outranks duplicate: reporting the duplicate would hide the
        // missing package behind a complaint about how often it is named.
        assert!(matches!(
            Workspace::new([
                package(cargo("core"), vec![]),
                package(
                    cargo("cli"),
                    vec![keyed(cargo("core")), keyed(cargo("absent"))]
                ),
            ]),
            Err(WorkspaceError::UnknownDependency { .. })
        ));

        // Cross-ecosystem outranks the missing target table, which is the same
        // ordering the section check gets and for the same reason.
        let mut targeted = edge(cargo("core"), DependencyKind::Normal);
        targeted.target = Some("cfg(windows)".to_string());
        assert!(matches!(
            Workspace::new([package(npm("cli"), vec![targeted])]),
            Err(WorkspaceError::CrossEcosystemDependency { .. })
        ));

        // No-such-section outranks the range protocol: an edge with no section to
        // live in is not yet a question about how its range is spelled.
        let mut sectionless = edge(cargo("core"), DependencyKind::Peer);
        sectionless.range = DeclaredRange::WorkspaceTracking(Tracking::Caret);
        assert!(matches!(
            Workspace::new([
                package(cargo("core"), vec![]),
                package(cargo("cli"), vec![sectionless]),
            ]),
            Err(WorkspaceError::KindNotInEcosystem { .. })
        ));

        // Cross-ecosystem outranks it too — and this ordering also keeps the
        // message honest, since it renders the dependent's ecosystem.
        let mut crossed = edge(npm("core"), DependencyKind::Normal);
        crossed.range = DeclaredRange::WorkspaceTracking(Tracking::Caret);
        assert!(matches!(
            Workspace::new([
                package(npm("core"), vec![]),
                package(cargo("cli"), vec![crossed]),
            ]),
            Err(WorkspaceError::CrossEcosystemDependency { .. })
        ));

        // No-such-section outranks the missing target table: an edge with no
        // section to live in is not yet a question about which table holds it.
        let mut sectionless = edge(npm("core"), DependencyKind::Build);
        sectionless.target = Some("cfg(windows)".to_string());
        assert!(matches!(
            Workspace::new([
                package(npm("core"), vec![]),
                package(npm("cli"), vec![sectionless]),
            ]),
            Err(WorkspaceError::KindNotInEcosystem { .. })
        ));

        // An unusable range protocol outranks unresolvable, on the same reasoning.
        let mut protocol_on_absent = edge(cargo("absent"), DependencyKind::Normal);
        protocol_on_absent.range = DeclaredRange::WorkspaceTracking(Tracking::Caret);
        assert!(matches!(
            Workspace::new([package(cargo("cli"), vec![protocol_on_absent])]),
            Err(WorkspaceError::RangeNotInEcosystem { .. })
        ));

        // And the missing target table outranks unresolvable: an npm edge cannot
        // carry one whether or not the package it names exists.
        let mut absent = edge(npm("absent"), DependencyKind::Normal);
        absent.target = Some("cfg(windows)".to_string());
        assert!(matches!(
            Workspace::new([package(npm("cli"), vec![absent])]),
            Err(WorkspaceError::TargetNotInEcosystem { .. })
        ));
    }

    /// npm has no target tables, so an edge carrying one is a discovery fault —
    /// and it widens the uniqueness key, letting two ranges through for one
    /// `package.json` entry.
    #[test]
    fn an_npm_edge_carrying_a_target_is_refused() {
        let mut targeted = edge(npm("core"), DependencyKind::Normal);
        targeted.target = Some("cfg(windows)".to_string());

        let error = Workspace::new([
            package(npm("core"), vec![]),
            package(npm("cli"), vec![targeted]),
        ])
        .expect_err("an npm target should be refused");

        assert_eq!(
            error.to_string(),
            "cli (npm) declares core (npm) under target `cfg(windows)`, which npm has no tables for"
        );
        assert_eq!(
            error,
            WorkspaceError::TargetNotInEcosystem {
                dependent: npm("cli"),
                dependency: npm("core"),
                target: "cfg(windows)".to_string(),
            }
        );
    }

    /// The section is derived, so a duplicate outside the default one has to name
    /// the table `version` would actually edit.
    #[test]
    fn a_duplicate_names_the_section_and_target_table_it_fired_in() {
        let npm_dev = Workspace::new([
            package(npm("core"), vec![]),
            package(
                npm("cli"),
                vec![
                    edge(npm("core"), DependencyKind::Development),
                    edge(npm("core"), DependencyKind::Development),
                ],
            ),
        ])
        .expect_err("a repeated npm development edge should be refused");
        assert_eq!(
            npm_dev.to_string(),
            "cli (npm) declares `core` more than once in devDependencies"
        );

        let mut windows = edge(cargo("core"), DependencyKind::Normal);
        windows.target = Some("cfg(windows)".to_string());
        let in_target = Workspace::new([
            package(cargo("core"), vec![]),
            package(cargo("cli"), vec![windows.clone(), windows]),
        ])
        .expect_err("a repeated edge inside one target table should be refused");
        assert_eq!(
            in_target.to_string(),
            "cli (cargo) declares `core` more than once in [target.'cfg(windows)'.dependencies]"
        );
    }

    /// `Display` is reachable only through `KindNotInEcosystem`, so the words are
    /// pinned here directly. The Cargo-optional render has to name the fix rather
    /// than read as "unsupported": Cargo does have optional dependencies, and a
    /// reader told otherwise may delete the flag instead of the wrong kind.
    #[test]
    fn every_kind_renders_its_own_word() {
        for (kind, word) in [
            (DependencyKind::Normal, "normal"),
            (DependencyKind::Peer, "peer"),
            (DependencyKind::Optional, "optional"),
            (DependencyKind::Build, "build"),
            (DependencyKind::Development, "development"),
        ] {
            assert_eq!(kind.to_string(), word);
        }

        let cargo_optional = WorkspaceError::KindNotInEcosystem {
            dependent: cargo("cli"),
            dependency: cargo("core"),
            kind: DependencyKind::Optional,
        }
        .to_string();
        assert!(
            cargo_optional.contains("`optional = true` entries in [dependencies]"),
            "the message does not name the fix: {cargo_optional}"
        );

        let npm_optional = WorkspaceError::KindNotInEcosystem {
            dependent: npm("cli"),
            dependency: npm("core"),
            kind: DependencyKind::Optional,
        }
        .to_string();
        assert!(
            !npm_optional.contains("optional = true"),
            "npm carries Cargo's advice: {npm_optional}"
        );

        let npm_build = WorkspaceError::KindNotInEcosystem {
            dependent: npm("cli"),
            dependency: npm("core"),
            kind: DependencyKind::Build,
        }
        .to_string();
        assert_eq!(
            npm_build,
            "cli (npm) declares core (npm) with kind build, which npm has no section for"
        );
    }

    /// Plans are compared whole, so order has to come from the ids rather than
    /// from insertion or a hash seed.
    #[test]
    fn packages_iterate_in_id_order_whatever_order_they_arrived_in() {
        let workspace = Workspace::new([
            package(cargo("zephyr"), vec![]),
            package(npm("alpha"), vec![]),
            package(cargo("alpha"), vec![]),
        ])
        .expect("workspace should build");

        let order: Vec<&PackageId> = workspace.packages().map(Package::id).collect();
        assert_eq!(
            order,
            vec![&npm("alpha"), &cargo("alpha"), &cargo("zephyr")]
        );
    }

    /// The pair above ties on name and breaks on ecosystem, which sorts the same
    /// way whichever field leads. This pair does not: name-major would reverse it.
    #[test]
    fn ids_sort_by_ecosystem_before_name() {
        let workspace = Workspace::new([
            package(cargo("alpha"), vec![]),
            package(npm("zephyr"), vec![]),
        ])
        .expect("workspace should build");

        let order: Vec<&PackageId> = workspace.packages().map(Package::id).collect();
        assert_eq!(order, vec![&npm("zephyr"), &cargo("alpha")]);
    }

    /// The publish-time rewrites ADR-0010 records, plus a prerelease case it does
    /// not cover — see `DeclaredRange::expand_tracking` for why the pre survives.
    #[test]
    fn a_tracking_range_publishes_as_adr_0010_says() {
        for (version, exact, tilde, caret) in [
            ("1.5.0", "=1.5.0", "~1.5.0", "^1.5.0"),
            ("1.5.0-rc.1", "=1.5.0-rc.1", "~1.5.0-rc.1", "^1.5.0-rc.1"),
        ] {
            let version = Version::parse(version).expect("test version should parse");
            for (tracking, published) in [
                (Tracking::Exact, exact),
                (Tracking::Tilde, tilde),
                (Tracking::Caret, caret),
            ] {
                assert_eq!(
                    DeclaredRange::expand_tracking(tracking, &version),
                    req(published),
                    "{version} {tracking:?}"
                );
            }
        }
    }

    /// The gate has to be able to fire. Expanding against the version the
    /// dependency is moving *to* would produce a range that contains it.
    #[test]
    fn an_exact_tracking_range_excludes_the_version_it_is_gating() {
        let at_last_tag = Version::new(1, 5, 0);
        let bumped_to = Version::new(1, 6, 0);

        let published = DeclaredRange::expand_tracking(Tracking::Exact, &at_last_tag);
        assert!(!published.matches(&bumped_to));
        assert!(published.matches(&at_last_tag));
    }

    #[test]
    fn workspace_tracking_admits_via_tag_expansion() {
        let at_tag = Version::new(1, 5, 0);
        let same = Version::new(1, 5, 0);
        let minor = Version::new(1, 6, 0);
        let major = Version::new(2, 0, 0);

        let exact = DeclaredRange::WorkspaceTracking(Tracking::Exact);
        assert!(exact.admits(&at_tag, &same));
        assert!(!exact.admits(&at_tag, &minor));

        let tilde = DeclaredRange::WorkspaceTracking(Tracking::Tilde);
        assert!(tilde.admits(&at_tag, &same));
        assert!(!tilde.admits(&at_tag, &minor));

        let caret = DeclaredRange::WorkspaceTracking(Tracking::Caret);
        assert!(caret.admits(&at_tag, &same));
        assert!(caret.admits(&at_tag, &minor));
        assert!(!caret.admits(&at_tag, &major));
    }

    /// A range that carries its own bounds gates on them, whatever the tag says.
    #[test]
    fn a_declared_range_admits_through_the_bounds_it_carries() {
        let moved_on = Version::new(9, 9, 9);
        for range in [
            plain_cargo("^1.5.0"),
            workspace_npm("^1.5.0"),
            catalog_npm(Some("react18"), "^1.5.0"),
        ] {
            assert!(range.admits(&moved_on, &Version::new(1, 5, 0)));
            assert!(!range.admits(&moved_on, &Version::new(2, 0, 0)));
        }
    }

    #[test]
    fn workspace_and_catalog_admit_through_their_carried_req() {
        let at_tag = Version::new(9, 9, 9);

        for range in [workspace_npm("^1.5.0"), catalog_npm(None, "^1.5.0")] {
            assert!(range.admits(&at_tag, &Version::new(1, 5, 0)));
            assert!(!range.admits(&at_tag, &Version::new(2, 0, 0)));
        }

        // Forms VersionReq cannot parse — proves protocol arms use npm Bounds.
        for range in [
            workspace_npm("^1.0.0 || ^2.0.0"),
            catalog_npm(None, "^1.0.0 || ^2.0.0"),
        ] {
            assert!(range.admits(&at_tag, &Version::new(1, 5, 0)));
            assert!(range.admits(&at_tag, &Version::new(2, 1, 0)));
            assert!(!range.admits(&at_tag, &Version::new(3, 0, 0)));
        }

        for range in [
            workspace_npm("1.5.0"),
            catalog_npm(Some("react18"), "1.5.0"),
        ] {
            assert!(range.admits(&at_tag, &Version::new(1, 5, 0)));
            assert!(!range.admits(&at_tag, &Version::new(1, 6, 0)));
        }
    }

    #[test]
    fn path_linked_on_cargo_builds_a_workspace() {
        let mut path = edge(cargo("core"), DependencyKind::Normal);
        path.range = DeclaredRange::PathLinked;
        let workspace = Workspace::new([
            package(cargo("core"), vec![]),
            package(cargo("cli"), vec![path]),
        ])
        .expect("path-linked Cargo edges should build");

        let edge = &workspace.get(&cargo("cli")).expect("cli").dependencies()[0];
        assert!(edge.range.is_path_linked());
        assert_eq!(workspace.dependents(&cargo("core")).count(), 1);
    }

    #[test]
    fn path_linked_never_admits() {
        let at_tag = Version::new(1, 0, 0);
        let next = Version::new(1, 0, 1);
        assert!(!DeclaredRange::PathLinked.admits(&at_tag, &at_tag));
        assert!(!DeclaredRange::PathLinked.admits(&at_tag, &next));
        assert_eq!(DeclaredRange::PathLinked.protocol(), None);
        assert!(DeclaredRange::PathLinked.is_path_linked());
        assert_eq!(
            DeclaredRange::PathLinked.retargeted_text(&Version::new(0, 2, 0)),
            None
        );
    }

    #[test]
    fn retarget_keeps_workspace_prefix_and_skips_tracking() {
        let new = Version::new(0, 2, 0);
        assert_eq!(
            plain_cargo("^0.1.3").retargeted_text(&new).as_deref(),
            Some("^0.2.0")
        );
        assert_eq!(
            workspace_npm("^0.1.3").retargeted_text(&new).as_deref(),
            Some("workspace:^0.2.0")
        );
        assert_eq!(
            DeclaredRange::WorkspaceTracking(Tracking::Caret).retargeted_text(&new),
            None
        );
        assert_eq!(catalog_npm(None, "^0.1.3").retargeted_text(&new), None);
    }

    #[test]
    fn npm_plain_admits_via_js_semver_not_version_req() {
        let at_tag = Version::new(1, 5, 0);
        let range = plain_npm("1.5.0");
        assert!(range.admits(&at_tag, &Version::new(1, 5, 0)));
        assert!(!range.admits(&at_tag, &Version::new(1, 6, 0)));
    }

    #[test]
    fn bare_version_at_declared_range_keeps_ecosystem_meaning() {
        let at_tag = Version::new(1, 5, 0);
        let cargo = plain_cargo("1.5.0");
        let npm = plain_npm("1.5.0");
        assert!(cargo.admits(&at_tag, &Version::new(1, 6, 0)));
        assert!(!npm.admits(&at_tag, &Version::new(1, 6, 0)));
    }

    #[test]
    fn a_range_shape_the_ecosystem_cannot_express_is_refused() {
        let mut path_on_npm = edge(npm("core"), DependencyKind::Normal);
        path_on_npm.range = DeclaredRange::PathLinked;
        assert_eq!(
            Workspace::new([
                package(npm("core"), vec![]),
                package(npm("cli"), vec![path_on_npm]),
            ])
            .expect_err("path-linked is Cargo-only"),
            WorkspaceError::BoundsNotInEcosystem {
                dependent: npm("cli"),
                dependency: npm("core"),
            }
        );

        let mut npm_bounds_on_cargo = edge(cargo("core"), DependencyKind::Normal);
        npm_bounds_on_cargo.range = plain_npm("^1.0.0");
        assert_eq!(
            Workspace::new([
                package(cargo("core"), vec![]),
                package(cargo("cli"), vec![npm_bounds_on_cargo]),
            ])
            .expect_err("npm Bounds on Cargo is refused"),
            WorkspaceError::BoundsNotInEcosystem {
                dependent: cargo("cli"),
                dependency: cargo("core"),
            }
        );

        let mut cargo_bounds_on_npm = edge(npm("core"), DependencyKind::Normal);
        cargo_bounds_on_npm.range = plain_cargo("^1.0.0");
        assert_eq!(
            Workspace::new([
                package(npm("core"), vec![]),
                package(npm("cli"), vec![cargo_bounds_on_npm]),
            ])
            .expect_err("Cargo Bounds on npm is refused"),
            WorkspaceError::BoundsNotInEcosystem {
                dependent: npm("cli"),
                dependency: npm("core"),
            }
        );

        let cargo_bounds = Bounds::from_cargo_text("^1.0.0").expect("cargo");
        for range in [
            DeclaredRange::Workspace(cargo_bounds.clone()),
            DeclaredRange::Catalog {
                name: None,
                bounds: cargo_bounds,
            },
        ] {
            let mut edge = edge(npm("core"), DependencyKind::Normal);
            edge.range = range;
            assert_eq!(
                Workspace::new([
                    package(npm("core"), vec![]),
                    package(npm("cli"), vec![edge]),
                ])
                .expect_err("Cargo Bounds on npm protocol arms is refused"),
                WorkspaceError::BoundsNotInEcosystem {
                    dependent: npm("cli"),
                    dependency: npm("core"),
                }
            );
        }
    }

    /// The row that broke release-plz: a caret on a `0.x` version does not span a
    /// minor bump. A claim about the semver crate, and it decides every cascade
    /// in a pre-1.0 workspace.
    #[test]
    fn a_caret_on_a_zero_major_excludes_the_next_minor() {
        assert!(!req("^0.1.3").matches(&Version::new(0, 2, 0)));
        assert!(req("^1.1.3").matches(&Version::new(1, 2, 0)));
    }

    /// See [`DeclaredRange`]: `1.5.0` and `=1.5.0` are what pnpm and yarn write
    /// for the same `workspace:*` declaration, and Cargo's parser reads the first
    /// as a caret.
    #[test]
    fn cargos_grammar_reads_a_bare_version_as_a_caret() {
        assert_ne!(req("1.5.0"), req("=1.5.0"));
        assert!(req("1.5.0").matches(&Version::new(1, 6, 0)));
        assert!(!req("=1.5.0").matches(&Version::new(1, 6, 0)));
    }

    #[test]
    fn either_route_to_build_time_resolution_reads_as_one() {
        for resolution in [BuildResolution::BinaryTarget, BuildResolution::Declared] {
            assert!(ResolvesDependenciesAt::Build(resolution).is_build());
        }
        assert!(!ResolvesDependenciesAt::Install.is_build());
    }

    /// ADR-0009 turns on this field surviving construction, and ADR-0014 on the
    /// version doing the same. A constructor that dropped either would be the
    /// under-release both exist to prevent.
    #[test]
    fn a_package_keeps_the_version_and_resolution_it_was_built_with() {
        let workspace = Workspace::new([Package::new(
            cargo("cli"),
            Version::new(2, 3, 4),
            ResolvesDependenciesAt::Build(BuildResolution::BinaryTarget),
            true,
            vec![],
        )])
        .expect("workspace should build");

        let cli = workspace.get(&cargo("cli")).expect("cli should be present");
        assert_eq!(cli.version(), &Version::new(2, 3, 4));
        assert_eq!(
            cli.resolves_dependencies_at(),
            ResolvesDependenciesAt::Build(BuildResolution::BinaryTarget)
        );
    }

    #[test]
    fn both_ecosystems_render_their_own_name() {
        assert_eq!(npm("x").to_string(), "x (npm)");
        assert_eq!(cargo("x").to_string(), "x (cargo)");
    }
}