fallow-config 2.77.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
mod diagnostics;
mod package_json;
mod parsers;
mod pnpm_catalog;
mod pnpm_overrides;

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

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

#[cfg(test)]
pub use diagnostics::capture_workspace_warnings;
pub use diagnostics::{
    WorkspaceDiagnostic, WorkspaceDiagnosticKind, WorkspaceLoadError, append_workspace_diagnostics,
    stash_workspace_diagnostics, workspace_diagnostics_for,
};
use diagnostics::{emit_warn, is_skip_listed_dir};
// `emit_warn` is wired only at the top-level `discover_workspaces_with_diagnostics`
// loop below; the collector helpers populate `Vec<WorkspaceDiagnostic>` without
// emitting so the legacy `discover_workspaces` back-compat path stays silent.
pub use package_json::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_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).
    #[serde(default)]
    pub patterns: Vec<String>,
}

/// Discovered workspace info from package.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.
    pub name: String,
    /// Whether this workspace is depended on by other workspaces.
    pub is_internal_dependency: bool,
}

/// 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. `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_warn` (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 tracing warnings only at the diagnostics-aware entry point. The
    // collector function returns the diagnostics vec without emitting, so
    // the legacy `discover_workspaces(root)` back-compat path (which passes
    // an empty `ignore_patterns` set and only needs the workspace list)
    // stays silent. Without this split, sibling analyze / file-discovery
    // callers that go through `discover_workspaces` would re-emit
    // `tracing::warn!` on paths the user already excluded via
    // `ignorePatterns`, because those callers have no access to the
    // resolved globset.
    for diag in &diagnostics {
        emit_warn(root, diag);
    }

    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.
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 workspaces = expand_patterns_to_workspaces(
        root,
        &patterns,
        &canonical_root,
        ignore_patterns,
        &mut diagnostics,
    );
    workspaces.extend(collect_tsconfig_workspaces(
        root,
        &canonical_root,
        ignore_patterns,
        &mut diagnostics,
    ));
    if patterns.is_empty() {
        workspaces.extend(collect_shallow_package_workspaces(root, &canonical_root));
    }

    if !workspaces.is_empty() {
        mark_internal_dependencies(&mut workspaces);
    }
    let workspaces = workspaces.into_iter().map(|(ws, _)| ws).collect();
    Ok((workspaces, 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> {
    // Only run when workspaces are declared. A malformed root package.json
    // is a discovery-blocking error (surfaced at exit 2 via
    // discover_workspaces_with_diagnostics); this back-compat helper treats
    // it as "no patterns" so the undeclared-workspace warning does not fire
    // on top of the hard error.
    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();

    // Walk first two levels of directories
    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() {
            continue;
        }

        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str.starts_with('.') || name_str == "node_modules" || name_str == "build" {
            continue;
        }

        // Check this directory itself
        check_undeclared(
            &path,
            root,
            &canonical_root,
            &declared_roots,
            ignore_patterns,
            &mut undeclared,
        );

        // Check immediate children (second level)
        let Ok(child_entries) = std::fs::read_dir(&path) else {
            continue;
        };
        for child in child_entries.filter_map(Result::ok) {
            let child_path = child.path();
            if !child_path.is_dir() {
                continue;
            }
            let child_name = child.file_name();
            let child_name_str = child_name.to_string_lossy();
            if child_name_str.starts_with('.')
                || child_name_str == "node_modules"
                || child_name_str == "build"
            {
                continue;
            }
            check_undeclared(
                &child_path,
                root,
                &canonical_root,
                &declared_roots,
                ignore_patterns,
                &mut undeclared,
            );
        }
    }

    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.join("package.json").exists() {
        return;
    }
    let canonical = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    // Skip the project root itself
    if canonical == *canonical_root {
        return;
    }
    if declared_roots.contains(&canonical) {
        return;
    }
    let relative = dir.strip_prefix(root).unwrap_or(dir);
    // Honor user-supplied ignorePatterns: directories explicitly excluded should not
    // trigger an undeclared-workspace warning. Match using forward-slash normalized
    // relative path so cross-platform globs (`references/*`) work on Windows.
    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())
    {
        return;
    }
    undeclared.push(WorkspaceDiagnostic::new(
        root,
        dir.to_path_buf(),
        WorkspaceDiagnosticKind::UndeclaredWorkspace,
    ));
}

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

    // Check root package.json for workspace patterns. A malformed root is
    // unrecoverable: without a parseable package.json there is no declared
    // workspace surface and downstream analysis would be fiction. Promote to
    // a hard error so the CLI exits 2 (mirrors validate_resolved_boundaries
    // from issue #468). When the file is simply absent, fall through: many
    // projects use only pnpm-workspace.yaml or tsconfig references.
    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,
                });
            }
        }
    }

    // Check pnpm-workspace.yaml. Yaml read/parse failures stay silent here:
    // pnpm itself surfaces them at install time and adding a fallow-side
    // diagnostic would double-report the 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));
    }

    Ok(patterns)
}

/// 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>,
) -> Vec<(WorkspaceInfo, Vec<String>)> {
    if patterns.is_empty() {
        return Vec::new();
    }

    let mut workspaces = Vec::new();

    // Separate positive and negated patterns.
    // Negated patterns (e.g., `!**/test/**`) are used as exclusion filters —
    // the `glob` crate does not support `!` prefixed patterns natively.
    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 {
        // Normalize the pattern for directory matching:
        // - `packages/*` → glob for `packages/*` (find all subdirs)
        // - `packages/` → glob for `packages/*` (trailing slash means "contents of")
        // - `apps`       → glob for `apps` (exact directory)
        let glob_pattern = if pattern.ends_with('/') {
            format!("{pattern}*")
        } else if !pattern.contains('*') && !pattern.contains('?') && !pattern.contains('{') {
            // Bare directory name — treat as exact match
            (*pattern).clone()
        } else {
            (*pattern).clone()
        };

        // Walk directories matching the glob. The with_diagnostics variant
        // surfaces glob matches that resolve to directories without
        // package.json as WorkspaceDiagnosticKind::GlobMatchedNoPackageJson
        // (filtered through the skip list + ignore_patterns).
        let matched_dirs = expand_workspace_glob_with_diagnostics(
            root,
            pattern,
            &glob_pattern,
            canonical_root,
            ignore_patterns,
            diagnostics,
        );
        for (dir, canonical_dir) in matched_dirs {
            // Skip workspace entries that point to the project root itself
            // (e.g. pnpm-workspace.yaml listing `.` as a workspace)
            if canonical_dir == *canonical_root {
                continue;
            }

            // Check against negation patterns. Directories that match any
            // negated pattern are skipped.
            let relative = dir.strip_prefix(root).unwrap_or(&dir);
            let relative_str = relative.to_string_lossy();
            if negation_matchers
                .iter()
                .any(|m| m.is_match(relative_str.as_ref()))
            {
                continue;
            }

            // package.json existence already checked in
            // expand_workspace_glob_with_diagnostics. A parse failure HERE is
            // the declared-workspace malformed case: emit a diagnostic and
            // continue (the user's own pnpm/npm install would fail too, but
            // fallow stays useful so the user can fix the typo).
            let ws_pkg_path = dir.join("package.json");
            match PackageJson::load(&ws_pkg_path) {
                Ok(pkg) => {
                    let dep_names = pkg.all_dependency_names();
                    let name = pkg.name.unwrap_or_else(|| {
                        dir.file_name()
                            .map(|n| n.to_string_lossy().to_string())
                            .unwrap_or_default()
                    });
                    workspaces.push((
                        WorkspaceInfo {
                            root: dir,
                            name,
                            is_internal_dependency: false,
                        },
                        dep_names,
                    ));
                }
                Err(error) => {
                    let diag = WorkspaceDiagnostic::new(
                        root,
                        dir.clone(),
                        WorkspaceDiagnosticKind::MalformedPackageJson { error },
                    );
                    diagnostics.push(diag);
                }
            }
        }
    }

    workspaces
}

/// 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>,
) -> Vec<(WorkspaceInfo, Vec<String>)> {
    let mut workspaces = Vec::new();

    for dir in parse_tsconfig_references_with_diagnostics(root, ignore_patterns, diagnostics) {
        let canonical_dir = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
        // Security: skip references pointing to project root or outside it
        if canonical_dir == *canonical_root || !canonical_dir.starts_with(canonical_root) {
            continue;
        }

        // Read package.json if available; otherwise use directory name.
        // A package.json that EXISTS but fails to parse is a declared-workspace
        // malformed case: emit a diagnostic and fall back to directory-name
        // semantics so the TypeScript-only composite project still resolves.
        let ws_pkg_path = dir.join("package.json");
        let (name, dep_names) = if ws_pkg_path.exists() {
            match PackageJson::load(&ws_pkg_path) {
                Ok(pkg) => {
                    let deps = pkg.all_dependency_names();
                    let n = pkg.name.unwrap_or_else(|| dir_name(&dir));
                    (n, deps)
                }
                Err(error) => {
                    let diag = WorkspaceDiagnostic::new(
                        root,
                        dir.clone(),
                        WorkspaceDiagnosticKind::MalformedPackageJson { error },
                    );
                    diagnostics.push(diag);
                    (dir_name(&dir), Vec::new())
                }
            }
        } else {
            // No package.json: use directory name, no deps. Valid for
            // TypeScript-only composite projects; stays silent (tsc itself
            // does not require a package.json for project references).
            (dir_name(&dir), Vec::new())
        };

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

    workspaces
}

/// 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,
) -> 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);

        let Ok(child_entries) = std::fs::read_dir(&path) else {
            continue;
        };
        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, &mut workspaces);
        }
    }

    workspaces
}

fn collect_shallow_workspace_candidate(
    dir: &Path,
    canonical_root: &Path,
    workspaces: &mut Vec<(WorkspaceInfo, Vec<String>)>,
) {
    let pkg_path = dir.join("package.json");
    if !pkg_path.exists() {
        return;
    }

    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(pkg) = PackageJson::load(&pkg_path) else {
        return;
    };
    let dep_names = pkg.all_dependency_names();
    let name = pkg.name.unwrap_or_else(|| dir_name(dir));

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

fn should_skip_workspace_scan_dir(name: &str) -> bool {
    // Delegate to the shared skip list so the shallow-scan fallback honors
    // the same exclusions as the glob-matched-no-package.json filter
    // (`dist`, `coverage`, `.cache`, `.next`, `.turbo`, etc.). Build
    // artifacts and tooling caches are conventionally NOT workspace
    // packages; pnpm/npm/yarn silently filter the same set.
    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>)>) {
    // Deduplicate by canonical path
    {
        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)
        });
    }

    // Mark workspaces that are depended on by other workspaces.
    // Uses dep names collected during initial package.json load
    // to avoid re-reading all workspace package.json files.
    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()
}

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

    #[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();

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

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

        // ui has NO package.json — name should fall back to directory name
        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();
        // "outside" is a sibling of "project", not inside it
        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();

        // Security: "../outside" points outside the project root and should be rejected
        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);
    }

    // ── dir_name ────────────────────────────────────────────────────

    #[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() {
        // Root path has no file_name component
        assert_eq!(dir_name(Path::new("/")), "");
    }

    // ── WorkspaceConfig deserialization ──────────────────────────────

    #[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());
    }

    // ── WorkspaceInfo ───────────────────────────────────────────────

    #[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);
    }

    // ── mark_internal_dependencies ──────────────────────────────────

    #[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);

        // "b" is depended on by "a", so it should be marked as internal
        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"
        );
    }

    // ── collect_workspace_patterns ──────────────────────────────────

    #[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());
    }

    // ── discover_workspaces integration ─────────────────────────────

    #[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");
        // pnpm-workspace.yaml listing "." should not add root as workspace
        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();
        // package.json without a name field
        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:?}"
        );
    }

    // ── find_undeclared_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();

        // Only packages/a is declared as a workspace
        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();

        // No workspaces field at all, non-monorepo project
        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();
        // Put package.json in node_modules and hidden dirs
        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() {
        // Reproduces issue #193: a `references/*` directory containing package.json
        // should not be reported as undeclared workspace when listed in ignorePatterns.
        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());
        // ignore pattern is unrelated to packages/b
        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() {
        // Some users write ignore patterns as `references/*/package.json`
        // (matching the file rather than the directory). Both styles should silence
        // the undeclared-workspace warning.
        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() {
        // `references/**` should also cover `references/<name>` candidates.
        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:?}"
        );
    }

    // ── Issue #473: loud workspace discovery diagnostics ────────────

    #[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();
        // Trailing comma makes this not valid JSON.
        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 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");
            }
            Ok(_) => panic!("expected MalformedRootPackageJson"),
        }
    }

    #[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();
        // packages/.cache and packages/scratch have NO package.json.

        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);
        // `.cache` should be in the skip list (silent); `scratch` is not, so
        // it produces a glob-matched-no-package-json diagnostic.
        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();
        // tsconfig with trailing-comma-after-trailing-comma (invalid even as
        // JSONC) so jsonc parsing fails.
        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");
        // No tsconfig.json at all. Many JS-only projects look like this.

        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() {
        // Severity policy: when the user has not declared workspaces and
        // fallow falls back to shallow scanning, a malformed nested
        // package.json must NOT produce a diagnostic. The user did not
        // declare the directory; the heuristic should not generate noise.
        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() {
        // The legacy wrapper preserves byte-identical behavior for callers
        // that have not migrated: malformed root collapses to empty result,
        // workspace-level diagnostics are dropped silently.
        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:?}"
        );
    }
}