fallow-core 2.77.0

Analysis orchestration for fallow codebase intelligence (dead code, duplication, plugins, cross-reference)
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
mod entry_points;
mod infrastructure;
mod parse_scripts;
mod walk;

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

use fallow_config::{PackageJson, ResolvedConfig};
use rustc_hash::FxHashSet;

// Re-export types from fallow-types
pub use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};

// Re-export public functions — preserves the existing `crate::discover::*` API
pub use entry_points::{
    CategorizedEntryPoints, compile_glob_set, discover_dynamically_loaded_entry_points,
    discover_entry_points, discover_plugin_entry_point_sets, discover_plugin_entry_points,
    discover_workspace_entry_points,
};
pub(crate) use entry_points::{
    EntryPointDiscovery, discover_entry_points_with_warnings_from_pkg,
    discover_workspace_entry_points_with_warnings_from_pkg, warn_skipped_entry_summary,
};
pub use infrastructure::discover_infrastructure_entry_points;
pub use walk::{
    HiddenDirScope, PRODUCTION_EXCLUDE_PATTERNS, SOURCE_EXTENSIONS, discover_files,
    discover_files_with_additional_hidden_dirs,
};

/// Collect package-scoped hidden directory traversal rules for active plugins.
///
/// Source discovery runs before full plugin execution, so this consults
/// package-activation checks and static plugin metadata only. Callers that
/// also need script-derived scopes should use [`collect_hidden_dir_scopes`]
/// instead, which loads each workspace's `package.json` once and feeds both
/// passes; standalone CLI command paths can use
/// [`discover_files_with_plugin_scopes`] when they have neither already.
#[must_use]
pub fn collect_plugin_hidden_dir_scopes(
    config: &ResolvedConfig,
    root_pkg: Option<&PackageJson>,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> Vec<HiddenDirScope> {
    let registry = crate::plugins::PluginRegistry::new(config.external_plugins.clone());
    let mut scopes = Vec::new();

    if let Some(pkg) = root_pkg {
        push_plugin_hidden_dir_scope(&mut scopes, &registry, pkg, &config.root);
    }

    for ws in workspaces {
        if let Ok(pkg) = PackageJson::load(&ws.root.join("package.json")) {
            push_plugin_hidden_dir_scope(&mut scopes, &registry, &pkg, &ws.root);
        }
    }

    scopes
}

/// Combined plugin-derived and script-derived hidden directory scopes.
///
/// Loads each workspace's `package.json` ONCE and feeds both the plugin
/// registry's `discovery_hidden_dirs` check and the
/// `package.json#scripts` extractor. Prefer this over calling
/// [`collect_plugin_hidden_dir_scopes`] and
/// [`collect_script_hidden_dir_scopes`] back-to-back: on monorepos with
/// many workspace packages, doing the workspace `package.json` read once
/// avoids quadratic I/O.
#[must_use]
pub fn collect_hidden_dir_scopes(
    config: &ResolvedConfig,
    root_pkg: Option<&PackageJson>,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> Vec<HiddenDirScope> {
    let _span = tracing::info_span!("collect_hidden_dir_scopes").entered();
    let registry = crate::plugins::PluginRegistry::new(config.external_plugins.clone());
    let mut scopes = Vec::new();

    if let Some(pkg) = root_pkg {
        push_plugin_hidden_dir_scope(&mut scopes, &registry, pkg, &config.root);
        if let Some(scope) = build_script_scope(pkg, &config.root) {
            scopes.push(scope);
        }
    }

    for ws in workspaces {
        if let Ok(pkg) = PackageJson::load(&ws.root.join("package.json")) {
            push_plugin_hidden_dir_scope(&mut scopes, &registry, &pkg, &ws.root);
            if let Some(scope) = build_script_scope(&pkg, &ws.root) {
                scopes.push(scope);
            }
        }
    }

    scopes
}

fn push_plugin_hidden_dir_scope(
    scopes: &mut Vec<HiddenDirScope>,
    registry: &crate::plugins::PluginRegistry,
    pkg: &PackageJson,
    root: &Path,
) {
    let dirs = registry.discovery_hidden_dirs(pkg, root);
    if !dirs.is_empty() {
        scopes.push(HiddenDirScope::new(root.to_path_buf(), dirs));
    }
}

/// Discover files with plugin-aware hidden directory traversal.
///
/// Convenience wrapper for command paths (list, dupes, health, flags, coverage)
/// that don't already have workspaces / root `package.json` on hand. Internally
/// loads the root `package.json` and discovers workspaces so plugin-contributed
/// hidden directories (e.g. React Router's `.client` / `.server` folders) AND
/// hidden directories referenced from `package.json#scripts` (e.g.
/// `eslint -c .config/eslint.config.js`) are traversed consistently across
/// every command.
#[must_use]
pub fn discover_files_with_plugin_scopes(config: &ResolvedConfig) -> Vec<DiscoveredFile> {
    let root_pkg = PackageJson::load(&config.root.join("package.json")).ok();
    let workspaces = fallow_config::discover_workspaces(&config.root);
    let scopes = collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces);
    discover_files_with_additional_hidden_dirs(config, &scopes)
}

/// Hidden (dot-prefixed) directories that should be included in file discovery.
///
/// Most hidden directories (`.git`, `.cache`, etc.) should be skipped, but certain
/// convention directories contain source or config files that fallow needs to see:
/// - `.storybook` — Storybook configuration (the Storybook plugin depends on this)
/// - `.vitepress` — VitePress configuration and theme files
/// - `.well-known` — Standard web convention directory
/// - `.changeset` — Changesets configuration
/// - `.github` — GitHub workflows and CI scripts
const ALLOWED_HIDDEN_DIRS: &[&str] = &[
    ".storybook",
    ".vitepress",
    ".well-known",
    ".changeset",
    ".github",
];

/// Hidden directories that must NEVER be auto-scoped from a `package.json#scripts`
/// reference. These are build caches, VCS metadata, IDE state, or package-manager
/// state where walking would tank performance or pollute analysis. A script that
/// happens to read or write into one of these directories (e.g. `nx run ... && cp
/// dist/foo .nx/cache/`) must not pull the entire directory into source discovery.
const SCRIPT_SCOPE_DENYLIST: &[&str] = &[
    ".git",
    ".next",
    ".nuxt",
    ".output",
    ".svelte-kit",
    ".turbo",
    ".nx",
    ".cache",
    ".parcel-cache",
    ".vercel",
    ".netlify",
    ".yarn",
    ".pnpm-store",
    ".docusaurus",
    ".vscode",
    ".idea",
    ".fallow",
    ".husky",
];

/// Collect package-scoped hidden directory traversal rules from
/// `package.json#scripts` references.
///
/// Many tools accept custom config paths via `--config` / `-c` flags or positional
/// file arguments (e.g. `eslint -c .config/eslint.config.js`,
/// `vitest --config .config/vitest.config.ts`, `tsx ./.scripts/build.ts`). The file
/// walker's hidden-directory filter would otherwise skip `.config/` and friends,
/// leaving the referenced file out of the file registry. The file is detected as
/// an entry point but never parsed, so its imports are never credited.
///
/// Guardrails:
/// - Only the structured outputs of `crate::scripts::parse_script`
///   (`config_args`, `file_args`) are inspected. Arbitrary script tokens are not
///   scanned, so a logging path like `.nx/cache/result.json` in a script body
///   cannot pull `.nx/` into scope.
/// - Paths containing `..` are skipped. A workspace script referencing
///   `../../.config/...` should not generate a scope rooted at that workspace.
/// - `SCRIPT_SCOPE_DENYLIST` excludes known build-cache, VCS, IDE, and
///   package-manager state directories regardless of script content.
#[must_use]
pub fn collect_script_hidden_dir_scopes(
    config: &ResolvedConfig,
    root_pkg: Option<&PackageJson>,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> Vec<HiddenDirScope> {
    let _span = tracing::info_span!("collect_script_hidden_dir_scopes").entered();
    let mut scopes = Vec::new();

    if let Some(pkg) = root_pkg
        && let Some(scope) = build_script_scope(pkg, &config.root)
    {
        scopes.push(scope);
    }
    for ws in workspaces {
        if let Ok(pkg) = PackageJson::load(&ws.root.join("package.json"))
            && let Some(scope) = build_script_scope(&pkg, &ws.root)
        {
            scopes.push(scope);
        }
    }
    scopes
}

fn build_script_scope(pkg: &PackageJson, root: &Path) -> Option<HiddenDirScope> {
    let scripts = pkg.scripts.as_ref()?;
    let mut seen = FxHashSet::default();
    let mut dirs: Vec<String> = Vec::new();

    for (script_name, script_value) in scripts {
        for cmd in crate::scripts::parse_script(script_value) {
            for path in cmd.config_args.iter().chain(cmd.file_args.iter()) {
                for hidden in extract_hidden_segments(path) {
                    if SCRIPT_SCOPE_DENYLIST.contains(&hidden.as_str()) {
                        continue;
                    }
                    if seen.insert(hidden.clone()) {
                        tracing::debug!(
                            dir = %hidden,
                            script = %script_name,
                            package_root = %root.display(),
                            "inferred hidden_dir_scope from package.json#scripts"
                        );
                        dirs.push(hidden);
                    }
                }
            }
        }
    }

    if dirs.is_empty() {
        None
    } else {
        Some(HiddenDirScope::new(root.to_path_buf(), dirs))
    }
}

/// Extract hidden (dot-prefixed) directory segments from a relative path.
///
/// Returns an empty vec when the path is absolute or contains any `..`
/// component, so scopes cannot escape a package root. Trailing file
/// components are not included (a path like `.config/eslint.config.js`
/// yields `[".config"]`, not `[".config", "eslint.config.js"]`).
///
/// A bare single-component path like `.env` is treated as a file (not a
/// directory) and yields empty. Real-world tools that accept a directory
/// as the value of `-c` are vanishingly rare; the common case is a file
/// path. Conflating the two would over-eagerly scope hidden filenames.
fn extract_hidden_segments(path: &str) -> Vec<String> {
    let p = Path::new(path);
    if p.is_absolute() {
        return Vec::new();
    }
    let components: Vec<Component> = p.components().collect();
    if components.iter().any(|c| matches!(c, Component::ParentDir)) {
        return Vec::new();
    }
    let mut out = Vec::new();
    // Skip the last component (treated as a filename: the walker filters
    // files by extension, not by hidden status, so hidden files are already
    // passed through without scoping).
    let upto = components.len().saturating_sub(1);
    for component in &components[..upto] {
        if let Component::Normal(name) = component {
            let s = name.to_string_lossy();
            if s.starts_with('.') && s.len() > 1 {
                out.push(s.into_owned());
            }
        }
    }
    out
}

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

    // ── ALLOWED_HIDDEN_DIRS exhaustiveness ───────────────────────────

    #[test]
    fn allowed_hidden_dirs_count() {
        // Guard: if a new dir is added, add a test for it
        assert_eq!(
            ALLOWED_HIDDEN_DIRS.len(),
            5,
            "update tests when adding new allowed hidden dirs"
        );
    }

    #[test]
    fn allowed_hidden_dirs_all_start_with_dot() {
        for dir in ALLOWED_HIDDEN_DIRS {
            assert!(
                dir.starts_with('.'),
                "allowed hidden dir '{dir}' must start with '.'"
            );
        }
    }

    #[test]
    fn allowed_hidden_dirs_no_duplicates() {
        let mut seen = rustc_hash::FxHashSet::default();
        for dir in ALLOWED_HIDDEN_DIRS {
            assert!(seen.insert(*dir), "duplicate allowed hidden dir: {dir}");
        }
    }

    #[test]
    fn allowed_hidden_dirs_no_trailing_slash() {
        for dir in ALLOWED_HIDDEN_DIRS {
            assert!(
                !dir.ends_with('/'),
                "allowed hidden dir '{dir}' should not have trailing slash"
            );
        }
    }

    // ── Re-export smoke tests ───────────────────────────────────────

    #[test]
    fn file_id_re_exported() {
        // Verify the re-export works by constructing a FileId through the discover module
        let id = FileId(42);
        assert_eq!(id.0, 42);
    }

    #[test]
    fn source_extensions_re_exported() {
        assert!(SOURCE_EXTENSIONS.contains(&"ts"));
        assert!(SOURCE_EXTENSIONS.contains(&"tsx"));
    }

    #[test]
    fn compile_glob_set_re_exported() {
        let result = compile_glob_set(&["**/*.ts".to_string()]);
        assert!(result.is_some());
    }

    // ── SCRIPT_SCOPE_DENYLIST exhaustiveness ────────────────────────

    #[test]
    fn script_scope_denylist_all_start_with_dot() {
        for dir in SCRIPT_SCOPE_DENYLIST {
            assert!(
                dir.starts_with('.'),
                "denylisted dir '{dir}' must start with '.'"
            );
        }
    }

    #[test]
    fn script_scope_denylist_no_duplicates() {
        let mut seen = rustc_hash::FxHashSet::default();
        for dir in SCRIPT_SCOPE_DENYLIST {
            assert!(seen.insert(*dir), "duplicate denylisted dir: {dir}");
        }
    }

    #[test]
    fn script_scope_denylist_does_not_overlap_allowlist() {
        for dir in SCRIPT_SCOPE_DENYLIST {
            assert!(
                !ALLOWED_HIDDEN_DIRS.contains(dir),
                "denylisted dir '{dir}' must not also appear in ALLOWED_HIDDEN_DIRS"
            );
        }
    }

    // ── extract_hidden_segments ─────────────────────────────────────

    #[test]
    fn extract_hidden_segments_single_segment() {
        assert_eq!(
            extract_hidden_segments(".config/eslint.config.js"),
            vec![".config".to_string()]
        );
    }

    #[test]
    fn extract_hidden_segments_with_leading_dot_slash() {
        assert_eq!(
            extract_hidden_segments("./.config/eslint.config.js"),
            vec![".config".to_string()]
        );
    }

    #[test]
    fn extract_hidden_segments_nested_hidden() {
        assert_eq!(
            extract_hidden_segments(".foo/.bar/x.js"),
            vec![".foo".to_string(), ".bar".to_string()]
        );
    }

    #[test]
    fn extract_hidden_segments_hidden_inside_normal_parent() {
        assert_eq!(
            extract_hidden_segments("sub/.config/eslint.config.js"),
            vec![".config".to_string()]
        );
    }

    #[test]
    fn extract_hidden_segments_no_hidden_returns_empty() {
        assert!(extract_hidden_segments("src/index.ts").is_empty());
    }

    #[test]
    fn extract_hidden_segments_skips_trailing_filename() {
        // The last component is a file. The walker filters files by extension,
        // not by hidden status, so it must not appear in the scope.
        assert!(extract_hidden_segments(".env").is_empty());
        assert!(extract_hidden_segments("src/.eslintrc.js").is_empty());
    }

    #[test]
    fn extract_hidden_segments_skips_paths_with_parent_dir() {
        // `..` anywhere in the path means the path can escape a package root.
        assert!(extract_hidden_segments("../.config/eslint.config.js").is_empty());
        assert!(extract_hidden_segments(".config/../other/x.js").is_empty());
        assert!(extract_hidden_segments("../../.config/eslint.config.js").is_empty());
    }

    #[test]
    fn extract_hidden_segments_skips_absolute_paths() {
        // Absolute paths cannot be safely scoped to a package root.
        #[cfg(unix)]
        {
            assert!(extract_hidden_segments("/etc/.config/eslint.config.js").is_empty());
        }
        #[cfg(windows)]
        {
            assert!(extract_hidden_segments(r"C:\etc\.config\eslint.config.js").is_empty());
        }
    }

    #[test]
    fn extract_hidden_segments_ignores_bare_dot() {
        // `.` is the current directory marker, not a hidden segment.
        assert!(extract_hidden_segments(".").is_empty());
        assert!(extract_hidden_segments("./src/index.ts").is_empty());
    }

    // ── collect_script_hidden_dir_scopes ────────────────────────────

    #[expect(
        clippy::disallowed_types,
        reason = "PackageJson::scripts uses std HashMap for serde compatibility"
    )]
    fn make_pkg_with_scripts(entries: &[(&str, &str)]) -> PackageJson {
        let mut pkg = PackageJson::default();
        let mut scripts: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for (name, value) in entries {
            scripts.insert((*name).to_string(), (*value).to_string());
        }
        pkg.scripts = Some(scripts);
        pkg
    }

    fn make_config(root: std::path::PathBuf) -> ResolvedConfig {
        fallow_config::FallowConfig::default().resolve(
            root,
            fallow_config::OutputFormat::Human,
            1,
            true,
            true,
            None,
        )
    }

    #[test]
    fn script_scope_extracts_dash_c_config_arg() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = make_pkg_with_scripts(&[("lint", "eslint -c .config/eslint.config.js")]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);

        assert_eq!(scopes.len(), 1, "one scope for the root package");
        // We cannot reach into HiddenDirScope's private fields, but we can verify
        // via the file walker that the directory is now traversed.
        let target_dir = dir.path().join(".config");
        std::fs::create_dir_all(&target_dir).unwrap();
        std::fs::write(target_dir.join("eslint.config.js"), "export default {};").unwrap();
        let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
        let names: Vec<String> = files
            .iter()
            .map(|f| {
                f.path
                    .strip_prefix(dir.path())
                    .unwrap_or(&f.path)
                    .to_string_lossy()
                    .replace('\\', "/")
            })
            .collect();
        assert!(
            names.contains(&".config/eslint.config.js".to_string()),
            "expected .config/eslint.config.js to be discovered; got {names:?}"
        );
    }

    #[test]
    fn script_scope_extracts_long_config_arg_with_equals() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = make_pkg_with_scripts(&[("test", "vitest --config=.config/vitest.config.ts")]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert_eq!(scopes.len(), 1);
    }

    #[test]
    fn script_scope_extracts_positional_file_arg() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = make_pkg_with_scripts(&[("build", "tsx ./.scripts/build.ts")]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert_eq!(scopes.len(), 1);
    }

    #[test]
    fn script_scope_denies_known_bad_dirs() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        // A script referencing a denied dir must NOT produce a scope.
        let pkg = make_pkg_with_scripts(&[
            ("cache", "tsx .nx/scripts/cache.ts"),
            ("vscode", "node .vscode/build.js"),
            ("yarn-state", "node .yarn/releases/yarn-4.0.0.cjs"),
        ]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert!(
            scopes.is_empty(),
            "denylisted dirs must not produce scopes; got {scopes:?}"
        );
    }

    #[test]
    fn script_scope_mixes_denied_and_allowed_dirs() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        // Mix of denied (.nx) and allowed (.config). Only the allowed survives.
        let pkg = make_pkg_with_scripts(&[(
            "lint",
            "nx run-many --target=lint && eslint -c .config/eslint.config.js",
        )]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert_eq!(scopes.len(), 1, "one scope for the .config reference");

        // Confirm by walking: .config/ should be discovered, .nx/ should not.
        std::fs::create_dir_all(dir.path().join(".config")).unwrap();
        std::fs::write(
            dir.path().join(".config/eslint.config.js"),
            "export default {};",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join(".nx/cache")).unwrap();
        std::fs::write(dir.path().join(".nx/cache/build.js"), "// cache").unwrap();

        let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
        let names: Vec<String> = files
            .iter()
            .map(|f| {
                f.path
                    .strip_prefix(dir.path())
                    .unwrap_or(&f.path)
                    .to_string_lossy()
                    .replace('\\', "/")
            })
            .collect();
        assert!(names.contains(&".config/eslint.config.js".to_string()));
        assert!(
            !names.contains(&".nx/cache/build.js".to_string()),
            "denylisted .nx must stay hidden"
        );
    }

    #[test]
    fn script_scope_skips_parent_dir_paths() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = make_pkg_with_scripts(&[("lint", "eslint -c ../../.config/eslint.config.js")]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert!(
            scopes.is_empty(),
            "paths with .. must not generate scopes; got {scopes:?}"
        );
    }

    #[test]
    fn script_scope_no_scripts_returns_empty() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = PackageJson::default();
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert!(scopes.is_empty());
    }

    #[test]
    fn script_scope_no_hidden_paths_returns_empty() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        let pkg = make_pkg_with_scripts(&[
            ("build", "tsc -p tsconfig.json"),
            ("lint", "eslint -c eslint.config.js"),
        ]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert!(scopes.is_empty());
    }

    #[test]
    fn script_scope_dedupes_within_package() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        // Two scripts both reference .config: should produce one scope with one dir.
        let pkg = make_pkg_with_scripts(&[
            ("lint", "eslint -c .config/eslint.config.js"),
            ("test", "vitest --config .config/vitest.config.ts"),
        ]);
        let scopes = collect_script_hidden_dir_scopes(&config, Some(&pkg), &[]);
        assert_eq!(scopes.len(), 1);
    }

    #[test]
    fn script_scope_workspace_packages_have_own_scope_root() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = make_config(dir.path().to_path_buf());
        // Workspace has its own .config/ that should be scoped to its root,
        // not the project root.
        let ws_root = dir.path().join("packages/app");
        std::fs::create_dir_all(&ws_root).unwrap();
        let ws_pkg_path = ws_root.join("package.json");
        std::fs::write(
            &ws_pkg_path,
            r#"{"name":"app","scripts":{"lint":"eslint -c .config/eslint.config.js"}}"#,
        )
        .unwrap();
        let ws = fallow_config::WorkspaceInfo {
            root: ws_root.clone(),
            name: "app".to_string(),
            is_internal_dependency: false,
        };
        let scopes = collect_script_hidden_dir_scopes(&config, None, &[ws]);
        assert_eq!(scopes.len(), 1);

        // The scope should only allow .config under the workspace root, not anywhere else.
        std::fs::create_dir_all(ws_root.join(".config")).unwrap();
        std::fs::write(
            ws_root.join(".config/eslint.config.js"),
            "export default {};",
        )
        .unwrap();
        // A sibling .config under a different (unscoped) package must stay hidden.
        let other_root = dir.path().join("packages/other");
        std::fs::create_dir_all(other_root.join(".config")).unwrap();
        std::fs::write(
            other_root.join(".config/eslint.config.js"),
            "export default {};",
        )
        .unwrap();

        let files = discover_files_with_additional_hidden_dirs(&config, &scopes);
        let names: Vec<String> = files
            .iter()
            .map(|f| {
                f.path
                    .strip_prefix(dir.path())
                    .unwrap_or(&f.path)
                    .to_string_lossy()
                    .replace('\\', "/")
            })
            .collect();
        assert!(names.contains(&"packages/app/.config/eslint.config.js".to_string()));
        assert!(
            !names.contains(&"packages/other/.config/eslint.config.js".to_string()),
            "unscoped workspace must not get .config traversed"
        );
    }
}