loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
//! Stack detection module for auto-configuring loctree based on project files.
//!
//! Detects project type by checking for common configuration files:
//! - Cargo.toml → Rust project
//! - tsconfig.json / package.json → TypeScript/JavaScript
//! - pyproject.toml / setup.py → Python
//! - src-tauri/ → Tauri preset
//! - vite.config.* → Vite project

use std::collections::HashSet;
use std::path::Path;

/// Result of stack detection
#[derive(Clone, Debug, Default)]
pub struct DetectedStack {
    /// File extensions to scan
    pub extensions: HashSet<String>,
    /// Patterns to ignore
    pub ignores: Vec<String>,
    /// Detected preset name (e.g., "tauri")
    pub preset_name: Option<String>,
    /// Human-readable description of detected stack
    pub description: String,
    /// Whether this appears to be a library/framework project (not an app)
    pub is_library: bool,
    /// Additional Python import roots (e.g., "Lib" for CPython)
    pub py_roots: Vec<std::path::PathBuf>,
}

impl DetectedStack {
    /// Check if anything was detected
    pub fn is_empty(&self) -> bool {
        self.extensions.is_empty() && self.preset_name.is_none()
    }
}

/// Detect additional Python package roots beyond the standard locations.
///
/// Heuristics:
/// 1. CPython/PyPy layout: `Lib/` directory alongside `Python/`, `Modules/`
/// 2. Directories with `__init__.py` that aren't standard names (src, tests, etc.)
/// 3. Hints from pyproject.toml `[tool.setuptools.packages]` or similar
fn detect_python_roots(root: &Path) -> Vec<std::path::PathBuf> {
    let mut roots = Vec::new();

    // CPython/PyPy detection: Lib/ alongside Python/ or Modules/
    let lib_dir = root.join("Lib");
    if lib_dir.is_dir() {
        let has_python_dir = root.join("Python").is_dir();
        let has_modules_dir = root.join("Modules").is_dir();
        let has_include_dir = root.join("Include").is_dir();

        // CPython has Lib + (Python or Modules or Include)
        if has_python_dir || has_modules_dir || has_include_dir {
            roots.push(std::path::PathBuf::from("Lib"));
        }
    }

    // Check pyproject.toml for explicit package locations
    let pyproject_path = root.join("pyproject.toml");
    if pyproject_path.exists()
        && let Ok(content) = std::fs::read_to_string(&pyproject_path)
    {
        // Look for [tool.setuptools.packages] or package-dir patterns
        // Simple heuristic: find lines like `packages = ["something"]`
        for line in content.lines() {
            let trimmed = line.trim();
            // Match patterns like: packages = ["Lib"] or package-dir = {src = "Lib"}
            if (trimmed.starts_with("packages") || trimmed.starts_with("package-dir"))
                && trimmed.contains('=')
            {
                // Extract directory names from the value
                if let Some(value_part) = trimmed.split('=').nth(1) {
                    for segment in value_part.split(['"', '\'', ',', '[', ']', '{', '}']) {
                        let dir_name = segment.trim();
                        if !dir_name.is_empty()
                            && !dir_name.contains('=')
                            && !dir_name.contains(':')
                            && dir_name != "src"
                            && dir_name != "."
                        {
                            let dir_path = root.join(dir_name);
                            if dir_path.is_dir() && !roots.contains(&dir_name.into()) {
                                roots.push(std::path::PathBuf::from(dir_name));
                            }
                        }
                    }
                }
            }
        }
    }

    roots
}

/// Detect project stack from root directory
pub fn detect_stack(root: &Path) -> DetectedStack {
    let mut result = DetectedStack::default();
    let mut detected_parts: Vec<&str> = Vec::new();

    // Check for Cargo.toml -> Rust project
    // Also check direct subdirectories for monorepo-style layouts (e.g., codex-rs/Cargo.toml)
    let has_cargo_toml = root.join("Cargo.toml").exists() || has_cargo_in_subdir(root);
    if has_cargo_toml {
        result.extensions.insert("rs".to_string());
        result.ignores.push("target".to_string());
        detected_parts.push("Rust");
    }

    // Check for Dart/Flutter (pubspec.yaml)
    if root.join("pubspec.yaml").exists() {
        result.extensions.insert("dart".to_string());
        result.ignores.push(".dart_tool".to_string());
        result.ignores.push("build".to_string());
        result.ignores.push(".packages".to_string());
        detected_parts.push("Dart/Flutter");
    }

    // Check for Go projects (go.mod or .go files)
    if root.join("go.mod").exists()
        || root
            .read_dir()
            .ok()
            .map(|entries| {
                entries.flatten().any(|entry| {
                    entry
                        .path()
                        .extension()
                        .is_some_and(|ext| ext.eq_ignore_ascii_case("go"))
                })
            })
            .unwrap_or(false)
    {
        result.extensions.insert("go".to_string());
        result.ignores.push("vendor".to_string());
        detected_parts.push("Go");
    }

    // Check for src-tauri/ -> Tauri preset (must check before generic TS)
    if root.join("src-tauri").exists() {
        result.preset_name = Some("tauri".to_string());
        result.extensions.insert("rs".to_string());
        result.extensions.insert("ts".to_string());
        result.extensions.insert("tsx".to_string());
        result.extensions.insert("js".to_string());
        result.extensions.insert("jsx".to_string());
        result.extensions.insert("css".to_string());
        result.ignores.push("target".to_string());
        result.ignores.push("node_modules".to_string());
        result.ignores.push("dist".to_string());
        detected_parts.push("Tauri");
    }

    // Check for package.json + tsconfig.json -> TypeScript
    let has_tsconfig = root.join("tsconfig.json").exists();
    let has_package_json = root.join("package.json").exists();

    if has_tsconfig || has_package_json {
        result.extensions.insert("ts".to_string());
        result.extensions.insert("tsx".to_string());
        result.extensions.insert("js".to_string());
        result.extensions.insert("jsx".to_string());
        result.extensions.insert("mjs".to_string());
        result.extensions.insert("cjs".to_string());

        if !result.ignores.contains(&"node_modules".to_string()) {
            result.ignores.push("node_modules".to_string());
        }
        if !result.ignores.contains(&"dist".to_string()) {
            result.ignores.push("dist".to_string());
        }

        if has_tsconfig && !detected_parts.contains(&"Tauri") {
            detected_parts.push("TypeScript");
        } else if has_package_json && !detected_parts.contains(&"Tauri") {
            detected_parts.push("JavaScript");
        }

        // Check if this is a library/framework project
        if is_npm_library(root) {
            result.is_library = true;
            if !detected_parts.contains(&"Library") {
                detected_parts.push("Library");
            }
        }
    }

    // Check for vite.config.* -> Vite project (add build to ignores)
    let vite_extensions = ["js", "ts", "mjs"];
    for ext in vite_extensions {
        if root.join(format!("vite.config.{}", ext)).exists() {
            if !result.ignores.contains(&"dist".to_string()) {
                result.ignores.push("dist".to_string());
            }
            result.ignores.push("build".to_string());
            if !detected_parts.contains(&"Vite") {
                detected_parts.push("Vite");
            }
            break;
        }
    }

    // Check for svelte.config.* -> SvelteKit project
    let svelte_exists =
        root.join("svelte.config.js").exists() || root.join("svelte.config.ts").exists();
    // Also check apps/* and packages/* for monorepos
    let mut svelte_in_subdir = false;
    for subdir in ["apps", "packages"] {
        let dir = root.join(subdir);
        if dir.is_dir()
            && let Ok(entries) = std::fs::read_dir(&dir)
        {
            for e in entries.flatten() {
                let path = e.path();
                if path.is_dir()
                    && (path.join("svelte.config.js").exists()
                        || path.join("svelte.config.ts").exists())
                {
                    svelte_in_subdir = true;
                    break;
                }
            }
        }
        if svelte_in_subdir {
            break;
        }
    }
    if svelte_exists || svelte_in_subdir {
        result.extensions.insert("svelte".to_string());
        result.ignores.push(".svelte-kit".to_string());
        if !detected_parts.contains(&"SvelteKit") {
            detected_parts.push("SvelteKit");
        }
    }

    // Check for Vue projects (vue.config.*, vite.config.* with Vue, or .vue files in src/)
    let vue_config_exists =
        root.join("vue.config.js").exists() || root.join("vue.config.ts").exists();
    let has_vue_files = root.join("src").exists()
        && std::fs::read_dir(root.join("src"))
            .map(|entries| {
                entries.flatten().any(|e| {
                    e.path()
                        .extension()
                        .is_some_and(|ext| ext.eq_ignore_ascii_case("vue"))
                })
            })
            .unwrap_or(false);
    // Also check packages/* for monorepos (common in Vue ecosystem)
    let mut vue_in_subdir = false;
    for subdir in ["packages", "packages-private", "apps"] {
        let dir = root.join(subdir);
        if dir.is_dir()
            && let Ok(entries) = std::fs::read_dir(&dir)
        {
            for e in entries.flatten() {
                let path = e.path();
                if path.is_dir() {
                    // Check for .vue files in this package's src/
                    let pkg_src = path.join("src");
                    if pkg_src.is_dir()
                        && std::fs::read_dir(&pkg_src)
                            .map(|entries| {
                                entries.flatten().any(|e| {
                                    e.path()
                                        .extension()
                                        .is_some_and(|ext| ext.eq_ignore_ascii_case("vue"))
                                })
                            })
                            .unwrap_or(false)
                    {
                        vue_in_subdir = true;
                        break;
                    }
                }
            }
        }
        if vue_in_subdir {
            break;
        }
    }
    if vue_config_exists || has_vue_files || vue_in_subdir {
        result.extensions.insert("vue".to_string());
        if !detected_parts.contains(&"Vue") {
            detected_parts.push("Vue");
        }
    }

    // Check for pyproject.toml / setup.py -> Python
    if root.join("pyproject.toml").exists() || root.join("setup.py").exists() {
        result.extensions.insert("py".to_string());
        result.ignores.push(".venv".to_string());
        result.ignores.push("venv".to_string());
        result.ignores.push("__pycache__".to_string());
        result.ignores.push(".pytest_cache".to_string());
        result.ignores.push(".mypy_cache".to_string());
        result.ignores.push(".ruff_cache".to_string());
        result.ignores.push("*.egg-info".to_string());
        result.ignores.push(".eggs".to_string());
        result.ignores.push("dist".to_string());
        result.ignores.push("build".to_string());
        result.ignores.push(".tox".to_string());
        // Common ML/data caches that often contain symlinks
        result.ignores.push(".fastembed_cache".to_string());
        result.ignores.push(".cache".to_string());
        result.ignores.push("logs".to_string());
        result.ignores.push("packaging".to_string());
        // uv specific
        result.ignores.push(".uv".to_string());
        detected_parts.push("Python");

        // Auto-detect additional Python package roots
        result.py_roots = detect_python_roots(root);
    }

    // Check for CSS files in common locations
    if root.join("src").exists() || root.join("styles").exists() {
        // Only add CSS if we have a JS/TS project
        if result.extensions.contains("ts") || result.extensions.contains("js") {
            result.extensions.insert("css".to_string());
        }
    }

    // Common dev/test directories to ignore (reduces noise in dead export reports)
    if !result.ignores.is_empty() {
        // These often contain test fixtures, mocks, or platform-specific code
        for dir in &[
            "e2e",
            "scripts",
            "mobile",
            "__mocks__",
            "__fixtures__",
            "fixtures",
        ] {
            if !result.ignores.contains(&dir.to_string()) {
                result.ignores.push(dir.to_string());
            }
        }
    }

    // Build description
    if !detected_parts.is_empty() {
        result.description = format!("Detected: {}", detected_parts.join(" + "));
    }

    result
}

/// Check if any direct subdirectory contains a Cargo.toml (monorepo detection)
fn has_cargo_in_subdir(root: &Path) -> bool {
    let Ok(entries) = std::fs::read_dir(root) else {
        return false;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            // Skip common non-Rust directories
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with('.')
                || name_str == "node_modules"
                || name_str == "dist"
                || name_str == "build"
            {
                continue;
            }

            if path.join("Cargo.toml").exists() {
                return true;
            }
        }
    }
    false
}

/// Check if a package.json indicates this is a library/framework (not an app)
///
/// Library indicators:
/// - Has "exports" field (npm package exports map)
/// - Has "main", "module", or "types" field (package entry points)
/// - Has "packages/" directory (monorepo with publishable packages)
/// - Lacks typical app indicators (index.html, vite.config.*, etc.)
fn is_npm_library(root: &Path) -> bool {
    let package_json_path = root.join("package.json");
    if !package_json_path.exists() {
        return false;
    }

    // Read and parse package.json
    let Ok(content) = std::fs::read_to_string(&package_json_path) else {
        return false;
    };

    let Ok(parsed): Result<serde_json::Value, _> = serde_json::from_str(&content) else {
        return false;
    };

    // Strong library indicators
    if parsed.get("exports").is_some() {
        // Modern npm package with exports field
        return true;
    }

    // Has package entry points (main, module, types)
    let has_main = parsed.get("main").is_some();
    let has_module = parsed.get("module").is_some();
    let has_types = parsed.get("types").is_some() || parsed.get("typings").is_some();

    if has_main || has_module || has_types {
        // Check if it's NOT an app by looking for app-specific files
        let has_index_html = root.join("index.html").exists();
        let has_public_html = root.join("public/index.html").exists();

        if !has_index_html && !has_public_html {
            // Likely a library - has entry points but no HTML
            return true;
        }
    }

    // Check for monorepo packages/ directory
    let packages_dir = root.join("packages");
    if packages_dir.is_dir()
        && std::fs::read_dir(&packages_dir)
            .map(|entries| {
                entries
                    .flatten()
                    .filter(|e| e.path().is_dir())
                    .any(|e| e.path().join("package.json").exists())
            })
            .unwrap_or(false)
    {
        return true;
    }

    false
}

/// Apply detected stack to parsed args if no explicit config provided
pub fn apply_detected_stack(
    root: &Path,
    extensions: &mut Option<HashSet<String>>,
    ignore_patterns: &mut Vec<String>,
    tauri_preset: &mut bool,
    library_mode: &mut bool,
    py_roots: &mut Vec<std::path::PathBuf>,
    verbose: bool,
) {
    // Skip if user already specified extensions
    if extensions.is_some() {
        return;
    }

    // Skip if tauri preset is already set
    if *tauri_preset {
        return;
    }

    let detected = detect_stack(root);

    if detected.is_empty() {
        return;
    }

    if verbose && !detected.description.is_empty() {
        eprintln!("[loctree][detect] {}", detected.description);
    }

    // Apply detected extensions
    if !detected.extensions.is_empty() {
        *extensions = Some(detected.extensions);
    }

    // Apply ignores only if user didn't specify any
    if ignore_patterns.is_empty() {
        *ignore_patterns = detected.ignores;
    }

    // Apply preset
    if let Some(preset) = detected.preset_name
        && preset == "tauri"
    {
        *tauri_preset = true;
    }

    // Apply library mode if detected and not already set by user
    if detected.is_library && !*library_mode {
        *library_mode = true;
        if verbose {
            eprintln!(
                "[loctree][detect] Detected library/framework project - enabling library mode"
            );
        }
    }

    // Apply detected Python roots if user didn't specify any
    if py_roots.is_empty() && !detected.py_roots.is_empty() {
        *py_roots = detected.py_roots;
        if verbose {
            let roots_str: Vec<_> = py_roots.iter().map(|p| p.display().to_string()).collect();
            eprintln!(
                "[loctree][detect] Auto-detected Python roots: {}",
                roots_str.join(", ")
            );
        }
    }
}

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

    #[test]
    fn test_detect_rust_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"test\"")
            .expect("write Cargo.toml");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("rs"));
        assert!(detected.ignores.contains(&"target".to_string()));
    }

    #[test]
    fn test_detect_typescript_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("tsconfig.json"), "{}").expect("write tsconfig.json");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("ts"));
        assert!(detected.extensions.contains("tsx"));
        assert!(detected.ignores.contains(&"node_modules".to_string()));
    }

    #[test]
    fn test_detect_tauri_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::create_dir(tmp.path().join("src-tauri")).expect("create src-tauri dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"test\"")
            .expect("write Cargo.toml");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write package.json");

        let detected = detect_stack(tmp.path());

        assert_eq!(detected.preset_name, Some("tauri".to_string()));
        assert!(detected.extensions.contains("rs"));
        assert!(detected.extensions.contains("ts"));
        assert!(detected.extensions.contains("tsx"));
    }

    #[test]
    fn test_detect_python_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("pyproject.toml"),
            "[project]\nname = \"test\"",
        )
        .expect("write pyproject.toml");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("py"));
        assert!(detected.ignores.contains(&".venv".to_string()));
        assert!(detected.ignores.contains(&"__pycache__".to_string()));
    }

    #[test]
    fn test_detect_empty_project() {
        let tmp = TempDir::new().expect("create temp dir");

        let detected = detect_stack(tmp.path());

        assert!(detected.is_empty());
    }

    #[test]
    fn test_detect_mixed_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "").expect("write Cargo.toml");
        std::fs::write(tmp.path().join("pyproject.toml"), "").expect("write pyproject.toml");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("rs"));
        assert!(detected.extensions.contains("py"));
    }

    #[test]
    fn test_detect_vite_project() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("vite.config.ts"), "export default {}").expect("write");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write");

        let detected = detect_stack(tmp.path());

        assert!(detected.ignores.contains(&"build".to_string()));
        assert!(detected.description.contains("Vite"));
    }

    #[test]
    fn test_detect_javascript_only() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write package.json");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("js"));
        assert!(detected.description.contains("JavaScript"));
    }

    #[test]
    fn test_detect_with_src_adds_css() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write package.json");
        std::fs::create_dir(tmp.path().join("src")).expect("create src");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("css"));
    }

    #[test]
    fn test_apply_detected_stack_skips_if_extensions_set() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "").expect("write");

        let mut extensions = Some(HashSet::from(["py".to_string()]));
        let mut ignores = Vec::new();
        let mut tauri = false;
        let mut library_mode = false;

        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            false,
        );

        // Should not have changed - user specified extensions
        assert!(extensions.as_ref().unwrap().contains("py"));
        assert!(!extensions.as_ref().unwrap().contains("rs"));
    }

    #[test]
    fn test_apply_detected_stack_skips_if_tauri_preset() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "").expect("write");

        let mut extensions: Option<HashSet<String>> = None;
        let mut ignores = Vec::new();
        let mut tauri = true; // Already set
        let mut library_mode = false;

        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            false,
        );

        // Should not have changed - tauri already set
        assert!(extensions.is_none());
    }

    #[test]
    fn test_apply_detected_stack_applies_tauri() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::create_dir(tmp.path().join("src-tauri")).expect("mkdir");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write");

        let mut extensions: Option<HashSet<String>> = None;
        let mut ignores = Vec::new();
        let mut tauri = false;
        let mut library_mode = false;

        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            false,
        );

        assert!(tauri);
        assert!(extensions.is_some());
        assert!(extensions.as_ref().unwrap().contains("ts"));
    }

    #[test]
    fn test_apply_detected_stack_preserves_user_ignores() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "").expect("write");

        let mut extensions: Option<HashSet<String>> = None;
        let mut ignores = vec!["custom_ignore".to_string()];
        let mut tauri = false;
        let mut library_mode = false;

        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            false,
        );

        // Should NOT have applied detected ignores since user specified their own
        assert_eq!(ignores, vec!["custom_ignore".to_string()]);
    }

    #[test]
    fn test_apply_detected_stack_verbose() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("Cargo.toml"), "").expect("write");

        let mut extensions: Option<HashSet<String>> = None;
        let mut ignores = Vec::new();
        let mut tauri = false;
        let mut library_mode = false;

        // Should not panic with verbose=true
        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            true,
        );
    }

    #[test]
    fn test_detected_stack_is_empty() {
        let empty = DetectedStack::default();
        assert!(empty.is_empty());

        let with_ext = DetectedStack {
            extensions: HashSet::from(["rs".to_string()]),
            ..Default::default()
        };
        assert!(!with_ext.is_empty());

        let with_preset = DetectedStack {
            preset_name: Some("tauri".to_string()),
            ..Default::default()
        };
        assert!(!with_preset.is_empty());
    }

    #[test]
    fn test_detect_rust_in_subdirectory() {
        // Monorepo layout: package.json at root, Cargo.toml in subdirectory
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write package.json");
        std::fs::create_dir(tmp.path().join("codex-rs")).expect("mkdir codex-rs");
        std::fs::write(
            tmp.path().join("codex-rs").join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .expect("write Cargo.toml");

        let detected = detect_stack(tmp.path());

        // Should detect both JavaScript and Rust
        assert!(detected.extensions.contains("rs"));
        assert!(detected.extensions.contains("js"));
        assert!(detected.description.contains("JavaScript"));
        assert!(detected.description.contains("Rust"));
    }

    #[test]
    fn test_has_cargo_in_subdir() {
        let tmp = TempDir::new().expect("create temp dir");

        // No subdirs yet
        assert!(!has_cargo_in_subdir(tmp.path()));

        // Add a subdir without Cargo.toml
        std::fs::create_dir(tmp.path().join("src")).expect("mkdir");
        assert!(!has_cargo_in_subdir(tmp.path()));

        // Add a subdir with Cargo.toml
        std::fs::create_dir(tmp.path().join("backend")).expect("mkdir");
        std::fs::write(tmp.path().join("backend").join("Cargo.toml"), "").expect("write");
        assert!(has_cargo_in_subdir(tmp.path()));
    }

    #[test]
    fn test_has_cargo_in_subdir_skips_hidden() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::create_dir(tmp.path().join(".hidden")).expect("mkdir");
        std::fs::write(tmp.path().join(".hidden").join("Cargo.toml"), "").expect("write");

        // Should not find Cargo.toml in hidden directories
        assert!(!has_cargo_in_subdir(tmp.path()));
    }

    #[test]
    fn test_detect_library_with_exports_field() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "solid-js", "exports": {"./jsx-runtime": "./jsx-runtime/index.js"}}"#,
        )
        .expect("write package.json");

        let detected = detect_stack(tmp.path());

        assert!(
            detected.is_library,
            "Should detect library project with exports field"
        );
        assert!(detected.description.contains("Library"));
    }

    #[test]
    fn test_detect_library_with_main_field_no_html() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "some-lib", "main": "dist/index.js", "types": "dist/index.d.ts"}"#,
        )
        .expect("write package.json");

        let detected = detect_stack(tmp.path());

        assert!(
            detected.is_library,
            "Should detect library with main/types but no HTML"
        );
    }

    #[test]
    fn test_detect_app_with_index_html() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "some-app", "main": "src/main.js"}"#,
        )
        .expect("write package.json");
        std::fs::write(tmp.path().join("index.html"), "<!DOCTYPE html>").expect("write index.html");

        let detected = detect_stack(tmp.path());

        assert!(
            !detected.is_library,
            "Should NOT detect library when index.html exists"
        );
    }

    #[test]
    fn test_detect_monorepo_with_packages() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(tmp.path().join("package.json"), "{}").expect("write package.json");
        std::fs::create_dir(tmp.path().join("packages")).expect("mkdir packages");
        std::fs::create_dir(tmp.path().join("packages/foo")).expect("mkdir foo");
        std::fs::write(tmp.path().join("packages/foo/package.json"), "{}")
            .expect("write foo package.json");

        let detected = detect_stack(tmp.path());

        assert!(
            detected.is_library,
            "Should detect monorepo with packages/ as library"
        );
    }

    #[test]
    fn test_library_mode_applied_automatically() {
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"name": "test-lib", "exports": {"./index": "./index.js"}}"#,
        )
        .expect("write package.json");

        let mut extensions: Option<HashSet<String>> = None;
        let mut ignores = Vec::new();
        let mut tauri = false;
        let mut library_mode = false;

        apply_detected_stack(
            tmp.path(),
            &mut extensions,
            &mut ignores,
            &mut tauri,
            &mut library_mode,
            &mut Vec::new(),
            false,
        );

        assert!(
            library_mode,
            "Library mode should be auto-enabled for library projects"
        );
    }

    #[test]
    fn test_detect_cpython_py_roots() {
        // CPython layout: Lib/ alongside Python/ and Modules/
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("pyproject.toml"),
            "[project]\nname = \"cpython\"",
        )
        .expect("write pyproject.toml");
        std::fs::create_dir(tmp.path().join("Lib")).expect("mkdir Lib");
        std::fs::create_dir(tmp.path().join("Python")).expect("mkdir Python");
        std::fs::create_dir(tmp.path().join("Modules")).expect("mkdir Modules");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("py"));
        assert_eq!(detected.py_roots.len(), 1);
        assert_eq!(detected.py_roots[0], std::path::PathBuf::from("Lib"));
    }

    #[test]
    fn test_detect_no_py_roots_for_standard_layout() {
        // Standard Python project without special py_roots
        let tmp = TempDir::new().expect("create temp dir");
        std::fs::write(
            tmp.path().join("pyproject.toml"),
            "[project]\nname = \"myapp\"",
        )
        .expect("write pyproject.toml");
        std::fs::create_dir(tmp.path().join("src")).expect("mkdir src");
        std::fs::create_dir(tmp.path().join("tests")).expect("mkdir tests");

        let detected = detect_stack(tmp.path());

        assert!(detected.extensions.contains("py"));
        assert!(
            detected.py_roots.is_empty(),
            "Standard layout should not add py_roots"
        );
    }
}