standarbuild-detect 0.3.0

Detect project kind (Rust, Node, Bun, Deno, Python, Lua, C/C++) AND workspace kind (Cargo, Npm/Pnpm/Yarn/Bun, Deno, Go, Lerna, Nx, Turborepo, Mira) in polyglot monorepos
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
//! Built-in detectors for the project AND workspace kinds the library knows
//! about. Each type is `pub` and `Default`-constructible so callers can pick
//! and choose, tweak the registry, or use [`register_all`] to install the
//! whole lot.

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

use crate::detector::{Detector, DetectorHit, DetectorRegistry};
use crate::kind::KindId;
use crate::workspace::WorkspaceKindId;

// ---- Helpers --------------------------------------------------------------

fn signal_if_exists(dir: &Path, name: &str, out: &mut Vec<String>) -> bool {
    if dir.join(name).exists() {
        out.push(name.to_string());
        true
    } else {
        false
    }
}

fn any_exists(dir: &Path, names: &[&str], out: &mut Vec<String>) -> bool {
    let mut found = false;
    for n in names {
        if signal_if_exists(dir, n, out) {
            found = true;
        }
    }
    found
}

fn has_extension(dir: &Path, ext: &str) -> bool {
    let Ok(read) = std::fs::read_dir(dir) else {
        return false;
    };
    for entry in read.flatten() {
        if entry.path().extension().map(|e| e == ext).unwrap_or(false) {
            return true;
        }
    }
    false
}

/// Resolve a Cargo/Node/glob-ish member pattern into concrete child
/// directories. Handles the two cases that cover ~all real manifests:
///   - exact path: `"crates/foo"` → `[root/crates/foo]` if it exists
///   - one-star tail: `"packages/*"` → every child dir of `root/packages/`
/// Anything more exotic is silently skipped (we doc the limitation).
fn expand_member(root: &Path, pattern: &str) -> Vec<PathBuf> {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return Vec::new();
    }
    if !pattern.contains('*') {
        let p = root.join(pattern);
        return if p.is_dir() { vec![p] } else { Vec::new() };
    }
    if let Some(prefix) = pattern.strip_suffix("/*") {
        let parent = if prefix.is_empty() {
            root.to_path_buf()
        } else {
            root.join(prefix)
        };
        let Ok(entries) = std::fs::read_dir(&parent) else {
            return Vec::new();
        };
        let mut out: Vec<PathBuf> = entries
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.is_dir())
            .collect();
        out.sort();
        return out;
    }
    Vec::new()
}

fn read_toml(path: &Path) -> Option<toml::Value> {
    let text = std::fs::read_to_string(path).ok()?;
    toml::from_str(&text).ok()
}

fn read_json(path: &Path) -> Option<serde_json::Value> {
    let text = std::fs::read_to_string(path).ok()?;
    // Tolerate JSON-with-comments for deno.jsonc / tsconfig-style files
    // by stripping trivial `// ...` line comments before parsing.
    let cleaned: String = text
        .lines()
        .map(|l| {
            if let Some(idx) = l.find("//") {
                &l[..idx]
            } else {
                l
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    serde_json::from_str(&cleaned).ok()
}

/// Minimal YAML extractor for `packages: [...]` / `packages:\n  - ...`. Good
/// enough for pnpm-workspace.yaml in practice; bails on nested anchors etc.
fn extract_yaml_packages(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut in_block = false;
    for raw in text.lines() {
        let line = raw.trim_end_matches('\r');
        let trimmed = line.trim_start();
        if !in_block {
            if let Some(rest) = trimmed.strip_prefix("packages:") {
                let rest = rest.trim();
                if rest.starts_with('[') {
                    let inner = rest.trim_start_matches('[').trim_end_matches(']');
                    for item in inner.split(',') {
                        let s = item.trim().trim_matches(|c| c == '"' || c == '\'');
                        if !s.is_empty() {
                            out.push(s.to_string());
                        }
                    }
                    return out;
                }
                in_block = true;
            }
            continue;
        }
        // In a block list: continue collecting `  - "pattern"` entries.
        if trimmed.starts_with("- ") {
            let s = trimmed[2..].trim().trim_matches(|c| c == '"' || c == '\'');
            if !s.is_empty() {
                out.push(s.to_string());
            }
            continue;
        }
        // Empty line stays in block. Non-list key at the same indent ends block.
        if trimmed.is_empty() {
            continue;
        }
        if !line.starts_with(' ') && !line.starts_with('\t') {
            break;
        }
        // Indented non-list content — probably a malformed list or nested map.
        // Bail out to keep the parser simple.
        break;
    }
    out
}

// ---- Cargo (project + workspace, unified) --------------------------------

/// `Cargo.toml` detector. Emits the appropriate facet(s) depending on
/// whether the manifest contains `[package]`, `[workspace]`, or both.
#[derive(Default)]
pub struct CargoDetector;

impl Detector for CargoDetector {
    fn name(&self) -> &str { "cargo" }
    fn priority(&self) -> i32 { 100 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::RUST) }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Cargo) }

    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let manifest = dir.join("Cargo.toml");
        if !manifest.is_file() {
            return None;
        }
        let signals = vec!["Cargo.toml".to_string()];
        let parsed = read_toml(&manifest);

        let has_package = parsed
            .as_ref()
            .and_then(|v| v.get("package"))
            .is_some();
        let workspace_table = parsed.as_ref().and_then(|v| v.get("workspace"));
        let has_workspace = workspace_table.is_some();

        let members: Vec<PathBuf> = workspace_table
            .and_then(|w| w.get("members"))
            .and_then(|m| m.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .flat_map(|p| expand_member(dir, p))
                    .collect()
            })
            .unwrap_or_default();

        match (has_package, has_workspace) {
            // No parse → still emit a project hit (legacy / unparseable Cargo.toml).
            (_, false) if parsed.is_none() => Some(DetectorHit::Project {
                kind: KindId::RUST,
                signals,
            }),
            (true, false) => Some(DetectorHit::Project {
                kind: KindId::RUST,
                signals,
            }),
            (false, true) => Some(DetectorHit::Workspace {
                kind: WorkspaceKindId::Cargo,
                members,
                signals,
            }),
            (true, true) => Some(DetectorHit::Both {
                project_kind: KindId::RUST,
                workspace_kind: WorkspaceKindId::Cargo,
                members,
                signals,
            }),
            // [false, false] = neither [package] nor [workspace]. Rare but
            // possible (e.g. a Cargo.toml with only [profile] for build
            // profiles in a sub-dir). Treat as project for back-compat.
            (false, false) => Some(DetectorHit::Project {
                kind: KindId::RUST,
                signals,
            }),
        }
    }
}

// ---- Node project (Bun > Deno > Node priority) ---------------------------

#[derive(Default)]
pub struct BunDetector;

impl Detector for BunDetector {
    fn name(&self) -> &str { "bun" }
    fn priority(&self) -> i32 { 80 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::BUN) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if any_exists(dir, &["bun.lock", "bun.lockb", "bunfig.toml"], &mut signals) {
            Some(DetectorHit::Project {
                kind: KindId::BUN,
                signals,
            })
        } else {
            None
        }
    }
}

#[derive(Default)]
pub struct DenoDetector;

impl Detector for DenoDetector {
    fn name(&self) -> &str { "deno" }
    fn priority(&self) -> i32 { 70 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::DENO) }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Deno) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if !any_exists(dir, &["deno.json", "deno.jsonc", "deno.lock"], &mut signals) {
            return None;
        }

        // Workspace facet: `"workspace": ["./pkg1", "./pkg2"]` (Deno >= 1.45)
        let manifest = if dir.join("deno.json").is_file() {
            dir.join("deno.json")
        } else {
            dir.join("deno.jsonc")
        };
        let members: Vec<PathBuf> = read_json(&manifest)
            .as_ref()
            .and_then(|v| v.get("workspace"))
            .and_then(|w| w.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .flat_map(|p| expand_member(dir, p.trim_start_matches("./")))
                    .collect()
            })
            .unwrap_or_default();

        if !members.is_empty() {
            return Some(DetectorHit::Both {
                project_kind: KindId::DENO,
                workspace_kind: WorkspaceKindId::Deno,
                members,
                signals,
            });
        }
        Some(DetectorHit::Project {
            kind: KindId::DENO,
            signals,
        })
    }
}

#[derive(Default)]
pub struct NodeDetector;

impl Detector for NodeDetector {
    fn name(&self) -> &str { "node" }
    fn priority(&self) -> i32 { 50 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::NODE) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if signal_if_exists(dir, "package.json", &mut signals) {
            Some(DetectorHit::Project {
                kind: KindId::NODE,
                signals,
            })
        } else {
            None
        }
    }
}

// ---- Python ---------------------------------------------------------------

#[derive(Default)]
pub struct PythonDetector;

impl Detector for PythonDetector {
    fn name(&self) -> &str { "python" }
    fn priority(&self) -> i32 { 40 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::PYTHON) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if any_exists(
            dir,
            &["pyproject.toml", "requirements.txt", "setup.py", "setup.cfg"],
            &mut signals,
        ) {
            Some(DetectorHit::Project {
                kind: KindId::PYTHON,
                signals,
            })
        } else {
            None
        }
    }
}

// ---- Lua ------------------------------------------------------------------

#[derive(Default)]
pub struct LuaDetector;

impl Detector for LuaDetector {
    fn name(&self) -> &str { "lua" }
    fn priority(&self) -> i32 { 30 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::LUA) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        let luarc = signal_if_exists(dir, ".luarc.json", &mut signals);
        let rockspec = has_extension(dir, "rockspec");
        if rockspec {
            signals.push("*.rockspec".to_string());
        }
        if luarc || rockspec {
            Some(DetectorHit::Project {
                kind: KindId::LUA,
                signals,
            })
        } else {
            None
        }
    }
}

// ---- C / C++ --------------------------------------------------------------

#[derive(Default)]
pub struct CppDetector;

impl Detector for CppDetector {
    fn name(&self) -> &str { "cpp" }
    fn priority(&self) -> i32 { 20 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::CPP) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if !signal_if_exists(dir, "CMakeLists.txt", &mut signals) {
            return None;
        }
        if has_extension(dir, "cpp") || has_extension(dir, "cc") || has_extension(dir, "cxx") {
            Some(DetectorHit::Project {
                kind: KindId::CPP,
                signals,
            })
        } else {
            None
        }
    }
}

#[derive(Default)]
pub struct CDetector;

impl Detector for CDetector {
    fn name(&self) -> &str { "c" }
    fn priority(&self) -> i32 { 10 }
    fn declared_project_kind(&self) -> Option<KindId> { Some(KindId::C) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let mut signals = Vec::new();
        if !signal_if_exists(dir, "CMakeLists.txt", &mut signals) {
            return None;
        }
        // Only match as pure C when there are no C++ sources around — otherwise
        // CppDetector should win.
        if has_extension(dir, "cpp") || has_extension(dir, "cc") || has_extension(dir, "cxx") {
            return None;
        }
        if has_extension(dir, "c") {
            Some(DetectorHit::Project {
                kind: KindId::C,
                signals,
            })
        } else {
            None
        }
    }
}

// ---- Node-family workspace detectors --------------------------------------

/// Read `package.json` and return the `"workspaces"` field as an array of
/// patterns. Handles both array form and the `{ packages: [...] }` object
/// form Yarn uses.
fn read_pkg_workspaces(dir: &Path) -> Option<Vec<String>> {
    let v = read_json(&dir.join("package.json"))?;
    let ws = v.get("workspaces")?;
    if let Some(arr) = ws.as_array() {
        return Some(
            arr.iter()
                .filter_map(|x| x.as_str().map(|s| s.to_string()))
                .collect(),
        );
    }
    ws.get("packages")
        .and_then(|p| p.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|x| x.as_str().map(|s| s.to_string()))
                .collect()
        })
}

fn has_any(dir: &Path, names: &[&str]) -> bool {
    names.iter().any(|n| dir.join(n).exists())
}

/// `bun.lockb` / `bun.lock` + `package.json` `workspaces`. Highest priority
/// among node-family workspace detectors.
#[derive(Default)]
pub struct BunWorkspaceDetector;

impl Detector for BunWorkspaceDetector {
    fn name(&self) -> &str { "bun-workspace" }
    fn priority(&self) -> i32 { 80 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Bun) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        if !has_any(dir, &["bun.lockb", "bun.lock"]) {
            return None;
        }
        let patterns = read_pkg_workspaces(dir)?;
        if patterns.is_empty() {
            return None;
        }
        let mut signals = Vec::new();
        let _ = any_exists(dir, &["bun.lockb", "bun.lock", "package.json"], &mut signals);
        let members = patterns
            .iter()
            .flat_map(|p| expand_member(dir, p))
            .collect();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Bun,
            members,
            signals,
        })
    }
}

/// `pnpm-workspace.yaml` (with or without `package.json`).
#[derive(Default)]
pub struct PnpmWorkspaceDetector;

impl Detector for PnpmWorkspaceDetector {
    fn name(&self) -> &str { "pnpm-workspace" }
    fn priority(&self) -> i32 { 70 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Pnpm) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let manifest = dir.join("pnpm-workspace.yaml");
        if !manifest.is_file() {
            return None;
        }
        let text = std::fs::read_to_string(&manifest).ok().unwrap_or_default();
        let patterns = extract_yaml_packages(&text);
        let members = patterns
            .iter()
            .flat_map(|p| expand_member(dir, p))
            .collect();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Pnpm,
            members,
            signals: vec!["pnpm-workspace.yaml".to_string()],
        })
    }
}

/// `.yarnrc.yml` or `.yarn/` directory + `package.json` workspaces.
#[derive(Default)]
pub struct YarnWorkspaceDetector;

impl Detector for YarnWorkspaceDetector {
    fn name(&self) -> &str { "yarn-workspace" }
    fn priority(&self) -> i32 { 60 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Yarn) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        // Skip if Bun markers are present — Bun owns this workspace.
        if has_any(dir, &["bun.lockb", "bun.lock"]) {
            return None;
        }
        let yarnrc = dir.join(".yarnrc.yml").is_file();
        let yarn_dir = dir.join(".yarn").is_dir();
        if !yarnrc && !yarn_dir {
            return None;
        }
        let patterns = read_pkg_workspaces(dir)?;
        if patterns.is_empty() {
            return None;
        }
        let mut signals = Vec::new();
        if yarnrc {
            signals.push(".yarnrc.yml".to_string());
        }
        if yarn_dir {
            signals.push(".yarn/".to_string());
        }
        signals.push("package.json".to_string());
        let members = patterns
            .iter()
            .flat_map(|p| expand_member(dir, p))
            .collect();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Yarn,
            members,
            signals,
        })
    }
}

/// `package.json` `workspaces` with no Bun/Yarn/Pnpm markers around it.
#[derive(Default)]
pub struct NpmWorkspaceDetector;

impl Detector for NpmWorkspaceDetector {
    fn name(&self) -> &str { "npm-workspace" }
    fn priority(&self) -> i32 { 50 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Npm) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        // Defer to bun/yarn/pnpm-specific detectors.
        if has_any(
            dir,
            &[
                "bun.lockb",
                "bun.lock",
                ".yarnrc.yml",
                ".yarn",
                "pnpm-workspace.yaml",
            ],
        ) {
            return None;
        }
        let patterns = read_pkg_workspaces(dir)?;
        if patterns.is_empty() {
            return None;
        }
        let members = patterns
            .iter()
            .flat_map(|p| expand_member(dir, p))
            .collect();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Npm,
            members,
            signals: vec!["package.json".to_string()],
        })
    }
}

// ---- Go workspace ---------------------------------------------------------

/// `go.work` — Go 1.18+ workspace.
#[derive(Default)]
pub struct GoWorkspaceDetector;

impl Detector for GoWorkspaceDetector {
    fn name(&self) -> &str { "go-workspace" }
    fn priority(&self) -> i32 { 50 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Go) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let manifest = dir.join("go.work");
        if !manifest.is_file() {
            return None;
        }
        let text = std::fs::read_to_string(&manifest).ok().unwrap_or_default();
        let members = parse_go_work_uses(&text)
            .into_iter()
            .flat_map(|p| {
                let stripped = p.trim_start_matches("./").to_string();
                expand_member(dir, &stripped)
            })
            .collect();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Go,
            members,
            signals: vec!["go.work".to_string()],
        })
    }
}

fn parse_go_work_uses(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut in_block = false;
    for raw in text.lines() {
        let line = raw.split("//").next().unwrap_or("").trim();
        if line.is_empty() {
            continue;
        }
        if in_block {
            if line == ")" {
                in_block = false;
                continue;
            }
            let s = line.trim_matches(|c| c == '"' || c == '\'').to_string();
            if !s.is_empty() {
                out.push(s);
            }
            continue;
        }
        if let Some(rest) = line.strip_prefix("use ") {
            let rest = rest.trim();
            if rest == "(" {
                in_block = true;
                continue;
            }
            // single-line: `use ./pkg`
            let s = rest
                .trim_start_matches('(')
                .trim_end_matches(')')
                .trim()
                .trim_matches(|c| c == '"' || c == '\'')
                .to_string();
            if !s.is_empty() {
                out.push(s);
            }
        }
    }
    out
}

// ---- Lerna / Nx / Turborepo (marker-file-only) ---------------------------

#[derive(Default)]
pub struct LernaWorkspaceDetector;

impl Detector for LernaWorkspaceDetector {
    fn name(&self) -> &str { "lerna-workspace" }
    fn priority(&self) -> i32 { 40 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Lerna) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        if !dir.join("lerna.json").is_file() {
            return None;
        }
        let members: Vec<PathBuf> = read_json(&dir.join("lerna.json"))
            .as_ref()
            .and_then(|v| v.get("packages"))
            .and_then(|p| p.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|x| x.as_str())
                    .flat_map(|p| expand_member(dir, p))
                    .collect()
            })
            .unwrap_or_default();
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Lerna,
            members,
            signals: vec!["lerna.json".to_string()],
        })
    }
}

#[derive(Default)]
pub struct NxWorkspaceDetector;

impl Detector for NxWorkspaceDetector {
    fn name(&self) -> &str { "nx-workspace" }
    fn priority(&self) -> i32 { 40 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Nx) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        if !dir.join("nx.json").is_file() {
            return None;
        }
        // Nx member enumeration is non-trivial (per-project `project.json`
        // scattered across the tree). Leave empty for v0.3; consumers that
        // need it can post-process by scanning for `project.json` files.
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Nx,
            members: Vec::new(),
            signals: vec!["nx.json".to_string()],
        })
    }
}

#[derive(Default)]
pub struct TurborepoWorkspaceDetector;

impl Detector for TurborepoWorkspaceDetector {
    fn name(&self) -> &str { "turborepo-workspace" }
    fn priority(&self) -> i32 { 40 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Turborepo) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        if !dir.join("turbo.json").is_file() {
            return None;
        }
        // Turborepo uses package.json workspaces under the hood — the
        // Bun/Pnpm/Yarn/Npm detector already enumerates members at the same
        // root. We just stamp the Turborepo facet here.
        Some(DetectorHit::Workspace {
            kind: WorkspaceKindId::Turborepo,
            members: Vec::new(),
            signals: vec!["turbo.json".to_string()],
        })
    }
}

// ---- Mira -----------------------------------------------------------------

/// `.sxb` (Standar*X B*uild) file at the root.
#[derive(Default)]
pub struct MiraWorkspaceDetector;

impl Detector for MiraWorkspaceDetector {
    fn name(&self) -> &str { "mira-workspace" }
    fn priority(&self) -> i32 { 40 }
    fn declared_workspace_kind(&self) -> Option<WorkspaceKindId> { Some(WorkspaceKindId::Mira) }
    fn detect(&self, dir: &Path) -> Option<DetectorHit> {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return None;
        };
        let mut signal = None;
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().map(|e| e == "sxb").unwrap_or(false) {
                signal = Some(
                    path.file_name()
                        .and_then(|s| s.to_str())
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| "*.sxb".to_string()),
                );
                break;
            }
        }
        signal.map(|s| DetectorHit::Workspace {
            kind: WorkspaceKindId::Mira,
            members: Vec::new(),
            signals: vec![s],
        })
    }
}

// ---- Registration helper -------------------------------------------------

/// Register every built-in detector into `registry`. Idempotent in the
/// sense that re-running it appends another copy (consistent with `add`'s
/// semantics); callers wanting a clean slate should start from
/// [`DetectorRegistry::empty`].
pub fn register_all(registry: &mut DetectorRegistry) {
    // Project facet
    registry
        .add(CargoDetector)
        .add(BunDetector)
        .add(DenoDetector)
        .add(NodeDetector)
        .add(PythonDetector)
        .add(LuaDetector)
        .add(CppDetector)
        .add(CDetector);
    // Workspace facet
    registry
        .add(BunWorkspaceDetector)
        .add(PnpmWorkspaceDetector)
        .add(YarnWorkspaceDetector)
        .add(NpmWorkspaceDetector)
        .add(GoWorkspaceDetector)
        .add(LernaWorkspaceDetector)
        .add(NxWorkspaceDetector)
        .add(TurborepoWorkspaceDetector)
        .add(MiraWorkspaceDetector);
}