fallow-config 3.28.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
//! Workspace and source-discovery diagnostics.
//!
//! Surfaces malformed `package.json`, unreachable glob matches, missing
//! tsconfig references, undeclared workspaces, and source files skipped during
//! source discovery as typed [`WorkspaceDiagnostic`] values. A diagnostic that
//! reports a DEGRADED run also emits a deduplicated `tracing::warn!` so users
//! running fallow with default tracing filters see the cause of "fallow doesn't
//! see my package" or "fallow ate all my memory."
//! [`WorkspaceDiagnosticKind::warns_on_stderr`] decides which kinds those are;
//! the rest reach consumers through `workspace_diagnostics[]` only.
//!
//! Repeated `GlobMatchedNoPackageJson` diagnostics are aggregated by glob
//! pattern at emission time so a wide glob matching hundreds of package-less
//! directories on a large monorepo collapses to one bounded summary line per
//! pattern instead of one line per directory (issue #637). The structured
//! `Vec<WorkspaceDiagnostic>` returned to callers stays full; only the stderr
//! surface is bounded.
//!
//! Mirrors the dedupe + capture pattern in
//! `crates/config/src/config/parsing.rs::warn_on_unknown_rule_keys` (issue
//! #467).

use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use rustc_hash::{FxHashMap, FxHashSet};

pub use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};

/// Render `path` relative to `root` with forward slashes. Mirrors the private
/// helper of the same name in `fallow_types::workspace`, kept here for the
/// aggregated stderr-message builders ([`build_glob_group_message`] and
/// [`build_tsconfig_refs_message`]) so the per-instance and aggregated message
/// surfaces format paths identically (the forward-slash normalisation is
/// load-bearing for cross-platform output stability).
fn display_relative(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
        .replace('\\', "/")
}

/// Workspace-discovery failures that prevent analysis from proceeding.
///
/// Returned only by `discover_workspaces_with_diagnostics` (in the parent
/// module) when a root package manifest itself is malformed: without a
/// parseable root, no workspace patterns can be collected, and analysis output
/// would be fiction. The CLI surfaces this as exit 2.
#[derive(Debug, Clone)]
pub enum WorkspaceLoadError {
    /// The project root's `package.json` exists but failed to parse.
    MalformedRootPackageJson {
        /// Path to the malformed manifest, shown in the diagnostic.
        path: PathBuf,
        /// Parser error message, embedded in the diagnostic.
        error: String,
    },
    /// The project root's `deno.json` or `deno.jsonc` exists but failed to parse.
    MalformedRootDenoConfig {
        /// Path to the malformed manifest, shown in the diagnostic.
        path: PathBuf,
        /// Parser error message, embedded in the diagnostic.
        error: String,
    },
}

impl std::fmt::Display for WorkspaceLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MalformedRootPackageJson { path, error } => write!(
                f,
                "root package.json at '{}' is not valid JSON ({error}). \
                 Fix the syntax before re-running fallow.",
                path.display()
            ),
            Self::MalformedRootDenoConfig { path, error } => write!(
                f,
                "root Deno config at '{}' is not valid JSONC ({error}). \
                 Fix the syntax before re-running fallow.",
                path.display()
            ),
        }
    }
}

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

/// Maximum number of example directories named in an aggregated
/// `GlobMatchedNoPackageJson` warning before the tail is summarised as
/// "and N more". Keeps a fanned-out glob to one bounded stderr line.
const GLOB_EXAMPLE_CAP: usize = 3;

/// Process-wide set of already-emitted diagnostic dedupe keys. Per-instance
/// keys (`root::kind::path`) and aggregated per-pattern keys
/// (`root::glob-matched-no-package-json-agg::pattern`) share one set so
/// combined-mode (check + dupes + health through one loader) and watch-mode
/// reruns warn at most once per logical diagnostic. The two key namespaces are
/// disjoint, so there is no cross-talk.
fn warned_keys() -> &'static Mutex<FxHashSet<String>> {
    static WARNED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
    WARNED.get_or_init(|| Mutex::new(FxHashSet::default()))
}

/// Insert `key` and return `true` when it was newly inserted (caller should
/// emit). On a poisoned mutex returns `true` so over-warning beats swallowing
/// a typo. Mirrors `parsing::warn_on_unknown_rule_keys` and
/// `plugins::registry::should_warn`.
fn should_emit(key: String) -> bool {
    warned_keys().lock().map_or(true, |mut set| set.insert(key))
}

/// A single planned stderr warning: its process-dedupe key and the rendered
/// message. The pure output of [`plan_warnings`] so the partition/aggregation
/// logic is unit-testable without a tracing subscriber or the process-wide
/// dedupe set.
#[derive(Debug, PartialEq, Eq)]
struct PlannedWarning {
    dedupe_key: String,
    message: String,
}

struct WarningGroups<'a> {
    plans: Vec<PlannedWarning>,
    glob_groups: Vec<(&'a str, Vec<&'a WorkspaceDiagnostic>)>,
    tsconfig_ref_misses: Vec<&'a WorkspaceDiagnostic>,
}

/// Turn a batch of workspace diagnostics into the bounded set of stderr
/// warnings to emit, collapsing the two kinds that fan out on large monorepos
/// (issue #637):
/// - `GlobMatchedNoPackageJson`: aggregated by glob pattern, one summary line
///   per pattern instead of one line per package-less directory.
/// - `TsconfigReferenceDirMissing`: aggregated together, one summary line
///   instead of one per missing `references[]` entry in the root tsconfig.
///
/// Kinds that [`WorkspaceDiagnosticKind::warns_on_stderr`] answers `false` for
/// plan no warning at all: they describe a check the user never configured
/// rather than a degraded run, and belong only in the structured array.
///
/// Pure: no tracing, no dedupe-set mutation. A group of exactly one keeps
/// today's per-instance message byte-for-byte (no regression for the common
/// single-match case); every other kind plans one per-instance warning. The
/// returned plan lists non-aggregated diagnostics first (in first-seen order),
/// then the glob-pattern summaries, then the tsconfig summary; ordering does
/// not affect correctness since these are independent stderr lines.
fn plan_warnings(root: &Path, diagnostics: &[WorkspaceDiagnostic]) -> Vec<PlannedWarning> {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let WarningGroups {
        mut plans,
        glob_groups,
        tsconfig_ref_misses,
    } = group_warning_diagnostics(diagnostics, &canonical);

    for (pattern, group) in glob_groups {
        if let [only] = group.as_slice() {
            plans.push(per_instance_warning(&canonical, only));
            continue;
        }
        let paths: Vec<&Path> = group.iter().map(|d| d.path.as_path()).collect();
        plans.push(PlannedWarning {
            dedupe_key: format!(
                "{}::glob-matched-no-package-json-agg::{pattern}",
                canonical.display()
            ),
            message: build_glob_group_message(root, pattern, &paths),
        });
    }

    if let [only] = tsconfig_ref_misses.as_slice() {
        plans.push(per_instance_warning(&canonical, only));
    } else if !tsconfig_ref_misses.is_empty() {
        let paths: Vec<&Path> = tsconfig_ref_misses
            .iter()
            .map(|d| d.path.as_path())
            .collect();
        plans.push(PlannedWarning {
            dedupe_key: format!(
                "{}::tsconfig-reference-dir-missing-agg",
                canonical.display()
            ),
            message: build_tsconfig_refs_message(root, &paths),
        });
    }

    plans
}

fn group_warning_diagnostics<'a>(
    diagnostics: &'a [WorkspaceDiagnostic],
    canonical: &Path,
) -> WarningGroups<'a> {
    let mut plans: Vec<PlannedWarning> = Vec::new();
    let mut glob_groups: Vec<(&str, Vec<&WorkspaceDiagnostic>)> = Vec::new();
    let mut tsconfig_ref_misses: Vec<&WorkspaceDiagnostic> = Vec::new();
    for diag in diagnostics {
        if !diag.kind.warns_on_stderr() {
            continue;
        }
        match &diag.kind {
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => {
                match glob_groups.iter_mut().find(|(p, _)| *p == pattern.as_str()) {
                    Some((_, group)) => group.push(diag),
                    None => glob_groups.push((pattern.as_str(), vec![diag])),
                }
            }
            WorkspaceDiagnosticKind::TsconfigReferenceDirMissing => tsconfig_ref_misses.push(diag),
            _ => plans.push(per_instance_warning(canonical, diag)),
        }
    }
    WarningGroups {
        plans,
        glob_groups,
        tsconfig_ref_misses,
    }
}

/// Plan one per-instance warning, keyed on what it PRINTS rather than on the
/// kind id plus the path.
///
/// The dedupe exists so combined mode and watch-mode reruns print one line per
/// logical diagnostic, and two entries that render different sentences are two
/// logical diagnostics however much of the key they share. An id-and-path key
/// swallowed the second of them: one Module Federation config whose `exposes`
/// AND `remotes` are both unreadable produces two entries on one path under one
/// kind, and only the first was ever printed (issue #2736). Matching
/// `merge_workspace_diagnostics`, which keys on the whole kind for the same
/// reason, the message stands in for the payload here: it is rendered from the
/// kind and the path, so two entries whose sentences are byte-identical would
/// print the same line twice and are still one key.
fn per_instance_warning(canonical: &Path, diag: &WorkspaceDiagnostic) -> PlannedWarning {
    PlannedWarning {
        dedupe_key: format!(
            "{}::{}::{}::{}",
            canonical.display(),
            diag.kind.id(),
            diag.path.display(),
            diag.message
        ),
        message: diag.message.clone(),
    }
}

/// Emit `tracing::warn!` lines for a batch of workspace diagnostics.
///
/// Delegates the partition/aggregation decisions to the pure [`plan_warnings`]
/// and applies the process-wide dedupe so combined-mode (check + dupes + health
/// through one loader) and watch-mode reruns warn at most once per logical
/// diagnostic. The returned/stashed `Vec<WorkspaceDiagnostic>` is unaffected;
/// only the stderr surface is bounded, so structured JSON consumers still see
/// every diagnostic.
pub(super) fn emit_diagnostics(root: &Path, diagnostics: &[WorkspaceDiagnostic]) {
    #[cfg(test)]
    for diag in diagnostics {
        capture_diag(diag);
    }

    for plan in plan_warnings(root, diagnostics) {
        if should_emit(plan.dedupe_key) {
            tracing::warn!("fallow: {}", plan.message);
        }
    }
}

/// Render up to [`GLOB_EXAMPLE_CAP`] project-relative example paths (sorted for
/// deterministic output) with an "and N more" tail when the count exceeds the
/// cap. Returns the joined example string and the total path count. Shared by
/// the aggregated-message builders.
fn summarize_examples(root: &Path, paths: &[&Path]) -> (String, usize) {
    let mut examples: Vec<String> = paths.iter().map(|p| display_relative(root, p)).collect();
    examples.sort();
    let count = examples.len();
    let shown = examples
        .iter()
        .take(GLOB_EXAMPLE_CAP)
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");
    let remaining = count.saturating_sub(GLOB_EXAMPLE_CAP);
    let listed = if remaining > 0 {
        format!("{shown}, and {remaining} more")
    } else {
        shown
    };
    (listed, count)
}

/// Build the aggregated message for a glob pattern that matched `paths`
/// package-less directories (always called with `paths.len() >= 2`).
fn build_glob_group_message(root: &Path, pattern: &str, paths: &[&Path]) -> String {
    let (listed, count) = summarize_examples(root, paths);
    format!(
        "Glob '{pattern}' matched {count} directories with no package.json \
         (e.g. {listed}). Add a package.json, narrow the pattern, or add \
         them to ignorePatterns."
    )
}

/// Build the aggregated message for `paths` `tsconfig.json` `references[]`
/// entries that point at missing directories (always called with
/// `paths.len() >= 2`).
fn build_tsconfig_refs_message(root: &Path, paths: &[&Path]) -> String {
    let (listed, count) = summarize_examples(root, paths);
    format!(
        "tsconfig.json references {count} directories that do not exist \
         (e.g. {listed}). Update or remove the references, or restore the \
         missing directories."
    )
}

thread_local! {
    /// Per-thread capture of workspace diagnostics, for tests that assert
    /// emission without inspecting tracing output. Parallel test execution
    /// stays race-free because the buffer is thread-local; production code
    /// keeps the cell empty so emission goes only to tracing.
    ///
    /// Mirrors `parsing::UNKNOWN_RULE_CAPTURE` (issue #467).
    #[cfg(test)]
    static WORKSPACE_DIAGNOSTIC_CAPTURE: std::cell::RefCell<Option<Vec<WorkspaceDiagnostic>>> =
        const { std::cell::RefCell::new(None) };
}

/// Push `diag` into the thread-local capture buffer when one is installed.
/// No-op when no test has called [`capture_workspace_warnings`] on the current
/// thread, so production code never allocates. Called once per diagnostic by
/// [`emit_diagnostics`] before the dedupe gate, so every diagnostic is observed
/// regardless of whether it was emitted per-instance or aggregated.
#[cfg(test)]
fn capture_diag(diag: &WorkspaceDiagnostic) {
    WORKSPACE_DIAGNOSTIC_CAPTURE.with(|cell| {
        if let Some(buf) = cell.borrow_mut().as_mut() {
            buf.push(diag.clone());
        }
    });
}

/// Install a thread-local capture buffer and run `body`. Returns the body's
/// result alongside every diagnostic passed through [`emit_diagnostics`] on the
/// current thread, in order.
///
/// Test-only. Diagnostics captured here also bypass the process-wide dedupe
/// (so two captures on the same root + kind + path inside one test both
/// observe the emission).
#[cfg(test)]
#[must_use]
pub fn capture_workspace_warnings<F: FnOnce() -> R, R>(body: F) -> (R, Vec<WorkspaceDiagnostic>) {
    WORKSPACE_DIAGNOSTIC_CAPTURE.with(|cell| {
        *cell.borrow_mut() = Some(Vec::new());
    });
    let result = body();
    let findings =
        WORKSPACE_DIAGNOSTIC_CAPTURE.with(|cell| cell.borrow_mut().take().unwrap_or_default());
    (result, findings)
}

/// Process-wide registry of workspace-discovery diagnostics, keyed by
/// canonical root. Populated by callers that run
/// [`super::discover_workspaces_with_diagnostics`] and (after config load
/// completes) by the analysis pipeline's `find_undeclared_workspaces_*`
/// pass. Consumers (`fallow list --workspaces`, the JSON envelope on
/// `fallow dead-code / dupes / health`) read via [`workspace_diagnostics_for`].
///
/// Canonicalisation matches the dedupe-key canonicalisation in
/// [`plan_warnings`]: two callers on the same physical root coalesce, and
/// nested-monorepo callers on different roots stay independent.
static WORKSPACE_DIAGNOSTICS: OnceLock<Mutex<FxHashMap<PathBuf, Vec<WorkspaceDiagnostic>>>> =
    OnceLock::new();

/// Replace the workspace-discovery diagnostics for `root` with `diagnostics`,
/// PRESERVING any source-discovery diagnostics (see
/// [`WorkspaceDiagnosticKind::is_source_discovery`]) and analysis-stage
/// diagnostics (see [`WorkspaceDiagnosticKind::is_analysis_stage`]) already
/// appended for the root.
///
/// Called at config-load time after [`super::discover_workspaces_with_diagnostics`]
/// completes; the analyze pipeline then APPENDS undeclared-workspace and
/// source-discovery (`skipped-large-file`, `skipped-source-dotdir`, and the
/// other kinds [`WorkspaceDiagnosticKind::is_source_discovery`] covers)
/// diagnostics via
/// [`append_workspace_diagnostics`]. The workspace-discovery set is authoritative
/// and replaced wholesale (so a fixed `package.json` clears its stale diagnostic
/// across watch-mode reruns), but source-discovery diagnostics are appended
/// AFTER this stash, so combined-mode's per-analysis config re-loads would
/// otherwise wipe a `skipped-large-file` entry that the first analysis's
/// discovery already recorded (issue #1086). Analysis-stage diagnostics
/// (`malformed-pnpm-workspace-yaml`, `bun-lockb-override-resolution-skipped`)
/// are recorded by the analyze pass through [`record_workspace_diagnostics`],
/// also after this stash, and are preserved for the same reason; each analyze
/// pass refreshes them through [`clear_analysis_stage_diagnostics`] (issue
/// #2366). Plugin-stage diagnostics
/// ([`WorkspaceDiagnosticKind::is_plugin_stage`]) are preserved on the same
/// grounds: framework plugins run after config load, and
/// [`record_plugin_config_diagnostics`] refreshes their set in one operation
/// (issue #2736).
///
/// The stored set is deduplicated on the whole `(kind, path)` the way every
/// fold is: a repository that declares one glob in both `package.json` and
/// `pnpm-workspace.yaml` produces the same diagnostic twice at config load, and
/// the standalone envelopes read this registry verbatim (issue #2366).
pub fn stash_workspace_diagnostics(root: &Path, diagnostics: Vec<WorkspaceDiagnostic>) {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let preserved = map.get(&canonical).map_or_else(Vec::new, |existing| {
            existing
                .iter()
                .filter(|d| {
                    d.kind.is_source_discovery()
                        || d.kind.is_analysis_stage()
                        || d.kind.is_health_stage()
                        || d.kind.is_plugin_stage()
                })
                .cloned()
                .collect()
        });
        map.insert(
            canonical,
            fallow_types::workspace::merge_workspace_diagnostics(diagnostics, preserved),
        );
    }
}

/// Append `additions` to the workspace-discovery diagnostics for `root`,
/// skipping any entry whose `(kind id, canonical path)` is already present.
///
/// Used by the analyze pipeline's undeclared-workspace pass to fold its
/// findings into the registry without re-emitting diagnostics that the
/// config-load pass already surfaced (e.g. a directory whose `package.json`
/// is malformed should NOT also produce a separate "undeclared" diagnostic
/// alongside the malformed-package-json one).
pub fn append_workspace_diagnostics(root: &Path, additions: Vec<WorkspaceDiagnostic>) {
    if additions.is_empty() {
        return;
    }
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let existing = map.entry(canonical).or_default();
        let mut seen: FxHashSet<(String, String)> = existing
            .iter()
            .map(|d| {
                (
                    d.kind.id().to_owned(),
                    dunce::canonicalize(&d.path)
                        .unwrap_or_else(|_| d.path.clone())
                        .display()
                        .to_string(),
                )
            })
            .collect();
        for addition in additions {
            let key = (
                addition.kind.id().to_owned(),
                dunce::canonicalize(&addition.path)
                    .unwrap_or_else(|_| addition.path.clone())
                    .display()
                    .to_string(),
            );
            if seen.insert(key) {
                existing.push(addition);
            }
        }
    }
}

/// Append `diagnostics` to the registry for `root` AND emit their deduplicated
/// stderr warnings, for analysis-stage callers outside this crate (e.g. the
/// pnpm catalog/override gathers in `fallow-core`) that surface a diagnostic
/// after config load completed. [`append_workspace_diagnostics`] alone would
/// reach `workspace_diagnostics[]` JSON but never warn a human on stderr.
pub fn record_workspace_diagnostics(root: &Path, diagnostics: Vec<WorkspaceDiagnostic>) {
    if diagnostics.is_empty() {
        return;
    }
    emit_diagnostics(root, &diagnostics);
    append_workspace_diagnostics(root, diagnostics);
}

/// Replace the plugin-stage diagnostics for `root` with `diagnostics` in ONE
/// registry operation, emit their deduplicated stderr warnings, and hand the
/// same list back to the caller.
///
/// Called once per analysis, at the end of the plugin run, which is the single
/// point where the root and workspace plugin results have converged. The
/// replacement is what keeps the set CURRENT across reruns, the way
/// [`replace_source_discovery_diagnostics`] does for a walk: a config the user
/// fixed drops out on the next run with no separate clear, and a long-lived
/// engine session or a watch-mode rerun does not accumulate stale entries.
///
/// Deliberately NOT [`append_workspace_diagnostics`], whose dedupe key is the
/// kind id plus the canonical path. One Module Federation config file can hold
/// two unreadable keys, which is two entries under one kind on one path, and
/// that key drops the second. This one dedupes the incoming list on the whole
/// `(kind, path)` the way every other fold does (issue #2736).
#[must_use]
pub fn record_plugin_config_diagnostics(
    root: &Path,
    diagnostics: Vec<WorkspaceDiagnostic>,
) -> Vec<WorkspaceDiagnostic> {
    let diagnostics = fallow_types::workspace::dedupe_workspace_diagnostics(diagnostics);
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let existing = map.entry(canonical).or_default();
        existing.retain(|diagnostic| !diagnostic.kind.is_plugin_stage());
        existing.extend(diagnostics.iter().cloned());
    }
    emit_diagnostics(root, &diagnostics);
    diagnostics
}

/// Replace source-read-failure diagnostics for `root` with the failures from
/// the current parse while preserving every workspace and discovery diagnostic
/// produced by other stages.
///
/// Returns the structured diagnostics so session-owned outputs can carry the
/// exact same values as the process registry used by direct core and CLI paths.
#[must_use]
pub fn record_source_read_failures(
    root: &Path,
    failures: &[fallow_types::extract::SourceReadFailure],
) -> Vec<WorkspaceDiagnostic> {
    let diagnostics: Vec<WorkspaceDiagnostic> = failures
        .iter()
        .map(|failure| {
            WorkspaceDiagnostic::new(
                root,
                failure.path.clone(),
                WorkspaceDiagnosticKind::SourceReadFailure {
                    error: failure.error.clone(),
                },
            )
        })
        .collect();
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let existing = map.entry(canonical).or_default();
        existing.retain(|diagnostic| {
            !matches!(
                diagnostic.kind,
                WorkspaceDiagnosticKind::SourceReadFailure { .. }
            )
        });
        existing.extend(diagnostics.iter().cloned());
    }
    emit_diagnostics(root, &diagnostics);
    diagnostics
}

/// Whether `root` should have a `node_modules` directory and does not.
///
/// The single predicate behind [`WorkspaceDiagnosticKind::NodeModulesMissing`].
/// A Deno project with no `package.json` legitimately runs without one, so it
/// is not reported.
#[must_use]
pub fn node_modules_missing(root: &Path) -> bool {
    !root.join("node_modules").is_dir() && !super::is_deno_without_node_modules(root)
}

/// Build the missing-`node_modules` diagnostic for `root`, or `None` once the
/// project has been installed.
///
/// Replaces the previous per-pipeline `tracing::warn!`, which existed twice
/// byte-identically and reached neither JSON output nor `fallow doctor`. The
/// source walk folds this into its own diagnostic set, so it reaches an
/// analysis by value like every other walk-recorded kind instead of through a
/// second registry writer.
#[must_use]
pub fn missing_node_modules_diagnostic(root: &Path) -> Option<WorkspaceDiagnostic> {
    node_modules_missing(root).then(|| {
        WorkspaceDiagnostic::new(
            root,
            root.join("node_modules"),
            WorkspaceDiagnosticKind::NodeModulesMissing,
        )
    })
}

/// Replace source-parse-degraded diagnostics for `root` with the degradations
/// from the current parse while preserving every workspace and discovery
/// diagnostic produced by other stages.
///
/// Mirrors [`record_source_read_failures`]: the parse stage owns this kind, so
/// a fixed file drops out of the set on the next run instead of persisting.
///
/// Returns the structured diagnostics so session-owned outputs can carry the
/// exact same values as the process registry used by direct core and CLI paths.
#[must_use]
pub fn record_source_parse_degradations(
    root: &Path,
    degradations: &[fallow_types::extract::SourceParseDegradation],
) -> Vec<WorkspaceDiagnostic> {
    let diagnostics: Vec<WorkspaceDiagnostic> = degradations
        .iter()
        .map(|degradation| {
            WorkspaceDiagnostic::new(
                root,
                degradation.path.clone(),
                WorkspaceDiagnosticKind::SourceParseDegraded {
                    error_count: degradation.error_count,
                    panicked: degradation.panicked,
                },
            )
        })
        .collect();
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let existing = map.entry(canonical).or_default();
        existing.retain(|diagnostic| {
            !matches!(
                diagnostic.kind,
                WorkspaceDiagnosticKind::SourceParseDegraded { .. }
            )
        });
        existing.extend(diagnostics.iter().cloned());
    }
    emit_diagnostics(root, &diagnostics);
    diagnostics
}

/// Replace every source-discovery diagnostic for `root` with `diagnostics` in
/// ONE registry operation, and hand the same list back to the caller.
///
/// Called at the END of each source walk (`discover_files`) so a stale
/// `skipped-large-file` entry from a previous analysis pass (a watch-mode
/// rerun after the user raised `--max-file-size` or added the file to
/// `ignorePatterns`) is dropped while the current walk's skips are written.
/// Pairs with the preserve in [`stash_workspace_diagnostics`]: this call keeps
/// the set CURRENT across reruns, the preserve keeps it ALIVE across
/// combined-mode's per-analysis config re-loads (issue #1086).
///
/// The clear-then-append pair this replaces was two separate lock
/// acquisitions, so a second source walk running concurrently on the same root
/// (combined mode runs the dead-code and duplication walks under `rayon::join`
/// whenever a per-analysis `production` split stops them from sharing a file
/// list) could interleave its clear between this walk's clear and its appends,
/// or between the appends and the walk's own read-back. Holding the lock across
/// the whole replacement makes the registry state a clean last-writer-wins, and
/// returning the list lets each analysis carry exactly what ITS walk skipped
/// without reading the shared registry back at all (issue #2366).
///
/// The retain also drops the parse stage's `source-read-failure` entries,
/// because [`WorkspaceDiagnosticKind::is_source_discovery`] covers that kind
/// too, so a concurrent walk on the same root can clear a read failure another
/// analysis's parse recorded. That window closes on its own:
/// [`record_source_read_failures`] replaces the read-failure set from each
/// analysis's own parse, and a fold's closing registry leg reads after both
/// walks have finished. Narrowing this retain to
/// [`WorkspaceDiagnosticKind::is_source_walk_recorded`] would leave the
/// read-failure set to its own recorder entirely.
#[must_use]
pub fn replace_source_discovery_diagnostics(
    root: &Path,
    diagnostics: Vec<WorkspaceDiagnostic>,
) -> Vec<WorkspaceDiagnostic> {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let registry = WORKSPACE_DIAGNOSTICS.get_or_init(|| Mutex::new(FxHashMap::default()));
    if let Ok(mut map) = registry.lock() {
        let existing = map.entry(canonical).or_default();
        existing.retain(|d| !d.kind.is_source_discovery());
        existing.extend(diagnostics.iter().cloned());
    }
    diagnostics
}

/// Remove all analysis-stage diagnostics (see
/// [`WorkspaceDiagnosticKind::is_analysis_stage`]) for `root` from the
/// registry, keeping every workspace-discovery and source-discovery entry.
///
/// Called at the START of each dead-code analyze pass so a stale
/// `malformed-pnpm-workspace-yaml` or `bun-lockb-override-resolution-skipped`
/// entry from a previous pass (a watch-mode rerun or a long-lived engine
/// session after the YAML was fixed or a text `bun.lock` was written) is
/// dropped before the detectors re-record only what still applies. Mirrors
/// [`replace_source_discovery_diagnostics`] and pairs with the preserve in
/// [`stash_workspace_diagnostics`] (issue #2366).
pub fn clear_analysis_stage_diagnostics(root: &Path) {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let Some(registry) = WORKSPACE_DIAGNOSTICS.get() else {
        return;
    };
    if let Ok(mut map) = registry.lock()
        && let Some(existing) = map.get_mut(&canonical)
    {
        existing.retain(|d| !d.kind.is_analysis_stage());
    }
}

/// Remove all health-stage diagnostics (see
/// [`WorkspaceDiagnosticKind::is_health_stage`]) for `root` from the registry,
/// keeping every other entry.
///
/// Called at the START of each health run so a stale `shallow-clone` or
/// `ownership-unavailable` entry from a previous run over the same root (a
/// watch-mode rerun, a long-lived engine session, the two passes of `fallow
/// audit`) is dropped before the pipeline re-records only what still applies.
/// Mirrors [`clear_analysis_stage_diagnostics`] and pairs with the preserve in
/// [`stash_workspace_diagnostics`] (issue #2689).
pub fn clear_health_stage_diagnostics(root: &Path) {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let Some(registry) = WORKSPACE_DIAGNOSTICS.get() else {
        return;
    };
    if let Ok(mut map) = registry.lock()
        && let Some(existing) = map.get_mut(&canonical)
    {
        existing.retain(|d| !d.kind.is_health_stage());
    }
}

/// Read only the health-stage diagnostics (see
/// [`WorkspaceDiagnosticKind::is_health_stage`]) the registry holds for `root`.
///
/// The health envelope captures `workspace_diagnostics` before the analysis
/// runs, so the pipeline's own diagnostics reach it through this read at
/// finalize time rather than by threading a mutable list through scoring,
/// churn, ownership, trend and coverage resolution (issue #2689).
#[must_use]
pub fn health_stage_workspace_diagnostics(root: &Path) -> Vec<WorkspaceDiagnostic> {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let Some(registry) = WORKSPACE_DIAGNOSTICS.get() else {
        return Vec::new();
    };
    registry
        .lock()
        .ok()
        .map(|map| {
            map.get(&canonical).map_or_else(Vec::new, |existing| {
                existing
                    .iter()
                    .filter(|d| d.kind.is_health_stage())
                    .cloned()
                    .collect()
            })
        })
        .unwrap_or_default()
}

/// Read the workspace-discovery diagnostics produced by the most recent
/// `stash_workspace_diagnostics` + any subsequent
/// `append_workspace_diagnostics` calls for `root`. Returns an empty vector
/// when nothing has been stashed for this root yet (e.g. programmatic
/// callers bypassing the standard loader).
#[must_use]
pub fn workspace_diagnostics_for(root: &Path) -> Vec<WorkspaceDiagnostic> {
    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let Some(registry) = WORKSPACE_DIAGNOSTICS.get() else {
        return Vec::new();
    };
    registry
        .lock()
        .ok()
        .and_then(|map| map.get(&canonical).cloned())
        .unwrap_or_default()
}

/// Read the registry leg of a diagnostics FOLD: everything
/// [`workspace_diagnostics_for`] holds for `root` EXCEPT the entries a source
/// walk records (see
/// [`WorkspaceDiagnosticKind::is_source_walk_recorded`]).
///
/// A fold combines an analysis's own captured list with the registry. The
/// analysis already carries its own walk's skips by value, and each walk
/// replaces the registry's source-discovery set for the root, so an unfiltered
/// registry read imports ANOTHER walk's file set: under a per-analysis
/// `production` split the dead-code and duplication walks see different files,
/// and the read answers whichever walk wrote last. That made the audit family
/// report a skip its dead-code analysis never saw, disagreeing with the MCP
/// `audit` tool, and made the order of the combined root's union depend on
/// which parallel walk won the race (issue #2366).
///
/// `source-read-failure` is deliberately still read: the parse stage records
/// it after the walk, so the registry is the only place it exists. Every
/// non-walk kind (workspace discovery, analysis stage) is likewise still read,
/// which is what lets `--skip check` and `--only health` report what their
/// analyses recorded after the section captured its list.
///
/// The result is ordered by `(path, kind id, message)` rather than by arrival.
/// Analysis-stage detectors record into the registry from a rayon pool, so
/// arrival order is a scheduling artefact: `boundaries-not-configured` and
/// `rule-packs-not-configured` swapped places between a one-worker and an
/// eight-worker run of the same command, on a `required` wire array. Ordering
/// the registry leg fixes that at the single point every consumer reads it.
/// The caller's own list keeps its meaningful discovery order; only this leg
/// is sorted, and `merge_workspace_diagnostics` puts it after that list.
#[must_use]
pub fn registry_diagnostics_to_fold(root: &Path) -> Vec<WorkspaceDiagnostic> {
    let mut diagnostics: Vec<WorkspaceDiagnostic> = workspace_diagnostics_for(root)
        .into_iter()
        .filter(|diagnostic| !diagnostic.kind.is_source_walk_recorded())
        .collect();
    diagnostics.sort_by(|left, right| {
        left.path
            .cmp(&right.path)
            .then_with(|| left.kind.id().cmp(right.kind.id()))
            .then_with(|| left.message.cmp(&right.message))
    });
    diagnostics
}

/// Directories that are conventionally NOT workspace packages even when a
/// glob like `packages/*` matches them. Mirrors pnpm/npm/yarn behavior of
/// silently filtering these out. Shared by workspace discovery and glob
/// diagnostics so both exclude hidden directories, build artifacts and tooling
/// caches.
#[must_use]
pub(super) fn is_skip_listed_dir(name: &str) -> bool {
    name.starts_with('.') || matches!(name, "node_modules" | "build" | "dist" | "coverage")
}

/// Test if a project-root-relative directory path is excluded by user
/// `ignorePatterns`. The directory itself and its `package.json` are both
/// checked because users variably write `packages/legacy/**` or
/// `packages/legacy/package.json` in their ignore globs.
#[must_use]
pub(super) fn is_ignored_workspace_dir(
    relative_dir: &Path,
    ignore_patterns: &globset::GlobSet,
) -> bool {
    if ignore_patterns.is_empty() {
        return false;
    }
    let relative_str = relative_dir.to_string_lossy().replace('\\', "/");
    ignore_patterns.is_match(relative_str.as_str())
        || ignore_patterns.is_match(format!("{relative_str}/package.json").as_str())
}

#[cfg(test)]
mod tests {
    use super::*;
    use fallow_types::discover::FileId;
    use fallow_types::extract::SourceReadFailure;

    fn glob_diag(root: &Path, pattern: &str, rel_path: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join(rel_path),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: pattern.to_owned(),
            },
        )
    }

    #[test]
    fn skipped_large_file_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("src/vendor/app.bundle.js"),
            WorkspaceDiagnosticKind::SkippedLargeFile {
                size_bytes: 6 * 1024 * 1024,
            },
        );
        assert_eq!(diag.kind.id(), "skipped-large-file");
        assert!(
            diag.message.contains("src/vendor/app.bundle.js"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message.contains("6.0 MB"),
            "message reports the size: {}",
            diag.message
        );
        assert!(
            diag.message.contains("--max-file-size"),
            "message names the override flag: {}",
            diag.message
        );
    }

    #[test]
    fn skipped_minified_file_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("src/assets/index-abc123.js"),
            WorkspaceDiagnosticKind::SkippedMinifiedFile {
                size_bytes: 2 * 1024 * 1024,
            },
        );
        assert_eq!(diag.kind.id(), "skipped-minified-file");
        assert!(
            diag.message.contains("src/assets/index-abc123.js"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message.contains("2.0 MB"),
            "message reports the size: {}",
            diag.message
        );
        assert!(
            diag.message.contains("--max-file-size 0"),
            "message names the opt-out: {}",
            diag.message
        );
    }

    #[test]
    fn skipped_source_dotdir_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join(".claude"),
            WorkspaceDiagnosticKind::SkippedSourceDotdir,
        );
        assert_eq!(diag.kind.id(), "skipped-source-dotdir");
        assert!(
            diag.message.contains(".claude"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message
                .contains("Its imports and exports are not analyzed."),
            "message states the consequence: {}",
            diag.message
        );
        assert!(
            diag.message.contains("--root"),
            "message names the real remedy: {}",
            diag.message
        );
        assert!(
            diag.message.contains("no config field"),
            "the message must say plainly that no config field traverses it: {}",
            diag.message
        );
    }

    #[test]
    fn stash_preserves_appended_skipped_large_file_across_restash() {
        // Unique synthetic root so the process-global registry does not collide
        // with sibling tests.
        let root = Path::new("/fallow-test-1086-stash-preserve");
        let undeclared = || {
            WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )
        };
        // First analysis loads config and stashes the workspace-discovery set.
        stash_workspace_diagnostics(root, vec![undeclared()]);
        // Its source discovery appends a skipped-large-file diagnostic.
        append_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("vendor/big.js"),
                WorkspaceDiagnosticKind::SkippedLargeFile {
                    size_bytes: 9_999_999,
                },
            )],
        );
        // A sibling analysis (combined-mode dupes/health) re-loads config and
        // re-stashes the same workspace-discovery set.
        stash_workspace_diagnostics(root, vec![undeclared()]);

        let after = workspace_diagnostics_for(root);
        assert_eq!(
            after
                .iter()
                .filter(|d| d.kind.is_source_discovery())
                .count(),
            1,
            "skipped-large-file survives the combined-mode re-stash exactly once (#1086): {after:?}"
        );
        assert_eq!(
            after
                .iter()
                .filter(|d| matches!(d.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace))
                .count(),
            1,
            "the workspace-discovery diagnostic is replaced, not duplicated"
        );
    }

    fn analysis_stage_diagnostics(root: &Path) -> Vec<WorkspaceDiagnostic> {
        vec![
            WorkspaceDiagnostic::new(
                root,
                root.join("pnpm-workspace.yaml"),
                WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
                    error: "could not find expected ':'".to_owned(),
                },
            ),
            WorkspaceDiagnostic::new(
                root,
                root.join("package.json"),
                WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
            ),
        ]
    }

    fn count_kind(diagnostics: &[WorkspaceDiagnostic], id: &str) -> usize {
        diagnostics.iter().filter(|d| d.kind.id() == id).count()
    }

    #[test]
    fn stash_preserves_recorded_analysis_stage_diagnostics_across_restash() {
        let root = Path::new("/fallow-test-2366-stash-preserve");
        let undeclared = || {
            WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )
        };
        // The check analysis loads config, then its analyze pass records both
        // analysis-stage kinds.
        stash_workspace_diagnostics(root, vec![undeclared()]);
        record_workspace_diagnostics(root, analysis_stage_diagnostics(root));
        // Combined-mode dupes/health re-load config and re-stash the same
        // workspace-discovery set before the JSON envelope is built.
        stash_workspace_diagnostics(root, vec![undeclared()]);

        let after = workspace_diagnostics_for(root);
        assert_eq!(
            count_kind(&after, "malformed-pnpm-workspace-yaml"),
            1,
            "malformed-pnpm-workspace-yaml survives the combined-mode re-stash exactly once (#2366): {after:?}"
        );
        assert_eq!(
            count_kind(&after, "bun-lockb-override-resolution-skipped"),
            1,
            "bun-lockb-override-resolution-skipped survives the combined-mode re-stash exactly once (#2366): {after:?}"
        );
        assert_eq!(
            count_kind(&after, "undeclared-workspace"),
            1,
            "the workspace-discovery diagnostic is replaced, not duplicated"
        );
    }

    #[test]
    fn source_read_failures_replace_only_their_previous_parse_set() {
        let root = Path::new("/fallow-test-source-read-replace");
        stash_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )],
        );
        append_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("vendor/big.js"),
                WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes: 99 },
            )],
        );
        let first = SourceReadFailure {
            file_id: FileId(1),
            path: root.join("src/first.ts"),
            error: "removed".to_string(),
        };
        let _ = record_source_read_failures(root, &[first]);
        let second = SourceReadFailure {
            file_id: FileId(2),
            path: root.join("src/second.ts"),
            error: "permission denied".to_string(),
        };

        let _ = record_source_read_failures(root, std::slice::from_ref(&second));

        let diagnostics = workspace_diagnostics_for(root);
        let source_failures: Vec<_> = diagnostics
            .iter()
            .filter(|diagnostic| {
                matches!(
                    diagnostic.kind,
                    WorkspaceDiagnosticKind::SourceReadFailure { .. }
                )
            })
            .collect();
        assert_eq!(source_failures.len(), 1);
        assert_eq!(source_failures[0].path, second.path);
        assert!(diagnostics.iter().any(|diagnostic| matches!(
            diagnostic.kind,
            WorkspaceDiagnosticKind::UndeclaredWorkspace
        )));
        assert!(diagnostics.iter().any(|diagnostic| matches!(
            diagnostic.kind,
            WorkspaceDiagnosticKind::SkippedLargeFile { .. }
        )));

        let _ = record_source_read_failures(root, &[]);
        assert!(workspace_diagnostics_for(root).iter().all(|diagnostic| {
            !matches!(
                diagnostic.kind,
                WorkspaceDiagnosticKind::SourceReadFailure { .. }
            )
        }));
    }

    #[test]
    fn clear_source_discovery_drops_stale_skip_keeps_workspace_diag() {
        let root = Path::new("/fallow-test-1086-clear-stale");
        stash_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )],
        );
        append_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("vendor/big.js"),
                WorkspaceDiagnosticKind::SkippedLargeFile {
                    size_bytes: 9_999_999,
                },
            )],
        );
        // A later walk (the file is no longer skipped) clears the stale entry.
        let replaced = replace_source_discovery_diagnostics(root, Vec::new());
        assert!(
            replaced.is_empty(),
            "the walk's own list is what it wrote, not what it removed"
        );

        let after = workspace_diagnostics_for(root);
        assert!(
            !after.iter().any(|d| d.kind.is_source_discovery()),
            "stale skipped-large-file is dropped on the next walk (#1086 watch-mode): {after:?}"
        );
        assert!(
            after
                .iter()
                .any(|d| matches!(d.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)),
            "the workspace-discovery diagnostic survives the source-discovery clear"
        );
    }

    #[test]
    fn clear_analysis_stage_drops_stale_entries_keeps_other_kinds() {
        let root = Path::new("/fallow-test-2366-clear-stale");
        stash_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )],
        );
        append_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("vendor/big.js"),
                WorkspaceDiagnosticKind::SkippedLargeFile {
                    size_bytes: 9_999_999,
                },
            )],
        );
        record_workspace_diagnostics(root, analysis_stage_diagnostics(root));
        // The next analyze pass (the yaml is fixed, a text bun.lock exists)
        // clears the stale entries before re-recording nothing.
        clear_analysis_stage_diagnostics(root);

        let after = workspace_diagnostics_for(root);
        assert!(
            !after.iter().any(|d| d.kind.is_analysis_stage()),
            "stale analysis-stage entries are dropped on the next analyze pass (#2366): {after:?}"
        );
        assert_eq!(
            count_kind(&after, "undeclared-workspace"),
            1,
            "the workspace-discovery diagnostic survives the analysis-stage clear"
        );
        assert_eq!(
            count_kind(&after, "skipped-large-file"),
            1,
            "the source-discovery diagnostic survives the analysis-stage clear"
        );
    }

    /// The health pipeline appends after config load, so combined mode's
    /// per-analysis config re-load must preserve its entries. It must also not
    /// preserve them past the next health run, or a fixed CODEOWNERS is
    /// reported forever (issue #2689).
    #[test]
    fn health_stage_entries_survive_a_config_reload_and_not_the_next_health_run() {
        let root = Path::new("/fallow-test-2689-health-stage");
        stash_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )],
        );
        append_workspace_diagnostics(
            root,
            vec![
                WorkspaceDiagnostic::new(
                    root,
                    root.to_path_buf(),
                    WorkspaceDiagnosticKind::HotspotsSkipped {
                        cause: "not-a-repository".to_owned(),
                    },
                ),
                WorkspaceDiagnostic::new(
                    root,
                    root.join("coverage/coverage-final.json"),
                    WorkspaceDiagnosticKind::CoverageAutoDetected,
                ),
            ],
        );

        // Combined mode re-loads config for the next analysis.
        stash_workspace_diagnostics(
            root,
            vec![WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )],
        );
        let after_reload = workspace_diagnostics_for(root);
        assert_eq!(count_kind(&after_reload, "hotspots-skipped"), 1);
        assert_eq!(count_kind(&after_reload, "coverage-auto-detected"), 1);

        // The dead-code analyze pass inside the health run must not take them.
        clear_analysis_stage_diagnostics(root);
        assert_eq!(
            health_stage_workspace_diagnostics(root).len(),
            2,
            "the analysis-stage clear must leave health-stage entries alone"
        );

        clear_health_stage_diagnostics(root);
        let after = workspace_diagnostics_for(root);
        assert!(
            !after.iter().any(|d| d.kind.is_health_stage()),
            "the next health run starts from nothing: {after:?}"
        );
        assert_eq!(
            count_kind(&after, "undeclared-workspace"),
            1,
            "the workspace-discovery diagnostic survives the health-stage clear"
        );
    }

    fn plugin_diagnostic(root: &Path, key: &str, reason: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join("module-federation.config.ts"),
            WorkspaceDiagnosticKind::PluginConfigUnreadable {
                plugin: "module-federation".to_owned(),
                key: key.to_owned(),
                reason: reason.to_owned(),
            },
        )
    }

    /// Plugins run after config load, so combined mode's per-analysis config
    /// re-load must preserve their entries, and the next plugin run must
    /// replace rather than accumulate them so a fixed config drops out
    /// (issue #2736).
    #[test]
    fn plugin_stage_entries_survive_a_config_reload_and_are_replaced_by_the_next_run() {
        let root = Path::new("/fallow-test-2736-plugin-stage");
        let undeclared = || {
            WorkspaceDiagnostic::new(
                root,
                root.join("pkg"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            )
        };
        stash_workspace_diagnostics(root, vec![undeclared()]);
        let recorded = record_plugin_config_diagnostics(
            root,
            vec![plugin_diagnostic(root, "exposes", "not-object-literal")],
        );
        assert_eq!(recorded.len(), 1, "the caller gets its own copy back");

        // Combined mode re-loads config for the next analysis.
        stash_workspace_diagnostics(root, vec![undeclared()]);
        let after_reload = workspace_diagnostics_for(root);
        assert_eq!(
            count_kind(&after_reload, "plugin-config-unreadable"),
            1,
            "the plugin entry survives the combined-mode re-stash exactly once: {after_reload:?}"
        );
        assert_eq!(count_kind(&after_reload, "undeclared-workspace"), 1);

        // The dead-code analyze pass clears its own stage on entry, and plugins
        // run inside that pass's prelude.
        clear_analysis_stage_diagnostics(root);
        assert_eq!(
            count_kind(&workspace_diagnostics_for(root), "plugin-config-unreadable"),
            1,
            "the analysis-stage clear must leave plugin-stage entries alone"
        );

        // A rerun after the config was fixed reports nothing, and the stale
        // entry goes with it.
        let _ = record_plugin_config_diagnostics(root, Vec::new());
        let after = workspace_diagnostics_for(root);
        assert!(
            !after.iter().any(|d| d.kind.is_plugin_stage()),
            "each plugin run replaces the previous set: {after:?}"
        );
        assert_eq!(
            count_kind(&after, "undeclared-workspace"),
            1,
            "the workspace-discovery diagnostic survives the plugin replace"
        );
    }

    /// One config file can hold two unreadable keys. They share a kind id and a
    /// path, so both the registry write and the stderr dedupe have to key on
    /// the payload, or the second one is invisible (issue #2736).
    #[test]
    fn two_unreadable_keys_in_one_config_are_recorded_and_printed_twice() {
        let root = Path::new("/fallow-test-2736-two-keys");
        let (_, captured) = capture_workspace_warnings(|| {
            record_plugin_config_diagnostics(
                root,
                vec![
                    plugin_diagnostic(root, "exposes", "not-object-literal"),
                    plugin_diagnostic(root, "remotes", "spread"),
                ],
            )
        });
        assert_eq!(
            captured.len(),
            2,
            "both keys reach the emitter: {captured:?}"
        );
        let stored = workspace_diagnostics_for(root);
        assert_eq!(
            count_kind(&stored, "plugin-config-unreadable"),
            2,
            "both keys are recorded: {stored:?}"
        );

        let plans = plan_warnings(
            root,
            &[
                plugin_diagnostic(root, "exposes", "not-object-literal"),
                plugin_diagnostic(root, "remotes", "spread"),
            ],
        );
        assert_eq!(plans.len(), 2, "two distinct lines are planned: {plans:?}");
        assert_ne!(
            plans[0].dedupe_key, plans[1].dedupe_key,
            "the process-wide dedupe must not swallow the second key: {plans:?}"
        );
    }

    /// The quiet kind reaches the registry and never the stderr plan, so a
    /// project whose `nuxt.config` fallow does not model is reported once in
    /// the envelope and never warned about again.
    #[test]
    fn the_not_modeled_kind_is_recorded_without_a_stderr_line() {
        let root = Path::new("/fallow-test-2736-not-modeled");
        let diagnostic = WorkspaceDiagnostic::new(
            root,
            root.join("nuxt.config.ts"),
            WorkspaceDiagnosticKind::PluginEffectNotModeled {
                plugin: "nuxt".to_owned(),
                key: "components".to_owned(),
                reason: "key-effect-not-modeled".to_owned(),
            },
        );
        let _ = record_plugin_config_diagnostics(root, vec![diagnostic.clone()]);
        assert_eq!(
            count_kind(
                &workspace_diagnostics_for(root),
                "plugin-effect-not-modeled"
            ),
            1
        );
        assert!(
            plan_warnings(root, &[diagnostic]).is_empty(),
            "a kind that does not degrade the run plans no stderr line"
        );
    }

    #[test]
    fn build_glob_group_message_caps_examples_and_summarises_tail() {
        let root = Path::new("/project");
        let paths = [
            root.join("playground/cli"),
            root.join("playground/lib-types"),
            root.join("playground/minify"),
            root.join("playground/ssr"),
            root.join("playground/worker"),
        ];
        let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
        let message = build_glob_group_message(root, "playground/**", &refs);

        assert!(
            message.starts_with("Glob 'playground/**' matched 5 directories with no package.json"),
            "count and pattern lead the message: {message}"
        );
        assert!(
            message.contains(
                "(e.g. playground/cli, playground/lib-types, playground/minify, and 2 more)"
            ),
            "three sorted examples + tail count: {message}"
        );
        assert!(
            message.ends_with(
                "Add a package.json, narrow the pattern, or add them to ignorePatterns."
            ),
            "next-step hint preserved: {message}"
        );
        assert!(
            !message.contains("playground/ssr"),
            "tail example not named: {message}"
        );
    }

    #[test]
    fn build_glob_group_message_no_tail_when_at_or_below_cap() {
        let root = Path::new("/project");
        let paths = [root.join("packages/a"), root.join("packages/b")];
        let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
        let message = build_glob_group_message(root, "packages/*", &refs);

        assert!(message.contains("matched 2 directories"), "{message}");
        assert!(
            message.contains("(e.g. packages/a, packages/b)"),
            "both examples named, no `and N more`: {message}"
        );
        assert!(!message.contains("more)"), "no tail clause: {message}");
    }

    #[test]
    fn plan_warnings_aggregates_repeated_glob_diagnostics_to_one_line() {
        let root = Path::new("/project");
        let diagnostics: Vec<WorkspaceDiagnostic> = (0..50)
            .map(|i| glob_diag(root, "playground/**", &format!("playground/p{i}")))
            .collect();

        let plans = plan_warnings(root, &diagnostics);

        assert_eq!(
            plans.len(),
            1,
            "50 same-pattern diagnostics collapse to one plan"
        );
        assert!(
            plans[0]
                .dedupe_key
                .ends_with("::glob-matched-no-package-json-agg::playground/**")
        );
        assert!(plans[0].message.contains("matched 50 directories"));
    }

    #[test]
    fn plan_warnings_keeps_distinct_patterns_separate() {
        let root = Path::new("/project");
        let diagnostics = vec![
            glob_diag(root, "apps/*", "apps/a"),
            glob_diag(root, "apps/*", "apps/b"),
            glob_diag(root, "packages/*", "packages/x"),
            glob_diag(root, "packages/*", "packages/y"),
        ];

        let plans = plan_warnings(root, &diagnostics);

        assert_eq!(plans.len(), 2, "one aggregated plan per distinct pattern");
        let messages: Vec<&str> = plans.iter().map(|p| p.message.as_str()).collect();
        assert!(
            messages
                .iter()
                .any(|m| m.contains("Glob 'apps/*' matched 2")),
            "{messages:?}"
        );
        assert!(
            messages
                .iter()
                .any(|m| m.contains("Glob 'packages/*' matched 2")),
            "{messages:?}"
        );
    }

    #[test]
    fn plan_warnings_single_match_keeps_per_instance_message_and_key() {
        let root = Path::new("/project");
        let diag = glob_diag(root, "packages/*", "packages/scratch");

        let plans = plan_warnings(root, std::slice::from_ref(&diag));

        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].message, diag.message);
        // The key embeds `diag.path` through a raw `Display`, so the expected
        // path segment carries the platform separator: the stored path is
        // rebuilt from its components and renders with backslashes on Windows.
        // It ends with the rendered message, which is what stands in for the
        // payload so two entries sharing a kind and a path stay two lines.
        let expected_path = Path::new("packages").join("scratch");
        assert!(
            plans[0]
                .dedupe_key
                .contains("::glob-matched-no-package-json::")
                && plans[0]
                    .dedupe_key
                    .contains(&expected_path.display().to_string())
                && plans[0].dedupe_key.ends_with(&diag.message),
            "per-instance key is `root::kind::path::message`, not the `-agg::pattern` form: {}",
            plans[0].dedupe_key
        );
        assert!(
            !plans[0].message.contains("directories"),
            "single match is not aggregated"
        );
    }

    #[test]
    fn plan_warnings_non_glob_kinds_stay_per_instance() {
        let root = Path::new("/project");
        let diagnostics = vec![
            WorkspaceDiagnostic::new(
                root,
                root.join("packages/a"),
                WorkspaceDiagnosticKind::UndeclaredWorkspace,
            ),
            WorkspaceDiagnostic::new(
                root,
                root.join("packages/b"),
                WorkspaceDiagnosticKind::MalformedPackageJson {
                    error: "trailing comma".to_owned(),
                },
            ),
        ];

        let plans = plan_warnings(root, &diagnostics);

        assert_eq!(
            plans.len(),
            2,
            "each non-glob diagnostic plans its own warning"
        );
        assert!(
            plans
                .iter()
                .all(|p| !p.message.contains("directories with no package.json"))
        );
    }

    /// The unconfigured-check kinds fire in the product's DEFAULT state, on
    /// every project that never opted into boundaries or rule packs, so a
    /// stderr warning for them is permanent noise whose only remedy is to write
    /// config to silence a warning about not having written config. They stay
    /// in `workspace_diagnostics[]` for a consumer that wants them.
    #[test]
    fn plan_warnings_drops_the_unconfigured_check_kinds() {
        let root = Path::new("/project");
        let diagnostics = vec![
            WorkspaceDiagnostic::new(
                root,
                root.to_path_buf(),
                WorkspaceDiagnosticKind::BoundariesNotConfigured,
            ),
            WorkspaceDiagnostic::new(
                root,
                root.to_path_buf(),
                WorkspaceDiagnosticKind::RulePacksNotConfigured,
            ),
        ];

        assert!(
            plan_warnings(root, &diagnostics).is_empty(),
            "an unconfigured check is not a degraded run and warns nobody"
        );
    }

    /// A missing dependency tree really does change what the analysis can see,
    /// so it keeps its stderr line while the unconfigured-check kinds lose
    /// theirs, even when both arrive in the same batch.
    #[test]
    fn plan_warnings_keeps_the_degradation_kinds_alongside_dropped_ones() {
        let root = Path::new("/project");
        let diagnostics = vec![
            WorkspaceDiagnostic::new(
                root,
                root.to_path_buf(),
                WorkspaceDiagnosticKind::BoundariesNotConfigured,
            ),
            WorkspaceDiagnostic::new(
                root,
                root.join("node_modules"),
                WorkspaceDiagnosticKind::NodeModulesMissing,
            ),
            WorkspaceDiagnostic::new(
                root,
                root.to_path_buf(),
                WorkspaceDiagnosticKind::RulePacksNotConfigured,
            ),
        ];

        let messages: Vec<String> = plan_warnings(root, &diagnostics)
            .into_iter()
            .map(|plan| plan.message)
            .collect();

        assert_eq!(
            messages.len(),
            1,
            "only the degradation warns: {messages:?}"
        );
        assert!(
            messages[0].contains("node_modules"),
            "the surviving line is the missing dependency tree: {messages:?}"
        );
    }

    fn tsconfig_ref_diag(root: &Path, rel_path: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join(rel_path),
            WorkspaceDiagnosticKind::TsconfigReferenceDirMissing,
        )
    }

    #[test]
    fn plan_warnings_aggregates_repeated_tsconfig_ref_misses_to_one_line() {
        let root = Path::new("/project");
        let diagnostics: Vec<WorkspaceDiagnostic> = (0..30)
            .map(|i| tsconfig_ref_diag(root, &format!("packages/p{i:02}/tsconfig.json")))
            .collect();

        let plans = plan_warnings(root, &diagnostics);

        assert_eq!(plans.len(), 1, "30 missing references collapse to one plan");
        assert!(
            plans[0]
                .dedupe_key
                .ends_with("::tsconfig-reference-dir-missing-agg")
        );
        assert!(
            plans[0]
                .message
                .starts_with("tsconfig.json references 30 directories that do not exist"),
            "{}",
            plans[0].message
        );
        assert!(
            plans[0].message.contains(
                "(e.g. packages/p00/tsconfig.json, packages/p01/tsconfig.json, \
                 packages/p02/tsconfig.json, and 27 more)"
            ),
            "three sorted examples + tail: {}",
            plans[0].message
        );
        assert!(
            plans[0]
                .message
                .ends_with("Update or remove the references, or restore the missing directories."),
            "{}",
            plans[0].message
        );
    }

    #[test]
    fn plan_warnings_single_tsconfig_ref_miss_keeps_per_instance_message() {
        let root = Path::new("/project");
        let diag = tsconfig_ref_diag(root, "packages/only/tsconfig.json");

        let plans = plan_warnings(root, std::slice::from_ref(&diag));

        assert_eq!(plans.len(), 1);
        assert_eq!(
            plans[0].message, diag.message,
            "single miss is not aggregated"
        );
        assert!(!plans[0].message.contains("directories that do not exist"));
    }

    #[test]
    fn plan_warnings_mixed_aggregatable_kinds_each_collapse_independently() {
        let root = Path::new("/project");
        let mut diagnostics: Vec<WorkspaceDiagnostic> = (0..5)
            .map(|i| glob_diag(root, "packages/*", &format!("packages/g{i}")))
            .collect();
        diagnostics.extend(
            (0..4).map(|i| tsconfig_ref_diag(root, &format!("packages/t{i}/tsconfig.json"))),
        );

        let plans = plan_warnings(root, &diagnostics);

        assert_eq!(plans.len(), 2, "one glob summary + one tsconfig summary");
        assert!(
            plans
                .iter()
                .any(|p| p.message.contains("matched 5 directories"))
        );
        assert!(
            plans
                .iter()
                .any(|p| p.message.contains("references 4 directories"))
        );
    }

    /// Issue #2366: the aggregated warning groups the diagnostics it is
    /// handed and counts the group, so a list that still holds the duplicate
    /// entries of one glob declared in two manifests reports a directory
    /// count that does not exist and names one directory twice among its
    /// examples. Deduplicating at discovery is what makes the summary true.
    #[test]
    fn two_manifest_glob_warning_counts_each_directory_once() {
        let dir = tempfile::tempdir().expect("create temp dir");
        crate::workspace::write_two_manifest_glob_project(dir.path());

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

        let messages: Vec<String> = plan_warnings(dir.path(), &diagnostics)
            .into_iter()
            .map(|plan| plan.message)
            .collect();

        assert_eq!(
            messages,
            vec![
                "Glob 'pkgs/*' matched 2 directories with no package.json \
                 (e.g. pkgs/aaa, pkgs/bbb). Add a package.json, narrow the \
                 pattern, or add them to ignorePatterns."
                    .to_owned()
            ],
            "the summary names the true directory count and each example once"
        );
    }
}