supercov-engine 4.1.0

Rust instrumentation, evidence, attribution, and query engine for Supercov
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
//! Deterministic first-party JavaScript/TypeScript source discovery.
//!
//! Discovery defines the coverage denominator. The walker never follows
//! links and turns unclassified first-party files into explicit blockers.

use std::{
    collections::{BTreeMap, BTreeSet},
    fs, io,
    path::{Component, Path, PathBuf},
};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

const GENERATED_DIRECTORIES: &[&str] = &[
    ".cache",
    "generated",
    ".git",
    ".mcdc-pool",
    ".next",
    ".nuxt",
    ".output",
    ".supercov",
    "build",
    "coverage",
    "dist",
    "node_modules",
    "out",
    "playwright-report",
    "results",
    "test-results",
    "vendor",
];
/// Whether a directory called `target` is a build tool's output rather than a
/// project's own code.
///
/// Cargo, Maven, sbt and Leiningen write there, but the name is not theirs: a
/// Flask application kept its whole package in `target/`, and dropping the
/// directory by name left the repository with no source at all. It is output
/// when a build that writes there is declared beside it, or when Cargo's own
/// markers are inside it, which also covers a `CARGO_TARGET_DIR` placed
/// elsewhere.
pub fn target_is_build_output(directory: &Path) -> bool {
    const BUILDS: &[&str] = &[
        "Cargo.toml",
        "pom.xml",
        "build.gradle",
        "build.gradle.kts",
        "settings.gradle",
        "settings.gradle.kts",
        "build.sbt",
        "project.clj",
    ];
    const MARKERS: &[&str] = &["CACHEDIR.TAG", ".rustc_info.json"];
    directory
        .parent()
        .is_some_and(|parent| BUILDS.iter().any(|name| parent.join(name).is_file()))
        || MARKERS.iter().any(|name| directory.join(name).is_file())
}

const SOURCE_DIRECTORIES: &[&str] = &[
    "app",
    "src",
    "lib",
    "server",
    "client",
    "functions",
    "api",
    "components",
    "pages",
];
/// The files Next.js reads from a project's root by name. `proxy` is what
/// Next 16 calls `middleware`.
const NEXT_ROOT_FILES: &[&str] = &[
    "proxy",
    "middleware",
    "instrumentation",
    "instrumentation-client",
];
/// The file names the App Router gives a meaning to under `app/`.
const NEXT_APP_FILES: &[&str] = &[
    "page",
    "layout",
    "route",
    "loading",
    "error",
    "global-error",
    "not-found",
    "template",
    "default",
    "forbidden",
    "unauthorized",
    "icon",
    "apple-icon",
    "opengraph-image",
    "twitter-image",
    "sitemap",
    "robots",
    "manifest",
];
const PACKAGE_PARENTS: &[&str] = &["apps", "packages", "services", "workspaces"];
const TEST_DIRECTORIES: &[&str] = &[
    "__tests__",
    "test",
    "tests",
    "spec",
    "specs",
    "e2e",
    "fixture",
    "fixtures",
    "mock",
    "mocks",
    "__mocks__",
];
const CONFIG_TOOLS: &[&str] = &[
    "babel",
    "eslint",
    "graphql",
    "jest",
    "next",
    "nuxt",
    "playwright",
    "postcss",
    "prettier",
    "remix",
    "rollup",
    "stylelint",
    "tailwind",
    "tsup",
    "vite",
    "vitest",
    "webpack",
];
const DOT_CONFIG_TOOLS: &[&str] = &["babel", "eslint", "graphql", "prettier", "stylelint"];

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceScopeStatus {
    Included,
    Excluded,
    Ambiguous,
}

/// Scope reason for a bundler's output found in the tree (see `built_asset`).
pub const BUILT_ASSET_REASON: &str = "built asset";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SourceScopeEntry {
    pub file: String,
    pub status: SourceScopeStatus,
    pub reason: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub package_root: Option<String>,
}

impl SourceScopeEntry {
    /// A file the wrapped command generates rather than one anyone edits: it
    /// is never instrumented or cached, and a bundler renames it on every
    /// build, so it must not feed the source fingerprint.
    pub fn is_generated_output(&self) -> bool {
        self.status == SourceScopeStatus::Excluded && self.reason == BUILT_ASSET_REASON
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceScopeMode {
    Automatic,
    Explicit,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SourceScope {
    pub version: u32,
    pub mode: SourceScopeMode,
    pub roots: Vec<String>,
    pub entries: Vec<SourceScopeEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SourceLimitation {
    pub id: String,
    pub kind: String,
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub source: String,
    pub reason: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DiscoveredSourceScope {
    pub source_files: Vec<String>,
    pub source_roots: Vec<String>,
    pub scope: SourceScope,
    pub limitations: Vec<SourceLimitation>,
}

#[derive(Debug)]
pub enum SourceDiscoveryError {
    Io { path: PathBuf, source: io::Error },
    NonUtf8Path(PathBuf),
    InvalidRoot(PathBuf),
}

impl std::fmt::Display for SourceDiscoveryError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { path, source } => write!(formatter, "{}: {source}", path.display()),
            Self::NonUtf8Path(path) => {
                write!(
                    formatter,
                    "source path is not valid UTF-8: {}",
                    path.display()
                )
            }
            Self::InvalidRoot(path) => write!(
                formatter,
                "source root is not a regular file or directory: {}",
                path.display()
            ),
        }
    }
}

impl std::error::Error for SourceDiscoveryError {}

fn io_error(path: &Path, source: io::Error) -> SourceDiscoveryError {
    SourceDiscoveryError::Io {
        path: path.to_owned(),
        source,
    }
}

/// The variable that names first-party source roots, for every frontend.
pub const SOURCE_ROOTS_VARIABLE: &str = "SUPERCOV_SOURCE_ROOTS";

/// Why a file a frontend would otherwise measure was left out.
pub const OUTSIDE_EXPLICIT_ROOTS: &str = "outside explicit source roots";

/// The first-party source roots named in `SUPERCOV_SOURCE_ROOTS`:
/// comma-separated, trimmed, empties dropped. `None` when the variable is unset
/// or names nothing, which leaves discovery automatic.
///
/// Every frontend reads the roots through here. It used to be read on the
/// JavaScript path alone while the documentation described it without a
/// language, so a Python project that set it had every file measured anyway --
/// a vendored tree beside flat-layout sources came out at 660 files instead of
/// fifteen, with nothing to say the variable had been ignored.
pub fn configured_source_roots(environment: &BTreeMap<String, String>) -> Option<Vec<String>> {
    let roots = environment
        .get(SOURCE_ROOTS_VARIABLE)?
        .split(',')
        .map(str::trim)
        .filter(|root| !root.is_empty())
        .map(str::to_owned)
        .collect::<Vec<_>>();
    (!roots.is_empty()).then_some(roots)
}

/// Fold the roots a run was measured under into its execution configuration,
/// the part of a run's identity that records how it was asked to run. Two runs
/// over different roots measure different denominators and are not the same
/// run; nothing is appended when no roots were named, so every existing
/// fingerprint stays as it was.
pub fn fold_roots_into_configuration(configuration: &mut Vec<u8>, roots: Option<&[String]>) {
    let Some(roots) = roots.filter(|roots| !roots.is_empty()) else {
        return;
    };
    configuration.push(0);
    configuration
        .extend_from_slice(format!("{SOURCE_ROOTS_VARIABLE}={}", roots.join(",")).as_bytes());
}

/// Explicit source roots resolved against a project root. Each is an existing
/// directory or a single file, so a flat layout can name the modules it keeps
/// at the root one by one. A root that does not exist names nothing to measure
/// and is skipped; one that is neither a file nor a directory is refused, since
/// a symlink root would reach outside what the project owns.
#[derive(Debug, Clone)]
pub struct ExplicitSourceRoots {
    root: PathBuf,
    roots: Vec<PathBuf>,
    configured: Vec<String>,
}

impl ExplicitSourceRoots {
    pub fn resolve(root: &Path, configured: &[String]) -> Result<Self, SourceDiscoveryError> {
        let root = lexical_normalize(root);
        let roots = existing_roots(configured.iter().map(|value| resolve(&root, value)), true)?;
        Ok(Self {
            root,
            roots,
            configured: configured.to_vec(),
        })
    }

    /// Read the roots from the environment, if any are named.
    pub fn from_environment(
        root: &Path,
        environment: &BTreeMap<String, String>,
    ) -> Result<Option<Self>, SourceDiscoveryError> {
        configured_source_roots(environment)
            .map(|configured| Self::resolve(root, &configured))
            .transpose()
    }

    /// Read the roots named against `project`, resolved inside `workspace` --
    /// the isolated copy Go, the JVM and Rust measure. The copy mirrors the
    /// project, so a relative root names the same file in both. An absolute one
    /// names the original tree, which nothing in the copy lies under, so it is
    /// rebased onto the copy; without that it would match nothing and read as a
    /// typo. The roots are still quoted as they were written.
    pub fn from_environment_in(
        project: &Path,
        workspace: &Path,
        environment: &BTreeMap<String, String>,
    ) -> Result<Option<Self>, SourceDiscoveryError> {
        let Some(configured) = configured_source_roots(environment) else {
            return Ok(None);
        };
        let project = lexical_normalize(project);
        let rebased = configured
            .iter()
            .map(|value| {
                let path = Path::new(value);
                if !path.is_absolute() {
                    return value.clone();
                }
                lexical_normalize(path)
                    .strip_prefix(&project)
                    .map(|rest| {
                        let rest = rest.to_string_lossy().into_owned();
                        if rest.is_empty() { ".".into() } else { rest }
                    })
                    .unwrap_or_else(|_| value.clone())
            })
            .collect::<Vec<_>>();
        let mut roots = Self::resolve(workspace, &rebased)?;
        roots.configured = configured;
        Ok(Some(roots))
    }

    /// Whether a project-relative file lies under these roots: inside a
    /// directory root, or the very file a file root names.
    pub fn contains(&self, relative: &str) -> bool {
        root_contains(&self.roots, &lexical_normalize(&self.root.join(relative)))
    }

    /// The roots exactly as they were written, including any that name nothing.
    /// An error about roots quotes these, because the one that does not exist
    /// is usually the typo the person needs to see.
    pub fn configured(&self) -> &[String] {
        &self.configured
    }

    /// Refuse roots that left a frontend nothing to measure. A typo in the
    /// variable must not become a green run over zero files -- the failure mode
    /// most likely to pass unnoticed in an agent loop.
    pub fn refuse_if_empty(&self, remaining: usize, language: &str) -> Result<(), String> {
        if remaining > 0 {
            return Ok(());
        }
        let missing = self
            .configured
            .iter()
            .filter(|value| fs::symlink_metadata(resolve(&self.root, value)).is_err())
            .cloned()
            .collect::<Vec<_>>();
        let mut message = format!(
            "{SOURCE_ROOTS_VARIABLE}={} left no {language} source to measure",
            self.configured.join(",")
        );
        if !missing.is_empty() {
            message.push_str(&format!("; {} does not exist", missing.join(", ")));
        }
        message.push_str("; name the directories or files that hold your own code");
        Err(message)
    }

    /// The scope a frontend that has no scope of its own records when explicit
    /// roots shaped what it measures: the files kept, and the files the roots
    /// left out. Without it, honouring the variable would be as invisible as
    /// ignoring it -- the complaint that started this -- since `runs <id>
    /// scope` would have nothing to show.
    pub fn scope(
        &self,
        included: &[String],
        excluded: &[(String, &'static str)],
    ) -> Result<SourceScope, SourceDiscoveryError> {
        let mut entries = included
            .iter()
            .map(|file| SourceScopeEntry {
                file: file.clone(),
                status: SourceScopeStatus::Included,
                reason: "explicit source root".into(),
                package_root: None,
            })
            .chain(
                excluded
                    .iter()
                    .filter(|(_, reason)| *reason == OUTSIDE_EXPLICIT_ROOTS)
                    .map(|(file, reason)| SourceScopeEntry {
                        file: file.clone(),
                        status: SourceScopeStatus::Excluded,
                        reason: (*reason).into(),
                        package_root: None,
                    }),
            )
            .collect::<Vec<_>>();
        entries.sort_by(|left, right| left.file.cmp(&right.file));
        Ok(SourceScope {
            version: 1,
            mode: SourceScopeMode::Explicit,
            roots: self.local_roots()?,
            entries,
        })
    }

    /// The roots as project-relative paths, as the recorded scope names them.
    pub fn local_roots(&self) -> Result<Vec<String>, SourceDiscoveryError> {
        self.roots
            .iter()
            .map(|path| local_path(&self.root, path))
            .collect()
    }

    /// Split `sources` into the files these roots keep and the ones they leave
    /// out, recording why each was left out. A frontend's own exclusions --
    /// tests, environments, build output -- have already been applied, so a
    /// root narrows what is measured and never pulls a test file back in.
    pub fn narrow<T>(
        &self,
        sources: &mut Vec<T>,
        excluded: &mut Vec<(String, &'static str)>,
        file: impl Fn(&T) -> &str,
    ) {
        let (kept, outside): (Vec<T>, Vec<T>) = sources
            .drain(..)
            .partition(|source| self.contains(file(source)));
        excluded.extend(
            outside
                .iter()
                .map(|source| (file(source).to_owned(), OUTSIDE_EXPLICIT_ROOTS)),
        );
        *sources = kept;
    }
}

/// The configured or discovered roots that exist, each a regular file or
/// directory. Shared by explicit and automatic discovery so the two cannot
/// disagree about what counts as a root. A root someone named that is
/// anything else is refused; a conventional one discovery merely guessed
/// (`lib` linked to `src`, a `main` entry linked into `dist/`) is passed
/// over, as the copy the run measures passes over a link out of the project.
fn existing_roots(
    candidates: impl IntoIterator<Item = PathBuf>,
    named: bool,
) -> Result<Vec<PathBuf>, SourceDiscoveryError> {
    let mut existing = BTreeSet::new();
    for path in candidates {
        match fs::symlink_metadata(&path) {
            Ok(metadata) if metadata.file_type().is_file() || metadata.file_type().is_dir() => {
                existing.insert(path);
            }
            Ok(_) if !named => {}
            Ok(_) => return Err(SourceDiscoveryError::InvalidRoot(path)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(io_error(&path, error)),
        }
    }
    Ok(existing.into_iter().collect())
}

/// Whether `path` lies under one of `roots`: inside a directory root, or equal
/// to a file root.
fn root_contains(roots: &[PathBuf], path: &Path) -> bool {
    roots.iter().any(|directory| {
        fs::symlink_metadata(directory)
            .map(|metadata| {
                if metadata.file_type().is_dir() {
                    within(directory, path)
                } else {
                    directory == path
                }
            })
            .unwrap_or(false)
    })
}

fn lexical_normalize(path: &Path) -> PathBuf {
    let mut output = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !output.pop() {
                    output.push(component.as_os_str());
                }
            }
            _ => output.push(component.as_os_str()),
        }
    }
    output
}

fn resolve(root: &Path, value: impl AsRef<Path>) -> PathBuf {
    let value = value.as_ref();
    let joined;
    let path = if value.is_absolute() {
        value
    } else {
        joined = root.join(value);
        &joined
    };
    lexical_normalize(path)
}

fn local_path(root: &Path, path: &Path) -> Result<String, SourceDiscoveryError> {
    let local = path
        .strip_prefix(root)
        .map_err(|_| SourceDiscoveryError::InvalidRoot(path.to_owned()))?;
    if local.as_os_str().is_empty() {
        return Ok(".".into());
    }
    local
        .components()
        .map(|component| {
            component
                .as_os_str()
                .to_str()
                .map(str::to_owned)
                .ok_or_else(|| SourceDiscoveryError::NonUtf8Path(path.to_owned()))
        })
        .collect::<Result<Vec<_>, _>>()
        .map(|parts| parts.join("/"))
}

fn generated_directory(name: &str) -> bool {
    GENERATED_DIRECTORIES.contains(&name)
}

fn owned_workspace_store(path: &Path) -> bool {
    crate::workspace::owned_workspace_path(path)
}

/// A directory carrying its own `.git` entry is another checkout — a nested
/// clone, a submodule, or an agent worktree such as `.claude/worktrees/*` —
/// not this project's source. Treating its files as ambiguous first-party
/// code turned one real project's report into 1,032 blocking limitations.
fn nested_checkout(path: &Path) -> bool {
    fs::symlink_metadata(path.join(".git")).is_ok()
}

/// A hidden directory at the project root is tool state (.shopify, .vercel,
/// .idea, .claude, ...) by convention, never application source. Nested
/// hidden directories keep their normal treatment so a source tree that
/// happens to contain one is not silently truncated.
/// A hashed bundle (`app-embed-Be-aUw9g.js`) inside an assets/static/public
/// directory is a bundler's output, not source: a theme extension's `assets/`
/// receives its Vite build, and every such bundle was an ambiguous blocker.
fn built_asset(file: &str) -> bool {
    let mut segments = file.rsplit('/');
    let Some(name) = segments.next() else {
        return false;
    };
    let in_asset_directory =
        segments.any(|segment| matches!(segment, "assets" | "static" | "public"));
    let Some(stem) = name
        .strip_suffix(".js")
        .or_else(|| name.strip_suffix(".mjs"))
        .or_else(|| name.strip_suffix(".cjs"))
    else {
        return false;
    };
    // Bundler hashes are eight base64url characters, which may themselves
    // contain '-', so take the suffix by length rather than splitting on it.
    if stem.len() < 10 || stem.as_bytes()[stem.len() - 9] != b'-' {
        return false;
    }
    let hash = &stem[stem.len() - 8..];
    let looks_hashed = hash
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
        && (hash.bytes().any(|byte| byte.is_ascii_digit())
            || (hash.bytes().any(|byte| byte.is_ascii_uppercase())
                && hash.bytes().any(|byte| byte.is_ascii_lowercase())));
    in_asset_directory && looks_hashed
}

fn root_tool_directory(root: &Path, path: &Path) -> bool {
    path.parent() == Some(root)
        && path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.starts_with('.'))
}

fn source_file(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    [
        ".js", ".jsx", ".ts", ".tsx", ".cjs", ".cjsx", ".cts", ".ctsx", ".mjs", ".mjsx", ".mts",
        ".mtsx",
    ]
    .iter()
    .any(|extension| lower.ends_with(extension))
}

fn declaration_file(file: &str) -> bool {
    let lower = file.to_ascii_lowercase();
    lower.ends_with(".d.ts") || lower.ends_with(".d.cts") || lower.ends_with(".d.mts")
}

fn test_or_fixture(file: &str) -> bool {
    let lower = file.to_ascii_lowercase();
    if lower
        .split('/')
        .any(|segment| TEST_DIRECTORIES.contains(&segment))
    {
        return true;
    }
    lower
        .split(['/', '_', '.', '-'])
        .any(|part| matches!(part, "test" | "spec"))
}

fn depends_on_next(manifest: &Value) -> bool {
    ["dependencies", "devDependencies", "peerDependencies"]
        .iter()
        .any(|field| {
            manifest
                .get(field)
                .is_some_and(|all| all.get("next").is_some())
        })
}

/// A file the App Router serves. Under `app/` a directory is a URL segment,
/// so `app/api/wordpress/test/route.ts` is the handler of `/api/wordpress/test`
/// and not a test: five such "test connection" endpoints of one application
/// were left out of what it measured. A folder that starts with `_` is private
/// to the project and is not a segment, which keeps `__tests__` a test folder.
fn next_app_file(app_directories: &[PathBuf], path: &Path) -> bool {
    let Some(local) = app_directories
        .iter()
        .find_map(|directory| path.strip_prefix(directory).ok())
    else {
        return false;
    };
    let Some(name) = local.file_name().and_then(|name| name.to_str()) else {
        return false;
    };
    let conventional = name.split_once('.').is_some_and(|(stem, extension)| {
        NEXT_APP_FILES.contains(&stem) && !extension.contains('.')
    });
    conventional
        && local.parent().is_none_or(|folders| {
            folders
                .components()
                .all(|folder| !folder.as_os_str().to_string_lossy().starts_with('_'))
        })
}

/// The path a named root leaves to judge: the part below it. Whoever names
/// `scripts` or `src/test-utils` as a source root has said what it holds, so
/// only what lies deeper is still guessed at. A root that is a file names that
/// file, and nothing about it is guessed.
fn below_named_root<'a>(roots: &[PathBuf], path: &'a Path) -> Option<&'a Path> {
    roots
        .iter()
        .filter_map(|root| path.strip_prefix(root).ok())
        .min_by_key(|local| local.components().count())
}

/// A benchmark: Vitest's `*.bench.ts` beside the code it measures, or a file
/// under a `bench`/`benchmarks` directory. It runs the product; it is not the
/// product. jshttp/cookie keeps four `src/*.bench.ts` files, which were
/// counted as application source and led the list of code no test ran.
fn benchmark(file: &str) -> bool {
    let lower = file.to_ascii_lowercase();
    let (directories, name) = lower.rsplit_once('/').unwrap_or(("", lower.as_str()));
    directories
        .split('/')
        .any(|segment| matches!(segment, "bench" | "benches" | "benchmark" | "benchmarks"))
        || name
            .split('.')
            .skip(1)
            .any(|part| matches!(part, "bench" | "benchmark"))
}

/// Example code at the top of the project or of a package: uuid keeps nine
/// example apps under `examples/`, which its tsconfig leaves out and which
/// were counted as application source, putting uuid at 32% of lines. A
/// directory of that name deeper in the source (`app/examples/page.tsx`) can
/// be the product and stays in.
fn example(file: &str, package_root: Option<&str>) -> bool {
    let local = package_root
        .and_then(|package| file.strip_prefix(package))
        .and_then(|rest| rest.strip_prefix('/'))
        .unwrap_or(file);
    local.split_once('/').is_some_and(|(first, _)| {
        matches!(first.to_ascii_lowercase().as_str(), "example" | "examples")
    })
}

fn tool_script(file: &str) -> bool {
    file.to_ascii_lowercase()
        .split('/')
        .any(|segment| segment == "scripts")
}

fn config_file(file: &str) -> bool {
    let lower = file.to_ascii_lowercase();
    let name = lower.rsplit('/').next().unwrap_or(&lower);
    source_file(name)
        && (CONFIG_TOOLS
            .iter()
            .any(|tool| name.starts_with(&format!("{tool}.config.")))
            || DOT_CONFIG_TOOLS
                .iter()
                .any(|tool| name.starts_with(&format!(".{tool}rc.")))
            || (!lower.contains('/')
                && (name.contains(".config.")
                    // wdio.conf.js, karma.conf.js, protractor.conf.js
                    || name.contains(".conf.")
                    || name.starts_with("build.")
                    || name.starts_with("gulpfile.")
                    || name.starts_with("gruntfile."))))
}

fn read_directory(path: &Path) -> Result<Vec<fs::DirEntry>, SourceDiscoveryError> {
    let mut entries = fs::read_dir(path)
        .map_err(|error| io_error(path, error))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| io_error(path, error))?;
    entries.sort_by_key(fs::DirEntry::file_name);
    Ok(entries)
}

/// Whether the repository around a project ignores the project's own
/// directory: a copy kept under another checkout's `tmp/` or `.supercov/`.
/// That repository's `.gitignore` files describe what it does not track, which
/// is all of this project; applying them left the project with no source.
fn ignored_by_enclosing_repository(root: &Path) -> bool {
    if root.join(".git").exists() {
        return false;
    }
    let Some(repository) = root
        .ancestors()
        .skip(1)
        .position(|ancestor| ancestor.join(".git").exists())
    else {
        return false;
    };
    // Outermost first, so a deeper file's decision wins as it does in git.
    root.ancestors()
        .skip(1)
        .take(repository + 1)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .fold(false, |ignored, directory| {
            let (rules, _) = ignore::gitignore::Gitignore::new(directory.join(".gitignore"));
            match rules.matched_path_or_any_parents(root, true) {
                ignore::Match::Ignore(_) => true,
                ignore::Match::Whitelist(_) => false,
                ignore::Match::None => ignored,
            }
        })
}

/// Source files under a root, in name order.
///
/// A file the project's own `.gitignore` excludes is not its source: recording
/// Actual counted `packages/loot-core/lib-dist/browser/kcab.worker.dev.js`, a
/// 5 MB bundle its build writes and git ignores, as application code, and
/// instrumented it. Only the project's `.gitignore` files are read, and only
/// inside a git repository; a user's global excludes and `.git/info/exclude`
/// differ between machines, and a run must count the same files on each.
fn files_under(
    root: &Path,
    directory: &Path,
    output: &mut Vec<PathBuf>,
) -> Result<(), SourceDiscoveryError> {
    let metadata = fs::symlink_metadata(directory).map_err(|error| io_error(directory, error))?;
    if !metadata.file_type().is_dir() {
        return Err(SourceDiscoveryError::InvalidRoot(directory.to_owned()));
    }
    let project = root.to_owned();
    let walker = ignore::WalkBuilder::new(directory)
        .standard_filters(false)
        .git_ignore(true)
        .parents(!ignored_by_enclosing_repository(directory))
        .require_git(true)
        .follow_links(false)
        .sort_by_file_name(|left, right| left.cmp(right))
        .filter_entry(move |entry| {
            entry.depth() == 0
                || !entry.file_type().is_some_and(|kind| kind.is_dir())
                || entry.file_name().to_str().is_some_and(|name| {
                    !generated_directory(name)
                        && !owned_workspace_store(entry.path())
                        && !nested_checkout(entry.path())
                        && !root_tool_directory(&project, entry.path())
                })
        })
        .build();
    for entry in walker {
        let entry =
            entry.map_err(|error| io_error(directory, io::Error::other(error.to_string())))?;
        let Some(kind) = entry.file_type() else {
            continue;
        };
        if kind.is_symlink() || !kind.is_file() {
            continue;
        }
        let name = entry
            .file_name()
            .to_str()
            .ok_or_else(|| SourceDiscoveryError::NonUtf8Path(entry.path().to_owned()))?;
        if source_file(name) {
            output.push(entry.into_path());
        }
    }
    Ok(())
}

fn read_json(path: &Path) -> Option<Value> {
    serde_json::from_slice(&fs::read(path).ok()?).ok()
}

fn package_directories(root: &Path) -> Result<Vec<PathBuf>, SourceDiscoveryError> {
    fn visit(
        root: &Path,
        directory: &Path,
        depth: usize,
        found: &mut BTreeSet<PathBuf>,
    ) -> Result<(), SourceDiscoveryError> {
        if depth > 5 {
            return Ok(());
        }
        for entry in read_directory(directory)? {
            let name = entry
                .file_name()
                .into_string()
                .map_err(|name| SourceDiscoveryError::NonUtf8Path(directory.join(name)))?;
            let path = entry.path();
            let file_type = entry.file_type().map_err(|error| io_error(&path, error))?;
            if !file_type.is_dir()
                || file_type.is_symlink()
                || generated_directory(&name)
                || owned_workspace_store(&path)
                || nested_checkout(&path)
                || root_tool_directory(root, &path)
            {
                continue;
            }
            let local = local_path(root, &path)?;
            let under_package_parent = local
                .split('/')
                .any(|segment| PACKAGE_PARENTS.contains(&segment));
            if path.join("package.json").is_file() && (depth == 0 || under_package_parent) {
                found.insert(path.clone());
            }
            visit(root, &path, depth + 1, found)?;
        }
        Ok(())
    }

    let mut found = BTreeSet::from([root.to_owned()]);
    visit(root, root, 0, &mut found)?;
    for directory in declared_workspace_packages(root)? {
        found.insert(directory);
    }
    Ok(found.into_iter().collect())
}

/// Packages the project itself declares: `workspaces` in the root
/// package.json (array or `{ "packages": [...] }`) and `packages:` in
/// pnpm-workspace.yaml. The manifest is the most authoritative statement of
/// where packages live, and it routinely names directories outside the
/// conventional parents (a real project keeps its Shopify extensions under
/// `app_extensions/*`; every file there was an ambiguous blocker).
fn declared_workspace_packages(root: &Path) -> Result<Vec<PathBuf>, SourceDiscoveryError> {
    let mut patterns = Vec::new();
    let manifest = read_json(&root.join("package.json")).unwrap_or(Value::Null);
    let declared = match manifest.get("workspaces") {
        Some(Value::Array(items)) => Some(items),
        Some(Value::Object(object)) => object.get("packages").and_then(Value::as_array),
        _ => None,
    };
    if let Some(items) = declared {
        patterns.extend(items.iter().filter_map(Value::as_str).map(str::to_owned));
    }
    if let Ok(pnpm) = fs::read_to_string(root.join("pnpm-workspace.yaml")) {
        let mut in_packages = false;
        for line in pnpm.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("packages:") {
                in_packages = true;
                continue;
            }
            if in_packages {
                if let Some(item) = trimmed.strip_prefix("- ") {
                    patterns.push(item.trim_matches(|c| c == '"' || c == '\'').to_owned());
                } else if !trimmed.is_empty() && !trimmed.starts_with('#') {
                    in_packages = false;
                }
            }
        }
    }
    let mut found = Vec::new();
    for pattern in patterns {
        let pattern = pattern.trim_start_matches("./").trim_end_matches('/');
        if pattern.starts_with('!') || pattern.contains("**") {
            continue;
        }
        let (parent, wildcard) = match pattern.strip_suffix("/*") {
            Some(parent) => (parent, true),
            None => (pattern, false),
        };
        if parent.is_empty()
            || parent
                .split('/')
                .any(|segment| segment.is_empty() || segment == ".." || segment.contains('*'))
        {
            continue;
        }
        let base = root.join(parent);
        let candidates: Vec<PathBuf> = if wildcard {
            match fs::read_dir(&base) {
                Ok(entries) => entries
                    .filter_map(Result::ok)
                    .map(|entry| entry.path())
                    .collect(),
                Err(_) => Vec::new(),
            }
        } else {
            vec![base]
        };
        for candidate in candidates {
            let is_dir = fs::symlink_metadata(&candidate)
                .is_ok_and(|metadata| metadata.file_type().is_dir());
            if is_dir
                && candidate.join("package.json").is_file()
                && !nested_checkout(&candidate)
                && !owned_workspace_store(&candidate)
            {
                found.push(candidate);
            }
        }
    }
    Ok(found)
}

fn string_targets(value: &Value, depth: usize, output: &mut Vec<String>) {
    if depth > 8 {
        return;
    }
    match value {
        Value::String(value) => output.push(value.clone()),
        Value::Array(values) => {
            for value in values {
                string_targets(value, depth + 1, output);
            }
        }
        Value::Object(values) => {
            for value in values.values() {
                string_targets(value, depth + 1, output);
            }
        }
        _ => {}
    }
}

fn entry_targets(directory: &Path, manifest: &Value) -> Vec<PathBuf> {
    let mut targets = Vec::new();
    for key in ["main", "module", "browser", "bin", "exports"] {
        if let Some(value) = manifest.get(key) {
            string_targets(value, 0, &mut targets);
        }
    }
    targets
        .into_iter()
        .filter_map(|target| {
            if !target.starts_with('.') || target.contains("node_modules") {
                return None;
            }
            let prefix = target.split('*').next()?.trim_end_matches('/');
            (!prefix.is_empty()).then(|| resolve(directory, prefix))
        })
        .collect()
}

pub(crate) fn strip_jsonc_comments(contents: &str) -> String {
    let mut output = String::with_capacity(contents.len());
    let mut chars = contents.chars().peekable();
    let mut string = false;
    let mut escaped = false;
    while let Some(character) = chars.next() {
        if string {
            output.push(character);
            if escaped {
                escaped = false;
            } else if character == '\\' {
                escaped = true;
            } else if character == '"' {
                string = false;
            }
            continue;
        }
        if character == '"' {
            string = true;
            output.push(character);
        } else if character == '/' && chars.peek() == Some(&'/') {
            chars.next();
            for comment in chars.by_ref() {
                if comment == '\n' {
                    output.push('\n');
                    break;
                }
            }
        } else if character == '/' && chars.peek() == Some(&'*') {
            chars.next();
            let mut previous = '\0';
            for comment in chars.by_ref() {
                if previous == '*' && comment == '/' {
                    break;
                }
                previous = comment;
            }
        } else {
            output.push(character);
        }
    }
    output
}

pub(crate) fn strip_trailing_commas(contents: &str) -> String {
    let chars = contents.chars().collect::<Vec<_>>();
    let mut output = String::with_capacity(contents.len());
    let mut string = false;
    let mut escaped = false;
    for (index, character) in chars.iter().copied().enumerate() {
        if string {
            output.push(character);
            if escaped {
                escaped = false;
            } else if character == '\\' {
                escaped = true;
            } else if character == '"' {
                string = false;
            }
            continue;
        }
        if character == '"' {
            string = true;
            output.push(character);
        } else if character == ','
            && chars[index + 1..]
                .iter()
                .find(|character| !character.is_whitespace())
                .is_some_and(|character| matches!(character, '}' | ']'))
        {
        } else {
            output.push(character);
        }
    }
    output
}

fn tsconfig_roots(directory: &Path) -> Vec<PathBuf> {
    let path = directory.join("tsconfig.json");
    let Some(contents) = fs::read_to_string(path).ok() else {
        return Vec::new();
    };
    let jsonc = strip_trailing_commas(&strip_jsonc_comments(&contents));
    let Some(config) = serde_json::from_str::<Value>(&jsonc).ok() else {
        return Vec::new();
    };
    let mut values = Vec::new();
    if let Some(root_dir) = config
        .get("compilerOptions")
        .and_then(|options| options.get("rootDir"))
        .and_then(Value::as_str)
    {
        values.push(root_dir.to_owned());
    }
    if let Some(include) = config.get("include").and_then(Value::as_array) {
        values.extend(include.iter().filter_map(Value::as_str).map(str::to_owned));
    }
    if values.is_empty() {
        return vec![directory.to_owned()];
    }
    values
        .into_iter()
        .filter_map(|value| {
            if value.starts_with('!') {
                return None;
            }
            let prefix = value
                .find(['?', '*', '{', '['])
                .map_or(value.as_str(), |index| &value[..index])
                .trim_end_matches('/');
            // `next-env.d.ts` is in every Next.js `include`; a declaration
            // holds nothing to measure and is not a root.
            (!prefix.is_empty() && !declaration_file(prefix)).then(|| resolve(directory, prefix))
        })
        .collect()
}

fn within(parent: &Path, child: &Path) -> bool {
    child == parent || child.starts_with(parent)
}

fn nearest_package_root<'a>(path: &Path, packages: &'a [PathBuf]) -> Option<&'a PathBuf> {
    packages
        .iter()
        .filter(|directory| within(directory, path))
        .max_by_key(|directory| directory.components().count())
}

fn scope_limitation(file: &str) -> SourceLimitation {
    let digest = Sha256::digest(file.as_bytes());
    let id = digest[..10]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<String>();
    SourceLimitation {
        id: format!("scope:{id}"),
        kind: "source-scope".into(),
        file: file.into(),
        line: 1,
        column: 1,
        source: file.into(),
        reason: "First-party JavaScript/TypeScript source could not be classified automatically. Configure SUPERCOV_SOURCE_ROOTS or move it under a discovered package source root.".into(),
    }
}

// A declared Jest setup file is test infrastructure even when it lives under
// a source root with an arbitrary name. Instrumenting its mock factories adds
// out-of-scope bindings that Babel's jest-hoist correctly rejects.
fn declared_test_setup(packages: &[PathBuf]) -> BTreeSet<PathBuf> {
    let mut paths = BTreeSet::new();
    for package in packages {
        let manifest = read_json(&package.join("package.json")).unwrap_or(Value::Null);
        let Some(jest) = manifest.get("jest") else {
            continue;
        };
        let root = jest
            .get("rootDir")
            .and_then(Value::as_str)
            .map(|value| {
                resolve(
                    package,
                    value.replace("<rootDir>", &package.to_string_lossy()),
                )
            })
            .unwrap_or_else(|| package.clone());
        for field in [
            "setupFiles",
            "setupFilesAfterEnv",
            "globalSetup",
            "globalTeardown",
        ] {
            let values = match jest.get(field) {
                Some(Value::Array(values)) => values.iter().collect::<Vec<_>>(),
                Some(value) => vec![value],
                None => Vec::new(),
            };
            for value in values.into_iter().filter_map(Value::as_str) {
                let path = resolve(&root, value.replace("<rootDir>", &root.to_string_lossy()));
                if path.is_file() {
                    paths.insert(path);
                }
            }
        }
    }
    paths
}

pub fn discover_source_scope(
    root: &Path,
    configured_roots: Option<&[String]>,
) -> Result<DiscoveredSourceScope, SourceDiscoveryError> {
    let root = lexical_normalize(root);
    let root_metadata = fs::symlink_metadata(&root).map_err(|error| io_error(&root, error))?;
    if !root_metadata.file_type().is_dir() {
        return Err(SourceDiscoveryError::InvalidRoot(root));
    }
    let packages = package_directories(&root)?;
    let test_setup = declared_test_setup(&packages);
    let explicit = configured_roots.is_some_and(|roots| !roots.is_empty());
    let include_roots = if explicit {
        configured_roots
            .unwrap_or_default()
            .iter()
            .map(|directory| resolve(&root, directory))
            .collect::<Vec<_>>()
    } else {
        packages
            .iter()
            .flat_map(|directory| {
                let manifest = read_json(&directory.join("package.json")).unwrap_or(Value::Null);
                let next_files = depends_on_next(&manifest)
                    .then_some(NEXT_ROOT_FILES)
                    .into_iter()
                    .flatten()
                    .flat_map(|name| {
                        ["ts", "tsx", "js", "jsx", "mjs"]
                            .map(|extension| directory.join(format!("{name}.{extension}")))
                    });
                let candidates = SOURCE_DIRECTORIES
                    .iter()
                    .map(|name| directory.join(name))
                    .chain(next_files)
                    .chain(entry_targets(directory, &manifest))
                    .chain(tsconfig_roots(directory))
                    .collect::<Vec<_>>();
                // A declared package that keeps its code somewhere
                // unconventional (a Shopify theme extension's `frontend/` and
                // `blocks/`, say) is still first-party source. Its own
                // directory becomes the root; generated subtrees stay excluded
                // by the walker as everywhere else.
                if directory != &root
                    && !candidates
                        .iter()
                        .any(|candidate| fs::symlink_metadata(candidate).is_ok())
                {
                    return vec![directory.clone()];
                }
                candidates
            })
            .collect()
    };
    let existing_roots = existing_roots(include_roots, explicit)?;
    let app_directories = packages
        .iter()
        .filter(|directory| {
            depends_on_next(&read_json(&directory.join("package.json")).unwrap_or(Value::Null))
        })
        .flat_map(|directory| [directory.join("app"), directory.join("src/app")])
        .collect::<Vec<_>>();
    let mut all_files = Vec::new();
    files_under(&root, &root, &mut all_files)?;
    all_files.sort();

    let mut entries = Vec::new();
    let mut included = Vec::new();
    let mut limitations = Vec::new();
    for path in all_files {
        let file = local_path(&root, &path)?;
        let package_root = nearest_package_root(&path, &packages)
            .map(|package| local_path(&root, package))
            .transpose()?
            .filter(|package| package != ".");
        let entry = |status, reason: &str| SourceScopeEntry {
            file: file.clone(),
            status,
            reason: reason.into(),
            package_root: package_root.clone(),
        };
        let named = explicit
            .then(|| below_named_root(&existing_roots, &path))
            .flatten();
        let guessed = match named {
            Some(local) => local.to_string_lossy().replace('\\', "/"),
            None => file.clone(),
        };
        if declaration_file(&file) {
            entries.push(entry(SourceScopeStatus::Excluded, "TypeScript declaration"));
        } else if test_setup.contains(&path) {
            entries.push(entry(SourceScopeStatus::Excluded, "declared test setup"));
        } else if test_or_fixture(&guessed) && !next_app_file(&app_directories, &path) {
            entries.push(entry(SourceScopeStatus::Excluded, "test or fixture source"));
        } else if tool_script(&guessed) {
            entries.push(entry(
                SourceScopeStatus::Excluded,
                "conventional tool script",
            ));
        } else if benchmark(&guessed) {
            entries.push(entry(SourceScopeStatus::Excluded, "benchmark"));
        } else if example(&file, package_root.as_deref()) {
            entries.push(entry(SourceScopeStatus::Excluded, "example"));
        } else if config_file(&file) {
            entries.push(entry(
                SourceScopeStatus::Excluded,
                "build/test/tool configuration",
            ));
        } else if built_asset(&file) {
            entries.push(entry(SourceScopeStatus::Excluded, BUILT_ASSET_REASON));
        } else if root_contains(&existing_roots, &path) {
            included.push(path);
            entries.push(entry(
                SourceScopeStatus::Included,
                if explicit {
                    "explicit source root"
                } else {
                    "discovered package source root"
                },
            ));
        } else if explicit {
            entries.push(entry(
                SourceScopeStatus::Excluded,
                "outside explicit source roots",
            ));
        } else {
            entries.push(entry(
                SourceScopeStatus::Ambiguous,
                "unclassified first-party source",
            ));
            limitations.push(scope_limitation(&file));
        }
    }
    let source_files = included
        .iter()
        .map(|path| local_path(&root, path))
        .collect::<Result<Vec<_>, _>>()?;
    let source_roots = existing_roots
        .iter()
        .map(|path| local_path(&root, path))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(DiscoveredSourceScope {
        source_files,
        source_roots: source_roots.clone(),
        scope: SourceScope {
            version: 1,
            mode: if explicit {
                SourceScopeMode::Explicit
            } else {
                SourceScopeMode::Automatic
            },
            roots: source_roots,
            entries,
        },
        limitations,
    })
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        time::{SystemTime, UNIX_EPOCH},
    };

    use super::*;

    fn repository(label: &str, files: &[(&str, &str)]) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "supercov-source-{label}-{}-{nonce}",
            std::process::id()
        ));
        fs::create_dir_all(&root).unwrap();
        for (file, contents) in files {
            let path = root.join(file);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, contents).unwrap();
        }
        root
    }

    fn entry<'a>(scope: &'a DiscoveredSourceScope, file: &str) -> &'a SourceScopeEntry {
        scope
            .scope
            .entries
            .iter()
            .find(|entry| entry.file == file)
            .unwrap()
    }

    #[test]
    fn a_file_the_project_tells_git_to_ignore_is_not_its_source() {
        // Actual's build writes a 5 MB worker bundle under
        // packages/loot-core/lib-dist, which its own nested .gitignore names.
        let files = [
            ("package.json", r#"{"workspaces":["packages/*"]}"#),
            ("packages/core/package.json", r#"{"name":"core"}"#),
            ("packages/core/.gitignore", "lib-dist\n"),
            ("packages/core/src/index.ts", "export const a = 1;"),
            (
                "packages/core/lib-dist/browser/worker.dev.js",
                "var bundled = 1;",
            ),
        ];
        let repository_root = repository("gitignored", &files);
        fs::create_dir_all(repository_root.join(".git")).unwrap();
        let discovered = discover_source_scope(&repository_root, None).unwrap();
        assert!(
            discovered
                .source_files
                .contains(&"packages/core/src/index.ts".into())
        );
        assert!(
            !discovered
                .source_files
                .iter()
                .any(|file| file.contains("lib-dist")),
            "{:?}",
            discovered.source_files
        );
        fs::remove_dir_all(repository_root).unwrap();

        // Outside a git repository a .gitignore means nothing.
        let plain = repository("not-a-repository", &files);
        let discovered = discover_source_scope(&plain, None).unwrap();
        assert!(
            discovered
                .scope
                .entries
                .iter()
                .any(|entry| entry.file.contains("lib-dist"))
        );
        fs::remove_dir_all(plain).unwrap();
    }

    #[test]
    fn a_project_kept_where_an_enclosing_repository_ignores_it_keeps_its_source() {
        let files = [
            // What Supercov's own store writes, so nothing inside is tracked.
            ("scratch/.gitignore", "*\n"),
            ("scratch/app/package.json", r#"{"name":"app"}"#),
            ("scratch/app/.gitignore", "dist\n"),
            ("scratch/app/src/index.js", "export const a = 1;"),
            ("scratch/app/dist/bundle.js", "var bundled = 1;"),
        ];
        let repository_root = repository("enclosing-ignore", &files);
        fs::create_dir_all(repository_root.join(".git")).unwrap();
        let discovered = discover_source_scope(&repository_root.join("scratch/app"), None).unwrap();
        assert_eq!(discovered.source_files, ["src/index.js"]);

        // A project the enclosing repository tracks still follows its rules.
        fs::remove_file(repository_root.join("scratch/.gitignore")).unwrap();
        fs::write(repository_root.join(".gitignore"), "*.gen.js\n").unwrap();
        fs::write(repository_root.join("scratch/app/src/api.gen.js"), "var a;").unwrap();
        let discovered = discover_source_scope(&repository_root.join("scratch/app"), None).unwrap();
        assert_eq!(discovered.source_files, ["src/index.js"]);
        fs::remove_dir_all(repository_root).unwrap();
    }

    #[test]
    fn excludes_declared_jest_setup_without_hiding_neighboring_application_code() {
        let root = repository(
            "jest-setup",
            &[
                (
                    "package.json",
                    r#"{"jest":{"setupFilesAfterEnv":["<rootDir>/src/bootstrap.js"]}}"#,
                ),
                (
                    "src/bootstrap.js",
                    "jest.mock('storage', () => ({read: () => null}));",
                ),
                ("src/index.js", "export const value = 1;"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(discovered.source_files, ["src/index.js"]);
        assert_eq!(
            entry(&discovered, "src/bootstrap.js").reason,
            "declared test setup"
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn example_apps_and_conf_files_are_not_source() {
        // uuid: a tsconfig with no `include` makes the whole checkout a root.
        let root = repository(
            "examples",
            &[
                ("package.json", r#"{"exports":{".":"./dist/index.js"}}"#),
                ("tsconfig.json", r#"{"exclude":["dist","examples"]}"#),
                ("src/v4.ts", "export const v4 = () => ''"),
                ("wdio.conf.js", "exports.config = {}"),
                ("karma.conf.cjs", "module.exports = () => {}"),
                ("examples/browser-esmodules/package.json", "{}"),
                ("examples/browser-esmodules/example.js", "console.log(1)"),
                ("examples/utils/testpage.js", "export default 1"),
                ("example/demo.js", "console.log(1)"),
                ("app/examples/page.tsx", "export default function Page() {}"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            discovered.source_files,
            ["app/examples/page.tsx", "src/v4.ts"]
        );
        for file in [
            "examples/browser-esmodules/example.js",
            "examples/utils/testpage.js",
            "example/demo.js",
        ] {
            assert_eq!(entry(&discovered, file).reason, "example", "{file}");
        }
        for file in ["wdio.conf.js", "karma.conf.cjs"] {
            assert_eq!(
                entry(&discovered, file).reason,
                "build/test/tool configuration",
                "{file}"
            );
        }
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn discovers_conventional_and_workspace_sources_and_blocks_ambiguity() {
        let root = repository(
            "automatic",
            &[
                ("package.json", r#"{"workspaces":["packages/*"]}"#),
                ("src/index.ts", "export const root = true"),
                ("lib/helper.js", "export const helper = true"),
                ("src/index.test.ts", "test('root', () => {})"),
                ("tests/e2e.spec.ts", "test('e2e', () => {})"),
                ("scripts/release.mjs", "export const release = true"),
                ("vite.config.ts", "export default {}"),
                ("build.mjs", "export default async function build() {}"),
                (".eslintrc.cjs", "module.exports = {}"),
                (".graphqlrc.ts", "export default {}"),
                ("orphan.ts", "export const missed = true"),
                ("packages/ui/package.json", r#"{"module":"./src/index.ts"}"#),
                ("packages/ui/src/index.ts", "export const ui = true"),
                ("packages/ui/tests/ui.spec.ts", "test('ui', () => {})"),
                ("dist/generated.js", "generated"),
                (".cache/tool/generated.js", "cached"),
                ("src/parse.bench.ts", "bench('parse', () => {})"),
                (
                    "benchmarks/value-slice.bench.ts",
                    "bench('slice', () => {})",
                ),
                ("src/benchmarkReport.ts", "export const report = 1"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            discovered.source_files,
            [
                "lib/helper.js",
                "packages/ui/src/index.ts",
                "src/benchmarkReport.ts",
                "src/index.ts"
            ]
        );
        for file in ["src/parse.bench.ts", "benchmarks/value-slice.bench.ts"] {
            assert_eq!(entry(&discovered, file).reason, "benchmark", "{file}");
        }
        assert_eq!(
            entry(&discovered, "orphan.ts").status,
            SourceScopeStatus::Ambiguous
        );
        assert_eq!(
            entry(&discovered, "scripts/release.mjs").reason,
            "conventional tool script"
        );
        assert_eq!(
            entry(&discovered, "build.mjs").reason,
            "build/test/tool configuration"
        );
        assert_eq!(
            entry(&discovered, "packages/ui/src/index.ts").package_root,
            Some("packages/ui".into())
        );
        assert_eq!(discovered.limitations.len(), 1);
        assert_eq!(discovered.limitations[0].file, "orphan.ts");
        assert_eq!(discovered.limitations[0].id.len(), "scope:".len() + 20);
        assert!(
            discovered
                .scope
                .entries
                .iter()
                .all(|entry| !entry.file.contains(".cache"))
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn declared_workspaces_outside_conventional_parents_are_package_roots() {
        let root = repository(
            "declared-workspaces",
            &[
                ("package.json", r#"{"workspaces":["app_extensions/*"]}"#),
                ("app/main.ts", "product"),
                ("app_extensions/discounts/package.json", "{}"),
                ("app_extensions/discounts/src/index.ts", "extension"),
                // No conventional source directory at all: the package itself
                // is the root, so its frontend code is still first-party.
                ("app_extensions/upsells/package.json", "{}"),
                ("app_extensions/upsells/frontend/embed.ts", "embed"),
                ("app_extensions/upsells/dist/embed.js", "built"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            discovered.source_files,
            [
                "app/main.ts",
                "app_extensions/discounts/src/index.ts",
                "app_extensions/upsells/frontend/embed.ts",
            ]
        );
        assert!(
            discovered.limitations.is_empty(),
            "declared packages must not be blockers: {:?}",
            discovered.limitations
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn hashed_bundles_in_asset_directories_are_built_assets() {
        let root = repository(
            "built-assets",
            &[
                ("package.json", r#"{"workspaces":["app_extensions/*"]}"#),
                ("app/main.ts", "product"),
                ("app_extensions/upsells/package.json", "{}"),
                ("app_extensions/upsells/frontend/embed.ts", "source"),
                (
                    "app_extensions/upsells/assets/app-embed-Be-aUw9g.js",
                    "bundle",
                ),
                ("app_extensions/upsells/assets/stylex-DAnmLURx.js", "bundle"),
                // A hand-written helper in assets keeps its ordinary treatment.
                (
                    "app_extensions/upsells/assets/theme-helper.js",
                    "hand written",
                ),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert!(
            !discovered
                .source_files
                .iter()
                .any(|file| file.contains("-Be-aUw9g.js") || file.contains("-DAnmLURx.js"))
        );
        assert_eq!(
            entry(
                &discovered,
                "app_extensions/upsells/assets/app-embed-Be-aUw9g.js"
            )
            .reason,
            "built asset"
        );
        assert!(
            discovered.limitations.is_empty(),
            "bundles are not blockers: {:?}",
            discovered.limitations
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn root_level_hidden_directories_are_tooling_not_source() {
        let root = repository(
            "root-hidden",
            &[
                ("package.json", "{}"),
                ("app/main.ts", "product"),
                (".shopify/bundle/upsells/frontend/embed.js", "cli bundle"),
                (".vercel/output/functions/index.js", "deploy output"),
                // A nested hidden directory inside a source root keeps its
                // ordinary treatment.
                ("app/.generated/schema.ts", "generated types"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            discovered.source_files,
            ["app/.generated/schema.ts", "app/main.ts"]
        );
        assert!(
            discovered.limitations.is_empty(),
            "{:?}",
            discovered.limitations
        );
        assert!(discovered.scope.entries.iter().all(
            |entry| !entry.file.starts_with(".shopify/") && !entry.file.starts_with(".vercel/")
        ));
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn nested_checkouts_are_neither_source_nor_limitations() {
        let root = repository(
            "nested-checkout",
            &[
                ("package.json", "{}"),
                ("app/main.ts", "product"),
                // An agent worktree: a full copy of the project carrying its own
                // `.git` file. Real project, 1,032 of these turned into blockers.
                (".claude/worktrees/agent-1/.git", "gitdir: /elsewhere"),
                (".claude/worktrees/agent-1/app/main.ts", "copy"),
                ("vendor-fork/.git/HEAD", "ref: refs/heads/main"),
                ("vendor-fork/src/index.ts", "clone"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(discovered.source_files, ["app/main.ts"]);
        assert!(
            discovered.limitations.is_empty(),
            "nested checkouts must not be blocking limitations: {:?}",
            discovered.limitations
        );
        assert!(
            discovered
                .scope
                .entries
                .iter()
                .all(|entry| !entry.file.starts_with(".claude/")
                    && !entry.file.starts_with("vendor-fork/")),
            "nested checkout files must not appear in scope at all"
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn roots_enter_a_runs_identity_only_when_named() {
        // Appending nothing when no roots are named is what keeps every
        // fingerprint recorded before this change valid.
        let mut unchanged = b"pytest\0-q".to_vec();
        fold_roots_into_configuration(&mut unchanged, None);
        assert_eq!(unchanged, b"pytest\0-q");
        fold_roots_into_configuration(&mut unchanged, Some(&[]));
        assert_eq!(unchanged, b"pytest\0-q");

        let mut folded = b"pytest\0-q".to_vec();
        fold_roots_into_configuration(&mut folded, Some(&["src".to_owned(), "a.py".to_owned()]));
        assert_eq!(folded, b"pytest\0-q\0SUPERCOV_SOURCE_ROOTS=src,a.py");
    }

    #[test]
    fn the_variable_is_read_the_same_way_for_every_frontend() {
        let read = |value: &str| {
            configured_source_roots(&BTreeMap::from([(
                SOURCE_ROOTS_VARIABLE.to_owned(),
                value.to_owned(),
            )]))
        };
        assert_eq!(
            read(" src , app ,"),
            Some(vec!["src".to_owned(), "app".to_owned()])
        );
        assert_eq!(
            read(" , "),
            None,
            "naming nothing leaves discovery automatic"
        );
        assert_eq!(configured_source_roots(&BTreeMap::new()), None);
    }

    #[test]
    fn a_next_application_is_measured_where_next_keeps_its_code() {
        // A stock Next.js layout reported 89 files it could not classify:
        // root `components/`, `proxy.ts` and `instrumentation.ts`. And five
        // "test connection" endpoints were left out as tests, because under
        // `app/` a directory named `test` is a URL segment.
        let root = repository(
            "next-layout",
            &[
                ("package.json", r#"{"dependencies":{"next":"16.1.1"}}"#),
                (
                    "tsconfig.json",
                    r#"{"include":["next-env.d.ts","**/*.ts",".next/types/**/*.ts"]}"#,
                ),
                ("next-env.d.ts", "declare const next: unknown;"),
                ("app/page.tsx", "page"),
                ("app/api/wordpress/test/route.ts", "route"),
                ("app/api/wordpress/test/route.test.ts", "test"),
                ("app/api/wordpress/test/helper.ts", "helper"),
                ("app/__tests__/page.tsx", "test"),
                ("components/button.tsx", "component"),
                ("pages/api/legacy.ts", "page"),
                ("proxy.ts", "proxy"),
                ("instrumentation.ts", "instrumentation"),
                ("simulators/echo.ts", "simulator"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            discovered.source_files,
            [
                "app/api/wordpress/test/route.ts",
                "app/page.tsx",
                "components/button.tsx",
                "instrumentation.ts",
                "pages/api/legacy.ts",
                "proxy.ts",
            ]
        );
        assert_eq!(
            discovered.source_roots,
            [
                "app",
                "components",
                "instrumentation.ts",
                "pages",
                "proxy.ts"
            ],
            "a declaration file is not a root"
        );
        for file in [
            "app/api/wordpress/test/route.test.ts",
            "app/api/wordpress/test/helper.ts",
            "app/__tests__/page.tsx",
        ] {
            assert_eq!(entry(&discovered, file).reason, "test or fixture source");
        }
        // Nothing says what `simulators/` is, so it is still asked about.
        assert_eq!(
            entry(&discovered, "simulators/echo.ts").status,
            SourceScopeStatus::Ambiguous
        );
        // Named roots keep the route too.
        let roots = vec!["app".into()];
        let named = discover_source_scope(&root, Some(&roots)).unwrap();
        assert_eq!(
            named.source_files,
            ["app/api/wordpress/test/route.ts", "app/page.tsx"]
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_route_file_name_means_nothing_outside_a_next_application() {
        let root = repository(
            "not-next",
            &[
                ("package.json", "{}"),
                ("app/main.ts", "main"),
                ("app/test/route.ts", "a test helper"),
                ("proxy.ts", "unknown"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(discovered.source_files, ["app/main.ts"]);
        assert_eq!(
            entry(&discovered, "app/test/route.ts").reason,
            "test or fixture source"
        );
        assert_eq!(
            entry(&discovered, "proxy.ts").status,
            SourceScopeStatus::Ambiguous
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_named_root_settles_what_it_names_and_guesses_only_below_it() {
        // `scripts`, or a directory called `test-utils`, read as tooling and
        // tests to discovery. Naming one as a source root says otherwise, and
        // there was no way to say it: the named root stayed excluded.
        let root = repository(
            "named-roots",
            &[
                ("package.json", "{}"),
                ("src/main.ts", "main"),
                ("src/test-utils/build.ts", "helper"),
                ("src/test-utils/__tests__/build.test.ts", "test"),
                ("scripts/release.ts", "script"),
                ("scripts/fixtures/sample.ts", "fixture"),
                ("tools/one.spec.ts", "named file"),
            ],
        );
        let roots = vec!["src".into()];
        let discovered = discover_source_scope(&root, Some(&roots)).unwrap();
        assert_eq!(discovered.source_files, ["src/main.ts"]);

        let roots = vec![
            "src/test-utils".into(),
            "scripts".into(),
            "tools/one.spec.ts".into(),
        ];
        let discovered = discover_source_scope(&root, Some(&roots)).unwrap();
        assert_eq!(
            discovered.source_files,
            [
                "scripts/release.ts",
                "src/test-utils/build.ts",
                "tools/one.spec.ts",
            ]
        );
        assert_eq!(
            entry(&discovered, "src/test-utils/__tests__/build.test.ts").reason,
            "test or fixture source"
        );
        assert_eq!(
            entry(&discovered, "scripts/fixtures/sample.ts").reason,
            "test or fixture source"
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn explicit_roots_are_authoritative_and_outside_files_are_not_limitations() {
        let root = repository(
            "explicit",
            &[
                ("package.json", "{}"),
                ("product/main.ts", "product"),
                ("orphan.ts", "outside"),
            ],
        );
        let roots = vec!["product".into()];
        let discovered = discover_source_scope(&root, Some(&roots)).unwrap();
        assert_eq!(discovered.source_files, ["product/main.ts"]);
        assert_eq!(discovered.scope.mode, SourceScopeMode::Explicit);
        assert_eq!(
            entry(&discovered, "orphan.ts").reason,
            "outside explicit source roots"
        );
        assert!(discovered.limitations.is_empty());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn parses_jsonc_tsconfig_defaults_and_unicode_paths_without_byte_corruption() {
        let root = repository(
            "jsonc",
            &[
                ("package.json", r#"{"main":"./dist/index.js"}"#),
                (
                    "tsconfig.json",
                    "{ // unicode survives: ž\n \"compilerOptions\": {\"target\": \"es2022\",},\n}",
                ),
                ("events.ts", "event"),
                ("žalias.ts", "unicode"),
                ("library.test.ts", "test"),
            ],
        );
        let discovered = discover_source_scope(&root, None).unwrap();
        assert!(discovered.source_roots.contains(&".".into()));
        assert_eq!(discovered.source_files, ["events.ts", "žalias.ts"]);
        assert!(discovered.limitations.is_empty());
        fs::remove_dir_all(root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn never_follows_source_directory_or_explicit_root_symlinks() {
        use std::os::unix::fs::symlink;

        let root = repository(
            "symlink",
            &[("package.json", "{}"), ("src/real.ts", "real")],
        );
        let outside = repository("outside", &[("secret.ts", "secret")]);
        symlink(&outside, root.join("linked")).unwrap();
        symlink(outside.join("secret.ts"), root.join("src/linked.ts")).unwrap();
        let discovered = discover_source_scope(&root, None).unwrap();
        assert_eq!(discovered.source_files, ["src/real.ts"]);
        let explicit = vec!["linked".into()];
        assert!(matches!(
            discover_source_scope(&root, Some(&explicit)),
            Err(SourceDiscoveryError::InvalidRoot(_))
        ));
        fs::remove_dir_all(root).unwrap();
        fs::remove_dir_all(outside).unwrap();
    }

    #[test]
    fn skips_only_marker_owned_workspace_stores_not_user_supercov_directories() {
        let root = repository(
            "workspace-store",
            &[
                ("package.json", "{}"),
                ("src/main.ts", "main"),
                ("supercov/user.ts", "user code"),
            ],
        );
        let before = discover_source_scope(&root, None).unwrap();
        assert_eq!(
            entry(&before, "supercov/user.ts").status,
            SourceScopeStatus::Ambiguous
        );
        fs::write(
            root.join("supercov/.supercov-workspace-store"),
            b"Supercov instrumented workspace. Safe to delete.\n",
        )
        .unwrap();
        let after = discover_source_scope(&root, None).unwrap();
        assert!(
            after
                .scope
                .entries
                .iter()
                .all(|entry| !entry.file.starts_with("supercov/"))
        );
        fs::remove_dir_all(root).unwrap();
    }
}