git-prism 0.8.0

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

use std::path::Path;

/// Languages that support import-based scoping.
const SCOPED_LANGUAGES: &[&str] = &["rs", "py", "go", "ts", "tsx", "js", "jsx"];

/// Returns true if the file extension supports import-scoped caller filtering.
pub fn supports_import_scoping(ext: &str) -> bool {
    SCOPED_LANGUAGES.contains(&ext)
}

/// Repo-level context that affects module path inference and import matching.
///
/// Loaded once per `build_function_context()` call. Fields are optional because
/// a mixed-language repo may have some but not others (e.g., a Rust crate has
/// `Cargo.toml` but no `go.mod`).
#[derive(Debug, Clone, Default)]
pub struct RepoContext {
    /// Crate name from `Cargo.toml` `[package] name`. Used to match Rust
    /// integration tests and external-crate imports (`use my_crate::foo;`).
    ///
    /// Cargo package names can contain hyphens, but in Rust source they appear
    /// with underscores (e.g., `git-prism` → `git_prism`). This field stores the
    /// underscore form for direct comparison against import paths.
    pub rust_crate_name: Option<String>,
    /// Module path from `go.mod` `module <path>` directive. Used to match Go
    /// imports whose full path is `<go_module>/<directory>`.
    pub go_module: Option<String>,
}

impl RepoContext {
    /// Load repo context by reading `Cargo.toml` and `go.mod` from the repo root.
    ///
    /// Missing or malformed files produce `None` fields rather than errors —
    /// scoping degrades gracefully to matching based only on file path structure.
    pub fn load(repo_root: &Path) -> Self {
        Self {
            rust_crate_name: read_cargo_crate_name(repo_root),
            go_module: read_go_module_path(repo_root),
        }
    }
}

fn read_cargo_crate_name(repo_root: &Path) -> Option<String> {
    let content = std::fs::read_to_string(repo_root.join("Cargo.toml")).ok()?;
    // Naive TOML scan: find the first `name = "..."` line under [package].
    // This avoids pulling in a TOML parser dependency for one field.
    let mut in_package = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            in_package = trimmed == "[package]";
            continue;
        }
        if !in_package {
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("name")
            && let Some(eq_pos) = rest.find('=')
        {
            let value = rest[eq_pos + 1..].trim();
            let name = value.trim_matches('"').trim_matches('\'');
            if !name.is_empty() {
                // Rust source uses underscores; Cargo package names may have hyphens.
                return Some(name.replace('-', "_"));
            }
        }
    }
    None
}

fn read_go_module_path(repo_root: &Path) -> Option<String> {
    let content = std::fs::read_to_string(repo_root.join("go.mod")).ok()?;
    for line in content.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("module ") {
            let name = rest.trim().trim_matches('"');
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Infer the module path for a file, as it would appear in import statements.
///
/// Returns `None` if the language is unsupported for module path inference.
pub fn infer_module_path(file_path: &str, ext: &str, ctx: &RepoContext) -> Option<String> {
    match ext {
        "rs" => infer_rust_module(file_path),
        "py" => infer_python_module(file_path),
        "go" => infer_go_module(file_path, ctx),
        "ts" | "tsx" | "js" | "jsx" => infer_ts_module(file_path),
        _ => None,
    }
}

/// Check whether a file's import list references the given module path.
///
/// `importer_path` is the path of the file being scanned (the potential caller).
/// `importer_ext` is its extension, used to select the matching logic.
pub fn imports_reference_module(
    imports: &[String],
    module_path: &str,
    importer_path: &str,
    importer_ext: &str,
    ctx: &RepoContext,
) -> bool {
    match importer_ext {
        "rs" => rust_imports_reference(imports, module_path, importer_path, ctx),
        "py" => python_imports_reference(imports, module_path, importer_path),
        "go" => go_imports_reference(imports, module_path, ctx),
        "ts" | "tsx" | "js" | "jsx" => ts_imports_reference(imports, module_path, importer_path),
        _ => false,
    }
}

/// Check whether two file paths share the same parent directory.
pub fn same_directory(a: &str, b: &str) -> bool {
    let parent_a = Path::new(a).parent();
    let parent_b = Path::new(b).parent();
    match (parent_a, parent_b) {
        (Some(pa), Some(pb)) => pa == pb,
        _ => false,
    }
}

// --- Rust ---

/// Infer the Rust module path for a file.
///
/// `src/lib.rs` and `src/main.rs` are the crate root and produce `crate`.
/// `src/foo.rs` produces `crate::foo`. `src/foo/mod.rs` produces `crate::foo`.
fn infer_rust_module(file_path: &str) -> Option<String> {
    let path = file_path.strip_suffix(".rs")?;
    // Strip `src/` prefix (standard Cargo layout). Non-standard layouts fall
    // through and produce paths like `crate::crates::foo::bar` which won't
    // match imports but also won't cause false positives.
    let path = path.strip_prefix("src/").unwrap_or(path);
    // Crate root: `src/lib.rs` (library) or `src/main.rs` (binary)
    if path == "lib" || path == "main" {
        return Some("crate".to_string());
    }
    // Module files: `src/foo/mod.rs` → `crate::foo`
    let path = path.strip_suffix("/mod").unwrap_or(path);
    Some(format!("crate::{}", path.replace('/', "::")))
}

/// Strip `use ` or `pub use ` from the start of an import statement.
fn strip_use_prefix(imp: &str) -> &str {
    let trimmed = imp.trim();
    if let Some(rest) = trimmed.strip_prefix("pub use ") {
        rest
    } else if let Some(rest) = trimmed.strip_prefix("use ") {
        rest
    } else {
        trimmed
    }
}

fn rust_imports_reference(
    imports: &[String],
    module_path: &str,
    importer_path: &str,
    ctx: &RepoContext,
) -> bool {
    // module_path is like "crate::foo::bar" or "crate" for the crate root.
    let module_tail = module_path.strip_prefix("crate::").unwrap_or(module_path);
    let is_crate_root = module_path == "crate";

    // Compute the importer's own module to resolve `super::` and `self::`.
    let importer_module = infer_rust_module(importer_path);

    imports.iter().any(|imp| {
        let raw = strip_use_prefix(imp).trim_end_matches(';').trim();

        // `crate::foo::bar::Thing` — internal absolute path
        if let Some(path) = raw.strip_prefix("crate::") {
            if is_crate_root {
                // Anything under `crate::` references the crate root.
                return true;
            }
            return path == module_tail
                || path.starts_with(&format!("{module_tail}::"))
                || path.starts_with(&format!("{module_tail}::*"));
        }

        // External crate name form — used by integration tests under `tests/`
        // and by any file that prefers the extern-crate name over `crate::`.
        if let Some(crate_name) = ctx.rust_crate_name.as_deref() {
            let ext_prefix = format!("{crate_name}::");
            if raw == crate_name || raw.starts_with(&ext_prefix) {
                if is_crate_root {
                    return true;
                }
                let path = &raw[ext_prefix.len()..];
                return path == module_tail
                    || path.starts_with(&format!("{module_tail}::"))
                    || path.starts_with(&format!("{module_tail}::*"));
            }
        }

        // Relative imports: resolve against the importer's module path.
        // `use super::foo` from `crate::a::b` means `crate::a::foo`.
        // `use self::foo` from `crate::a::b` means `crate::a::b::foo`.
        if let Some(importer_mod) = importer_module.as_deref() {
            if let Some(rel) = raw.strip_prefix("super::")
                && let Some(resolved) = resolve_rust_super(importer_mod, rel)
            {
                return rust_path_matches(&resolved, module_path, module_tail);
            }
            if let Some(rel) = raw.strip_prefix("self::") {
                let resolved = if importer_mod == "crate" {
                    format!("crate::{rel}")
                } else {
                    format!("{importer_mod}::{rel}")
                };
                return rust_path_matches(&resolved, module_path, module_tail);
            }
        }

        false
    })
}

/// Resolve `super::tail` from an importer module path.
/// E.g., importer `crate::a::b::c`, tail `foo::Bar` → `crate::a::b::foo::Bar`.
fn resolve_rust_super(importer_module: &str, tail: &str) -> Option<String> {
    let parent = importer_module.rsplit_once("::").map(|(p, _)| p)?;
    if parent.is_empty() {
        return None;
    }
    Some(format!("{parent}::{tail}"))
}

/// Check if a resolved path references the changed module.
fn rust_path_matches(resolved: &str, module_path: &str, module_tail: &str) -> bool {
    if module_path == "crate" {
        return resolved == "crate" || resolved.starts_with("crate::");
    }
    let rtail = resolved.strip_prefix("crate::").unwrap_or(resolved);
    rtail == module_tail || rtail.starts_with(&format!("{module_tail}::"))
}

// --- Python ---

fn infer_python_module(file_path: &str) -> Option<String> {
    let path = file_path.strip_suffix(".py")?;
    let path = path.strip_suffix("/__init__").unwrap_or(path);
    Some(path.replace('/', "."))
}

/// Walk up `depth` levels from a dotted module path.
fn python_parent_module(module: &str, depth: usize) -> Option<String> {
    let parts: Vec<&str> = module.split('.').collect();
    if depth >= parts.len() {
        return None;
    }
    let remaining = parts.len() - depth;
    Some(parts[..remaining].join("."))
}

fn python_imports_reference(imports: &[String], module_path: &str, importer_path: &str) -> bool {
    let importer_module = infer_python_module(importer_path);

    imports.iter().any(|imp| {
        let imp = imp.trim();

        // --- `from X import Y` form ---
        if let Some(rest) = imp.strip_prefix("from ") {
            let mut parts = rest.splitn(2, " import ");
            let source = parts.next().unwrap_or("").trim();
            let imported_names = parts.next().unwrap_or("").trim();

            // Handle relative imports: `from . import x`, `from ..pkg import y`
            if source.starts_with('.') {
                let depth = source.chars().take_while(|c| *c == '.').count();
                let suffix = &source[depth..];
                if let Some(importer_mod) = importer_module.as_deref() {
                    let anchor = if suffix.is_empty() {
                        // `from . import x` resolves relative to importer's parent
                        python_parent_module(importer_mod, depth)
                    } else {
                        // `from .sub import x` resolves to parent + suffix
                        python_parent_module(importer_mod, depth).map(|p| {
                            if p.is_empty() {
                                suffix.to_string()
                            } else {
                                format!("{p}.{suffix}")
                            }
                        })
                    };
                    if let Some(resolved) = anchor
                        && python_module_matches(&resolved, imported_names, module_path)
                    {
                        return true;
                    }
                }
                return false;
            }

            // Absolute imports
            return python_module_matches(source, imported_names, module_path);
        }

        // --- `import X` or `import X.Y as Z` form ---
        if let Some(rest) = imp.strip_prefix("import ") {
            // Handle comma-separated: `import os, sys`
            for item in rest.split(',') {
                let item = item.trim();
                // Strip ` as alias` if present
                let module = item
                    .split_whitespace()
                    .next()
                    .unwrap_or("")
                    .trim_end_matches(',');
                if module == module_path
                    || module.starts_with(&format!("{module_path}."))
                    || module_path.starts_with(&format!("{module}."))
                {
                    return true;
                }
            }
            return false;
        }

        false
    })
}

/// Check if a `from X import Y` form references `module_path`.
///
/// Matches if:
/// - `X` == `module_path` (plain attribute import)
/// - `X.Y` == `module_path` for any `Y` in the imported names (submodule import)
/// - `X` starts with `module_path.` (subpackage of the changed module)
fn python_module_matches(source: &str, imported_names: &str, module_path: &str) -> bool {
    if source == module_path || source.starts_with(&format!("{module_path}.")) {
        return true;
    }
    // Parentheses and trailing commas can appear in multi-line imports.
    // cargo-mutants: skip -- equivalent under current pipeline. The chained
    // `.replace([')', '('], "")` strips parens regardless of trim_matches, and
    // the per-name `.trim()` below removes any whitespace these alternations
    // would have caught at the edges.
    let cleaned = imported_names
        .trim_matches(|c: char| c == '(' || c == ')' || c.is_whitespace())
        .replace([')', '('], "");
    for name in cleaned.split(',') {
        let name = name.trim();
        // Strip ` as alias`
        let name = name.split_whitespace().next().unwrap_or("");
        // cargo-mutants: skip -- equivalent. The candidate `format!("{source}.{name}")`
        // produced when this `continue` is bypassed (`name == ""` -> "src." or
        // `name == "*"` -> "src.*") cannot match a real dotted module path,
        // so the loop returns the same overall result either way.
        if name.is_empty() || name == "*" {
            continue;
        }
        let candidate = format!("{source}.{name}");
        if candidate == module_path {
            return true;
        }
    }
    false
}

// --- Go ---

fn infer_go_module(file_path: &str, ctx: &RepoContext) -> Option<String> {
    let parent = Path::new(file_path).parent()?;
    let dir = parent.to_str()?;
    if let Some(module) = ctx.go_module.as_deref() {
        if dir.is_empty() {
            return Some(module.to_string());
        }
        return Some(format!("{module}/{dir}"));
    }
    // No go.mod: fall back to bare directory path (caller matches by suffix).
    if dir.is_empty() {
        return Some(".".to_string());
    }
    Some(dir.to_string())
}

fn go_imports_reference(imports: &[String], module_path: &str, ctx: &RepoContext) -> bool {
    imports.iter().any(|imp| {
        if ctx.go_module.is_some() {
            // With go.mod, match full import paths exactly.
            imp == module_path
        } else {
            // Fallback: suffix match by directory name.
            imp == module_path || imp.ends_with(&format!("/{module_path}"))
        }
    })
}

// --- TypeScript / JavaScript ---

fn infer_ts_module(file_path: &str) -> Option<String> {
    // Strip extension for matching
    let path = file_path
        .strip_suffix(".ts")
        .or_else(|| file_path.strip_suffix(".tsx"))
        .or_else(|| file_path.strip_suffix(".js"))
        .or_else(|| file_path.strip_suffix(".jsx"))?;
    // Strip /index suffix
    let path = path.strip_suffix("/index").unwrap_or(path);
    Some(path.to_string())
}

fn ts_imports_reference(imports: &[String], module_path: &str, importer_path: &str) -> bool {
    let importer_dir = Path::new(importer_path)
        .parent()
        .and_then(|p| p.to_str())
        .unwrap_or("");

    imports.iter().any(|imp| {
        // Extract the module specifier from: import ... from 'specifier';
        let spec = match extract_ts_module_specifier(imp) {
            Some(s) => s,
            None => return false,
        };
        // Only handle relative imports (starts with . or ..)
        if !spec.starts_with('.') {
            return false;
        }
        // Resolve relative to importer's directory
        let resolved = resolve_relative_path(importer_dir, &spec);
        resolved == module_path
    })
}

fn extract_ts_module_specifier(import_stmt: &str) -> Option<String> {
    // Find the string between quotes after "from"
    let from_idx = import_stmt.find("from")?;
    let after_from = &import_stmt[from_idx + 4..];
    let quote_char = if after_from.contains('\'') { '\'' } else { '"' };
    let start = after_from.find(quote_char)? + 1;
    let rest = &after_from[start..];
    let end = rest.find(quote_char)?;
    Some(rest[..end].to_string())
}

fn resolve_relative_path(base_dir: &str, relative: &str) -> String {
    let mut parts: Vec<&str> = if base_dir.is_empty() {
        vec![]
    } else {
        base_dir.split('/').collect()
    };

    for segment in relative.split('/') {
        match segment {
            "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }

    parts.join("/")
}

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

    fn empty_ctx() -> RepoContext {
        RepoContext::default()
    }

    fn rust_ctx() -> RepoContext {
        RepoContext {
            rust_crate_name: Some("git_prism".to_string()),
            go_module: None,
        }
    }

    fn go_ctx() -> RepoContext {
        RepoContext {
            rust_crate_name: None,
            go_module: Some("example.com/foo".to_string()),
        }
    }

    // --- Rust module inference ---

    #[test]
    fn rust_module_from_file() {
        assert_eq!(
            infer_module_path("src/foo/bar.rs", "rs", &empty_ctx()).unwrap(),
            "crate::foo::bar"
        );
    }

    #[test]
    fn rust_module_from_mod_rs() {
        assert_eq!(
            infer_module_path("src/foo/mod.rs", "rs", &empty_ctx()).unwrap(),
            "crate::foo"
        );
    }

    #[test]
    fn rust_module_from_lib_is_crate_root() {
        assert_eq!(
            infer_module_path("src/lib.rs", "rs", &empty_ctx()).unwrap(),
            "crate"
        );
    }

    #[test]
    fn rust_module_from_main_is_crate_root() {
        assert_eq!(
            infer_module_path("src/main.rs", "rs", &empty_ctx()).unwrap(),
            "crate"
        );
    }

    // --- Rust import matching ---

    #[test]
    fn rust_import_matches_module() {
        let imports = vec!["use crate::foo::bar::Thing;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::foo::bar",
            "src/other.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_import_does_not_match_unrelated() {
        let imports = vec!["use crate::baz::Thing;".to_string()];
        assert!(!rust_imports_reference(
            &imports,
            "crate::foo::bar",
            "src/other.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_import_matches_crate_root() {
        let imports = vec!["use crate::foo;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate",
            "src/other.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_pub_use_is_matched() {
        let imports = vec!["pub use crate::foo::bar::Thing;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::foo::bar",
            "src/reexport.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_extern_crate_name_matches() {
        let imports = vec!["use git_prism::foo::bar::Thing;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::foo::bar",
            "tests/integration.rs",
            &rust_ctx()
        ));
    }

    #[test]
    fn rust_extern_crate_name_matches_crate_root() {
        let imports = vec!["use git_prism::compute;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate",
            "tests/integration.rs",
            &rust_ctx()
        ));
    }

    #[test]
    fn rust_super_resolves_against_importer() {
        // Importer is `crate::tools::context` (src/tools/context.rs).
        // `use super::manifest` → `crate::tools::manifest`.
        let imports = vec!["use super::manifest::build;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::tools::manifest",
            "src/tools/context.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_super_does_not_match_unrelated_sibling() {
        // Importer is `crate::tools::context` but the changed module is
        // `crate::git::reader` — super::manifest does NOT reference it.
        let imports = vec!["use super::manifest::build;".to_string()];
        assert!(!rust_imports_reference(
            &imports,
            "crate::git::reader",
            "src/tools/context.rs",
            &empty_ctx()
        ));
    }

    #[test]
    fn rust_self_resolves_against_importer() {
        // Importer is `crate::tools::context`. `use self::helper` →
        // `crate::tools::context::helper` which is under the importer itself;
        // should match if the importer IS the changed file.
        let imports = vec!["use self::helper;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::tools::context",
            "src/tools/context.rs",
            &empty_ctx()
        ));
    }

    // --- Python module inference ---

    #[test]
    fn python_module_from_file() {
        assert_eq!(
            infer_module_path("src/validation.py", "py", &empty_ctx()).unwrap(),
            "src.validation"
        );
    }

    #[test]
    fn python_module_from_init() {
        assert_eq!(
            infer_module_path("utils/__init__.py", "py", &empty_ctx()).unwrap(),
            "utils"
        );
    }

    #[test]
    fn python_module_from_top_level() {
        assert_eq!(
            infer_module_path("lib.py", "py", &empty_ctx()).unwrap(),
            "lib"
        );
    }

    // --- Python import matching ---

    #[test]
    fn python_from_import_matches() {
        let imports = vec!["from lib import compute".to_string()];
        assert!(python_imports_reference(&imports, "lib", "importer.py"));
    }

    #[test]
    fn python_import_matches() {
        let imports = vec!["import lib".to_string()];
        assert!(python_imports_reference(&imports, "lib", "importer.py"));
    }

    #[test]
    fn python_import_no_match() {
        let imports = vec!["from other import compute".to_string()];
        assert!(!python_imports_reference(&imports, "lib", "importer.py"));
    }

    #[test]
    fn python_submodule_import_matches_trailing_segment() {
        // `from lib import compute` where the changed file is lib/compute.py
        // (module `lib.compute`). The imported NAME is the submodule.
        let imports = vec!["from lib import compute".to_string()];
        assert!(python_imports_reference(
            &imports,
            "lib.compute",
            "importer.py"
        ));
    }

    #[test]
    fn python_dotted_from_import_matches() {
        // `from pkg.sub import foo` should match changed module `pkg.sub.foo`.
        let imports = vec!["from pkg.sub import foo".to_string()];
        assert!(python_imports_reference(
            &imports,
            "pkg.sub.foo",
            "importer.py"
        ));
    }

    #[test]
    fn python_relative_import_resolves_single_dot() {
        // Importer is `pkg.sub.module`, `from . import sibling` →
        // references `pkg.sub.sibling`.
        let imports = vec!["from . import sibling".to_string()];
        assert!(python_imports_reference(
            &imports,
            "pkg.sub.sibling",
            "pkg/sub/module.py"
        ));
    }

    #[test]
    fn python_relative_import_resolves_dotted_sibling() {
        // `from .sibling import x` from `pkg.sub.module` → `pkg.sub.sibling`.
        let imports = vec!["from .sibling import x".to_string()];
        assert!(python_imports_reference(
            &imports,
            "pkg.sub.sibling",
            "pkg/sub/module.py"
        ));
    }

    #[test]
    fn python_relative_import_resolves_parent() {
        // `from .. import sibling` from `pkg.sub.module` → `pkg.sibling`.
        let imports = vec!["from .. import sibling".to_string()];
        assert!(python_imports_reference(
            &imports,
            "pkg.sibling",
            "pkg/sub/module.py"
        ));
    }

    #[test]
    fn python_relative_import_does_not_match_unrelated() {
        let imports = vec!["from . import sibling".to_string()];
        assert!(!python_imports_reference(
            &imports,
            "other.module",
            "pkg/sub/module.py"
        ));
    }

    // --- Go module inference ---

    #[test]
    fn go_module_from_file_with_go_mod() {
        assert_eq!(
            infer_module_path("internal/parser/parser.go", "go", &go_ctx()).unwrap(),
            "example.com/foo/internal/parser"
        );
    }

    #[test]
    fn go_module_from_file_without_go_mod() {
        assert_eq!(
            infer_module_path("lib/lib.go", "go", &empty_ctx()).unwrap(),
            "lib"
        );
    }

    // --- Go import matching ---

    #[test]
    fn go_import_matches_full_path_with_go_mod() {
        let imports = vec!["example.com/foo/internal/parser".to_string()];
        assert!(go_imports_reference(
            &imports,
            "example.com/foo/internal/parser",
            &go_ctx()
        ));
    }

    #[test]
    fn go_unrelated_external_does_not_match_with_go_mod() {
        // With go.mod set, matching is exact — unrelated external repos that
        // happen to suffix-match the directory should NOT be included.
        let imports = vec!["github.com/unrelated/parser".to_string()];
        assert!(!go_imports_reference(
            &imports,
            "example.com/foo/internal/parser",
            &go_ctx()
        ));
    }

    #[test]
    fn go_import_suffix_matches_without_go_mod() {
        let imports = vec!["example/lib".to_string()];
        assert!(go_imports_reference(&imports, "lib", &empty_ctx()));
    }

    // --- TypeScript module inference ---

    #[test]
    fn ts_module_from_file() {
        assert_eq!(
            infer_module_path("lib.ts", "ts", &empty_ctx()).unwrap(),
            "lib"
        );
    }

    #[test]
    fn ts_module_from_nested() {
        assert_eq!(
            infer_module_path("src/utils/helper.ts", "ts", &empty_ctx()).unwrap(),
            "src/utils/helper"
        );
    }

    #[test]
    fn ts_module_from_index() {
        assert_eq!(
            infer_module_path("src/utils/index.ts", "ts", &empty_ctx()).unwrap(),
            "src/utils"
        );
    }

    // --- TypeScript import matching ---

    #[test]
    fn ts_relative_import_matches() {
        let imports = vec!["import { compute } from './lib';".to_string()];
        assert!(ts_imports_reference(&imports, "lib", "importer.ts"));
    }

    #[test]
    fn ts_relative_import_no_match() {
        let imports = vec!["import { compute } from './other';".to_string()];
        assert!(!ts_imports_reference(&imports, "lib", "importer.ts"));
    }

    #[test]
    fn ts_bare_import_never_matches() {
        let imports = vec!["import React from 'react';".to_string()];
        assert!(!ts_imports_reference(&imports, "lib", "importer.ts"));
    }

    #[test]
    fn ts_parent_dir_import_resolves() {
        let imports = vec!["import { x } from '../lib';".to_string()];
        assert!(ts_imports_reference(
            &imports,
            "src/lib",
            "src/handlers/api.ts"
        ));
    }

    // --- Module specifier extraction ---

    #[test]
    fn extracts_single_quote_specifier() {
        assert_eq!(
            extract_ts_module_specifier("import { x } from './lib';"),
            Some("./lib".to_string())
        );
    }

    #[test]
    fn extracts_double_quote_specifier() {
        assert_eq!(
            extract_ts_module_specifier("import { x } from \"./lib\";"),
            Some("./lib".to_string())
        );
    }

    // --- Same directory ---

    #[test]
    fn same_directory_detects_match() {
        assert!(same_directory("src/lib.rs", "src/main.rs"));
    }

    #[test]
    fn same_directory_detects_mismatch() {
        assert!(!same_directory("src/lib.rs", "tests/test.rs"));
    }

    // --- supports_import_scoping ---

    #[test]
    fn supported_languages_return_true() {
        for ext in &["rs", "py", "go", "ts", "tsx", "js", "jsx"] {
            assert!(supports_import_scoping(ext), "expected true for {ext}");
        }
    }

    #[test]
    fn unsupported_languages_return_false() {
        for ext in &["rb", "c", "java", "php", "cs", "swift", "kt"] {
            assert!(!supports_import_scoping(ext), "expected false for {ext}");
        }
    }

    // --- RepoContext loading ---

    #[test]
    fn repo_context_reads_cargo_crate_name() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let ctx = RepoContext::load(dir.path());
        // Hyphens become underscores.
        assert_eq!(ctx.rust_crate_name.as_deref(), Some("my_crate"));
    }

    #[test]
    fn repo_context_handles_missing_cargo_toml() {
        let dir = tempfile::TempDir::new().unwrap();
        let ctx = RepoContext::load(dir.path());
        assert!(ctx.rust_crate_name.is_none());
    }

    #[test]
    fn repo_context_reads_go_module_path() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("go.mod"),
            "module example.com/foo\n\ngo 1.21\n",
        )
        .unwrap();
        let ctx = RepoContext::load(dir.path());
        assert_eq!(ctx.go_module.as_deref(), Some("example.com/foo"));
    }

    #[test]
    fn repo_context_only_reads_package_name_not_dependencies() {
        // A [dependencies] section with name = "..." must not be mistaken
        // for the package name.
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"real-crate\"\n\n[dependencies]\nserde = \"1.0\"\n",
        )
        .unwrap();
        let ctx = RepoContext::load(dir.path());
        assert_eq!(ctx.rust_crate_name.as_deref(), Some("real_crate"));
    }

    // --- imports_reference_module dispatcher ---
    //
    // Each language extension must route to its own matcher. The mutants below
    // delete individual match arms from the dispatcher (or replace its entire
    // body with `true`); each test asserts a positive match for one extension
    // PLUS a negative for an unsupported extension, so a deleted arm or a
    // blanket `true` falls back to the catch-all `false` and the test fails.

    // Kill mutant: line 115 replace imports_reference_module -> bool with true.
    // An unsupported extension must return false; if the body is replaced with
    // `true` this assertion fires.
    #[test]
    fn dispatcher_returns_false_for_unsupported_extension() {
        let imports = vec!["use crate::foo;".to_string()];
        assert!(!imports_reference_module(
            &imports,
            "crate::foo",
            "src/x.rb",
            "rb",
            &empty_ctx()
        ));
    }

    // Kill mutant: line 117 delete match arm "py".
    // If the `"py"` arm is deleted, the dispatcher falls through to `_ => false`
    // and a real Python import is missed.
    #[test]
    fn dispatcher_routes_py_extension_to_python_matcher() {
        let imports = vec!["from lib import compute".to_string()];
        assert!(imports_reference_module(
            &imports,
            "lib",
            "importer.py",
            "py",
            &empty_ctx()
        ));
    }

    // Kill mutant: line 118 delete match arm "go".
    #[test]
    fn dispatcher_routes_go_extension_to_go_matcher() {
        let imports = vec!["example.com/foo/internal/parser".to_string()];
        assert!(imports_reference_module(
            &imports,
            "example.com/foo/internal/parser",
            "internal/caller/caller.go",
            "go",
            &go_ctx()
        ));
    }

    // Kill mutant: line 119 delete match arm "ts" | "tsx" | "js" | "jsx".
    // Each of the four extensions in the alternation must reach the TS matcher.
    // Listing them all defends against future single-extension splits as well
    // as the reported full-arm deletion.
    #[test]
    fn it_dispatches_ts_extension_to_typescript_matcher() {
        let imports = vec!["import { x } from './lib';".to_string()];
        assert!(imports_reference_module(
            &imports,
            "lib",
            "importer.ts",
            "ts",
            &empty_ctx()
        ));
    }

    #[test]
    fn it_dispatches_tsx_extension_to_typescript_matcher() {
        let imports = vec!["import { x } from './lib';".to_string()];
        assert!(imports_reference_module(
            &imports,
            "lib",
            "importer.tsx",
            "tsx",
            &empty_ctx()
        ));
    }

    #[test]
    fn it_dispatches_js_extension_to_typescript_matcher() {
        let imports = vec!["import { x } from './lib';".to_string()];
        assert!(imports_reference_module(
            &imports,
            "lib",
            "importer.js",
            "js",
            &empty_ctx()
        ));
    }

    #[test]
    fn it_dispatches_jsx_extension_to_typescript_matcher() {
        let imports = vec!["import { x } from './lib';".to_string()];
        assert!(imports_reference_module(
            &imports,
            "lib",
            "importer.jsx",
            "jsx",
            &empty_ctx()
        ));
    }

    // --- rust_imports_reference (line 198, 203) ---

    // Kill mutant: line 198 replace == with != in rust_imports_reference
    // (`raw == crate_name`). The bare `use git_prism;` form has no `::` segment,
    // so the only way to recognize it as referencing the crate root is the
    // direct equality check — `starts_with(ext_prefix)` would NOT match because
    // `ext_prefix` is `"git_prism::"`.
    #[test]
    fn rust_bare_extern_crate_name_matches_crate_root() {
        let imports = vec!["use git_prism;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate",
            "tests/integration.rs",
            &rust_ctx()
        ));
    }

    // Kill mutant: line 203 replace == with != in rust_imports_reference
    // (`path == module_tail`). The import `use git_prism::foo::bar;` strips the
    // crate prefix to leave `path = "foo::bar"`, which equals `module_tail`
    // exactly. Without the `==` branch, the matcher would only catch
    // `starts_with("foo::bar::")` and miss the bare-equal case.
    #[test]
    fn rust_extern_crate_path_equals_module_tail() {
        let imports = vec!["use git_prism::foo::bar;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate::foo::bar",
            "tests/integration.rs",
            &rust_ctx()
        ));
    }

    // --- rust_path_matches (line 245) ---

    // Kill mutants: line 245:25 replace == with != AND line 245:36 replace || with &&.
    //
    // When `module_path == "crate"` the function should match any path under
    // `crate::`. With `!=`, the if-branch is skipped for `module_path == "crate"`
    // and the function falls through to the tail logic which never matches.
    // With `&&` (resolved == "crate" && resolved.starts_with("crate::")), both
    // operands cannot be true simultaneously, so the branch always returns false.
    //
    // Setup: importer at `src/foo.rs` (module `crate::foo`), `use super::bar;`
    // resolves to `crate::bar`. Asking whether that import references the crate
    // root (`module_path = "crate"`) must return true.
    #[test]
    fn rust_super_import_matches_crate_root() {
        let imports = vec!["use super::bar;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate",
            "src/foo.rs",
            &empty_ctx()
        ));
    }

    // Triangulation for line 245:36 || with &&: a `self::` import where the
    // importer IS the crate root (`src/lib.rs`). Resolved becomes
    // `crate::helper`, module_path is `crate`. The right operand of the OR
    // (`resolved.starts_with("crate::")`) is the deciding factor; with `&&`
    // the branch returns false because `resolved != "crate"`.
    #[test]
    fn rust_self_import_from_lib_root_matches_crate_root() {
        let imports = vec!["use self::helper;".to_string()];
        assert!(rust_imports_reference(
            &imports,
            "crate",
            "src/lib.rs",
            &empty_ctx()
        ));
    }

    // --- python_imports_reference (line 325) ---

    // Kill mutant: line 325 replace || with && in python_imports_reference
    // (the `import X` form, third operand
    //  `module_path.starts_with(&format!("{module}."))`).
    //
    // `import lib` referencing module `lib.compute` requires the third operand
    // (parent-module match): `"lib.compute".starts_with("lib.")` is true while
    // `module == module_path` and `module.starts_with("lib.compute.")` are
    // both false. Replacing this `||` with `&&` makes the conjunction false
    // because the first two operands are false.
    #[test]
    fn python_bare_import_matches_submodule_changed_path() {
        let imports = vec!["import lib".to_string()];
        assert!(python_imports_reference(
            &imports,
            "lib.compute",
            "importer.py"
        ));
    }

    // --- python_module_matches (lines 349, 355) ---
    //
    // The mutants on line 349 (`||` -> `&&` in the `trim_matches` callback's
    // paren / whitespace alternation) and line 355 (`name.is_empty() || name
    // == "*"`) are equivalent under the current implementation: the chained
    // `.replace([')', '('], "")` and per-name `.trim()` make the `trim_matches`
    // outcome irrelevant, and the only candidates produced when the `*`/empty
    // continue is skipped are `format!("{source}.*")` or `format!("{source}.")`
    // which can never match a real dotted module path. We document this in
    // skip-annotations on the function rather than writing artificial-looking
    // tests that assert against impossible inputs.

    // --- go_imports_reference (line 391) ---

    // Kill mutant: line 391 replace == with != in go_imports_reference (the
    // no-go.mod fallback `imp == module_path`). Without go.mod, an exact
    // single-segment match (`imports = ["lib"]`, `module_path = "lib"`) is the
    // only way the equality path can fire — `ends_with("/lib")` is false for a
    // string that has no slash at all.
    #[test]
    fn go_bare_import_exact_match_without_go_mod() {
        let imports = vec!["lib".to_string()];
        assert!(go_imports_reference(&imports, "lib", &empty_ctx()));
    }

    // --- extract_ts_module_specifier (line 435) ---

    // Kill mutant: line 435 replace + with - in extract_ts_module_specifier
    // (`&import_stmt[from_idx + 4..]`). The `+ 4` skips past the literal
    // `from ` keyword so the subsequent quote-search lands on the module
    // specifier's quotes. `- 4` slices from before `from`, picking up any
    // earlier quote in the statement.
    //
    // A destructured default value `{ x = 'default' }` introduces single
    // quotes BEFORE `from`. With `+ 4` the function correctly finds `./lib`;
    // with `- 4` the search anchors on the `'default'` quotes and returns
    // `default` instead.
    #[test]
    fn extract_ts_specifier_ignores_quotes_before_from_keyword() {
        let stmt = "import { x = 'default' } from './lib';";
        assert_eq!(extract_ts_module_specifier(stmt), Some("./lib".to_string()));
    }
}