fallow-config 3.22.0

Configuration types and workspace discovery for fallow codebase intelligence
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
mod deno_json;
mod diagnostics;
mod npm_overrides;
mod package_json;
mod parsers;
mod pnpm_catalog;
mod pnpm_overrides;

use std::path::{Path, PathBuf};

use rustc_hash::FxHashMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

pub use deno_json::{
    DirManifestProbe, dir_has_deno_json, dir_has_package_manifest, is_deno_without_node_modules,
    load_deno_import_map, load_dir_package_json, load_member_package_manifest,
    load_root_deno_workspace_patterns, probe_dir_manifest,
};
#[cfg(test)]
pub use diagnostics::capture_workspace_warnings;
pub use diagnostics::{
    WorkspaceDiagnostic, WorkspaceDiagnosticKind, WorkspaceLoadError, append_workspace_diagnostics,
    clear_analysis_stage_diagnostics, record_source_read_failures, record_workspace_diagnostics,
    registry_diagnostics_to_fold, replace_source_discovery_diagnostics,
    stash_workspace_diagnostics, workspace_diagnostics_for,
};
use diagnostics::{emit_diagnostics, is_skip_listed_dir};
pub use npm_overrides::{parse_bun_package_json_resolutions, parse_npm_package_json_overrides};
pub use package_json::{NapiConfig, PackageJson};
pub use parsers::parse_tsconfig_root_dir;
use parsers::{
    expand_workspace_glob_with_diagnostics, parse_pnpm_workspace_yaml,
    parse_tsconfig_references_with_diagnostics,
};
pub use pnpm_catalog::{
    PnpmCatalog, PnpmCatalogData, PnpmCatalogEntry, PnpmCatalogGroup,
    parse_package_json_catalog_data, parse_pnpm_catalog_data,
};
pub use pnpm_overrides::{
    MisconfigReason, OverrideSource, ParsedOverrideKey, PnpmOverrideData, PnpmOverrideEntry,
    is_valid_override_value, override_misconfig_reason, override_source_label, parse_override_key,
    parse_pnpm_package_json_overrides, parse_pnpm_workspace_overrides,
};

/// Workspace configuration for monorepo support.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
pub struct WorkspaceConfig {
    /// Additional workspace patterns (beyond what's in root package.json).
    ///
    /// `packages` is accepted as a back-compat alias: an older `fallow init --toml`
    /// wrote `[workspaces]` with a `packages` key, and reading it as `patterns`
    /// keeps those existing configs scoping correctly. schemars omits serde
    /// aliases, so `schema.json` documents only `patterns`.
    #[serde(default, alias = "packages")]
    pub patterns: Vec<String>,
}

/// Discovered workspace info from package.json, deno.json, pnpm-workspace.yaml,
/// or tsconfig.json references.
#[derive(Debug, Clone)]
pub struct WorkspaceInfo {
    /// Workspace root path.
    pub root: PathBuf,
    /// Package name from package.json or deno.json.
    pub name: String,
    /// Whether this workspace is depended on by other workspaces.
    pub is_internal_dependency: bool,
}

/// Return whether a workspace package name is selected by `publicPackages`.
///
/// Exact names and glob patterns share one config-owned matcher so analysis
/// surfaces cannot disagree about which workspace APIs are public. Invalid
/// patterns do not match, preserving the existing fail-closed behavior.
#[must_use]
pub fn workspace_is_public(name: &str, public_packages: &[String]) -> bool {
    public_packages.iter().any(|pattern| {
        name == pattern
            || globset::Glob::new(pattern)
                .ok()
                .is_some_and(|glob| glob.compile_matcher().is_match(name))
    })
}

/// Discover all workspace packages in a monorepo.
///
/// Sources (additive, deduplicated by canonical path):
/// 1. `package.json` `workspaces` field
/// 2. `pnpm-workspace.yaml` `packages` field
/// 3. `deno.json` / `deno.jsonc` `workspace` field
/// 4. `tsconfig.json` `references` field (TypeScript project references)
///
/// Back-compat wrapper: drops any diagnostics and silently treats a malformed
/// root `package.json` as "no workspaces". New callers should use
/// [`discover_workspaces_with_diagnostics`] to receive typed
/// [`WorkspaceDiagnostic`] values and to surface root-malformed errors as
/// hard exits.
///
/// This wrapper goes through the silent collector path that does NOT call
/// `emit_diagnostics` (private helper in `crates/config/src/workspace/diagnostics.rs`
/// that does the `tracing::warn!` emission). Without that split, sibling
/// callers in `core/src/lib.rs` (analyze) and `core/src/discover/mod.rs`
/// (file discovery) would re-emit `tracing::warn!` on paths the user already
/// excluded via `ignorePatterns`, because the back-compat wrapper has no
/// access to the user's globset.
#[must_use]
pub fn discover_workspaces(root: &Path) -> Vec<WorkspaceInfo> {
    collect_workspaces_and_diagnostics(root, &globset::GlobSet::empty())
        .map(|(workspaces, _)| workspaces)
        .unwrap_or_default()
}

/// Discover workspace packages and return any diagnostics produced along the
/// way.
///
/// Replaces the four silent-drop sites in [`discover_workspaces`] with typed
/// [`WorkspaceDiagnostic`] values:
/// - malformed declared-workspace `package.json` (warn-and-continue),
/// - glob match resolving to a directory without `package.json` (warn,
///   filtered through `ignore_patterns` and an extended skip list),
/// - malformed `tsconfig.json` (warn-and-continue),
/// - tsconfig `references[].path` pointing to a missing directory (warn).
///
/// `ignore_patterns` mirrors the precedent in
/// [`find_undeclared_workspaces_with_ignores`]: directories the user already
/// excluded do not trigger a redundant diagnostic.
///
/// Returns [`WorkspaceLoadError::MalformedRootPackageJson`] when the root
/// `package.json` exists but fails to parse: without a parseable root, no
/// workspace patterns can be collected and the analysis output would be
/// fiction. The CLI surfaces this as exit 2.
///
/// Shallow-scan fallback candidates (`collect_shallow_workspace_candidate`)
/// stay silent: the user did not declare them, so a stray malformed
/// `package.json` two levels deep in a `tools/scratch/` directory should not
/// produce noise.
///
/// # Errors
///
/// Returns [`WorkspaceLoadError`] when the project root's `package.json`
/// exists but is not valid JSON. Callers map this to a hard exit.
pub fn discover_workspaces_with_diagnostics(
    root: &Path,
    ignore_patterns: &globset::GlobSet,
) -> Result<(Vec<WorkspaceInfo>, Vec<WorkspaceDiagnostic>), WorkspaceLoadError> {
    let (workspaces, diagnostics) = collect_workspaces_and_diagnostics(root, ignore_patterns)?;

    emit_diagnostics(root, &diagnostics);

    Ok((workspaces, diagnostics))
}

/// Collect workspaces and diagnostics without emitting `tracing::warn!`.
///
/// Both [`discover_workspaces_with_diagnostics`] (which adds the emit step)
/// and [`discover_workspaces`] (which drops both diagnostics and emission)
/// route through this function. Keeping emission in the public top-level
/// only means downstream callers that have no access to the user's
/// `ignorePatterns` cannot accidentally re-emit warnings on paths the user
/// already excluded.
///
/// The returned diagnostics are deduplicated on the whole `(kind, path)`, the
/// way every downstream fold is. The sources are additive, so a repository that
/// declares one glob in both `package.json` `workspaces` and
/// `pnpm-workspace.yaml` `packages` walks it twice and reports every
/// package-less directory under it twice. Folding here rather than only in the
/// process registry is what keeps the returned list, the `workspaces` and
/// `list --workspaces` envelopes, the MCP `project_info` tool and the
/// aggregated stderr warning (whose per-pattern grouping counts the entries it
/// is handed) agreeing on one entry per distinct matching pattern (issue
/// #2366). Two overlapping globs (`["packages/*", "packages/*/*"]`) still
/// report the same directory once per `pattern`: the payload is part of the
/// key.
fn collect_workspaces_and_diagnostics(
    root: &Path,
    ignore_patterns: &globset::GlobSet,
) -> Result<(Vec<WorkspaceInfo>, Vec<WorkspaceDiagnostic>), WorkspaceLoadError> {
    let mut diagnostics = Vec::new();
    let patterns = collect_workspace_patterns(root)?;
    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let mut manifest_cache = ManifestCache::default();

    let mut workspaces = expand_patterns_to_workspaces(
        root,
        &patterns,
        &canonical_root,
        ignore_patterns,
        &mut diagnostics,
        &mut manifest_cache,
    );
    workspaces.extend(collect_tsconfig_workspaces(
        root,
        &canonical_root,
        ignore_patterns,
        &mut diagnostics,
        &mut manifest_cache,
    ));
    if patterns.is_empty() {
        workspaces.extend(collect_shallow_package_workspaces(
            root,
            &canonical_root,
            &mut manifest_cache,
        ));
    }

    if !workspaces.is_empty() {
        mark_internal_dependencies(&mut workspaces);
    }
    let workspaces = workspaces.into_iter().map(|(ws, _)| ws).collect();
    Ok((
        workspaces,
        fallow_types::workspace::dedupe_workspace_diagnostics(diagnostics),
    ))
}

/// Find directories containing `package.json` that are not declared as workspaces.
///
/// Only meaningful in monorepos that declare workspaces (via `package.json` `workspaces`
/// field or `pnpm-workspace.yaml`). Scans up to two directory levels deep, skipping
/// hidden directories, `node_modules`, and `build`.
#[must_use]
pub fn find_undeclared_workspaces(
    root: &Path,
    declared: &[WorkspaceInfo],
) -> Vec<WorkspaceDiagnostic> {
    find_undeclared_workspaces_with_ignores(root, declared, &globset::GlobSet::empty())
}

/// Find directories containing `package.json` that are not declared as workspaces,
/// excluding candidates covered by the supplied ignore globset.
///
/// This is the ignore-aware variant used by the full analyzer after config
/// resolution. See [`find_undeclared_workspaces`] for the compatibility wrapper.
///
/// Directories whose project-root-relative path matches `ignore_patterns` are skipped
/// so users who already excluded a path via `ignorePatterns` don't see a redundant
/// "not declared as workspace" warning. See issue #193.
#[must_use]
pub fn find_undeclared_workspaces_with_ignores(
    root: &Path,
    declared: &[WorkspaceInfo],
    ignore_patterns: &globset::GlobSet,
) -> Vec<WorkspaceDiagnostic> {
    let patterns = collect_workspace_patterns(root).unwrap_or_default();
    if patterns.is_empty() {
        return Vec::new();
    }

    let declared_roots: rustc_hash::FxHashSet<PathBuf> = declared
        .iter()
        .map(|w| dunce::canonicalize(&w.root).unwrap_or_else(|_| w.root.clone()))
        .collect();

    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());

    let mut undeclared = Vec::new();

    let Ok(top_entries) = std::fs::read_dir(root) else {
        return Vec::new();
    };

    for entry in top_entries.filter_map(Result::ok) {
        let path = entry.path();
        if !path.is_dir() || is_undeclared_scan_skip_dir(&entry.file_name().to_string_lossy()) {
            continue;
        }

        let mut input = UndeclaredScanInput {
            root,
            canonical_root: &canonical_root,
            declared_roots: &declared_roots,
            ignore_patterns,
            undeclared: &mut undeclared,
        };
        check_undeclared(
            &path,
            input.root,
            input.canonical_root,
            input.declared_roots,
            input.ignore_patterns,
            input.undeclared,
        );
        scan_child_dirs_for_undeclared(&path, &mut input);
    }

    undeclared
}

/// Whether an undeclared-workspace scan should skip a directory by leaf name.
fn is_undeclared_scan_skip_dir(name: &str) -> bool {
    name.starts_with('.') || name == "node_modules" || name == "build"
}

/// Borrowed inputs threaded through the second-level undeclared-workspace scan.
struct UndeclaredScanInput<'a> {
    root: &'a Path,
    canonical_root: &'a Path,
    declared_roots: &'a rustc_hash::FxHashSet<PathBuf>,
    ignore_patterns: &'a globset::GlobSet,
    undeclared: &'a mut Vec<WorkspaceDiagnostic>,
}

/// Check each immediate child of `parent` for an undeclared workspace.
fn scan_child_dirs_for_undeclared(parent: &Path, input: &mut UndeclaredScanInput<'_>) {
    let Ok(child_entries) = std::fs::read_dir(parent) else {
        return;
    };
    for child in child_entries.filter_map(Result::ok) {
        let child_path = child.path();
        if !child_path.is_dir() || is_undeclared_scan_skip_dir(&child.file_name().to_string_lossy())
        {
            continue;
        }
        check_undeclared(
            &child_path,
            input.root,
            input.canonical_root,
            input.declared_roots,
            input.ignore_patterns,
            input.undeclared,
        );
    }
}

/// Check a single directory for an undeclared workspace.
fn check_undeclared(
    dir: &Path,
    root: &Path,
    canonical_root: &Path,
    declared_roots: &rustc_hash::FxHashSet<PathBuf>,
    ignore_patterns: &globset::GlobSet,
    undeclared: &mut Vec<WorkspaceDiagnostic>,
) {
    if !dir_has_package_manifest(dir) {
        return;
    }
    let canonical = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    if canonical == *canonical_root {
        return;
    }
    if declared_roots.contains(&canonical) {
        return;
    }
    let relative = dir.strip_prefix(root).unwrap_or(dir);
    let relative_str = relative.to_string_lossy().replace('\\', "/");
    if ignore_patterns.is_match(relative_str.as_str())
        || ignore_patterns.is_match(format!("{relative_str}/package.json").as_str())
        || ignore_patterns.is_match(format!("{relative_str}/deno.json").as_str())
        || ignore_patterns.is_match(format!("{relative_str}/deno.jsonc").as_str())
    {
        return;
    }
    undeclared.push(WorkspaceDiagnostic::new(
        root,
        dir.to_path_buf(),
        WorkspaceDiagnosticKind::UndeclaredWorkspace,
    ));
}

/// Collect glob patterns from `package.json` `workspaces`, `pnpm-workspace.yaml`,
/// and Deno `deno.json` / `deno.jsonc` `workspace`.
fn collect_workspace_patterns(root: &Path) -> Result<Vec<String>, WorkspaceLoadError> {
    let mut patterns = Vec::new();

    let pkg_path = root.join("package.json");
    if pkg_path.exists() {
        match PackageJson::load(&pkg_path) {
            Ok(pkg) => patterns.extend(pkg.workspace_patterns()),
            Err(error) => {
                return Err(WorkspaceLoadError::MalformedRootPackageJson {
                    path: pkg_path,
                    error,
                });
            }
        }
    }

    let pnpm_workspace = root.join("pnpm-workspace.yaml");
    if pnpm_workspace.exists()
        && let Ok(content) = std::fs::read_to_string(&pnpm_workspace)
    {
        patterns.extend(parse_pnpm_workspace_yaml(&content));
    }

    if let Some((_path, deno_patterns)) = load_root_deno_workspace_patterns(root)
        .map_err(|(path, error)| WorkspaceLoadError::MalformedRootDenoConfig { path, error })?
    {
        patterns.extend(deno_patterns);
    }

    Ok(patterns)
}

/// Memoized [`load_member_package_manifest`] outcomes for one discovery run.
///
/// The same directory is commonly matched by more than one workspace source
/// (identical globs in `package.json` and `pnpm-workspace.yaml`, tsconfig
/// references overlapping npm workspaces). Each manifest load costs a
/// `package.json` read plus Deno `deno.json` / `deno.jsonc` probes, so repeat
/// visits replay the memoized outcome instead of touching the filesystem again.
type ManifestCache = FxHashMap<PathBuf, Result<Option<(String, PackageJson, Vec<String>)>, String>>;

/// Load a member manifest through the per-discovery memo, preserving the
/// exact per-call outcome (including errors) on repeat visits.
fn load_member_package_manifest_cached(
    dir: &Path,
    cache: &mut ManifestCache,
) -> Result<Option<(String, PackageJson, Vec<String>)>, String> {
    if let Some(cached) = cache.get(dir) {
        return cached.clone();
    }
    let outcome = load_member_package_manifest(dir);
    cache.insert(dir.to_path_buf(), outcome.clone());
    outcome
}

/// Expand workspace glob patterns to discover workspace directories.
///
/// Handles positive/negated pattern splitting, glob matching, and package.json
/// loading for each matched directory.
fn expand_patterns_to_workspaces(
    root: &Path,
    patterns: &[String],
    canonical_root: &Path,
    ignore_patterns: &globset::GlobSet,
    diagnostics: &mut Vec<WorkspaceDiagnostic>,
    manifest_cache: &mut ManifestCache,
) -> Vec<(WorkspaceInfo, Vec<String>)> {
    if patterns.is_empty() {
        return Vec::new();
    }

    let mut workspaces = Vec::new();

    let (positive, negative): (Vec<&String>, Vec<&String>) =
        patterns.iter().partition(|p| !p.starts_with('!'));
    let negation_matchers: Vec<globset::GlobMatcher> = negative
        .iter()
        .filter_map(|p| {
            let stripped = p.strip_prefix('!').unwrap_or(p);
            globset::Glob::new(stripped)
                .ok()
                .map(|g| g.compile_matcher())
        })
        .collect();

    for pattern in &positive {
        let glob_pattern = if pattern.ends_with('/') {
            format!("{pattern}*")
        } else {
            (*pattern).clone()
        };

        let matched_dirs = expand_workspace_glob_with_diagnostics(
            root,
            pattern,
            &glob_pattern,
            canonical_root,
            ignore_patterns,
            diagnostics,
        );
        for (dir, canonical_dir) in matched_dirs {
            if canonical_dir == *canonical_root {
                continue;
            }
            if matches_negation(root, &dir, &negation_matchers) {
                continue;
            }
            register_matched_workspace(root, dir, &mut workspaces, diagnostics, manifest_cache);
        }
    }

    workspaces
}

/// Whether a matched directory is excluded by a negated workspace pattern.
fn matches_negation(root: &Path, dir: &Path, negation_matchers: &[globset::GlobMatcher]) -> bool {
    let relative = dir.strip_prefix(root).unwrap_or(dir);
    let relative_str = relative.to_string_lossy();
    negation_matchers
        .iter()
        .any(|m| m.is_match(relative_str.as_ref()))
}

/// Load a matched directory's package manifest (`package.json` or `deno.json`)
/// and push a workspace, or a malformed-package diagnostic on parse failure.
/// A manifest removed after glob expansion is treated as a stale match.
fn register_matched_workspace(
    root: &Path,
    dir: PathBuf,
    workspaces: &mut Vec<(WorkspaceInfo, Vec<String>)>,
    diagnostics: &mut Vec<WorkspaceDiagnostic>,
    manifest_cache: &mut ManifestCache,
) {
    match load_member_package_manifest_cached(&dir, manifest_cache) {
        Ok(Some((name, _pkg, dep_names))) => {
            workspaces.push((
                WorkspaceInfo {
                    root: dir,
                    name,
                    is_internal_dependency: false,
                },
                dep_names,
            ));
        }
        Ok(None) => {}
        Err(error) => {
            let diag = WorkspaceDiagnostic::new(
                root,
                dir,
                WorkspaceDiagnosticKind::MalformedPackageJson { error },
            );
            diagnostics.push(diag);
        }
    }
}

/// Discover workspaces from TypeScript project references in `tsconfig.json`.
///
/// Referenced directories are added as workspaces, supplementing npm/pnpm workspaces.
/// This enables cross-workspace resolution for TypeScript composite projects.
fn collect_tsconfig_workspaces(
    root: &Path,
    canonical_root: &Path,
    ignore_patterns: &globset::GlobSet,
    diagnostics: &mut Vec<WorkspaceDiagnostic>,
    manifest_cache: &mut ManifestCache,
) -> Vec<(WorkspaceInfo, Vec<String>)> {
    let mut workspaces = Vec::new();

    for dir in parse_tsconfig_references_with_diagnostics(root, ignore_patterns, diagnostics) {
        if let Some(workspace) =
            tsconfig_workspace_from_dir(root, dir, canonical_root, diagnostics, manifest_cache)
        {
            workspaces.push(workspace);
        }
    }

    workspaces
}

fn tsconfig_workspace_from_dir(
    root: &Path,
    dir: PathBuf,
    canonical_root: &Path,
    diagnostics: &mut Vec<WorkspaceDiagnostic>,
    manifest_cache: &mut ManifestCache,
) -> Option<(WorkspaceInfo, Vec<String>)> {
    let canonical_dir = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
    if canonical_dir == *canonical_root || !canonical_dir.starts_with(canonical_root) {
        return None;
    }

    let (name, dep_names) =
        load_tsconfig_workspace_package(root, &dir, diagnostics, manifest_cache);
    Some((
        WorkspaceInfo {
            root: dir,
            name,
            is_internal_dependency: false,
        },
        dep_names,
    ))
}

fn load_tsconfig_workspace_package(
    root: &Path,
    dir: &Path,
    diagnostics: &mut Vec<WorkspaceDiagnostic>,
    manifest_cache: &mut ManifestCache,
) -> (String, Vec<String>) {
    match load_member_package_manifest_cached(dir, manifest_cache) {
        Ok(Some((name, _pkg, deps))) => (name, deps),
        Ok(None) => (dir_name(dir), Vec::new()),
        Err(error) => {
            let diag = WorkspaceDiagnostic::new(
                root,
                dir.to_path_buf(),
                WorkspaceDiagnosticKind::MalformedPackageJson { error },
            );
            diagnostics.push(diag);
            (dir_name(dir), Vec::new())
        }
    }
}

/// Discover shallow package workspaces when no explicit workspace config exists.
///
/// Scans direct children of the project root and their immediate children for
/// `package.json` files. This catches repos that contain multiple standalone
/// packages (for example `benchmarks/` or `editors/vscode/`) without declaring
/// npm/pnpm workspaces at the root.
fn collect_shallow_package_workspaces(
    root: &Path,
    canonical_root: &Path,
    manifest_cache: &mut ManifestCache,
) -> Vec<(WorkspaceInfo, Vec<String>)> {
    let mut workspaces = Vec::new();
    let Ok(top_entries) = std::fs::read_dir(root) else {
        return workspaces;
    };

    for entry in top_entries.filter_map(Result::ok) {
        let path = entry.path();
        if !path.is_dir() || should_skip_workspace_scan_dir(&entry.file_name().to_string_lossy()) {
            continue;
        }

        collect_shallow_workspace_candidate(&path, canonical_root, &mut workspaces, manifest_cache);
        collect_shallow_child_workspaces(&path, canonical_root, &mut workspaces, manifest_cache);
    }

    workspaces
}

fn collect_shallow_child_workspaces(
    parent: &Path,
    canonical_root: &Path,
    workspaces: &mut Vec<(WorkspaceInfo, Vec<String>)>,
    manifest_cache: &mut ManifestCache,
) {
    let Ok(child_entries) = std::fs::read_dir(parent) else {
        return;
    };
    for child in child_entries.filter_map(Result::ok) {
        let child_path = child.path();
        if !child_path.is_dir()
            || should_skip_workspace_scan_dir(&child.file_name().to_string_lossy())
        {
            continue;
        }

        collect_shallow_workspace_candidate(
            &child_path,
            canonical_root,
            workspaces,
            manifest_cache,
        );
    }
}

fn collect_shallow_workspace_candidate(
    dir: &Path,
    canonical_root: &Path,
    workspaces: &mut Vec<(WorkspaceInfo, Vec<String>)>,
    manifest_cache: &mut ManifestCache,
) {
    let canonical_dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    if canonical_dir == *canonical_root || !canonical_dir.starts_with(canonical_root) {
        return;
    }

    let Ok(Some((name, _pkg, dep_names))) =
        load_member_package_manifest_cached(dir, manifest_cache)
    else {
        return;
    };

    workspaces.push((
        WorkspaceInfo {
            root: dir.to_path_buf(),
            name,
            is_internal_dependency: false,
        },
        dep_names,
    ));
}

fn should_skip_workspace_scan_dir(name: &str) -> bool {
    is_skip_listed_dir(name)
}

/// Deduplicate workspaces by canonical path and mark internal dependencies.
///
/// Overlapping sources (npm workspaces + tsconfig references pointing to the same
/// directory) are collapsed. npm-discovered entries take precedence (they appear first).
/// Workspaces depended on by other workspaces are marked as `is_internal_dependency`.
fn mark_internal_dependencies(workspaces: &mut Vec<(WorkspaceInfo, Vec<String>)>) {
    {
        let mut seen = rustc_hash::FxHashSet::default();
        workspaces.retain(|(ws, _)| {
            let canonical = dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone());
            seen.insert(canonical)
        });
    }

    let all_dep_names: rustc_hash::FxHashSet<String> = workspaces
        .iter()
        .flat_map(|(_, deps)| deps.iter().cloned())
        .collect();

    for (ws, _) in &mut *workspaces {
        ws.is_internal_dependency = all_dep_names.contains(&ws.name);
    }
}

/// Extract the directory name as a string, for workspace name fallback.
fn dir_name(dir: &Path) -> String {
    dir.file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default()
}

/// Build the issue-2366 repository shape: one glob declared in both
/// `package.json` (spelled `./pkgs/*`) and `pnpm-workspace.yaml` (spelled
/// `pkgs/*`), over two directories that carry no `package.json`.
///
/// Shared with the emission tests in `diagnostics.rs`, which assert that the
/// aggregated stderr warning counts each directory once.
#[cfg(test)]
pub fn write_two_manifest_glob_project(root: &Path) {
    std::fs::create_dir_all(root.join("pkgs/aaa")).unwrap();
    std::fs::create_dir_all(root.join("pkgs/bbb")).unwrap();
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"two-manifest-root","private":true,"workspaces":["./pkgs/*"]}"#,
    )
    .unwrap();
    std::fs::write(
        root.join("pnpm-workspace.yaml"),
        "packages:\n  - \"pkgs/*\"\n",
    )
    .unwrap();
    std::fs::write(root.join("pkgs/aaa/readme.txt"), "no package.json here\n").unwrap();
    std::fs::write(root.join("pkgs/bbb/readme.txt"), "no package.json here\n").unwrap();
}

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

    #[test]
    fn public_workspace_selection_supports_exact_names_and_globs() {
        assert!(!workspace_is_public("@scope/core", &[]));
        assert!(workspace_is_public(
            "@scope/core",
            &["@scope/core".to_string()]
        ));
        assert!(workspace_is_public(
            "@scope/core",
            &["@scope/*".to_string()]
        ));
        assert!(!workspace_is_public(
            "@scope/core",
            &["[invalid".to_string(), "@other/*".to_string()]
        ));
    }

    #[test]
    fn discover_workspaces_from_tsconfig_references() {
        let temp_dir = std::env::temp_dir().join("fallow-test-ws-tsconfig-refs");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("packages/core")).unwrap();
        std::fs::create_dir_all(temp_dir.join("packages/ui")).unwrap();

        std::fs::write(
            temp_dir.join("tsconfig.json"),
            r#"{"references": [{"path": "./packages/core"}, {"path": "./packages/ui"}]}"#,
        )
        .unwrap();

        std::fs::write(
            temp_dir.join("packages/core/package.json"),
            r#"{"name": "@project/core"}"#,
        )
        .unwrap();

        let workspaces = discover_workspaces(&temp_dir);
        assert_eq!(workspaces.len(), 2);
        assert!(workspaces.iter().any(|ws| ws.name == "@project/core"));
        assert!(workspaces.iter().any(|ws| ws.name == "ui"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn tsconfig_references_outside_root_rejected() {
        let temp_dir = std::env::temp_dir().join("fallow-test-tsconfig-outside");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("project/packages/core")).unwrap();
        std::fs::create_dir_all(temp_dir.join("outside")).unwrap();

        std::fs::write(
            temp_dir.join("project/tsconfig.json"),
            r#"{"references": [{"path": "./packages/core"}, {"path": "../outside"}]}"#,
        )
        .unwrap();

        let workspaces = discover_workspaces(&temp_dir.join("project"));
        assert_eq!(
            workspaces.len(),
            1,
            "reference outside project root should be rejected: {workspaces:?}"
        );
        assert!(
            workspaces[0]
                .root
                .to_string_lossy()
                .contains("packages/core")
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn dir_name_extracts_last_component() {
        assert_eq!(dir_name(Path::new("/project/packages/core")), "core");
        assert_eq!(dir_name(Path::new("/my-app")), "my-app");
    }

    #[test]
    fn dir_name_empty_for_root_path() {
        assert_eq!(dir_name(Path::new("/")), "");
    }

    #[test]
    fn workspace_config_deserialize_json() {
        let json = r#"{"patterns": ["packages/*", "apps/*"]}"#;
        let config: WorkspaceConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.patterns, vec!["packages/*", "apps/*"]);
    }

    #[test]
    fn workspace_config_deserialize_empty_patterns() {
        let json = r#"{"patterns": []}"#;
        let config: WorkspaceConfig = serde_json::from_str(json).unwrap();
        assert!(config.patterns.is_empty());
    }

    #[test]
    fn workspace_config_default_patterns() {
        let json = "{}";
        let config: WorkspaceConfig = serde_json::from_str(json).unwrap();
        assert!(config.patterns.is_empty());
    }

    #[test]
    fn workspace_info_default_not_internal() {
        let ws = WorkspaceInfo {
            root: PathBuf::from("/project/packages/a"),
            name: "a".to_string(),
            is_internal_dependency: false,
        };
        assert!(!ws.is_internal_dependency);
    }

    #[test]
    fn mark_internal_deps_detects_cross_references() {
        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = temp_dir.path().join("a");
        let pkg_b = temp_dir.path().join("b");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_b).unwrap();

        let mut workspaces = vec![
            (
                WorkspaceInfo {
                    root: pkg_a,
                    name: "@scope/a".to_string(),
                    is_internal_dependency: false,
                },
                vec!["@scope/b".to_string()], // "a" depends on "b"
            ),
            (
                WorkspaceInfo {
                    root: pkg_b,
                    name: "@scope/b".to_string(),
                    is_internal_dependency: false,
                },
                vec!["lodash".to_string()], // "b" depends on external only
            ),
        ];

        mark_internal_dependencies(&mut workspaces);

        let ws_a = workspaces
            .iter()
            .find(|(ws, _)| ws.name == "@scope/a")
            .unwrap();
        assert!(
            !ws_a.0.is_internal_dependency,
            "a is not depended on by others"
        );

        let ws_b = workspaces
            .iter()
            .find(|(ws, _)| ws.name == "@scope/b")
            .unwrap();
        assert!(ws_b.0.is_internal_dependency, "b is depended on by a");
    }

    #[test]
    fn mark_internal_deps_no_cross_references() {
        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = temp_dir.path().join("a");
        let pkg_b = temp_dir.path().join("b");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_b).unwrap();

        let mut workspaces = vec![
            (
                WorkspaceInfo {
                    root: pkg_a,
                    name: "a".to_string(),
                    is_internal_dependency: false,
                },
                vec!["react".to_string()],
            ),
            (
                WorkspaceInfo {
                    root: pkg_b,
                    name: "b".to_string(),
                    is_internal_dependency: false,
                },
                vec!["lodash".to_string()],
            ),
        ];

        mark_internal_dependencies(&mut workspaces);

        assert!(!workspaces[0].0.is_internal_dependency);
        assert!(!workspaces[1].0.is_internal_dependency);
    }

    #[test]
    fn mark_internal_deps_deduplicates_by_path() {
        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = temp_dir.path().join("a");
        std::fs::create_dir_all(&pkg_a).unwrap();

        let mut workspaces = vec![
            (
                WorkspaceInfo {
                    root: pkg_a.clone(),
                    name: "a".to_string(),
                    is_internal_dependency: false,
                },
                vec![],
            ),
            (
                WorkspaceInfo {
                    root: pkg_a,
                    name: "a".to_string(),
                    is_internal_dependency: false,
                },
                vec![],
            ),
        ];

        mark_internal_dependencies(&mut workspaces);
        assert_eq!(
            workspaces.len(),
            1,
            "duplicate paths should be deduplicated"
        );
    }

    #[test]
    fn collect_patterns_from_package_json() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*", "apps/*"]}"#,
        )
        .unwrap();

        let patterns = collect_workspace_patterns(dir.path()).expect("valid root package.json");
        assert_eq!(patterns, vec!["packages/*", "apps/*"]);
    }

    #[test]
    fn collect_patterns_from_pnpm_workspace() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "packages:\n  - 'packages/*'\n  - 'libs/*'\n",
        )
        .unwrap();

        let patterns = collect_workspace_patterns(dir.path()).expect("no root package.json");
        assert_eq!(patterns, vec!["packages/*", "libs/*"]);
    }

    #[test]
    fn collect_patterns_combines_sources() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "packages:\n  - 'apps/*'\n",
        )
        .unwrap();

        let patterns = collect_workspace_patterns(dir.path()).expect("valid root package.json");
        assert!(patterns.contains(&"packages/*".to_string()));
        assert!(patterns.contains(&"apps/*".to_string()));
    }

    #[test]
    fn collect_patterns_empty_when_no_configs() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let patterns = collect_workspace_patterns(dir.path()).expect("no root package.json");
        assert!(patterns.is_empty());
    }

    #[test]
    fn discover_workspaces_from_package_json() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let pkg_b = dir.path().join("packages").join("b");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_b).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(
            pkg_a.join("package.json"),
            r#"{"name": "@test/a", "dependencies": {"@test/b": "workspace:*"}}"#,
        )
        .unwrap();
        std::fs::write(pkg_b.join("package.json"), r#"{"name": "@test/b"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert_eq!(workspaces.len(), 2);

        let ws_a = workspaces.iter().find(|ws| ws.name == "@test/a").unwrap();
        assert!(!ws_a.is_internal_dependency);

        let ws_b = workspaces.iter().find(|ws| ws.name == "@test/b").unwrap();
        assert!(ws_b.is_internal_dependency, "b is depended on by a");
    }

    #[test]
    fn discover_workspaces_empty_project() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let workspaces = discover_workspaces(dir.path());
        assert!(workspaces.is_empty());
    }

    #[test]
    fn discover_workspaces_falls_back_to_shallow_packages_without_workspace_config() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let benchmarks = dir.path().join("benchmarks");
        let vscode = dir.path().join("editors").join("vscode");
        let deep = dir.path().join("tests").join("fixtures").join("demo");
        std::fs::create_dir_all(&benchmarks).unwrap();
        std::fs::create_dir_all(&vscode).unwrap();
        std::fs::create_dir_all(&deep).unwrap();

        std::fs::write(benchmarks.join("package.json"), r#"{"name": "benchmarks"}"#).unwrap();
        std::fs::write(vscode.join("package.json"), r#"{"name": "fallow-vscode"}"#).unwrap();
        std::fs::write(deep.join("package.json"), r#"{"name": "deep-fixture"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        let names: Vec<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();

        assert!(
            names.contains(&"benchmarks"),
            "top-level nested package should be discovered: {workspaces:?}"
        );
        assert!(
            names.contains(&"fallow-vscode"),
            "second-level nested package should be discovered: {workspaces:?}"
        );
        assert!(
            !names.contains(&"deep-fixture"),
            "fallback should stay shallow and skip deep fixtures: {workspaces:?}"
        );
    }

    #[test]
    fn discover_workspaces_with_negated_patterns() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let pkg_test = dir.path().join("packages").join("test-utils");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_test).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*", "!packages/test-*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(pkg_test.join("package.json"), r#"{"name": "test-utils"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert_eq!(workspaces.len(), 1);
        assert_eq!(workspaces[0].name, "a");
    }

    #[test]
    fn discover_workspaces_skips_root_as_workspace() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("pnpm-workspace.yaml"),
            "packages:\n  - '.'\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("package.json"), r#"{"name": "root"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert!(
            workspaces.is_empty(),
            "root directory should not be added as workspace"
        );
    }

    #[test]
    fn discover_workspaces_name_fallback_to_dir_name() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("my-app");
        std::fs::create_dir_all(&pkg_a).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), "{}").unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert_eq!(workspaces.len(), 1);
        assert_eq!(workspaces[0].name, "my-app", "should fall back to dir name");
    }

    #[test]
    fn discover_workspaces_explicit_patterns_disable_shallow_fallback() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let benchmarks = dir.path().join("benchmarks");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&benchmarks).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(benchmarks.join("package.json"), r#"{"name": "benchmarks"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        let names: Vec<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();

        assert_eq!(workspaces.len(), 1);
        assert!(names.contains(&"a"));
        assert!(
            !names.contains(&"benchmarks"),
            "explicit workspace config should keep undeclared packages out: {workspaces:?}"
        );
    }

    #[test]
    fn discover_workspaces_recovers_package_under_bare_glob_intermediate() {
        // Issue #842 (reporter metrists/metrists): root declares
        // `["./packages/*", "./themes/*"]`, but the real package lives two levels
        // deep at `packages/themes/metrists-theme-next` while `packages/themes`
        // itself has no package.json. The single-level glob only matches the bare
        // `packages/themes`; without recovery the deep package is never discovered,
        // its files fall back to the root manifest, and its declared deps (react)
        // are reported as unlisted. Discovery must recover the named deep package.
        let dir = tempfile::tempdir().expect("create temp dir");
        let theme = dir
            .path()
            .join("packages")
            .join("themes")
            .join("metrists-theme-next");
        std::fs::create_dir_all(&theme).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"name": "metrists-monorepo", "workspaces": ["./packages/*", "./themes/*"]}"#,
        )
        .unwrap();
        // packages/themes intentionally has NO package.json (bare grouping dir).
        std::fs::write(
            theme.join("package.json"),
            r#"{"name": "metrists-theme-next", "dependencies": {"react": "^18"}}"#,
        )
        .unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert!(
            workspaces.iter().any(|ws| ws.name == "metrists-theme-next"),
            "deep package under a bare glob-matched intermediate must be discovered: {workspaces:?}"
        );
    }

    #[test]
    fn undeclared_workspace_detected() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let pkg_b = dir.path().join("packages").join("b");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_b).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/a"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(pkg_b.join("package.json"), r#"{"name": "b"}"#).unwrap();

        let declared = discover_workspaces(dir.path());
        assert_eq!(declared.len(), 1);

        let undeclared = find_undeclared_workspaces(dir.path(), &declared);
        assert_eq!(undeclared.len(), 1);
        assert!(
            undeclared[0]
                .path
                .to_string_lossy()
                .replace('\\', "/")
                .contains("packages/b"),
            "should detect packages/b as undeclared: {:?}",
            undeclared[0].path
        );
    }

    #[test]
    fn no_undeclared_when_all_covered() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        std::fs::create_dir_all(&pkg_a).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();

        let declared = discover_workspaces(dir.path());
        let undeclared = find_undeclared_workspaces(dir.path(), &declared);
        assert!(undeclared.is_empty());
    }

    #[test]
    fn no_undeclared_when_no_workspace_patterns() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let sub = dir.path().join("lib");
        std::fs::create_dir_all(&sub).unwrap();

        std::fs::write(dir.path().join("package.json"), r#"{"name": "app"}"#).unwrap();
        std::fs::write(sub.join("package.json"), r#"{"name": "lib"}"#).unwrap();

        let undeclared = find_undeclared_workspaces(dir.path(), &[]);
        assert!(
            undeclared.is_empty(),
            "should skip check when no workspace patterns exist"
        );
    }

    #[test]
    fn undeclared_skips_node_modules_and_hidden_dirs() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let nm = dir.path().join("node_modules").join("some-pkg");
        let hidden = dir.path().join(".hidden");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::create_dir_all(&hidden).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(nm.join("package.json"), r#"{"name": "nm-pkg"}"#).unwrap();
        std::fs::write(hidden.join("package.json"), r#"{"name": "hidden"}"#).unwrap();

        let undeclared = find_undeclared_workspaces(dir.path(), &[]);
        assert!(
            undeclared.is_empty(),
            "should not flag node_modules or hidden directories"
        );
    }

    fn build_globset(patterns: &[&str]) -> globset::GlobSet {
        let mut builder = globset::GlobSetBuilder::new();
        for pattern in patterns {
            builder.add(globset::Glob::new(pattern).expect("valid glob"));
        }
        builder.build().expect("build globset")
    }

    #[test]
    fn undeclared_skips_dirs_matching_ignore_patterns() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let vitest_ref = dir.path().join("references").join("vitest");
        let tanstack_ref = dir.path().join("references").join("tanstack-router");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&vitest_ref).unwrap();
        std::fs::create_dir_all(&tanstack_ref).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(
            vitest_ref.join("package.json"),
            r#"{"name": "vitest-reference"}"#,
        )
        .unwrap();
        std::fs::write(
            tanstack_ref.join("package.json"),
            r#"{"name": "tanstack-reference"}"#,
        )
        .unwrap();

        let declared = discover_workspaces(dir.path());
        let ignore = build_globset(&["references/*"]);
        let undeclared = find_undeclared_workspaces_with_ignores(dir.path(), &declared, &ignore);
        assert!(
            undeclared.is_empty(),
            "references/* should be ignored: {undeclared:?}"
        );
    }

    #[test]
    fn undeclared_still_reported_when_ignore_does_not_match() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_b = dir.path().join("packages").join("b");
        std::fs::create_dir_all(&pkg_b).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/a"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_b.join("package.json"), r#"{"name": "b"}"#).unwrap();

        let declared = discover_workspaces(dir.path());
        let ignore = build_globset(&["references/*"]);
        let undeclared = find_undeclared_workspaces_with_ignores(dir.path(), &declared, &ignore);
        assert_eq!(
            undeclared.len(),
            1,
            "non-matching ignore patterns should not silence other undeclared dirs"
        );
    }

    #[test]
    fn undeclared_skips_dirs_matching_package_json_glob() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let vitest_ref = dir.path().join("references").join("vitest");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&vitest_ref).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(
            vitest_ref.join("package.json"),
            r#"{"name": "vitest-reference"}"#,
        )
        .unwrap();

        let declared = discover_workspaces(dir.path());
        let ignore = build_globset(&["references/*/package.json"]);
        let undeclared = find_undeclared_workspaces_with_ignores(dir.path(), &declared, &ignore);
        assert!(
            undeclared.is_empty(),
            "package.json-suffixed glob should silence the warning: {undeclared:?}"
        );
    }

    #[test]
    fn undeclared_skips_dirs_matching_doublestar_ignore() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let nested_ref = dir.path().join("references").join("vitest");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&nested_ref).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(
            nested_ref.join("package.json"),
            r#"{"name": "vitest-reference"}"#,
        )
        .unwrap();

        let declared = discover_workspaces(dir.path());
        let ignore = build_globset(&["**/references/**"]);
        let undeclared = find_undeclared_workspaces_with_ignores(dir.path(), &declared, &ignore);
        assert!(
            undeclared.is_empty(),
            "**/references/** should ignore nested package.json dirs: {undeclared:?}"
        );
    }

    #[test]
    fn malformed_workspace_package_json_emits_diagnostic() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let pkg_bad = dir.path().join("packages").join("bad");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&pkg_bad).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(pkg_bad.join("package.json"), r#"{"name": "bad",}"#).unwrap();

        let (result, captured) = capture_workspace_warnings(|| {
            discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty())
        });
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert_eq!(workspaces.len(), 1, "the valid workspace still discovers");
        assert_eq!(workspaces[0].name, "a");
        assert_eq!(diagnostics.len(), 1);
        assert!(matches!(
            diagnostics[0].kind,
            WorkspaceDiagnosticKind::MalformedPackageJson { .. }
        ));
        assert!(
            captured
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedPackageJson { .. }))
        );
    }

    #[test]
    fn malformed_bridge_deno_config_emits_recoverable_member_diagnostic() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_good = dir.path().join("packages/good");
        let pkg_bad = dir.path().join("packages/bad");
        std::fs::create_dir_all(&pkg_good).unwrap();
        std::fs::create_dir_all(&pkg_bad).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
        std::fs::write(pkg_bad.join("package.json"), r#"{"name": "bad"}"#).unwrap();
        std::fs::write(pkg_bad.join("deno.jsonc"), "{ imports: [ }").unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert_eq!(workspaces.len(), 1, "valid sibling should still discover");
        assert_eq!(workspaces[0].name, "good");
        assert_eq!(diagnostics.len(), 1);
        assert!(matches!(
            diagnostics[0].kind,
            WorkspaceDiagnosticKind::MalformedPackageJson { .. }
        ));
        assert!(diagnostics[0].message.contains("deno.jsonc"));
    }

    /// A member reached through two workspace sources (npm glob + tsconfig
    /// reference) is diagnosed, and diagnosed ONCE: the two sources produce
    /// byte-identical diagnostics, so the discovery fold reports the member
    /// once where every envelope used to report it twice (issue #2366).
    ///
    /// That the tsconfig leg replayed the memoized `Err` rather than silently
    /// resolving is NOT observable here (both `Ok(None)` and `Err` fall back
    /// to the directory name, and the fold hides a second diagnostic);
    /// [`manifest_cache_replays_the_same_err_on_every_visit`] pins it.
    #[test]
    fn malformed_member_reached_via_two_sources_is_diagnosed_once() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_good = dir.path().join("packages").join("good");
        let pkg_bad = dir.path().join("packages").join("bad");
        std::fs::create_dir_all(&pkg_good).unwrap();
        std::fs::create_dir_all(&pkg_bad).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join("tsconfig.json"),
            r#"{"references": [{"path": "./packages/bad"}]}"#,
        )
        .unwrap();
        std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
        std::fs::write(pkg_bad.join("package.json"), r"{,}").unwrap();

        let (result, _) = capture_workspace_warnings(|| {
            discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty())
        });
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert!(
            workspaces.iter().any(|w| w.name == "good"),
            "valid sibling should still discover: {workspaces:?}"
        );
        assert!(
            workspaces.iter().any(|w| w.name == "bad"),
            "tsconfig reference falls back to the directory name on manifest error"
        );
        let malformed: Vec<_> = diagnostics
            .iter()
            .filter(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedPackageJson { .. }))
            .collect();
        assert_eq!(
            malformed.len(),
            1,
            "the replayed Err is one diagnostic, not one per source: {diagnostics:?}"
        );
        assert!(
            malformed[0].path.ends_with("bad"),
            "the diagnostic points at the malformed member"
        );
    }

    /// The per-discovery [`ManifestCache`] memoizes `Err` outcomes and every
    /// repeat visit must get the same `Err` back. Both callers that can reach
    /// one member ([`register_matched_workspace`] for an npm glob and
    /// [`load_tsconfig_workspace_package`] for a tsconfig reference) diagnose
    /// from the outcome the cache hands them, so a replay that degraded to
    /// `Ok(None)` would silently drop the diagnostic on whichever source is
    /// second. No end-to-end assertion can witness that: `Ok(None)` and `Err`
    /// both fall back to the directory name for the workspace, and the
    /// discovery fold collapses the two byte-identical diagnostics into one
    /// either way.
    #[test]
    fn manifest_cache_replays_the_same_err_on_every_visit() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let member = dir.path().join("packages").join("bad");
        std::fs::create_dir_all(&member).unwrap();
        std::fs::write(member.join("package.json"), r"{,}").unwrap();

        let mut cache = ManifestCache::default();
        let first = load_member_package_manifest_cached(&member, &mut cache)
            .expect_err("a malformed member manifest is an Err");
        assert_eq!(cache.len(), 1, "the outcome is memoized: {cache:?}");

        std::fs::remove_file(member.join("package.json")).unwrap();
        let replayed = load_member_package_manifest_cached(&member, &mut cache)
            .expect_err("the memoized Err replays instead of re-reading the directory");
        assert_eq!(
            replayed, first,
            "the replayed outcome is byte-identical to the first, so both \
             workspace sources diagnose the same member the same way"
        );
    }

    #[test]
    fn multiple_malformed_workspace_package_jsons_all_diagnosed() {
        let dir = tempfile::tempdir().expect("create temp dir");
        for name in ["a", "b", "c"] {
            let pkg = dir.path().join("packages").join(name);
            std::fs::create_dir_all(&pkg).unwrap();
            std::fs::write(pkg.join("package.json"), r"{,}").unwrap();
        }
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();

        let (result, _) = capture_workspace_warnings(|| {
            discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty())
        });
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert!(workspaces.is_empty(), "all three malformed; nothing valid");
        assert_eq!(diagnostics.len(), 3, "each malformed workspace surfaces");
        assert!(
            diagnostics
                .iter()
                .all(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedPackageJson { .. })),
            "every diagnostic should be malformed-package-json"
        );
    }

    #[test]
    fn malformed_root_package_json_returns_load_error() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(dir.path().join("package.json"), "this is not json").unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());

        match result {
            Err(WorkspaceLoadError::MalformedRootPackageJson { path, error }) => {
                assert!(path.ends_with("package.json"));
                assert!(!error.is_empty(), "underlying parse error is preserved");
            }
            other => panic!("expected MalformedRootPackageJson, got {other:?}"),
        }
    }

    #[test]
    fn glob_match_without_package_json_emits_diagnostic_unless_skip_listed() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let cache_dir = dir.path().join("packages").join(".cache");
        let scratch_dir = dir.path().join("packages").join("scratch");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&cache_dir).unwrap();
        std::fs::create_dir_all(&scratch_dir).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert_eq!(workspaces.len(), 1);
        let kinds: Vec<&str> = diagnostics.iter().map(|d| d.kind.id()).collect();
        assert!(
            kinds.contains(&"glob-matched-no-package-json"),
            "scratch should diagnose: {kinds:?}"
        );
        assert!(
            !diagnostics.iter().any(|d| d.path.ends_with(".cache")),
            ".cache must be skip-listed: {diagnostics:?}"
        );
    }

    #[test]
    fn glob_match_without_package_json_honors_ignore_patterns() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_a = dir.path().join("packages").join("a");
        let legacy_dir = dir.path().join("packages").join("legacy");
        std::fs::create_dir_all(&pkg_a).unwrap();
        std::fs::create_dir_all(&legacy_dir).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_a.join("package.json"), r#"{"name": "a"}"#).unwrap();

        let mut builder = globset::GlobSetBuilder::new();
        builder.add(globset::Glob::new("packages/legacy").unwrap());
        let ignore = builder.build().unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &ignore);
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert_eq!(workspaces.len(), 1);
        assert!(
            diagnostics.is_empty(),
            "user-excluded path must not produce a diagnostic: {diagnostics:?}"
        );
    }

    #[test]
    fn malformed_tsconfig_emits_diagnostic() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(dir.path().join("tsconfig.json"), r#"{"references": [,,,]}"#).unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (_, diagnostics) = result.expect("root package.json is valid");

        assert!(
            diagnostics
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedTsconfig { .. })),
            "expected MalformedTsconfig diagnostic; got: {diagnostics:?}"
        );
    }

    #[test]
    fn tsconfig_missing_reference_dir_emits_diagnostic() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(
            dir.path().join("tsconfig.json"),
            r#"{"references": [{"path": "./packages/missing"}]}"#,
        )
        .unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (_, diagnostics) = result.expect("no package.json at root is OK");

        assert!(
            diagnostics
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::TsconfigReferenceDirMissing)),
            "expected TsconfigReferenceDirMissing; got: {diagnostics:?}"
        );
    }

    #[test]
    fn missing_tsconfig_is_silent() {
        let dir = tempfile::tempdir().expect("create temp dir");

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (_, diagnostics) = result.expect("no root package.json is OK");

        assert!(
            !diagnostics
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedTsconfig { .. })),
            "missing tsconfig must not produce MalformedTsconfig: {diagnostics:?}"
        );
    }

    #[test]
    fn shallow_scan_malformed_package_json_stays_silent() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let scratch = dir.path().join("scratch");
        std::fs::create_dir_all(&scratch).unwrap();
        std::fs::write(scratch.join("package.json"), r"{not valid json}").unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (_, diagnostics) = result.expect("no root package.json is OK");

        assert!(
            !diagnostics
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::MalformedPackageJson { .. })),
            "shallow-scan malformed must stay silent: {diagnostics:?}"
        );
    }

    #[test]
    fn mixed_valid_and_malformed_workspaces_partial_recovery() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let pkg_good = dir.path().join("packages").join("good");
        let pkg_bad = dir.path().join("packages").join("bad");
        std::fs::create_dir_all(&pkg_good).unwrap();
        std::fs::create_dir_all(&pkg_bad).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/*"]}"#,
        )
        .unwrap();
        std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
        std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());
        let (workspaces, diagnostics) = result.expect("root package.json is valid");

        assert_eq!(workspaces.len(), 1);
        assert_eq!(workspaces[0].name, "good");
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].kind.id(), "malformed-package-json");
    }

    #[test]
    fn discover_workspaces_back_compat_drops_diagnostics_and_errors() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(dir.path().join("package.json"), r"{bad json").unwrap();

        let workspaces = discover_workspaces(dir.path());
        assert!(
            workspaces.is_empty(),
            "back-compat wrapper returns empty on root-malformed: {workspaces:?}"
        );
    }

    #[test]
    fn discovers_deno_workspace_members_without_package_json() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let core = dir.path().join("packages").join("core");
        let app = dir.path().join("apps").join("desktop");
        std::fs::create_dir_all(&core).unwrap();
        std::fs::create_dir_all(&app).unwrap();

        std::fs::write(
            dir.path().join("deno.json"),
            r#"{
              "workspace": ["./apps/*", "./packages/*"],
              "imports": { "@std/assert": "jsr:@std/assert@1" }
            }"#,
        )
        .unwrap();
        std::fs::write(
            core.join("deno.json"),
            r#"{
              "name": "@fallow/core",
              "exports": { ".": "./mod.ts", "./result": "./result.ts" }
            }"#,
        )
        .unwrap();
        std::fs::write(
            app.join("deno.json"),
            r#"{ "name": "@fallow/desktop", "exports": { ".": "./main.ts" } }"#,
        )
        .unwrap();

        let workspaces = discover_workspaces(dir.path());
        let mut names: Vec<_> = workspaces.iter().map(|w| w.name.as_str()).collect();
        names.sort_unstable();
        assert_eq!(names, vec!["@fallow/core", "@fallow/desktop"]);
        assert!(
            workspaces
                .iter()
                .all(|w| !w.root.join("package.json").exists())
        );
        assert!(
            workspaces.iter().all(|w| !w.is_internal_dependency),
            "Deno packages need dependency evidence before inventory marks them internal"
        );
    }

    #[test]
    fn malformed_root_deno_config_returns_load_error() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::write(dir.path().join("deno.jsonc"), "{ workspace: [ }").unwrap();

        let result = discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty());

        match result {
            Err(WorkspaceLoadError::MalformedRootDenoConfig { path, error }) => {
                assert!(path.ends_with("deno.jsonc"));
                assert!(!error.is_empty(), "underlying parse error is preserved");
            }
            other => panic!("expected MalformedRootDenoConfig, got {other:?}"),
        }
    }

    #[test]
    fn deno_and_npm_workspace_patterns_are_additive() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let a = dir.path().join("packages").join("a");
        let b = dir.path().join("packages").join("b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();

        std::fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces": ["packages/a"]}"#,
        )
        .unwrap();
        std::fs::write(a.join("package.json"), r#"{"name": "a"}"#).unwrap();
        std::fs::write(
            dir.path().join("deno.json"),
            r#"{"workspace": ["./packages/b"]}"#,
        )
        .unwrap();
        std::fs::write(b.join("deno.json"), r#"{"name": "b"}"#).unwrap();

        let workspaces = discover_workspaces(dir.path());
        let mut names: Vec<_> = workspaces.iter().map(|w| w.name.as_str()).collect();
        names.sort_unstable();
        assert_eq!(names, vec!["a", "b"]);
    }

    /// Issue #2366: `package.json` `workspaces` and `pnpm-workspace.yaml`
    /// `packages` are additive sources, so one glob declared in both is walked
    /// twice. Deduplicating at the discovery choke point is what lets the JSON
    /// envelopes report one entry per distinct matching pattern and lets the
    /// aggregated stderr warning count the directories it actually found.
    #[test]
    fn one_glob_declared_in_two_manifests_reports_each_directory_once() {
        let dir = tempfile::tempdir().expect("create temp dir");
        write_two_manifest_glob_project(dir.path());

        let (_, diagnostics) =
            discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty())
                .expect("root package.json is valid");

        let mut reported: Vec<(String, String)> = diagnostics
            .iter()
            .filter_map(|diagnostic| match &diagnostic.kind {
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => Some((
                    pattern.clone(),
                    diagnostic
                        .path
                        .strip_prefix(dir.path())
                        .unwrap_or(&diagnostic.path)
                        .display()
                        .to_string()
                        .replace('\\', "/"),
                )),
                _ => None,
            })
            .collect();
        reported.sort();

        assert_eq!(
            reported,
            vec![
                ("pkgs/*".to_owned(), "pkgs/aaa".to_owned()),
                ("pkgs/*".to_owned(), "pkgs/bbb".to_owned()),
            ],
            "one glob spelled two ways is one diagnostic per directory: {diagnostics:?}"
        );
    }

    /// The control for the fold above: the key is the WHOLE kind, payload
    /// included. Two overlapping globs each report the same package-less
    /// directory with their own `pattern`, and both survive.
    #[test]
    fn overlapping_globs_still_report_one_directory_once_per_pattern() {
        let dir = tempfile::tempdir().expect("create temp dir");
        std::fs::create_dir_all(dir.path().join("pkgs/aaa")).unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"name":"overlap-root","private":true,"workspaces":["pkgs/*","pkgs/a*"]}"#,
        )
        .unwrap();
        std::fs::write(dir.path().join("pkgs/aaa/readme.txt"), "no package.json\n").unwrap();

        let (_, diagnostics) =
            discover_workspaces_with_diagnostics(dir.path(), &globset::GlobSet::empty())
                .expect("root package.json is valid");

        let patterns: Vec<&str> = diagnostics
            .iter()
            .filter_map(|diagnostic| match &diagnostic.kind {
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => {
                    Some(pattern.as_str())
                }
                _ => None,
            })
            .collect();

        assert_eq!(
            patterns,
            ["pkgs/*", "pkgs/a*"],
            "distinct patterns are distinct diagnostics: {diagnostics:?}"
        );
    }
}