codescout 0.15.0

High-performance coding agent toolkit MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
use std::path::{Path, PathBuf};

/// Sentinel project ID used when no specific sub-project claims a file or
/// when the root of the workspace has no build manifest.
pub const ROOT_PROJECT_ID: &str = "root";

/// A project discovered by manifest walk during onboarding.
#[derive(Debug, Clone)]
pub struct DiscoveredProject {
    pub id: String,
    pub relative_root: PathBuf,
    pub languages: Vec<String>,
    pub manifest: Option<String>,
}

/// Read up to `max_bytes` of a file as UTF-8. Used for manifest reads where
/// an unbounded `read_to_string` would DoS if the file is pathologically large.
/// Returns `Err` if the file cannot be opened or if the truncated bytes are
/// not valid UTF-8 — both are treated as "skip this manifest" by callers.
fn read_file_capped(path: &Path, max_bytes: u64) -> std::io::Result<String> {
    use std::io::Read;
    let f = std::fs::File::open(path)?;
    let mut buf = String::new();
    f.take(max_bytes).read_to_string(&mut buf)?;
    Ok(buf)
}

/// Walk the workspace root for build manifests and return discovered sub-projects.
pub fn discover_projects(
    workspace_root: &Path,
    max_depth: usize,
    exclude: &[String],
) -> Vec<DiscoveredProject> {
    let manifests: &[(&str, &[&str])] = &[
        ("Cargo.toml", &["rust"]),
        ("build.gradle.kts", &["kotlin", "java"]),
        ("build.gradle", &["kotlin", "java"]),
        ("go.mod", &["go"]),
        ("pom.xml", &["java"]),
        ("CMakeLists.txt", &["c", "cpp"]),
        ("mix.exs", &["elixir"]),
        ("Gemfile", &["ruby"]),
    ];
    let conditional_manifests: &[(&str, &[&str])] = &[
        ("package.json", &["typescript", "javascript"]),
        ("pyproject.toml", &["python"]),
        ("setup.py", &["python"]),
        ("requirements.txt", &["python"]),
    ];

    let mut manifest_dirs: std::collections::BTreeMap<PathBuf, (String, Vec<String>)> =
        std::collections::BTreeMap::new();

    let walker = ignore::WalkBuilder::new(workspace_root)
        .hidden(true)
        .git_ignore(true)
        .max_depth(Some(max_depth + 1))
        .build();

    for entry in walker.flatten() {
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }
        let file_name = entry.file_name().to_string_lossy().to_string();
        let dir = entry.path().parent().unwrap_or(entry.path()).to_path_buf();

        let rel_dir = dir.strip_prefix(workspace_root).unwrap_or(&dir);

        // Skip excluded directories
        if exclude.iter().any(|ex| {
            rel_dir
                .components()
                .any(|c| c.as_os_str().to_string_lossy() == *ex)
        }) {
            continue;
        }

        // Skip node_modules explicitly (ignore crate won't skip without .gitignore)
        if rel_dir
            .components()
            .any(|c| c.as_os_str() == "node_modules")
        {
            continue;
        }

        // Check unconditional manifests
        for (manifest_name, langs) in manifests {
            if file_name == *manifest_name && !manifest_dirs.contains_key(&dir) {
                manifest_dirs.insert(
                    dir.clone(),
                    (
                        manifest_name.to_string(),
                        langs.iter().map(|s| s.to_string()).collect(),
                    ),
                );
                break;
            }
        }

        // Check conditional manifests
        for (manifest_name, langs) in conditional_manifests {
            if file_name != *manifest_name || manifest_dirs.contains_key(&dir) {
                continue;
            }
            if *manifest_name == "package.json" {
                // Cap read at 1 MiB — matches config-file cap. A package.json
                // above this is pathological and would otherwise DoS agent
                // startup (discover_projects is called on every Agent::new /
                // activate, so a large manifest pays on every activation).
                if let Ok(content) = read_file_capped(entry.path(), 1024 * 1024) {
                    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
                        let has_scripts = json
                            .get("scripts")
                            .and_then(|v| v.as_object())
                            .map(|o| !o.is_empty())
                            .unwrap_or(false);
                        let has_main = json.get("main").is_some() || json.get("module").is_some();
                        if !has_scripts && !has_main {
                            continue;
                        }
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
            if *manifest_name == "requirements.txt" && dir.join("pyproject.toml").exists() {
                continue;
            }
            manifest_dirs.insert(
                dir.clone(),
                (
                    manifest_name.to_string(),
                    langs.iter().map(|s| s.to_string()).collect(),
                ),
            );
            break;
        }
    }

    let workspace_name = workspace_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unnamed")
        .to_string();

    // Sort by depth so shallower (parent) projects come first
    let mut dirs: Vec<_> = manifest_dirs.into_iter().collect();
    dirs.sort_by_key(|(p, _)| p.components().count());

    let mut found: Vec<DiscoveredProject> = Vec::new();
    let mut found_roots: Vec<PathBuf> = Vec::new();

    for (dir, (manifest, languages)) in dirs {
        let rel = dir.strip_prefix(workspace_root).unwrap_or(&dir);
        let rel_path = if rel.as_os_str().is_empty() {
            PathBuf::from(".")
        } else {
            rel.to_path_buf()
        };

        // Skip if dominated by a shallower project with matching language
        let dominated = found_roots.iter().any(|existing| {
            if rel_path == std::path::Path::new(".") || existing == std::path::Path::new(".") {
                return false;
            }
            rel_path.starts_with(existing)
                && found.iter().any(|p| {
                    p.relative_root == *existing
                        && p.languages.iter().any(|l| languages.contains(l))
                })
        });
        if dominated {
            continue;
        }

        let id = if rel_path == std::path::Path::new(".") {
            workspace_name.clone()
        } else {
            rel_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unnamed")
                .to_string()
        };

        // Deduplicate: if id already taken, use path-based name
        let final_id = if found.iter().any(|p| p.id == id) {
            rel_path.to_string_lossy().replace('/', "-")
        } else {
            id
        };

        found_roots.push(rel_path.clone());
        found.push(DiscoveredProject {
            id: final_id,
            relative_root: rel_path,
            languages,
            manifest: Some(manifest),
        });
    }

    // File-content dominance pass (after the manifest-based domination logic, so
    // it doesn't perturb project detection). Each project's `languages` should
    // reflect its actual file mix (dominance-ordered), not just its build
    // manifest — a polyglot root whose manifest ≠ dominant language (e.g. a
    // Python repo keeping package.json for tooling) was mislabeled. Manifest-only
    // dirs (empty scan) keep their manifest langs unchanged.
    // (2026-06-03-project-languages-from-manifest-not-files)
    for p in &mut found {
        let dominance = scan_languages_by_dominance(&workspace_root.join(&p.relative_root));
        if !dominance.is_empty() {
            p.languages = merge_languages(dominance, &p.languages);
        }
    }

    // Ensure root project is first
    if let Some(root_idx) = found
        .iter()
        .position(|p| p.relative_root == std::path::Path::new("."))
    {
        if root_idx != 0 {
            let root = found.remove(root_idx);
            found.insert(0, root);
        }
    }

    found
}

/// Source languages in `dir`, ordered by file-count dominance (most files
/// first). Bounded — `discover_projects` runs on every `Agent::new` / activate,
/// so the walk is depth- and count-capped and gitignore-aware. Ties broken
/// alphabetically for deterministic output.
/// (2026-06-03-project-languages-from-manifest-not-files)
pub(crate) fn scan_languages_by_dominance(dir: &Path) -> Vec<String> {
    const MAX_DEPTH: usize = 6;
    const FILE_CAP: usize = 1000;
    let mut counts: std::collections::HashMap<&'static str, usize> =
        std::collections::HashMap::new();
    let walker = ignore::WalkBuilder::new(dir)
        .hidden(true)
        .git_ignore(true)
        .max_depth(Some(MAX_DEPTH))
        .build();
    let mut scanned = 0usize;
    for entry in walker.flatten() {
        if scanned >= FILE_CAP {
            break;
        }
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }
        if entry
            .path()
            .components()
            .any(|c| c.as_os_str() == "node_modules")
        {
            continue;
        }
        scanned += 1;
        if let Some(lang) = crate::ast::detect_language(entry.path()) {
            *counts.entry(lang).or_default() += 1;
        }
    }
    let mut pairs: Vec<(&'static str, usize)> = counts.into_iter().collect();
    pairs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
    pairs.into_iter().map(|(l, _)| l.to_string()).collect()
}

/// The dominant programming language in `dir` for `primary_language`, skipping
/// documentation/markup kinds that should never be a project's primary language.
pub(crate) fn dominant_language(dir: &Path) -> Option<String> {
    const SKIP: &[&str] = &["markdown"];
    scan_languages_by_dominance(dir)
        .into_iter()
        .find(|l| !SKIP.contains(&l.as_str()))
}

/// Merge file-dominance languages (ordered, most files first) with
/// manifest-declared languages: dominance first, manifest langs appended as a
/// fallback so manifest-only dirs (no source files) still resolve. Order-
/// preserving and de-duplicated.
fn merge_languages(dominance: Vec<String>, manifest: &[String]) -> Vec<String> {
    let mut out = dominance;
    for m in manifest {
        if !out.iter().any(|l| l == m) {
            out.push(m.clone());
        }
    }
    out
}

/// Lexically collapse `.` / `..` components in a path without touching the
/// filesystem. Used to prevent prefix-match bypass in `resolve_project_for_path`
/// — without this, `/workspace/project/../../etc/passwd` would lexically
/// start-with `/workspace/project` and be incorrectly attributed to the project.
///
/// Does not resolve symlinks; if the path exists, prefer `std::fs::canonicalize`.
fn lexically_normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::ParentDir => {
                // Pop a Normal component; otherwise preserve the `..` (e.g. a
                // path starting with `../` has nothing to pop).
                if !matches!(
                    out.components().next_back(),
                    Some(std::path::Component::Normal(_))
                ) {
                    out.push("..");
                } else {
                    out.pop();
                }
            }
            std::path::Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Resolve which project a file path belongs to using longest-prefix match.
///
/// The input path is lexically normalized (`..` collapsed) before the prefix
/// check so that traversal attempts like `project/../../etc/passwd` cannot
/// lexically match a project root. Callers downstream that read/write the
/// returned project's files must still re-validate the original `file_path`
/// with `path_security` — this function only classifies, it does not gate I/O.
pub fn resolve_project_for_path<'a>(
    projects: &'a [DiscoveredProject],
    workspace_root: &Path,
    file_path: &Path,
) -> Option<&'a DiscoveredProject> {
    let abs_file = if file_path.is_relative() {
        workspace_root.join(file_path)
    } else {
        file_path.to_path_buf()
    };
    let abs_file = lexically_normalize(&abs_file);

    projects
        .iter()
        .filter(|p| {
            let project_abs = if p.relative_root == std::path::Path::new(".") {
                workspace_root.to_path_buf()
            } else {
                workspace_root.join(&p.relative_root)
            };
            let project_abs = lexically_normalize(&project_abs);
            abs_file.starts_with(&project_abs)
        })
        .max_by_key(|p| p.relative_root.components().count())
}

/// Given a file path and a list of discovered projects, return the project ID.
/// Falls back to `ROOT_PROJECT_ID` if no project claims the file.
pub fn resolve_project_id(
    projects: &[DiscoveredProject],
    workspace_root: &Path,
    file_path: &Path,
) -> String {
    resolve_project_for_path(projects, workspace_root, file_path)
        .map(|p| p.id.clone())
        .unwrap_or_else(|| ROOT_PROJECT_ID.to_string())
}

/// State of a project within the workspace.
pub enum ProjectState {
    /// Not yet activated — LSP not started, config not loaded.
    Dormant,
    /// Fully activated with config, memory, LSP running.
    Activated(Box<crate::agent::ActiveProject>),
}

/// A project within the workspace — discovered metadata + runtime state.
pub struct Project {
    pub discovered: DiscoveredProject,
    pub state: ProjectState,
}

impl Project {
    pub fn new_dormant(discovered: DiscoveredProject) -> Self {
        Self {
            discovered,
            state: ProjectState::Dormant,
        }
    }
}

/// The top-level workspace containing all discovered projects.
pub struct Workspace {
    pub root: PathBuf,
    pub projects: Vec<Project>,
    /// Currently focused project ID (used by require_project_root).
    pub focused: Option<String>,
}

impl Workspace {
    pub fn new(root: PathBuf, projects: Vec<Project>) -> Self {
        // Focus defaults to the root project if present, else first project
        let focused = projects
            .iter()
            .find(|p| p.discovered.relative_root == std::path::Path::new("."))
            .or_else(|| projects.first())
            .map(|p| p.discovered.id.clone());
        Self {
            root,
            projects,
            focused,
        }
    }

    /// Return the absolute root path of the focused project.
    pub fn focused_project_root(&self) -> anyhow::Result<PathBuf> {
        let id = self
            .focused
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("No focused project"))?;
        self.project_root_by_id(id)
    }

    /// Return the absolute root path for a project by ID.
    pub fn project_root_by_id(&self, id: &str) -> anyhow::Result<PathBuf> {
        let project = self
            .projects
            .iter()
            .find(|p| p.discovered.id == id)
            .ok_or_else(|| anyhow::anyhow!("Project '{}' not found in workspace", id))?;
        let abs = if project.discovered.relative_root == std::path::Path::new(".") {
            self.root.clone()
        } else {
            self.root.join(&project.discovered.relative_root)
        };
        Ok(abs)
    }

    /// Resolve root: explicit project ID > file hint > focused project.
    pub fn resolve_root(
        &self,
        project: Option<&str>,
        file_hint: Option<&Path>,
    ) -> anyhow::Result<PathBuf> {
        match (project, file_hint) {
            (Some(id), _) => self.project_root_by_id(id),
            (None, Some(path)) => {
                // Longest-prefix match
                let discovered: Vec<_> =
                    self.projects.iter().map(|p| p.discovered.clone()).collect();
                let result = resolve_project_for_path(&discovered, &self.root, path);
                match result {
                    Some(p) => self.project_root_by_id(&p.id),
                    None => self.focused_project_root(),
                }
            }
            (None, None) => self.focused_project_root(),
        }
    }

    /// Return the focused project, if any.
    pub fn focused_active(&self) -> Option<&Project> {
        let id = self.focused.as_deref()?;
        self.projects.iter().find(|p| p.discovered.id == id)
    }

    pub fn focused_active_mut(&mut self) -> Option<&mut Project> {
        // borrow-checker: clone here to release the immutable borrow on self.focused
        // before mutably iterating self.projects.
        let id = self.focused.clone()?;
        self.projects.iter_mut().find(|p| p.discovered.id == id)
    }

    /// Switch focus to a project by ID.
    pub fn set_focused(&mut self, project_id: &str) -> anyhow::Result<()> {
        if self.projects.iter().any(|p| p.discovered.id == project_id) {
            self.focused = Some(project_id.to_string());
            Ok(())
        } else {
            Err(anyhow::anyhow!(
                "Project '{}' not found in workspace",
                project_id
            ))
        }
    }

    /// Return all project IDs in the workspace.
    pub fn project_ids(&self) -> Vec<String> {
        self.projects
            .iter()
            .map(|p| p.discovered.id.clone())
            .collect()
    }

    /// Memory directory for a project. Root project -> workspace-level, sub-projects -> per-project.
    ///
    /// An unknown `project_id` is treated as a sub-project (returns a per-project
    /// subdirectory under `projects/<id>/`). Previously defaulted to the root
    /// memory dir on unknown ID, which silently co-mingled memories from typos
    /// or stale IDs with the workspace root's memories — a bug that would go
    /// unnoticed until a user noticed crossed-over memories.
    pub fn memory_dir_for_project(&self, project_id: &str) -> PathBuf {
        let is_root = self
            .projects
            .iter()
            .find(|p| p.discovered.id == project_id)
            .map(|p| p.discovered.relative_root == std::path::Path::new("."))
            .unwrap_or(false);
        if is_root {
            self.root.join(".codescout").join("memories")
        } else {
            self.root
                .join(".codescout")
                .join("projects")
                .join(project_id)
                .join("memories")
        }
    }
}

/// Helper to extract `&ActiveProject` from a focused project's activated state.
impl Project {
    pub fn as_active(&self) -> Option<&crate::agent::ActiveProject> {
        match &self.state {
            ProjectState::Activated(ap) => Some(ap.as_ref()),
            ProjectState::Dormant => None,
        }
    }

    pub fn as_active_mut(&mut self) -> Option<&mut crate::agent::ActiveProject> {
        match &mut self.state {
            ProjectState::Activated(ap) => Some(ap.as_mut()),
            ProjectState::Dormant => None,
        }
    }
}

/// Normalize a relative path reference against a base directory without touching
/// the filesystem (handles `../` components manually).
///
/// # Security
///
/// **NOT a filesystem-safe path normalizer.** This function intentionally
/// permits escaping `base` (e.g. `..` components that rise above it), because
/// it exists to resolve cross-project dependency paths in manifest files —
/// a Cargo workspace member may legitimately reference `../sibling-crate`,
/// which resolves to workspace-root/sibling-crate (above `base = project_root`).
///
/// The result is used only as a lookup key against a closed set of known
/// projects (`project_by_abs` in `infer_depends_on`). Unknown paths silently
/// miss the lookup and are discarded — they never reach an I/O sink.
///
/// **Callers wiring this to a filesystem read/write, shell command, or any
/// other capability that acts on the path MUST re-validate with `path_security`
/// (or equivalent) before using the result.** Keep this function private;
/// making it `pub` creates a cross-crate footgun.
fn normalize_path(base: &Path, relative: &str) -> PathBuf {
    let mut result = base.to_path_buf();
    for component in Path::new(relative).components() {
        match component {
            std::path::Component::ParentDir => {
                result.pop();
            }
            std::path::Component::Normal(c) => result.push(c),
            std::path::Component::CurDir => {}
            _ => result.push(component),
        }
    }
    result
}

/// Parse Cargo.toml `[dependencies]` / `[dev-dependencies]` for `path = "..."` entries.
fn deps_from_cargo(project_root: &Path) -> Vec<String> {
    let Ok(content) = std::fs::read_to_string(project_root.join("Cargo.toml")) else {
        return vec![];
    };
    let Ok(table) = toml::from_str::<toml::Value>(&content) else {
        return vec![];
    };
    let mut paths = vec![];
    for section in &["dependencies", "dev-dependencies", "build-dependencies"] {
        if let Some(deps) = table.get(section).and_then(|v| v.as_table()) {
            for dep in deps.values() {
                if let Some(p) = dep.get("path").and_then(|v| v.as_str()) {
                    paths.push(p.to_string());
                }
            }
        }
    }
    paths
}

/// Parse package.json for `"file:../..."` or `"workspace:../..."` dependency values.
fn deps_from_npm(project_root: &Path) -> Vec<String> {
    let Ok(content) = std::fs::read_to_string(project_root.join("package.json")) else {
        return vec![];
    };
    let Ok(pkg) = serde_json::from_str::<serde_json::Value>(&content) else {
        return vec![];
    };
    let mut paths = vec![];
    for section in &["dependencies", "devDependencies", "peerDependencies"] {
        if let Some(deps) = pkg.get(section).and_then(|v| v.as_object()) {
            for val in deps.values() {
                if let Some(s) = val.as_str() {
                    if let Some(path) = s
                        .strip_prefix("file:")
                        .or_else(|| s.strip_prefix("workspace:"))
                    {
                        if path.starts_with("../") || path.starts_with("./") {
                            paths.push(path.to_string());
                        }
                    }
                }
            }
        }
    }
    paths
}

/// Parse pyproject.toml for `{path = "..."}` dependency entries.
fn deps_from_pyproject(project_root: &Path) -> Vec<String> {
    let Ok(content) = std::fs::read_to_string(project_root.join("pyproject.toml")) else {
        return vec![];
    };
    let Ok(table) = toml::from_str::<toml::Value>(&content) else {
        return vec![];
    };
    let mut paths = vec![];
    // poetry: [tool.poetry.dependencies]
    for dep in table
        .get("tool")
        .and_then(|t| t.get("poetry"))
        .and_then(|p| p.get("dependencies"))
        .and_then(|d| d.as_table())
        .into_iter()
        .flat_map(|t| t.values())
    {
        if let Some(p) = dep.get("path").and_then(|v| v.as_str()) {
            paths.push(p.to_string());
        }
    }
    // PEP 517 / uv: [dependencies] with path entries (less common but handle it)
    for dep in table
        .get("project")
        .and_then(|p| p.get("dependencies"))
        .and_then(|d| d.as_array())
        .into_iter()
        .flatten()
    {
        if let Some(s) = dep.as_str() {
            // Editable path dep: "my-pkg @ file:../sibling" or just "../sibling"
            if let Some(rest) = s.find("@ file:").map(|i| &s[i + 7..]) {
                if rest.starts_with("../") || rest.starts_with("./") {
                    paths.push(rest.to_string());
                }
            }
        }
    }
    paths
}

/// Parse requirements.txt for `-e ../sibling` editable installs.
fn deps_from_requirements(project_root: &Path) -> Vec<String> {
    let Ok(content) = std::fs::read_to_string(project_root.join("requirements.txt")) else {
        return vec![];
    };
    content
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            let path = line.strip_prefix("-e ")?;
            if path.starts_with("../") || path.starts_with("./") {
                Some(path.to_string())
            } else {
                None
            }
        })
        .collect()
}

/// Parse settings.gradle / settings.gradle.kts for `includeBuild("../sibling")`.
fn deps_from_gradle(project_root: &Path) -> Vec<String> {
    let content = ["settings.gradle.kts", "settings.gradle"]
        .iter()
        .find_map(|f| std::fs::read_to_string(project_root.join(f)).ok())
        .unwrap_or_default();

    let mut paths = vec![];
    for line in content.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("includeBuild(") {
            // Extract quoted string: includeBuild("../sibling")
            let inner = rest.trim_end_matches(')').trim();
            let path = inner
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .or_else(|| inner.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')));
            if let Some(p) = path {
                if p.starts_with("../") || p.starts_with("./") {
                    paths.push(p.to_string());
                }
            }
        }
    }
    paths
}

/// Infer cross-project dependencies for a single project from its manifest files.
///
/// Returns a sorted, deduplicated list of project IDs that `project_root` depends on,
/// based on path references found in Cargo.toml, package.json, pyproject.toml,
/// requirements.txt, and settings.gradle(.kts).
///
/// Only same-workspace references are returned — external paths are silently ignored.
pub fn infer_depends_on(
    project_root: &Path,
    workspace_root: &Path,
    all_projects: &[DiscoveredProject],
) -> Vec<String> {
    // Build a map: canonical absolute root → project id
    let project_by_abs: std::collections::HashMap<PathBuf, &str> = all_projects
        .iter()
        .map(|p| (workspace_root.join(&p.relative_root), p.id.as_str()))
        .collect();

    let raw_paths: Vec<String> = [
        deps_from_cargo(project_root),
        deps_from_npm(project_root),
        deps_from_pyproject(project_root),
        deps_from_requirements(project_root),
        deps_from_gradle(project_root),
    ]
    .into_iter()
    .flatten()
    .collect();

    let mut deps = std::collections::BTreeSet::new();
    for raw in raw_paths {
        let abs = normalize_path(project_root, &raw);
        if let Some(&id) = project_by_abs.get(&abs) {
            // Don't add self-references
            if abs != *project_root {
                deps.insert(id.to_string());
            }
        }
    }
    deps.into_iter().collect()
}

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

    #[test]
    fn resolve_project_for_path_rejects_dotdot_escape() {
        // Regression for S3: lexical starts_with without normalization would
        // attribute `/workspace/project-a/../../etc/passwd` to `project-a`
        // because the string prefix matches. After normalization the path
        // collapses to `/etc/passwd` and no project prefix matches.
        use std::path::PathBuf;
        let workspace = PathBuf::from("/workspace");
        let projects = vec![DiscoveredProject {
            id: "project-a".into(),
            relative_root: PathBuf::from("project-a"),
            languages: vec!["rust".into()],
            manifest: Some("Cargo.toml".into()),
        }];
        let escaped = PathBuf::from("/workspace/project-a/../../etc/passwd");
        let resolved = resolve_project_for_path(&projects, &workspace, &escaped);
        assert!(
            resolved.is_none(),
            "escape path must not match any project, got {:?}",
            resolved.map(|p| &p.id)
        );

        // Sanity: a real file inside the project still resolves.
        let legit = PathBuf::from("/workspace/project-a/src/main.rs");
        assert_eq!(
            resolve_project_for_path(&projects, &workspace, &legit).map(|p| p.id.as_str()),
            Some("project-a")
        );
    }

    #[test]
    fn discover_single_project_repo() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/main.rs"), "fn main() {}").unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert_eq!(projects.len(), 1);
        assert_eq!(
            projects[0].id,
            dir.path().file_name().unwrap().to_str().unwrap()
        );
        assert_eq!(projects[0].relative_root, std::path::Path::new("."));
        assert_eq!(projects[0].manifest, Some("Cargo.toml".to_string()));
    }

    #[test]
    fn discover_multi_project_repo() {
        let dir = tempdir().unwrap();
        // Root: Kotlin
        fs::write(dir.path().join("build.gradle.kts"), "").unwrap();
        // Sub: TypeScript
        let mcp = dir.path().join("mcp-server");
        fs::create_dir_all(&mcp).unwrap();
        fs::write(mcp.join("package.json"), r#"{"scripts":{"build":"tsc"}}"#).unwrap();
        // Sub: Python
        let py = dir.path().join("python-services");
        fs::create_dir_all(&py).unwrap();
        fs::write(py.join("requirements.txt"), "flask\n").unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert_eq!(projects.len(), 3);

        // Root project first
        assert_eq!(projects[0].relative_root, std::path::Path::new("."));
        assert_eq!(projects[0].manifest, Some("build.gradle.kts".to_string()));

        // Sub-projects sorted by id
        let ids: Vec<&str> = projects.iter().map(|p| p.id.as_str()).collect();
        assert!(ids.contains(&"mcp-server"));
        assert!(ids.contains(&"python-services"));
    }

    #[test]
    fn skips_node_modules_manifests() {
        let dir = tempdir().unwrap();
        // Root has a real project (non-empty scripts)
        fs::write(
            dir.path().join("package.json"),
            r#"{"scripts":{"test":"jest"}}"#,
        )
        .unwrap();
        let nm = dir.path().join("node_modules").join("dep");
        fs::create_dir_all(&nm).unwrap();
        fs::write(nm.join("package.json"), r#"{"name":"dep"}"#).unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert_eq!(projects.len(), 1); // only root, not node_modules/dep
    }

    #[test]
    fn respects_exclude_list() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("build.gradle.kts"), "").unwrap();
        let tools = dir.path().join("tools");
        fs::create_dir_all(&tools).unwrap();
        fs::write(tools.join("requirements.txt"), "click\n").unwrap();

        let projects = discover_projects(dir.path(), 3, &["tools".to_string()]);
        assert_eq!(projects.len(), 1); // tools excluded
    }

    #[test]
    fn max_depth_limits_discovery() {
        let dir = tempdir().unwrap();
        // Manifest at depth 4 — should be skipped with max_depth=3
        let deep = dir
            .path()
            .join("a")
            .join("b")
            .join("c")
            .join("deep-service");
        fs::create_dir_all(&deep).unwrap();
        fs::write(deep.join("Cargo.toml"), "[package]\nname = \"deep\"").unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert!(
            projects.is_empty(),
            "manifest at depth 4 should be skipped with max_depth=3"
        );

        // But discoverable with max_depth=5
        let projects = discover_projects(dir.path(), 5, &[]);
        assert_eq!(projects.len(), 1);
    }

    #[test]
    fn id_collision_is_deduplicated() {
        let dir = tempdir().unwrap();
        // Two subdirectories named "api" at different paths
        let svc_api = dir.path().join("services").join("api");
        fs::create_dir_all(&svc_api).unwrap();
        fs::write(svc_api.join("Cargo.toml"), "[package]\nname = \"svc-api\"").unwrap();

        let tools_api = dir.path().join("tools").join("api");
        fs::create_dir_all(&tools_api).unwrap();
        fs::write(
            tools_api.join("Cargo.toml"),
            "[package]\nname = \"tools-api\"",
        )
        .unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        let ids: Vec<&str> = projects.iter().map(|p| p.id.as_str()).collect();
        // IDs must be unique — one gets the plain name, other gets path-based name
        assert_eq!(ids.len(), 2);
        assert_ne!(ids[0], ids[1], "IDs must be unique: got {:?}", ids);
    }

    #[test]
    fn resolve_project_from_path_uses_longest_prefix() {
        let dir = tempdir().unwrap();
        let projects = vec![
            DiscoveredProject {
                id: ROOT_PROJECT_ID.into(),
                relative_root: ".".into(),
                languages: vec!["kotlin".into()],
                manifest: Some("build.gradle.kts".into()),
            },
            DiscoveredProject {
                id: "mcp-server".into(),
                relative_root: "mcp-server".into(),
                languages: vec!["typescript".into()],
                manifest: Some("package.json".into()),
            },
        ];

        // File inside mcp-server → resolves to mcp-server
        let result = resolve_project_for_path(
            &projects,
            dir.path(),
            &dir.path().join("mcp-server/src/index.ts"),
        );
        assert_eq!(result.unwrap().id, "mcp-server");

        // File at root → resolves to root
        let result = resolve_project_for_path(
            &projects,
            dir.path(),
            &dir.path().join("src/main/kotlin/App.kt"),
        );
        assert_eq!(result.unwrap().id, ROOT_PROJECT_ID);
    }

    // ── infer_depends_on tests ──────────────────────────────────────────────

    fn make_project(id: &str, relative_root: &str) -> DiscoveredProject {
        DiscoveredProject {
            id: id.to_string(),
            relative_root: PathBuf::from(relative_root),
            languages: vec![],
            manifest: None,
        }
    }

    #[test]
    fn infer_depends_on_cargo_path_dep() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let api = ws.join("api");
        let shared = ws.join("shared");
        fs::create_dir_all(&api).unwrap();
        fs::create_dir_all(&shared).unwrap();
        fs::write(
            api.join("Cargo.toml"),
            "[package]\nname = \"api\"\n\n[dependencies]\nshared = { path = \"../shared\" }\n",
        )
        .unwrap();
        let projects = vec![make_project("api", "api"), make_project("shared", "shared")];
        let deps = infer_depends_on(&api, ws, &projects);
        assert_eq!(deps, vec!["shared"]);
    }

    #[test]
    fn infer_depends_on_npm_workspace_protocol() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let web = ws.join("web");
        let ui = ws.join("ui");
        fs::create_dir_all(&web).unwrap();
        fs::create_dir_all(&ui).unwrap();
        fs::write(
            web.join("package.json"),
            r#"{"name":"web","scripts":{"build":"tsc"},"dependencies":{"@app/ui":"workspace:../ui"}}"#,
        )
        .unwrap();
        let projects = vec![make_project("web", "web"), make_project("ui", "ui")];
        let deps = infer_depends_on(&web, ws, &projects);
        assert_eq!(deps, vec!["ui"]);
    }

    #[test]
    fn infer_depends_on_requirements_txt_editable() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let svc = ws.join("svc");
        let lib = ws.join("lib");
        fs::create_dir_all(&svc).unwrap();
        fs::create_dir_all(&lib).unwrap();
        fs::write(svc.join("requirements.txt"), "-e ../lib\nrequests==2.31\n").unwrap();
        let projects = vec![make_project("svc", "svc"), make_project("lib", "lib")];
        let deps = infer_depends_on(&svc, ws, &projects);
        assert_eq!(deps, vec!["lib"]);
    }

    #[test]
    fn infer_depends_on_gradle_include_build() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let app = ws.join("app");
        let core = ws.join("core");
        fs::create_dir_all(&app).unwrap();
        fs::create_dir_all(&core).unwrap();
        fs::write(
            app.join("settings.gradle.kts"),
            "includeBuild(\"../core\")\n",
        )
        .unwrap();
        let projects = vec![make_project("app", "app"), make_project("core", "core")];
        let deps = infer_depends_on(&app, ws, &projects);
        assert_eq!(deps, vec!["core"]);
    }

    #[test]
    fn infer_depends_on_no_manifests_returns_empty() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let a = ws.join("a");
        fs::create_dir_all(&a).unwrap();
        let projects = vec![make_project("a", "a"), make_project("b", "b")];
        let deps = infer_depends_on(&a, ws, &projects);
        assert!(deps.is_empty());
    }

    #[test]
    fn infer_depends_on_ignores_external_paths() {
        let dir = tempdir().unwrap();
        let ws = dir.path();
        let api = ws.join("api");
        fs::create_dir_all(&api).unwrap();
        // References a path outside the workspace
        fs::write(
            api.join("Cargo.toml"),
            "[package]\nname = \"api\"\n\n[dependencies]\nexternal = { path = \"../../outside\" }\n",
        )
        .unwrap();
        let projects = vec![make_project("api", "api")];
        let deps = infer_depends_on(&api, ws, &projects);
        assert!(deps.is_empty());
    }

    #[test]
    fn package_json_without_scripts_or_main_is_skipped() {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("data");
        fs::create_dir_all(&sub).unwrap();
        // package.json with no scripts/main/module — not a real project
        fs::write(
            sub.join("package.json"),
            r#"{"name":"data","version":"1.0"}"#,
        )
        .unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert!(projects.is_empty());
    }
    #[test]
    fn polyglot_root_languages_reflect_file_dominance() {
        // Regression (2026-06-03-project-languages-from-manifest-not-files): a
        // Python-dominant repo keeping a package.json for tooling was labeled
        // typescript/javascript with Python DROPPED entirely (python is not in the
        // package.json manifest langs). languages must reflect the actual file mix.
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name":"poly","scripts":{"build":"tsc"}}"#,
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        for n in 0..4 {
            fs::write(
                dir.path().join(format!("src/mod{n}.py")),
                "def f():\n    pass\n",
            )
            .unwrap();
        }
        fs::write(dir.path().join("src/util.ts"), "export const x = 1;\n").unwrap();

        let projects = discover_projects(dir.path(), 3, &[]);
        assert_eq!(
            projects.len(),
            1,
            "expected single root project: {:?}",
            projects
        );
        // Manifest detection unchanged — package.json is the only manifest present.
        assert_eq!(projects[0].manifest, Some("package.json".to_string()));
        let langs = &projects[0].languages;
        // Pre-fix: ["typescript","javascript"] — python dropped. Post-fix: python
        // leads (4 .py vs 1 .ts), with manifest langs unioned as fallback.
        assert_eq!(
            langs.first().map(String::as_str),
            Some("python"),
            "python should lead: {:?}",
            langs
        );
        assert!(
            langs.iter().any(|l| l == "python"),
            "python must be present (was dropped pre-fix): {:?}",
            langs
        );
        assert!(
            langs.iter().any(|l| l == "typescript"),
            "manifest lang retained as fallback: {:?}",
            langs
        );
        assert_eq!(dominant_language(dir.path()).as_deref(), Some("python"));
    }
}