cabinpkg-build 0.16.0

Backend-independent build graph planner for Cabin
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
#[cfg(unix)]
use std::path::Path;

use camino::Utf8Path;

#[cfg(unix)]
use super::lowering::promote_dir;
use super::*;
use cabin_core::{
    Dependency, DependencySource, Package, PackageName, ProfileDefinition, ProfileName,
    ProfileSelection, ResolvedProfile, Target as CoreTarget, TargetName, resolve_profile,
};
use cabin_workspace::{PackageGraph, PackageKind, WorkspacePackage};
use camino::Utf8PathBuf;
use std::collections::BTreeMap;

use cabin_driver::{LoweredAction, LoweredActionKind, lower};

/// Lower a semantic action to inspect the concrete argv / backend
/// kind the Ninja writer will render. Lowering is infallible because
/// the semantic IR already carries UTF-8 paths. These tests anchor
/// on the GNU/Clang dialect, the historic default.
fn lowered(action: &BuildAction) -> LoweredAction {
    lower(Dialect::GnuLike, action)
}

/// The lowered (backend) kind of each action, in graph order.
fn lowered_kinds(bg: &BuildGraph) -> Vec<LoweredActionKind> {
    bg.actions.iter().map(|a| lowered(a).kind).collect()
}

/// Borrow every compile action in the graph, in order.
fn compile_actions(bg: &BuildGraph) -> Vec<&CompileAction> {
    bg.actions
        .iter()
        .filter_map(|a| match a {
            BuildAction::Compile(c) => Some(c),
            _ => None,
        })
        .collect()
}

/// The single link action in the graph.
fn link_action(bg: &BuildGraph) -> &LinkAction {
    bg.actions
        .iter()
        .find_map(|a| match a {
            BuildAction::Link(l) => Some(l),
            _ => None,
        })
        .expect("link action present")
}

/// Primary output of an action (object, library, or executable;
/// the stamp in syntax-only mode).
fn primary_output(action: &BuildAction) -> &Utf8Path {
    match action {
        BuildAction::Compile(c) => match &c.mode {
            CompileMode::Object => &c.object,
            CompileMode::SyntaxOnly { stamp } => stamp,
        },
        BuildAction::Archive(a) => &a.output,
        BuildAction::Link(l) => &l.output,
    }
}

fn dev_profile() -> ResolvedProfile {
    resolve_profile(
        &ProfileSelection::default_dev(),
        &BTreeMap::<ProfileName, ProfileDefinition>::new(),
    )
    .expect("built-in dev resolves")
}

fn release_profile() -> ResolvedProfile {
    resolve_profile(
        &ProfileSelection::release_alias(),
        &BTreeMap::<ProfileName, ProfileDefinition>::new(),
    )
    .expect("built-in release resolves")
}

fn version() -> semver::Version {
    semver::Version::parse("0.1.0").unwrap()
}

fn pkg_name(name: &str) -> PackageName {
    PackageName::new(name).unwrap()
}

fn target_name(name: &str) -> TargetName {
    TargetName::new(name).unwrap()
}

fn target(name: &str, kind: TargetKind, sources: &[&str], deps: &[&str]) -> CoreTarget {
    CoreTarget {
        name: target_name(name),
        kind,
        sources: sources.iter().map(Utf8PathBuf::from).collect(),
        include_dirs: Vec::new(),
        defines: Vec::new(),
        deps: deps.iter().map(|d| (*d).to_owned()).collect(),
        language: Default::default(),
    }
}

fn target_with_includes(
    name: &str,
    kind: TargetKind,
    sources: &[&str],
    includes: &[&str],
    deps: &[&str],
) -> CoreTarget {
    CoreTarget {
        name: target_name(name),
        kind,
        sources: sources.iter().map(Utf8PathBuf::from).collect(),
        include_dirs: includes.iter().map(Utf8PathBuf::from).collect(),
        defines: Vec::new(),
        deps: deps.iter().map(|d| (*d).to_owned()).collect(),
        language: Default::default(),
    }
}

fn dep(name: &str, path: &str) -> Dependency {
    Dependency {
        name: pkg_name(name),
        source: DependencySource::Path(Utf8PathBuf::from(path)),
        kind: cabin_core::DependencyKind::Normal,
        optional: false,
        features: Vec::new(),
        default_features: true,
        condition: None,
    }
}

fn toolchain() -> ResolvedToolchain {
    use cabin_core::{ResolvedTool, ToolKind, ToolSource, ToolSpec};
    ResolvedToolchain {
        cxx: ResolvedTool {
            kind: ToolKind::CxxCompiler,
            path: Utf8PathBuf::from("/usr/bin/g++"),
            spec: ToolSpec::Name("g++".into()),
            source: ToolSource::Default,
        },
        ar: ResolvedTool {
            kind: ToolKind::Archiver,
            path: Utf8PathBuf::from("/usr/bin/ar"),
            spec: ToolSpec::Name("ar".into()),
            source: ToolSource::Default,
        },
        cc: None,
    }
}

/// Toolchain with both compilers resolved. Used by tests that
/// exercise the C compile path or the link-driver pick.
fn toolchain_with_cc() -> ResolvedToolchain {
    use cabin_core::{ResolvedTool, ToolKind, ToolSource, ToolSpec};
    let mut tc = toolchain();
    tc.cc = Some(ResolvedTool {
        kind: ToolKind::CCompiler,
        path: Utf8PathBuf::from("/usr/bin/cc"),
        spec: ToolSpec::Name("cc".into()),
        source: ToolSource::Default,
    });
    tc
}

fn empty_build_flags() -> HashMap<usize, ResolvedProfileFlags> {
    HashMap::new()
}

fn no_language_standards() -> HashMap<usize, cabin_core::ResolvedLanguageStandards> {
    HashMap::new()
}

fn no_flag_conflicts() -> HashMap<usize, Vec<cabin_core::StandardFlagConflict>> {
    HashMap::new()
}

fn make_pkg(
    _name: &str,
    manifest_dir: &str,
    package: Package,
    deps: Vec<usize>,
) -> WorkspacePackage {
    let manifest_dir = PathBuf::from(manifest_dir);
    let manifest_path = manifest_dir.join("cabin.toml");
    WorkspacePackage {
        package,
        manifest_path,
        manifest_dir,
        deps: deps
            .into_iter()
            .map(|index| cabin_workspace::DependencyEdge {
                index,
                kind: cabin_core::DependencyKind::Normal,
                condition: None,
            })
            .collect(),
        kind: PackageKind::Local,
        is_port: false,
    }
}

fn graph_with(
    packages: Vec<WorkspacePackage>,
    primaries: Vec<usize>,
    root: Option<usize>,
) -> PackageGraph {
    let root_dir = packages
        .first()
        .map_or_else(|| PathBuf::from("/abs"), |p| p.manifest_dir.clone());
    let root_manifest = root_dir.join("cabin.toml");
    PackageGraph {
        root_manifest_path: root_manifest,
        root_dir,
        is_workspace_root: false,
        root_package: root,
        root_settings: Default::default(),
        primary_packages: primaries,
        default_members: Vec::new(),
        excluded_members: Vec::new(),
        packages,
    }
}

fn single_package_graph(package: Package, manifest_dir: &str) -> PackageGraph {
    let name = package.name.as_str().to_owned();
    let pkg = make_pkg(&name, manifest_dir, package, vec![]);
    graph_with(vec![pkg], vec![0], Some(0))
}

#[test]
fn plans_single_executable() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let req = PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    };
    let bg = plan(&req).unwrap();
    assert_eq!(bg.actions.len(), 2);
    assert_eq!(
        lowered_kinds(&bg),
        vec![
            LoweredActionKind::CompileCpp,
            LoweredActionKind::LinkExecutable
        ]
    );
    assert_eq!(
        bg.default_outputs,
        vec![Utf8PathBuf::from(
            "/abs/proj/build/dev/packages/hello/hello"
        )]
    );
    let cc = &bg.compile_commands[0];
    assert_eq!(
        cc.output,
        Utf8PathBuf::from("/abs/proj/build/dev/packages/hello/obj/hello/src/main.cc.o")
    );
    assert!(cc.arguments.iter().any(|a| a == "-std=c++17"));
}

#[test]
fn default_selection_without_buildable_targets_errors() {
    // A package whose only target is a `test` (excluded from the
    // default build enumeration) yields no buildable default
    // selection, so `plan` reports `EmptySelectedPackages`.
    let package = Package::new(
        pkg_name("only_tests"),
        version(),
        vec![target("only_tests", TargetKind::Test, &["tests/t.cc"], &[])],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let req = PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    };
    assert!(matches!(plan(&req), Err(BuildError::EmptySelectedPackages)));
}

#[test]
fn compiler_wrapper_prefixes_only_the_ninja_command() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let wrapper = ResolvedCompilerWrapper {
        kind: cabin_core::CompilerWrapperKind::Ccache,
        path: Utf8PathBuf::from("/usr/local/bin/ccache"),
        spec: "ccache".into(),
        source: cabin_core::CompilerWrapperSource::Cli,
        identity: None,
    };
    let req = PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: Some(&wrapper),
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    };
    let bg = plan(&req).unwrap();
    let compile = lowered(
        bg.actions
            .iter()
            .find(|a| matches!(a, BuildAction::Compile(_)))
            .expect("compile action present"),
    );
    assert_eq!(compile.command[0], "/usr/local/bin/ccache");
    assert_eq!(compile.command[1], "/usr/bin/g++");
    let cc = &bg.compile_commands[0];
    // compile_commands.json must keep the underlying compiler
    // first so clangd / IDE tooling continues to recognize the
    // command shape.
    assert_eq!(cc.arguments[0], "/usr/bin/g++");
    // Link / archive paths are never wrapped.
    let link = lowered(
        bg.actions
            .iter()
            .find(|a| matches!(a, BuildAction::Link(_)))
            .expect("link action present"),
    );
    assert_eq!(link.command[0], "/usr/bin/g++");
    assert!(
        !link.command.iter().any(|a| a == "/usr/local/bin/ccache"),
        "wrapper must not appear in link command"
    );
}

#[test]
fn compiler_wrapper_does_not_prefix_c_compile_commands() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.c"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain_with_cc();
    let wrapper = ResolvedCompilerWrapper {
        kind: cabin_core::CompilerWrapperKind::Ccache,
        path: Utf8PathBuf::from("/usr/local/bin/ccache"),
        spec: "ccache".into(),
        source: cabin_core::CompilerWrapperSource::Cli,
        identity: None,
    };
    let req = PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: Some(&wrapper),
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    };
    let bg = plan(&req).unwrap();
    let compile = lowered(
        bg.actions
            .iter()
            .find(|a| matches!(a, BuildAction::Compile(c) if c.standard.language() == SourceLanguage::C))
            .expect("C compile action present"),
    );
    assert_eq!(compile.command[0], "/usr/bin/cc");
    assert!(
        !compile.command.iter().any(|a| a == "/usr/local/bin/ccache"),
        "wrapper must not appear in C compile command"
    );
}

#[test]
fn release_profile_uses_release_flags() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: release_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let cc = &bg.compile_commands[0];
    assert!(cc.arguments.iter().any(|a| a == "-O3"));
    assert!(cc.arguments.iter().any(|a| a == "-DNDEBUG"));
    assert!(!cc.arguments.iter().any(|a| a == "-O0"));
}

#[test]
fn plans_library_then_executable_within_one_package() {
    let package = Package::new(
        pkg_name("multi"),
        version(),
        vec![
            target_with_includes(
                "greet",
                TargetKind::Library,
                &["src/greet.cc"],
                &["include"],
                &[],
            ),
            target(
                "hello",
                TargetKind::Executable,
                &["src/main.cc"],
                &["greet"],
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    assert_eq!(
        lowered_kinds(&bg),
        vec![
            LoweredActionKind::CompileCpp,
            LoweredActionKind::ArchiveStaticLibrary,
            LoweredActionKind::CompileCpp,
            LoweredActionKind::LinkExecutable,
        ]
    );
    let BuildAction::Link(link) = &bg.actions[3] else {
        panic!("expected a link action at index 3");
    };
    assert!(link.inputs.contains(&Utf8PathBuf::from(
        "/abs/proj/build/dev/packages/multi/libgreet.a"
    )));
    let BuildAction::Compile(hello_compile) = &bg.actions[2] else {
        panic!("expected a compile action at index 2");
    };
    // greet's include dir is carried semantically, not yet as argv.
    assert!(
        hello_compile
            .arguments
            .include_dirs
            .contains(&Utf8PathBuf::from("/abs/proj/include"))
    );
}

#[test]
fn cross_package_path_dep_links_library() {
    // greet at /abs/greet, app at /abs/app depending on greet.
    let greet_proj = Package::new(
        pkg_name("greet"),
        version(),
        vec![target_with_includes(
            "greet",
            TargetKind::Library,
            &["src/greet.cc"],
            &["include"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &["greet"],
        )],
        vec![dep("greet", "../greet")],
    )
    .unwrap();
    let greet_pkg = make_pkg("greet", "/abs/greet", greet_proj, vec![]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    let graph = graph_with(vec![greet_pkg, app_pkg], vec![1], Some(1));
    let tc = toolchain();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();

    // Outputs should be namespaced by package.
    let greet_lib = Utf8PathBuf::from("/abs/build/dev/packages/greet/libgreet.a");
    let app_exe = Utf8PathBuf::from("/abs/build/dev/packages/app/app");
    // app's link action must include greet's static archive.
    let link = link_action(&bg);
    assert!(link.inputs.contains(&greet_lib));
    assert_eq!(link.output, app_exe);

    // Default outputs are only the primary package's targets (app).
    assert_eq!(bg.default_outputs, vec![app_exe]);

    // greet's include dir should propagate into app's compile action.
    let app_compile = compile_actions(&bg)
        .into_iter()
        // Normalize separators: object paths join with `\` on Windows.
        .find(|c| c.object.as_str().replace('\\', "/").contains("/app/"))
        .expect("app compile action present");
    assert!(
        app_compile
            .arguments
            .include_dirs
            .contains(&Utf8PathBuf::from("/abs/greet/include"))
    );
    // A plain path dependency is the user's own code: nothing routes
    // to the system bucket.
    assert!(app_compile.arguments.system_include_dirs.is_empty());
}

/// Two-package fixture for the include-provenance tests: local `app`
/// (executable) depends on `greet` (library with an `include` dir),
/// with greet's provenance set by the caller.
fn provenance_graph(greet_kind: PackageKind, greet_is_port: bool) -> PackageGraph {
    let greet_proj = Package::new(
        pkg_name("greet"),
        version(),
        vec![target_with_includes(
            "greet",
            TargetKind::Library,
            &["src/greet.cc"],
            &["include"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &["greet"],
        )],
        vec![dep("greet", "../greet")],
    )
    .unwrap();
    let mut greet_pkg = make_pkg("greet", "/abs/greet", greet_proj, vec![]);
    greet_pkg.kind = greet_kind;
    greet_pkg.is_port = greet_is_port;
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    graph_with(vec![greet_pkg, app_pkg], vec![1], Some(1))
}

/// The compile action whose object path contains `marker`
/// (separator-normalized for Windows object paths).
fn compile_for<'a>(bg: &'a BuildGraph, marker: &str) -> &'a CompileAction {
    compile_actions(bg)
        .into_iter()
        .find(|c| c.object.as_str().replace('\\', "/").contains(marker))
        .expect("compile action present")
}

fn plan_provenance_graph(
    graph: &PackageGraph,
    dialect: Dialect,
    msvc_external_includes: bool,
) -> BuildGraph {
    let tc = toolchain();
    plan(&PlanRequest {
        graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect,
        msvc_external_includes,
    })
    .unwrap()
}

#[test]
fn registry_dep_include_dirs_become_system_includes() {
    // greet is an extracted registry archive: third-party code whose
    // headers the user cannot fix, so its include dir routes to the
    // system bucket (`-isystem`) on the consumer's compiles.
    let graph = provenance_graph(PackageKind::Registry, false);
    let bg = plan_provenance_graph(&graph, Dialect::GnuLike, true);

    let app_compile = compile_for(&bg, "/app/");
    let greet_include = Utf8PathBuf::from("/abs/greet/include");
    assert!(
        app_compile
            .arguments
            .system_include_dirs
            .contains(&greet_include)
    );
    assert!(!app_compile.arguments.include_dirs.contains(&greet_include));

    // Building greet itself keeps its own headers as user includes:
    // a package always sees its own code under `-I`.
    let greet_compile = compile_for(&bg, "/greet/");
    assert!(
        greet_compile
            .arguments
            .include_dirs
            .contains(&greet_include)
    );
    assert!(greet_compile.arguments.system_include_dirs.is_empty());

    // The compile database spells the system bucket as `-isystem`.
    let cc = bg
        .compile_commands
        .iter()
        .find(|c| c.output.as_str().replace('\\', "/").contains("/app/"))
        .expect("app compile command present");
    let isystem = cc
        .arguments
        .iter()
        .position(|a| a == "-isystem")
        .expect("-isystem present");
    // Normalize separators: the planner joins include dirs with `\`
    // on Windows.
    assert_eq!(
        cc.arguments[isystem + 1].replace('\\', "/"),
        "/abs/greet/include"
    );
}

#[test]
fn port_dep_include_dirs_become_system_includes() {
    // Foundation ports are trust-local (their flags come from the
    // curated recipe) but code-wise third-party upstream sources, so
    // their headers take the system bucket like registry packages.
    let graph = provenance_graph(PackageKind::Local, true);
    let bg = plan_provenance_graph(&graph, Dialect::GnuLike, true);
    let app_compile = compile_for(&bg, "/app/");
    let greet_include = Utf8PathBuf::from("/abs/greet/include");
    assert!(
        app_compile
            .arguments
            .system_include_dirs
            .contains(&greet_include)
    );
    assert!(!app_compile.arguments.include_dirs.contains(&greet_include));
}

#[test]
fn msvc_with_external_support_keeps_system_includes() {
    let graph = provenance_graph(PackageKind::Registry, false);
    let bg = plan_provenance_graph(&graph, Dialect::Msvc, true);
    let app_compile = compile_for(&bg, "/app/");
    assert!(
        app_compile
            .arguments
            .system_include_dirs
            .contains(&Utf8PathBuf::from("/abs/greet/include"))
    );
    let cc = bg
        .compile_commands
        .iter()
        .find(|c| c.output.as_str().replace('\\', "/").contains("/app/"))
        .expect("app compile command present");
    assert!(cc.arguments.iter().any(|a| a == "/external:W0"));
    let ext = cc
        .arguments
        .iter()
        .position(|a| a == "/external:I")
        .expect("/external:I present");
    // Normalize separators: the planner joins include dirs with `\`
    // on Windows.
    assert_eq!(
        cc.arguments[ext + 1].replace('\\', "/"),
        "/abs/greet/include"
    );
}

#[test]
fn msvc_without_external_support_collapses_system_includes() {
    // A `cl` older than VS2019 16.10 rejects `/external:I`, so the
    // planner falls back to spelling every dependency include dir as
    // a plain `/I` — exactly the pre-system-include behavior.
    let graph = provenance_graph(PackageKind::Registry, false);
    let bg = plan_provenance_graph(&graph, Dialect::Msvc, false);
    let app_compile = compile_for(&bg, "/app/");
    let greet_include = Utf8PathBuf::from("/abs/greet/include");
    assert!(app_compile.arguments.system_include_dirs.is_empty());
    assert!(app_compile.arguments.include_dirs.contains(&greet_include));
    let cc = bg
        .compile_commands
        .iter()
        .find(|c| c.output.as_str().replace('\\', "/").contains("/app/"))
        .expect("app compile command present");
    assert!(!cc.arguments.iter().any(|a| a.starts_with("/external:")));
}

#[test]
fn flag_system_include_dirs_route_to_system_bucket() {
    // `ResolvedProfileFlags::system_include_dirs` (the pkg-config
    // contribution) lands in the compile's system bucket.
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let mut flags = HashMap::new();
    flags.insert(
        0,
        ResolvedProfileFlags {
            system_include_dirs: vec![Utf8PathBuf::from("/opt/zlib/include")],
            ..Default::default()
        },
    );
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &flags,
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/proj/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let compile = compile_for(&bg, "/hello/");
    assert!(
        compile
            .arguments
            .system_include_dirs
            .contains(&Utf8PathBuf::from("/opt/zlib/include"))
    );
    assert!(
        !compile
            .arguments
            .include_dirs
            .contains(&Utf8PathBuf::from("/opt/zlib/include"))
    );
}

#[test]
fn link_libs_propagate_to_consumer_link_after_archives() {
    // A library package declares `link-libs` (resolved into its
    // per-package build flags); an executable in another package
    // depends on it. The library's system libraries must appear on
    // the *executable's* link line, emitted as `-l<name>` AFTER the
    // library archive so GNU `ld`'s left-to-right resolution finds
    // them. macOS/libSystem resolves regardless of order, so this
    // plan-level assertion is what actually guards the ordering.
    let crypto_proj = Package::new(
        pkg_name("crypto"),
        version(),
        vec![target(
            "crypto",
            TargetKind::Library,
            &["src/crypto.c"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target(
            "app",
            TargetKind::Executable,
            &["src/main.c"],
            &["crypto"],
        )],
        vec![dep("crypto", "../crypto")],
    )
    .unwrap();
    let crypto_pkg = make_pkg("crypto", "/abs/crypto", crypto_proj, vec![]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    let graph = graph_with(vec![crypto_pkg, app_pkg], vec![1], Some(1));
    let tc = toolchain_with_cc();

    // crypto (package index 0) requires `-lpthread -lm`.
    let mut build_flags: HashMap<usize, ResolvedProfileFlags> = HashMap::new();
    build_flags.insert(
        0,
        ResolvedProfileFlags {
            link_libs: vec!["pthread".to_owned(), "m".to_owned()],
            ..Default::default()
        },
    );

    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &build_flags,
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();

    let link = link_action(&bg);
    assert_eq!(
        link.link_libs,
        vec!["pthread".to_owned(), "m".to_owned()],
        "library link-libs propagate to the consumer link as bare names"
    );
    assert!(
        link.arguments.is_empty(),
        "`arguments` carries only ldflags; link-libs live in their own field, got {:?}",
        link.arguments
    );

    // Order check on the fully lowered GNU argv: the archive input
    // must precede the `-l` flags the dialect layer spells.
    let argv = lowered(&BuildAction::Link(link.clone())).command;
    let archive_pos = argv
        .iter()
        .position(|a| a.replace('\\', "/").ends_with("/libcrypto.a"))
        .expect("crypto archive on link line");
    let lpthread_pos = argv
        .iter()
        .position(|a| a == "-lpthread")
        .expect("-lpthread on link line");
    assert!(
        archive_pos < lpthread_pos,
        "archive must precede -lpthread for GNU ld; argv = {argv:?}"
    );
}

#[test]
fn qualified_target_selector_picks_specific_target() {
    let greet_proj = Package::new(
        pkg_name("greet"),
        version(),
        vec![target("greet", TargetKind::Library, &["src/greet.cc"], &[])],
        Vec::new(),
    )
    .unwrap();
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![
            target("app", TargetKind::Executable, &["src/main.cc"], &["greet"]),
            target("other", TargetKind::Executable, &["src/other.cc"], &[]),
        ],
        vec![dep("greet", "../greet")],
    )
    .unwrap();
    let greet_pkg = make_pkg("greet", "/abs/greet", greet_proj, vec![]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    let graph = graph_with(vec![greet_pkg, app_pkg], vec![1], Some(1));
    let tc = toolchain();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("app:app")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    // Only app:app and greet:greet should appear; not app:other.
    let outs: Vec<String> = bg
        .actions
        .iter()
        // Normalize separators: output paths join with `\` on Windows.
        .map(|a| primary_output(a).to_string().replace('\\', "/"))
        .collect();
    assert!(outs.iter().any(|o| o.ends_with("/packages/app/app")));
    assert!(!outs.iter().any(|o| o.contains("/packages/app/other")));
}

#[test]
fn ambiguous_unqualified_target_errors() {
    // Workspace with two member packages each having a target "build".
    let a = Package::new(
        pkg_name("a"),
        version(),
        vec![target("build", TargetKind::Executable, &["a.cc"], &[])],
        Vec::new(),
    )
    .unwrap();
    let b = Package::new(
        pkg_name("b"),
        version(),
        vec![target("build", TargetKind::Executable, &["b.cc"], &[])],
        Vec::new(),
    )
    .unwrap();
    let pkg_a = make_pkg("a", "/abs/a", a, vec![]);
    let pkg_b = make_pkg("b", "/abs/b", b, vec![]);
    let mut graph = graph_with(vec![pkg_a, pkg_b], vec![0, 1], None);
    graph.is_workspace_root = true;
    let tc = toolchain();
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("build")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    assert!(matches!(err, BuildError::AmbiguousTarget(_, _)));
}

#[test]
fn unknown_package_in_qualified_selector_errors() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("nope:thing")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    assert!(matches!(
        err,
        BuildError::UnknownPackageInTargetSelector { .. }
    ));
}

#[test]
fn target_dep_cycle_within_package_is_reported() {
    let package = Package {
        name: pkg_name("cyc"),
        version: version(),
        targets: vec![
            target("a", TargetKind::Library, &["a.cc"], &["b"]),
            target("b", TargetKind::Library, &["b.cc"], &["a"]),
        ],
        dependencies: Vec::new(),
        system_dependencies: Vec::new(),
        features: Default::default(),
        profiles: Default::default(),
        toolchain: Default::default(),
        build: Default::default(),
        language: Default::default(),
        compiler_wrapper: Default::default(),
        patches: Default::default(),
    };
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    match err {
        BuildError::DependencyCycle(cycle) => {
            assert_eq!(cycle.first(), cycle.last());
            assert!(cycle.iter().any(|s| s == "cyc:a"));
            assert!(cycle.iter().any(|s| s == "cyc:b"));
        }
        other => panic!("expected DependencyCycle, got {other:?}"),
    }
}

#[test]
fn unknown_target_in_qualified_selector_errors() {
    let package = Package::new(
        pkg_name("hello"),
        version(),
        vec![target(
            "hello",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("hello:missing")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    assert!(matches!(err, BuildError::UnknownTargetInPackage { .. }));
}

/// Helper: the lowered link-action argv of a planned graph, so
/// tests can assert on `command[0]` (the chosen driver). Panics if
/// no link action is present.
fn link_command(bg: &BuildGraph) -> Vec<String> {
    let action = bg
        .actions
        .iter()
        .find(|a| matches!(a, BuildAction::Link(_)))
        .expect("link action present");
    lowered(action).command
}

#[test]
fn link_driver_is_c_when_target_has_only_c_sources() {
    // A pure-C executable must link through the C driver so
    // the C++ runtime is not pulled in.
    let package = Package::new(
        pkg_name("cdemo"),
        version(),
        vec![target(
            "cdemo_exe",
            TargetKind::Executable,
            &["src/main.c"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/cdemo");
    let tc = toolchain_with_cc();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/cdemo/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let link = link_command(&bg);
    assert_eq!(link[0], "/usr/bin/cc");
}

#[test]
fn link_driver_is_cxx_when_target_has_any_cpp_source() {
    // Mixed C/C++ executable in a single target must link
    // through the C++ driver because the closure has C++
    // objects.
    let package = Package::new(
        pkg_name("mixed"),
        version(),
        vec![target(
            "mixed_exe",
            TargetKind::Executable,
            &["src/c_part.c", "src/cpp_part.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/mixed");
    let tc = toolchain_with_cc();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/mixed/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let link = link_command(&bg);
    assert_eq!(link[0], "/usr/bin/g++");
}

#[test]
fn link_driver_is_cxx_when_dependency_has_cpp_objects() {
    // Pure-C executable that links a C++ static library
    // must use the C++ driver — the runtime is required
    // because the library carries C++ objects.
    let cpp_lib = target("cppcore", TargetKind::Library, &["src/cpp_part.cc"], &[]);
    let c_exe = target(
        "c_runner",
        TargetKind::Executable,
        &["src/main.c"],
        &["cppcore"],
    );
    let package = Package::new(
        pkg_name("interop"),
        version(),
        vec![cpp_lib, c_exe],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/interop");
    let tc = toolchain_with_cc();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/interop/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("c_runner")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let link = link_command(&bg);
    assert_eq!(link[0], "/usr/bin/g++");
}

#[test]
fn link_driver_stays_c_when_dependency_is_also_pure_c() {
    // C executable + C library: still link through the C
    // driver because the closure has no C++ objects.
    let c_lib = target("ccore", TargetKind::Library, &["src/util.c"], &[]);
    let c_exe = target(
        "c_runner",
        TargetKind::Executable,
        &["src/main.c"],
        &["ccore"],
    );
    let package = Package::new(
        pkg_name("clib_only"),
        version(),
        vec![c_lib, c_exe],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/clib_only");
    let tc = toolchain_with_cc();
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/clib_only/build"),
        profile: dev_profile(),
        selected: Some(vec![ManifestTargetSelector::parse("c_runner")]),
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let link = link_command(&bg);
    assert_eq!(link[0], "/usr/bin/cc");
}

#[test]
fn missing_c_compiler_yields_actionable_error_with_target_id() {
    // C source + no `cc` resolved → MissingCCompiler error
    // that names both the package and the target so a
    // monorepo user can map the failure to the right
    // manifest.
    let package = Package::new(
        pkg_name("cdemo"),
        version(),
        vec![target(
            "cdemo_exe",
            TargetKind::Executable,
            &["src/main.c"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/cdemo");
    let tc = toolchain(); // no cc populated
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/cdemo/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    let rendered = err.to_string();
    assert!(
        rendered.contains("cdemo:cdemo_exe"),
        "error should name the package:target, got: {rendered}"
    );
    assert!(
        rendered.contains("CC") || rendered.contains("`--cc"),
        "error should suggest how to set the C compiler, got: {rendered}"
    );
}

#[test]
fn unrecognized_source_extension_yields_actionable_error() {
    let package = Package::new(
        pkg_name("broken"),
        version(),
        vec![target(
            "broken",
            TargetKind::Library,
            &["src/file.txt"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/broken");
    let tc = toolchain_with_cc();
    let err = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/broken/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap_err();
    let rendered = err.to_string();
    assert!(
        rendered.contains("broken:broken"),
        "error should name package:target, got: {rendered}"
    );
    assert!(
        rendered.contains(".c") && rendered.contains(".cc"),
        "error should enumerate the supported extensions, got: {rendered}"
    );
}

// The standard-flag-per-language and profile-flag ordering is now
// owned and tested by `cabin-driver`'s GNU/Clang lowering; the
// planner tests below assert it end-to-end through the lowered
// `compile_commands` argv instead.

/// Build a single-package graph with a `mixed` library
/// target carrying one C source and one C++ source. Used by
/// the per-language flag-routing tests below.
fn graph_with_mixed_sources() -> PackageGraph {
    let package = Package::new(
        pkg_name("mixed"),
        version(),
        vec![target(
            "mixed",
            TargetKind::Library,
            &["src/c_part.c", "src/cpp_part.cc"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap();
    single_package_graph(package, "/abs/mixed")
}

/// Build per-package flag map carrying a single
/// `ResolvedProfileFlags` for the mixed package.
fn build_flags_map(flags: ResolvedProfileFlags) -> HashMap<usize, ResolvedProfileFlags> {
    let mut out = HashMap::new();
    out.insert(0usize, flags);
    out
}

/// Plan and return the compile actions for the mixed
/// fixture under the supplied build flags. Used by every
/// per-language flag-routing test below to keep the
/// boilerplate to one place.
fn plan_compile_actions(flags: ResolvedProfileFlags) -> Vec<CompileAction> {
    let graph = graph_with_mixed_sources();
    let tc = toolchain_with_cc();
    let map = build_flags_map(flags);
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &map,
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/mixed/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    bg.actions
        .into_iter()
        .filter_map(|a| match a {
            BuildAction::Compile(c) => Some(c),
            _ => None,
        })
        .collect()
}

fn compile_action_for(actions: &[CompileAction], language: SourceLanguage) -> &CompileAction {
    actions
        .iter()
        .find(|c| c.standard.language() == language)
        .unwrap_or_else(|| panic!("expected a {language:?} compile action"))
}

#[test]
fn cflags_route_to_c_compile_only() {
    // The C-only escape-hatch reaches every C compile
    // command and never reaches a C++ compile. Without this
    // routing, a flag that is invalid for C++ (`-std=c99`,
    // `-Wno-pointer-sign`) would break C++ builds.
    let flags = ResolvedProfileFlags {
        cflags: vec!["-DC_ONLY_FLAG=1".to_owned()],
        ..ResolvedProfileFlags::default()
    };
    let actions = plan_compile_actions(flags);
    let c = compile_action_for(&actions, SourceLanguage::C);
    let cxx = compile_action_for(&actions, SourceLanguage::Cxx);
    assert!(
        c.arguments
            .extra_flags
            .iter()
            .any(|a| a == "-DC_ONLY_FLAG=1"),
        "C compile must include the C-only define, got: {:?}",
        c.arguments.extra_flags
    );
    assert!(
        !cxx.arguments
            .extra_flags
            .iter()
            .any(|a| a == "-DC_ONLY_FLAG=1"),
        "C-only define must NOT leak into the C++ compile, got: {:?}",
        cxx.arguments.extra_flags
    );
}

#[test]
fn cxxflags_route_to_cxx_compile_only() {
    // Mirror of the C-only test: a C++-only flag never
    // reaches the C compile command. Required so a flag
    // that is invalid for C (`-fno-rtti`, `-std=c++20`)
    // does not break C builds.
    let flags = ResolvedProfileFlags {
        cxxflags: vec!["-DCXX_ONLY_FLAG=1".to_owned()],
        ..ResolvedProfileFlags::default()
    };
    let actions = plan_compile_actions(flags);
    let c = compile_action_for(&actions, SourceLanguage::C);
    let cxx = compile_action_for(&actions, SourceLanguage::Cxx);
    assert!(
        cxx.arguments
            .extra_flags
            .iter()
            .any(|a| a == "-DCXX_ONLY_FLAG=1"),
        "C++ compile must include the C++-only define, got: {:?}",
        cxx.arguments.extra_flags
    );
    assert!(
        !c.arguments
            .extra_flags
            .iter()
            .any(|a| a == "-DCXX_ONLY_FLAG=1"),
        "C++-only define must NOT leak into the C compile, got: {:?}",
        c.arguments.extra_flags
    );
}

#[test]
fn language_neutral_extra_compile_args_reach_both_compile_kinds() {
    // The language-neutral slot is the documented home for
    // flags that are valid for both C/C++. It must
    // appear on every compile command.
    let flags = ResolvedProfileFlags {
        extra_compile_args: vec!["-Wall".to_owned()],
        ..ResolvedProfileFlags::default()
    };
    let actions = plan_compile_actions(flags);
    let c = compile_action_for(&actions, SourceLanguage::C);
    let cxx = compile_action_for(&actions, SourceLanguage::Cxx);
    assert!(
        c.arguments.extra_flags.iter().any(|a| a == "-Wall"),
        "C compile must include the language-neutral flag, got: {:?}",
        c.arguments.extra_flags
    );
    assert!(
        cxx.arguments.extra_flags.iter().any(|a| a == "-Wall"),
        "C++ compile must include the language-neutral flag, got: {:?}",
        cxx.arguments.extra_flags
    );
}

#[test]
fn ldflags_appear_on_link_command_only() {
    // Link-only flags must reach every link command and
    // never appear on a compile command.
    let package = Package::new(
        pkg_name("mixed"),
        version(),
        vec![
            target(
                "mixedlib",
                TargetKind::Library,
                &["src/c_part.c", "src/cpp_part.cc"],
                &[],
            ),
            target(
                "app",
                TargetKind::Executable,
                &["src/main.cc"],
                &["mixedlib"],
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/mixed");
    let tc = toolchain_with_cc();
    let mut map = HashMap::new();
    let flags = ResolvedProfileFlags {
        ldflags: vec!["-Wl,--as-needed".to_owned()],
        ..ResolvedProfileFlags::default()
    };
    map.insert(0usize, flags);
    let bg = plan(&PlanRequest {
        graph: &graph,
        toolchain: &tc,
        build_flags: &map,
        language_standards: &no_language_standards(),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/mixed/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect: Dialect::GnuLike,
        msvc_external_includes: true,
    })
    .unwrap();
    let link = link_action(&bg);
    assert!(
        link.arguments.iter().any(|a| a == "-Wl,--as-needed"),
        "link command must include the link-only flag, got: {:?}",
        link.arguments
    );
    for compile in compile_actions(&bg) {
        // The link-only flag must not leak anywhere into the
        // lowered compile argv.
        let command = lowered(&BuildAction::Compile(compile.clone())).command;
        assert!(
            !command.iter().any(|a| a == "-Wl,--as-needed"),
            "link-only flag must NOT appear on compile, got: {command:?}",
        );
    }
}

#[cfg(unix)]
#[test]
fn promote_dir_rejects_non_utf8() {
    use std::os::unix::ffi::OsStrExt;
    // A non-UTF-8 build or manifest directory cannot anchor the
    // UTF-8 build model, so the planner rejects it with a typed
    // error rather than lossily promoting it.
    let p = Path::new(std::ffi::OsStr::from_bytes(b"/tmp/\xff/build"));
    assert!(matches!(promote_dir(p), Err(BuildError::NonUtf8Path(_))));
}

// ---------------------------------------------------------------------------
// language standards
// ---------------------------------------------------------------------------

/// Per-package effective standards for `graph`, mirroring the CLI's
/// `resolve_per_package_language_standards` loop.
fn standards_for(graph: &PackageGraph) -> HashMap<usize, cabin_core::ResolvedLanguageStandards> {
    graph
        .packages
        .iter()
        .enumerate()
        .map(|(idx, pkg)| {
            (
                idx,
                cabin_core::resolve_language_standards(&pkg.package.language),
            )
        })
        .collect()
}

fn plan_with_standards(graph: &PackageGraph, dialect: Dialect) -> Result<BuildGraph, BuildError> {
    let tc = toolchain_with_cc();
    plan(&PlanRequest {
        graph,
        toolchain: &tc,
        build_flags: &empty_build_flags(),
        language_standards: &standards_for(graph),
        standard_flag_conflicts: &no_flag_conflicts(),
        build_dir: PathBuf::from("/abs/build"),
        profile: dev_profile(),
        selected: None,
        configuration: None,
        selected_packages: None,
        compiler_wrapper: None,
        dialect,
        msvc_external_includes: true,
    })
}

fn target_with_language(
    name: &str,
    kind: TargetKind,
    sources: &[&str],
    deps: &[&str],
    language: cabin_core::LanguageStandardSettings,
) -> CoreTarget {
    let mut t = target(name, kind, sources, deps);
    t.language = language;
    t
}

#[test]
fn compile_actions_carry_per_target_effective_standards() {
    use cabin_core::{
        CStandard, CxxStandard, LanguageStandard, LanguageStandardSettings, StandardDeclaration,
    };
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target_with_language(
                "core",
                TargetKind::Library,
                &["src/core.cc"],
                &[],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                    // Keep the interface at the package default so the
                    // c++14 consumer below stays compatible.
                    interface_cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx14)),
                    ..Default::default()
                },
            ),
            target(
                "app",
                TargetKind::Executable,
                &["src/main.cc", "src/util.c"],
                &["core"],
            ),
        ],
        Vec::new(),
    )
    .unwrap()
    .with_language(LanguageStandardSettings {
        cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx14)),
        ..Default::default()
    });
    let graph = single_package_graph(package, "/abs/proj");
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();

    // `core` overrides the package default with c++20.
    let core_compile = compile_for(&bg, "/core/");
    assert_eq!(
        core_compile.standard,
        LanguageStandard::Cxx(CxxStandard::Cxx20)
    );
    // `app`'s C++ source inherits the package-level c++14; its C
    // source falls back to the built-in default c11.
    let compiles = compile_actions(&bg);
    let app_cxx = compiles
        .iter()
        .find(|c| c.source.as_str().ends_with("main.cc"))
        .unwrap();
    assert_eq!(app_cxx.standard, LanguageStandard::Cxx(CxxStandard::Cxx14));
    let app_c = compiles
        .iter()
        .find(|c| c.source.as_str().ends_with("util.c"))
        .unwrap();
    assert_eq!(app_c.standard, LanguageStandard::C(CStandard::C11));
    // The lowered compile database spells both.
    let cc = bg
        .compile_commands
        .iter()
        .find(|c| c.file.as_str().ends_with("main.cc"))
        .unwrap();
    assert!(cc.arguments.iter().any(|a| a == "-std=c++14"));
}

#[test]
fn msvc_dialect_rejects_standards_without_stable_flag() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![target_with_language(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &[],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx23)),
                ..Default::default()
            },
        )],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    // Planning records the violation (deferred so `cabin check` can
    // prune dependency compiles first) and omits the un-lowerable
    // compile-commands entry; surfacing it is
    // `validate_planned_standards`' job.
    let bg = plan_with_standards(&graph, Dialect::Msvc).unwrap();
    assert_eq!(bg.standard_violations.len(), 1);
    assert!(matches!(
        &bg.standard_violations[0],
        crate::StandardViolation::MsvcSpelling {
            standard: "c++23",
            ..
        }
    ));
    assert!(
        bg.compile_commands.is_empty(),
        "a compile without a stable /std: flag has no lowerable argv"
    );
    let err = crate::validate_planned_standards(&bg).unwrap_err();
    match err {
        BuildError::StandardUnsupportedOnMsvcDialect { standard, .. } => {
            assert_eq!(standard, "c++23");
        }
        other => panic!("expected StandardUnsupportedOnMsvcDialect, got {other}"),
    }
    // The same plan succeeds on the GNU dialect, with no violations
    // and a normal compile-commands entry.
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();
    assert!(bg.standard_violations.is_empty());
    assert_eq!(bg.compile_commands.len(), 1);
    crate::validate_planned_standards(&bg).unwrap();
}

#[test]
fn interface_requirement_blocks_lower_consumer() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target_with_language(
                "core",
                TargetKind::Library,
                &["src/core.cc"],
                &[],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                    ..Default::default()
                },
            ),
            target_with_language(
                "app",
                TargetKind::Executable,
                &["src/main.cc"],
                &["core"],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                    ..Default::default()
                },
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    // Planning records the incompatibility (deferred so the
    // `cabin check` rewrite can prune dependency compiles first);
    // surfacing it is `validate_planned_standards`' job.
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();
    assert_eq!(bg.standard_violations.len(), 1);
    let err = crate::validate_planned_standards(&bg).unwrap_err();
    match err {
        BuildError::IncompatibleLanguageStandard {
            consumer,
            dependency,
            required,
            requirement_source,
            ..
        } => {
            assert_eq!(consumer, "demo:app");
            assert_eq!(dependency, "demo:core");
            assert_eq!(required, "c++20");
            assert!(
                requirement_source.contains("effective implementation standard"),
                "unexpected source: {requirement_source}"
            );
        }
        other => panic!("expected IncompatibleLanguageStandard, got {other}"),
    }
}

#[test]
fn interface_override_unblocks_consumer() {
    use cabin_core::{
        CxxStandard, LanguageStandard, LanguageStandardSettings, StandardDeclaration,
    };
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target_with_language(
                "core",
                TargetKind::Library,
                &["src/core.cc"],
                &[],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                    interface_cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                    ..Default::default()
                },
            ),
            target_with_language(
                "app",
                TargetKind::Executable,
                &["src/main.cc"],
                &["core"],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                    ..Default::default()
                },
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();
    // The library's own objects still compile with its declared c++20
    // implementation standard.
    let core_compile = compile_for(&bg, "/core/");
    assert_eq!(
        core_compile.standard,
        LanguageStandard::Cxx(CxxStandard::Cxx20)
    );
}

#[test]
fn pure_c_dependency_imposes_no_cxx_requirement() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target("clib", TargetKind::Library, &["src/clib.c"], &[]),
            target_with_language(
                "app",
                TargetKind::Executable,
                &["src/main.cc"],
                &["clib"],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx14)),
                    ..Default::default()
                },
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    // The undeclared C library's built-in c11 is irrelevant to the
    // consumer's C++ side, and `app` compiles no C sources, so its
    // effective C standard never compares against the dependency.
    plan_with_standards(&graph, Dialect::GnuLike).unwrap();
}

#[test]
fn package_level_implementation_default_creates_no_relevance() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    // Dependency package declares a package-level cxx-standard, but
    // its library target carries only C sources: no C++ relevance,
    // so the c++17-default consumer plans fine.
    let dep_proj = Package::new(
        pkg_name("greet"),
        version(),
        vec![target("greet", TargetKind::Library, &["src/greet.c"], &[])],
        Vec::new(),
    )
    .unwrap()
    .with_language(LanguageStandardSettings {
        cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
        ..Default::default()
    });
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &["greet"],
        )],
        vec![dep("greet", "../greet")],
    )
    .unwrap();
    let greet_pkg = make_pkg("greet", "/abs/greet", dep_proj, vec![]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    let graph = graph_with(vec![greet_pkg, app_pkg], vec![1], Some(1));
    plan_with_standards(&graph, Dialect::GnuLike).unwrap();
}

#[test]
fn header_only_package_interface_standard_binds_consumers() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    let dep_proj = Package::new(
        pkg_name("hdrs"),
        version(),
        vec![target_with_includes(
            "hdrs",
            TargetKind::HeaderOnly,
            &[],
            &["include"],
            &[],
        )],
        Vec::new(),
    )
    .unwrap()
    .with_language(LanguageStandardSettings {
        interface_cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
        ..Default::default()
    });
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &["hdrs"],
        )],
        vec![dep("hdrs", "../hdrs")],
    )
    .unwrap();
    let hdrs_pkg = make_pkg("hdrs", "/abs/hdrs", dep_proj, vec![]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![0]);
    let graph = graph_with(vec![hdrs_pkg, app_pkg], vec![1], Some(1));
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();
    assert_eq!(bg.standard_violations.len(), 1);
    let err = crate::validate_planned_standards(&bg).unwrap_err();
    match err {
        BuildError::IncompatibleLanguageStandard {
            dependency,
            required,
            requirement_source,
            ..
        } => {
            assert_eq!(dependency, "hdrs:hdrs");
            assert_eq!(required, "c++20");
            assert!(
                requirement_source.contains("package-level interface standard"),
                "unexpected source: {requirement_source}"
            );
        }
        other => panic!("expected IncompatibleLanguageStandard, got {other}"),
    }
}

#[test]
fn dependency_internal_interface_violation_is_pruned_by_check() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    // app (c++20) -> liba (impl c++17) -> libb (interface c++20):
    // the incompatible pair is liba/libb, recorded on liba's compile.
    // `cabin build` of app surfaces it; `cabin check` of app prunes
    // liba's compiles and with them the violation.
    let leaf_proj = Package::new(
        pkg_name("libb"),
        version(),
        vec![target_with_language(
            "libb",
            TargetKind::Library,
            &["src/b.cc"],
            &[],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                ..Default::default()
            },
        )],
        Vec::new(),
    )
    .unwrap();
    let mid_proj = Package::new(
        pkg_name("liba"),
        version(),
        vec![target_with_language(
            "liba",
            TargetKind::Library,
            &["src/a.cc"],
            &["libb"],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                ..Default::default()
            },
        )],
        vec![dep("libb", "../libb")],
    )
    .unwrap();
    let app_proj = Package::new(
        pkg_name("app"),
        version(),
        vec![target_with_language(
            "app",
            TargetKind::Executable,
            &["src/main.cc"],
            &["liba"],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                ..Default::default()
            },
        )],
        vec![dep("liba", "../liba")],
    )
    .unwrap();
    let leaf_pkg = make_pkg("libb", "/abs/libb", leaf_proj, vec![]);
    let mid_pkg = make_pkg("liba", "/abs/liba", mid_proj, vec![0]);
    let app_pkg = make_pkg("app", "/abs/app", app_proj, vec![1]);
    let graph = graph_with(vec![leaf_pkg, mid_pkg, app_pkg], vec![2], Some(2));
    let bg = plan_with_standards(&graph, Dialect::GnuLike).unwrap();
    assert_eq!(bg.standard_violations.len(), 1);
    match &bg.standard_violations[0] {
        crate::StandardViolation::InterfaceIncompatibility {
            consumer,
            dependency,
            object,
            ..
        } => {
            assert_eq!(consumer, "liba:liba");
            assert_eq!(dependency, "libb:libb");
            assert!(
                object.starts_with("/abs/build/dev/packages/liba"),
                "violation must sit on the consumer's own compile, got {object}"
            );
        }
        other => panic!("expected InterfaceIncompatibility, got {other:?}"),
    }
    // A full build still surfaces the incompatibility...
    assert!(crate::validate_planned_standards(&bg).is_err());
    // ...while checking only `app` prunes liba's compiles and with
    // them the dependency-internal violation.
    let checked = crate::into_check_graph(bg, &[PathBuf::from("/abs/build/dev/packages/app")]);
    assert!(checked.standard_violations.is_empty());
    crate::validate_planned_standards(&checked).unwrap();
}

#[test]
fn requested_standards_follow_the_planned_selection() {
    use cabin_core::{CxxStandard, LanguageStandardSettings, StandardDeclaration};
    // Two executables; only `app` is selected. The sibling's c++23
    // must not appear in the requested set — it is never planned, so
    // it must not gate toolchain validation (`cabin run --bin app`).
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target("app", TargetKind::Executable, &["src/main.cc"], &[]),
            target_with_language(
                "exotic",
                TargetKind::Executable,
                &["src/exotic.cc"],
                &[],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx23)),
                    ..Default::default()
                },
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let tc = toolchain();
    let plan_for = |selected: Option<Vec<ManifestTargetSelector>>| {
        plan(&PlanRequest {
            graph: &graph,
            toolchain: &tc,
            build_flags: &empty_build_flags(),
            language_standards: &standards_for(&graph),
            standard_flag_conflicts: &no_flag_conflicts(),
            build_dir: PathBuf::from("/abs/build"),
            profile: dev_profile(),
            selected,
            configuration: None,
            selected_packages: None,
            compiler_wrapper: None,
            dialect: Dialect::GnuLike,
            msvc_external_includes: true,
        })
        .unwrap()
    };

    let narrowed = plan_for(Some(vec![ManifestTargetSelector::parse("app")]));
    let requested = crate::requested_standards_of(&narrowed);
    assert_eq!(
        requested.cxx,
        std::collections::BTreeSet::from([CxxStandard::Cxx17]),
        "the unbuilt sibling's c++23 must not gate validation"
    );
    assert!(requested.c.is_empty());

    // The default selection plans both executables, so both
    // standards are requested.
    let full = plan_for(None);
    let requested = crate::requested_standards_of(&full);
    assert_eq!(
        requested.cxx,
        std::collections::BTreeSet::from([CxxStandard::Cxx17, CxxStandard::Cxx23])
    );
}

#[test]
fn flag_conflicts_scope_to_planned_compiles() {
    use cabin_core::{
        CxxStandard, LanguageStandardSettings, SourceLanguage, StandardDeclaration,
        StandardFlagConflict,
    };
    // `exotic` declares a target-level cxx-standard while the package
    // flags pin one via `-std=`: the candidate covers only `exotic`'s
    // compiles, so selecting `app` must plan without a violation.
    let package = Package::new(
        pkg_name("demo"),
        version(),
        vec![
            target("app", TargetKind::Executable, &["src/main.cc"], &[]),
            target_with_language(
                "exotic",
                TargetKind::Executable,
                &["src/exotic.cc"],
                &[],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                    ..Default::default()
                },
            ),
        ],
        Vec::new(),
    )
    .unwrap();
    let graph = single_package_graph(package, "/abs/proj");
    let conflicts: HashMap<usize, Vec<StandardFlagConflict>> = HashMap::from([(
        0,
        vec![StandardFlagConflict {
            package: "demo".to_owned(),
            language: SourceLanguage::Cxx,
            field: "cxx-standard",
            flag_list: "cxxflags",
            flag: "-std=c++17".to_owned(),
            target: Some("exotic".to_owned()),
        }],
    )]);
    let tc = toolchain();
    let plan_for = |selected: Option<Vec<ManifestTargetSelector>>| {
        plan(&PlanRequest {
            graph: &graph,
            toolchain: &tc,
            build_flags: &empty_build_flags(),
            language_standards: &standards_for(&graph),
            standard_flag_conflicts: &conflicts,
            build_dir: PathBuf::from("/abs/build"),
            profile: dev_profile(),
            selected,
            configuration: None,
            selected_packages: None,
            compiler_wrapper: None,
            dialect: Dialect::GnuLike,
            msvc_external_includes: true,
        })
        .unwrap()
    };

    // Only `app` planned: the candidate's scope is never compiled.
    let narrowed = plan_for(Some(vec![ManifestTargetSelector::parse("app")]));
    assert!(narrowed.standard_violations.is_empty());
    crate::validate_planned_standards(&narrowed).unwrap();

    // Default selection plans `exotic` too: the conflict surfaces.
    let full = plan_for(None);
    assert!(matches!(
        full.standard_violations.first(),
        Some(crate::StandardViolation::FlagConflict { .. })
    ));
    let err = crate::validate_planned_standards(&full).unwrap_err();
    assert!(
        std::error::Error::source(&err).is_some_and(|s| s.to_string().contains("cxx-standard")),
        "the typed conflict must stay on the error chain: {err}"
    );
}