lean-ctx-server 3.12.13

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
use super::{GRAPH_SOURCE_EXTS, open_graph};
use crate::tools::graph_meta::{graph_summary, project_meta};
use crate::tools::output_format::OutputFormat;
use lean_ctx::core::graph_index::rust_modules;
use lean_ctx::core::property_graph::{CodeGraph, Edge, EdgeKind, Node};
use lean_ctx::core::tokens::count_tokens;
use lean_ctx::core::type_ref_edges::{DefIndex, ExtMethodIndex};
use lean_ctx_ext::core::git_util::{git_dirty, git_out};
use serde_json::json;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::Path;
use std::process::Stdio;

fn walk_supported_sources(root_path: &Path) -> (Vec<String>, Vec<(String, String, String)>) {
    let walker = ignore::WalkBuilder::new(root_path)
        .hidden(true)
        .git_ignore(true)
        .require_git(false)
        .filter_entry(lean_ctx::core::walk_filter::keep_entry)
        .build();

    let mut file_paths: Vec<String> = Vec::new();
    let mut file_contents: Vec<(String, String, String)> = Vec::new();
    let root = root_path.to_string_lossy().into_owned();
    // No total budget beyond the reader's per-file limit: a build covers the
    // project, as before.
    let mut remaining = usize::MAX;

    for entry in walker.flatten() {
        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
            continue;
        }

        let path = entry.path();
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

        if !GRAPH_SOURCE_EXTS.contains(&ext) {
            continue;
        }

        // Canonical `/` separators: graph node keys must be platform-stable
        // so queries like `impact_analysis("Models/Engine.cs")` match the
        // same node on Windows (output determinism, #498).
        let rel_path = path
            .strip_prefix(root_path)
            .unwrap_or(path)
            .to_string_lossy()
            .replace('\\', "/");

        // Secret-like paths never enter the persisted property graph, same
        // rule as the BM25 walk (GHSA-rxv5-4c3x-g4q6 A).
        if lean_ctx::core::io_boundary::is_secret_like(Path::new(&rel_path)).is_some() {
            continue;
        }

        file_paths.push(rel_path.clone());

        // The property graph is a persisted derived store: symbols, edges and
        // content hashes are built from the ADMITTED text of a source whose
        // ORIGINAL may be kept (G01), read through the common rooted reader.
        // A source that is withheld, restricted or incompletely decoded keeps
        // its path as a file node above and contributes nothing else.
        let read = crate::tools::admitted_sources::read(
            &path.to_string_lossy(),
            &root,
            "ctx_impact",
            &mut remaining,
        );
        if let Some(content) = read.storable() {
            file_contents.push((rel_path, content.to_owned(), ext.to_string()));
        }
    }

    file_paths.sort();
    file_paths.dedup();
    file_contents.sort_by(|a, b| a.0.cmp(&b.0));
    (file_paths, file_contents)
}

/// Per-file analysis borrowed from the walked contents: (path, content, ext, analysis).
type AnalyzedFile<'a> = (
    &'a str,
    &'a str,
    &'a str,
    lean_ctx::core::deep_queries::DeepAnalysis,
);

/// Analyze every walked source file once (parallel) and build the global
/// symbol-definition index and the extension-method index. Shared by full
/// build and incremental update on both builder paths.
fn analyze_all(
    file_contents: &[(String, String, String)],
) -> (Vec<AnalyzedFile<'_>>, DefIndex, ExtMethodIndex) {
    use rayon::prelude::*;
    let per_file: Vec<AnalyzedFile<'_>> = file_contents
        .par_iter()
        .map(|(p, c, e)| {
            (
                p.as_str(),
                c.as_str(),
                e.as_str(),
                lean_ctx::core::deep_queries::analyze(c.as_str(), e.as_str()),
            )
        })
        .collect();

    // Single source of truth for the #398 indexes (shared with the graph_index
    // mirror so both builders resolve identical type-usage edges).
    let def_index = lean_ctx::core::type_ref_edges::build_def_index(
        per_file.iter().map(|(p, _, _, a)| (*p, a)),
    );
    let ext_method_index = lean_ctx::core::type_ref_edges::build_ext_method_index(
        per_file.iter().map(|(p, _, _, a)| (*p, a)),
    );

    (per_file, def_index, ext_method_index)
}

/// Structurally resolved Rust edges (gh-2269) of the walked sources, keyed by
/// source file. Built with the same resolver and the same edge conversion
/// ([`rust_modules::RustModuleGraph::index_edges`]) as the `graph_index`
/// scan, so `ctx_graph impact` answers identically after `ctx_impact build`
/// or `update` and after `ctx_graph build`.
#[derive(Default)]
struct RustEdges {
    /// `.rs` files placed in a crate's module tree.
    mapped: HashSet<String>,
    /// Source file -> (import targets, `mod` child files), each sorted.
    by_file: HashMap<String, (Vec<String>, Vec<String>)>,
}

impl RustEdges {
    /// Resolve every walked `.rs` source of the workspace. Only admitted,
    /// storable sources take part: the resolver would read any other file
    /// from disk, so a withheld source stays outside the module tree (its
    /// dependents are then reported as unknown, never as none).
    fn resolve(root_path: &Path, file_contents: &[(String, String, String)]) -> Self {
        let contents: HashMap<String, String> = file_contents
            .iter()
            .filter(|(_, _, ext)| ext == "rs")
            .map(|(path, content, _)| (path.clone(), content.clone()))
            .collect();
        if contents.is_empty() {
            return Self::default();
        }
        let mut files: Vec<String> = contents.keys().cloned().collect();
        files.sort();
        let graph = rust_modules::resolve_workspace(root_path, &files, &contents);
        let mut by_file: HashMap<String, (Vec<String>, Vec<String>)> = HashMap::new();
        for edge in graph.index_edges() {
            let entry = by_file.entry(edge.from).or_default();
            match edge.kind.as_str() {
                rust_modules::IMPORT_EDGE_KIND => entry.0.push(edge.to),
                rust_modules::MODULE_EDGE_KIND => entry.1.push(edge.to),
                _ => {}
            }
        }
        Self {
            mapped: graph.mapped,
            by_file,
        }
    }
}

/// The files `rel_path` imports, and the child files its `mod` declarations
/// name. A Rust file in a crate's module tree takes its structural
/// resolution; every other file the per-file import resolver, as before.
fn file_dependencies(
    rel_path: &str,
    ext: &str,
    analysis: &lean_ctx::core::deep_queries::DeepAnalysis,
    resolver_ctx: &lean_ctx::core::import_resolver::ResolverContext,
    rust: &RustEdges,
) -> (Vec<String>, Vec<String>) {
    if rust.mapped.contains(rel_path) {
        return rust.by_file.get(rel_path).cloned().unwrap_or_default();
    }
    let resolved = lean_ctx::core::import_resolver::resolve_imports(
        &analysis.imports,
        rel_path,
        ext,
        resolver_ctx,
    );
    let mut targets: Vec<String> = resolved
        .into_iter()
        .filter(|imp| !imp.is_external)
        .filter_map(|imp| imp.resolved_path)
        .filter(|p| p != rel_path)
        .collect();
    targets.sort();
    targets.dedup();
    (targets, Vec::new())
}

/// Insert one `kind` edge from `file_node_id` to each of `targets`; returns
/// (target nodes, edges) written.
fn insert_file_edges(
    graph: &CodeGraph,
    file_node_id: i64,
    targets: &[String],
    kind: &EdgeKind,
) -> (usize, usize) {
    let (mut nodes, mut edges) = (0usize, 0usize);
    for target_path in targets {
        let Ok(target_id) = graph.upsert_node(&Node::file(target_path)) else {
            continue;
        };
        nodes += 1;
        let _ = graph.upsert_edge(&Edge::new(file_node_id, target_id, kind.clone()));
        edges += 1;
    }
    (nodes, edges)
}

/// Insert `TypeRef` edges for every resolved type usage:
/// - file -> defining file (drives `impact_analysis` blast radius; the
///   `graph_index` mirror produces the identical file edge via
///   [`lean_ctx::core::type_ref_edges::cross_file_type_edges`] so a reindex cannot
///   drop it — GH #398),
/// - file -> defined type symbol (clears the symbol from `dead_code`, whose
///   query already exempts `type_ref` targets; symbol-level edges live only on
///   this builder path).
fn insert_type_ref_edges(
    graph: &CodeGraph,
    file_node_id: i64,
    rel_path: &str,
    type_uses: &[lean_ctx::core::deep_queries::TypeUse],
    def_index: &DefIndex,
    scope: &lean_ctx::core::type_ref_edges::ResolveScope,
) -> usize {
    let mut added = 0usize;
    for (target_file, type_name, line_start, line_end) in
        lean_ctx::core::type_ref_edges::type_ref_targets(
            def_index,
            type_uses,
            rel_path,
            &scope.visible_ns,
            scope.allow_global_fallback,
        )
    {
        let Ok(target_id) = graph.upsert_node(&Node::file(&target_file)) else {
            continue;
        };
        let _ = graph.upsert_edge(&Edge::new(file_node_id, target_id, EdgeKind::TypeRef));
        added += 1;

        let sym_node = Node::symbol(
            &type_name,
            &target_file,
            lean_ctx::core::property_graph::NodeKind::Symbol,
        )
        .with_lines(line_start, line_end);
        if let Ok(sym_id) = graph.upsert_node(&sym_node) {
            let _ = graph.upsert_edge(&Edge::new(file_node_id, sym_id, EdgeKind::TypeRef));
            added += 1;
        }
    }
    added
}

/// Insert `TypeRef` edges for resolved C# extension-method calls: a
/// `value.Foo()` call links the consuming file to the file that defines the
/// `this`-parameter method `Foo`. Mirrors `insert_type_ref_edges` (file +
/// symbol edge). Resolution is by method name alone, so the same self-filter
/// and a failsafe cap keep it bounded; the index only ever holds genuine
/// extension methods, which keeps the name space small and distinct.
fn insert_ext_method_edges(
    graph: &CodeGraph,
    file_node_id: i64,
    rel_path: &str,
    calls: &[lean_ctx::core::deep_queries::CallSite],
    ext_method_index: &ExtMethodIndex,
) -> usize {
    let mut added = 0usize;
    for (target_file, method_name, line_start, line_end) in
        lean_ctx::core::type_ref_edges::ext_method_targets(ext_method_index, calls, rel_path)
    {
        let Ok(target_id) = graph.upsert_node(&Node::file(&target_file)) else {
            continue;
        };
        let _ = graph.upsert_edge(&Edge::new(file_node_id, target_id, EdgeKind::TypeRef));
        added += 1;

        let sym_node = Node::symbol(
            &method_name,
            &target_file,
            lean_ctx::core::property_graph::NodeKind::Symbol,
        )
        .with_lines(line_start, line_end);
        if let Ok(sym_id) = graph.upsert_node(&sym_node) {
            let _ = graph.upsert_edge(&Edge::new(file_node_id, sym_id, EdgeKind::TypeRef));
            added += 1;
        }
    }
    added
}

fn normalize_git_path(line: &str) -> String {
    line.trim().replace('\\', "/")
}

fn git_diff_name_only_lines(project_root: &Path, args: &[&str]) -> Option<Vec<String>> {
    let out = std::process::Command::new("git")
        .args(args)
        .current_dir(project_root)
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    Some(
        s.lines()
            .map(normalize_git_path)
            .filter(|l| !l.is_empty())
            .collect(),
    )
}

fn collect_git_changed_paths(project_root: &Path, last_git_head: &str) -> Option<BTreeSet<String>> {
    let range = format!("{last_git_head}..HEAD");
    let mut set: BTreeSet<String> = BTreeSet::new();
    for line in git_diff_name_only_lines(project_root, &["diff", "--name-only", &range])? {
        set.insert(line);
    }
    for line in git_diff_name_only_lines(project_root, &["diff", "--name-only"])? {
        set.insert(line);
    }
    for line in git_diff_name_only_lines(project_root, &["diff", "--name-only", "--cached"])? {
        set.insert(line);
    }
    Some(set)
}

#[cfg(feature = "embeddings")]
fn enclosing_symbol_name_for_line(
    types: &[lean_ctx::core::deep_queries::TypeDef],
    line: usize,
) -> String {
    let mut best: Option<(&lean_ctx::core::deep_queries::TypeDef, usize)> = None;
    for t in types {
        if line >= t.line && line <= t.end_line {
            let span = t.end_line.saturating_sub(t.line);
            match best {
                None => best = Some((t, span)),
                Some((_, prev_span)) => {
                    if span < prev_span {
                        best = Some((t, span));
                    }
                }
            }
        }
    }
    best.map_or_else(|| "<module>".to_string(), |(t, _)| t.name.clone())
}

#[cfg(feature = "embeddings")]
/// Binds a callee name to its definition site in the caller's scope — the
/// same ladder as the call graph (`call_graph::rank_callee_def_file`): the
/// caller's own file, then exactly one imported file, then exactly one file
/// project-wide. Ambiguous names yield `None`; the previous fallback picked
/// the alphabetically first file and invented edges.
#[cfg_attr(not(feature = "embeddings"), allow(dead_code))]
fn resolve_call_callee_site(
    def_index: &DefIndex,
    callee: &str,
    caller_file: &str,
    imported: &[String],
) -> Option<(
    String,
    usize,
    usize,
    lean_ctx::core::semantic::EvidenceGrade,
)> {
    use lean_ctx::core::semantic::EvidenceGrade;
    let sites = def_index.get(callee)?;
    // The single definition of `callee` in `file`; several (other namespace,
    // other `impl` block) cannot be told apart without type information.
    let first_in = |file: &str| {
        let mut in_file = sites.iter().filter(|(f, ..)| f == file);
        let (f, _, ls, le) = in_file.next()?;
        in_file.next().is_none().then(|| (f.clone(), *ls, *le))
    };
    let mut files: Vec<&str> = sites.iter().map(|(f, ..)| f.as_str()).collect();
    files.sort_unstable();
    files.dedup();

    if files.contains(&caller_file) {
        // Defined in the caller's own file: bind it there, or — when that
        // file defines it several times — refuse rather than look elsewhere.
        let (f, ls, le) = first_in(caller_file)?;
        return Some((f, ls, le, EvidenceGrade::ResolvedStructural));
    }
    let in_scope: Vec<&str> = files
        .iter()
        .copied()
        .filter(|f| imported.iter().any(|i| i == f))
        .collect();
    if let [only] = in_scope.as_slice() {
        let (f, ls, le) = first_in(only)?;
        return Some((f, ls, le, EvidenceGrade::ResolvedStructural));
    }
    if let [only] = files.as_slice() {
        let (f, ls, le) = first_in(only)?;
        return Some((f, ls, le, EvidenceGrade::HeuristicStructural));
    }
    None
}

/// The workspace-wide indexes every per-file indexer reads.
#[derive(Clone, Copy)]
struct BuildIndexes<'a> {
    resolver_ctx: &'a lean_ctx::core::import_resolver::ResolverContext,
    rust: &'a RustEdges,
    def_index: &'a DefIndex,
    ext_method_index: &'a ExtMethodIndex,
}

/// Record `rel_path` in the file catalog. Every build path writes it: a
/// property graph without catalog rows is never served (`graph_provider`
/// requires them), so `ctx_graph` would silently fall back to a rebuild.
fn upsert_catalog_entry(
    graph: &CodeGraph,
    rel_path: &str,
    content: &str,
    ext: &str,
    analysis: &lean_ctx::core::deep_queries::DeepAnalysis,
) {
    let exports: Vec<String> = analysis
        .types
        .iter()
        .filter(|t| t.is_exported)
        .map(|t| t.name.clone())
        .collect();
    let line_count = content.lines().count();
    let token_count = lean_ctx::core::tokens::count_tokens(content);
    let hash = {
        use md5::{Digest, Md5};
        let mut h = Md5::new();
        h.update(content.as_bytes());
        lean_ctx::core::agent_identity::hex_encode(&h.finalize())
    };
    let _ = graph.upsert_file_catalog(&lean_ctx::core::property_graph::FileCatalogEntry {
        path: rel_path.to_string(),
        hash,
        language: ext.to_string(),
        line_count,
        token_count,
        exports,
        summary: String::new(),
    });
}

#[cfg(feature = "embeddings")]
fn index_graph_file_embeddings(
    graph: &CodeGraph,
    rel_path: &str,
    content: &str,
    ext: &str,
    analysis: &lean_ctx::core::deep_queries::DeepAnalysis,
    idx: &BuildIndexes<'_>,
) -> (usize, usize) {
    let BuildIndexes {
        resolver_ctx,
        rust,
        def_index,
        ext_method_index,
    } = *idx;
    let mut total_nodes = 0usize;
    let mut total_edges = 0usize;

    let Ok(file_node_id) = graph.upsert_node(&Node::file(rel_path)) else {
        return (0, 0);
    };
    total_nodes += 1;

    for type_def in &analysis.types {
        let sym_node = Node::symbol(
            &type_def.name,
            rel_path,
            lean_ctx::core::property_graph::NodeKind::Symbol,
        )
        .with_lines(type_def.line, type_def.end_line);
        if let Ok(sym_id) = graph.upsert_node(&sym_node) {
            total_nodes += 1;
            let _ = graph.upsert_edge(&Edge::new(file_node_id, sym_id, EdgeKind::Defines));
            total_edges += 1;
            if type_def.is_exported {
                let _ = graph.upsert_edge(&Edge::new(sym_id, file_node_id, EdgeKind::Exports));
                total_edges += 1;
            }
        }
    }

    let (targets, modules) = file_dependencies(rel_path, ext, analysis, resolver_ctx, rust);
    total_edges += insert_file_edges(graph, file_node_id, &targets, &EdgeKind::Imports).1;
    total_edges += insert_file_edges(graph, file_node_id, &modules, &EdgeKind::Module).1;

    for call in &analysis.calls {
        let caller_name = enclosing_symbol_name_for_line(&analysis.types, call.line);
        let mut caller_node = Node::symbol(
            &caller_name,
            rel_path,
            lean_ctx::core::property_graph::NodeKind::Symbol,
        );
        if let Some(t) = analysis.types.iter().find(|t| t.name == caller_name) {
            caller_node = caller_node.with_lines(t.line, t.end_line);
        }
        let Ok(caller_id) = graph.upsert_node(&caller_node) else {
            continue;
        };
        total_nodes += 1;

        let Some((callee_file, c_line, c_end, grade)) =
            resolve_call_callee_site(def_index, &call.callee, rel_path, &targets)
        else {
            continue;
        };
        let evidence = lean_ctx::core::semantic::EdgeEvidence::new(
            grade,
            lean_ctx::core::semantic::EvidenceOrigin::ImpactIndex,
            None,
            1,
        );

        let callee_node = Node::symbol(
            &call.callee,
            &callee_file,
            lean_ctx::core::property_graph::NodeKind::Symbol,
        )
        .with_lines(c_line, c_end);
        let Ok(callee_id) = graph.upsert_node(&callee_node) else {
            continue;
        };
        total_nodes += 1;
        let _ = graph.upsert_edge_with_evidence(caller_id, callee_id, &EdgeKind::Calls, &evidence);
        total_edges += 1;

        if callee_file != rel_path {
            let Ok(callee_file_id) = graph.upsert_node(&Node::file(&callee_file)) else {
                continue;
            };
            let _ = graph.upsert_edge_with_evidence(
                file_node_id,
                callee_file_id,
                &EdgeKind::Calls,
                &evidence,
            );
            total_edges += 1;
        }
    }

    // Type-usage edges close the same-namespace gap (C#/Java/Go/Kotlin,
    // GH #398): a file consuming a project type without importing it still
    // depends on the defining file. Scope is per-language (namespace-aware for
    // C#/Kotlin, directory-strict for Go).
    let scope = lean_ctx::core::type_ref_edges::resolve_scope(rel_path, ext, analysis);
    total_edges += insert_type_ref_edges(
        graph,
        file_node_id,
        rel_path,
        &analysis.type_uses,
        def_index,
        &scope,
    );
    // Extension-method calls (`value.Foo()`) depend on the defining file too.
    total_edges += insert_ext_method_edges(
        graph,
        file_node_id,
        rel_path,
        &analysis.calls,
        ext_method_index,
    );

    upsert_catalog_entry(graph, rel_path, content, ext, analysis);

    (total_nodes, total_edges)
}

#[cfg(not(feature = "embeddings"))]
fn index_graph_file_minimal(
    graph: &CodeGraph,
    rel_path: &str,
    content: &str,
    ext: &str,
    analysis: &lean_ctx::core::deep_queries::DeepAnalysis,
    idx: &BuildIndexes<'_>,
) -> (usize, usize) {
    let BuildIndexes {
        resolver_ctx,
        rust,
        def_index,
        ext_method_index,
    } = *idx;
    let Ok(file_node_id) = graph.upsert_node(&Node::file(rel_path)) else {
        return (0, 0);
    };
    let mut total_nodes = 1usize;
    let mut total_edges = 0usize;

    let (targets, modules) = file_dependencies(rel_path, ext, analysis, resolver_ctx, rust);
    for (list, kind) in [(&targets, EdgeKind::Imports), (&modules, EdgeKind::Module)] {
        let (n, e) = insert_file_edges(graph, file_node_id, list, &kind);
        total_nodes += n;
        total_edges += e;
    }

    for type_def in &analysis.types {
        if type_def.is_exported {
            let sym_node = Node::symbol(
                &type_def.name,
                rel_path,
                lean_ctx::core::property_graph::NodeKind::Symbol,
            )
            .with_lines(type_def.line, type_def.end_line);
            if let Ok(sym_id) = graph.upsert_node(&sym_node) {
                total_nodes += 1;
                let _ = graph.upsert_edge(&Edge::new(file_node_id, sym_id, EdgeKind::Defines));
                let _ = graph.upsert_edge(&Edge::new(sym_id, file_node_id, EdgeKind::Exports));
                total_edges += 2;
            }
        }
    }

    // Same-namespace type consumption (C#/Java/Go/Kotlin, GH #398) — see the
    // embeddings-path counterpart in `index_graph_file_embeddings`.
    let scope = lean_ctx::core::type_ref_edges::resolve_scope(rel_path, ext, analysis);
    total_edges += insert_type_ref_edges(
        graph,
        file_node_id,
        rel_path,
        &analysis.type_uses,
        def_index,
        &scope,
    );
    total_edges += insert_ext_method_edges(
        graph,
        file_node_id,
        rel_path,
        &analysis.calls,
        ext_method_index,
    );

    upsert_catalog_entry(graph, rel_path, content, ext, analysis);

    (total_nodes, total_edges)
}

pub(super) fn handle_build(root: &str, fmt: OutputFormat) -> String {
    let t0 = std::time::Instant::now();
    let root_path = Path::new(root);

    let graph = match open_graph(root) {
        Ok(g) => g,
        Err(e) => return e,
    };

    let incremental_hint: Option<&'static str> = {
        let nodes_ok = graph.node_count().unwrap_or(0) > 0;
        let has_head = lean_ctx::core::property_graph::load_meta(root)
            .and_then(|m| m.git_head)
            .is_some_and(|s| !s.is_empty());
        if nodes_ok && has_head {
            Some(
                "Hint: Graph already indexed — for faster refresh, use ctx_impact action='update' \
                 to apply incremental git-based updates instead of a full rebuild.",
            )
        } else {
            None
        }
    };

    if let Err(e) = graph.clear() {
        return format!("Failed to clear graph: {e}");
    }

    let (file_paths, file_contents) = walk_supported_sources(root_path);

    let cs_contents: std::collections::HashMap<String, String> = file_contents
        .iter()
        .filter(|(_, _, e)| e.eq_ignore_ascii_case("cs"))
        .map(|(p, c, _)| (p.clone(), c.clone()))
        .collect();
    let resolver_ctx = lean_ctx::core::import_resolver::ResolverContext::new(
        root_path,
        file_paths.clone(),
        &cs_contents,
    );

    let mut total_nodes = 0usize;
    let mut total_edges = 0usize;

    let (per_file, def_index, ext_method_index) = analyze_all(&file_contents);
    let rust_edges = RustEdges::resolve(root_path, &file_contents);
    let indexes = BuildIndexes {
        resolver_ctx: &resolver_ctx,
        rust: &rust_edges,
        def_index: &def_index,
        ext_method_index: &ext_method_index,
    };

    #[cfg(feature = "embeddings")]
    for (rel_path, content, ext, analysis) in &per_file {
        let (n, e) =
            index_graph_file_embeddings(&graph, rel_path, content, ext, analysis, &indexes);
        total_nodes += n;
        total_edges += e;
    }

    #[cfg(not(feature = "embeddings"))]
    for (rel_path, content, ext, analysis) in &per_file {
        let (n, e) = index_graph_file_minimal(&graph, rel_path, content, ext, analysis, &indexes);
        total_nodes += n;
        total_edges += e;
    }

    let build_time_ms = t0.elapsed().as_millis() as u64;

    let db_display = graph.db_path().display();
    let mut result = format!(
        "Graph built: {total_nodes} nodes, {total_edges} edges from {} files\n\
         Stored at: {db_display}\n\
         Build time: {build_time_ms}ms",
        file_contents.len(),
    );
    if let Some(h) = incremental_hint {
        result.push('\n');
        result.push_str(h);
    }

    let _ = lean_ctx::core::property_graph::write_meta(
        root,
        &lean_ctx::core::property_graph::PropertyGraphMetaV1 {
            schema_version: 1,
            engine_version: lean_ctx::core::property_graph::GRAPH_ENGINE_VERSION,
            built_with: env!("CARGO_PKG_VERSION").to_string(),
            project_root: lean_ctx::core::graph_index::normalize_project_root(root),
            built_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
            git_head: git_out(root_path, &["rev-parse", "--short", "HEAD"]),
            git_dirty: Some(git_dirty(root_path)),
            nodes: graph.node_count().ok(),
            edges: graph.edge_count().ok(),
            files_indexed: Some(file_contents.len()),
            build_time_ms: Some(build_time_ms),
        },
    );

    let tokens = count_tokens(&result);
    match fmt {
        OutputFormat::Json => {
            let mut v = serde_json::json!({
                "schema_version": lean_ctx::core::contracts::GRAPH_REPRODUCIBILITY_V1_SCHEMA_VERSION,
                "tool": "ctx_impact",
                "action": "build",
                "project": project_meta(root),
                "graph": graph_summary(root),
                "graph_meta": lean_ctx::core::property_graph::load_meta(root),
                "indexed_files": file_contents.len(),
                "nodes": total_nodes,
                "edges": total_edges,
                "build_time_ms": build_time_ms,
                "db_path": graph.db_path().display().to_string()
            });
            if let Some(h) = incremental_hint {
                v.as_object_mut()
                    .map(|m| m.insert("incremental_hint".to_string(), json!(h)));
            }
            serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".to_string())
        }
        OutputFormat::Text => format!("{result}\n[ctx_impact build: {tokens} tok]"),
    }
}

/// The files an incremental update re-indexes. Rust module resolution is
/// workspace-wide: a changed `.rs` file or `Cargo.toml` can move, add or drop
/// edges of files that did not change (a new `mod`, a re-export, a renamed
/// crate), so any such change re-resolves and re-indexes every walked `.rs`
/// source alongside the changed files. Sorted and deduplicated.
fn update_reindex_set(
    changed: &BTreeSet<String>,
    file_contents: &[(String, String, String)],
) -> Vec<String> {
    let rust_changed = changed.iter().any(|path| {
        let p = Path::new(path);
        p.extension().is_some_and(|e| e == "rs") || p.file_name().is_some_and(|n| n == "Cargo.toml")
    });
    let mut set: BTreeSet<String> = changed.iter().cloned().collect();
    if rust_changed {
        set.extend(
            file_contents
                .iter()
                .filter(|(_, _, ext)| ext == "rs")
                .map(|(path, _, _)| path.clone()),
        );
    }
    set.into_iter().collect()
}

pub(super) fn handle_update(root: &str, fmt: OutputFormat) -> String {
    let t0 = std::time::Instant::now();
    let root_path = Path::new(root);

    let graph = match open_graph(root) {
        Ok(g) => g,
        Err(e) => return e,
    };

    if graph.node_count().unwrap_or(0) == 0 {
        return handle_build(root, fmt);
    }

    let Some(meta) = lean_ctx::core::property_graph::load_meta(root) else {
        return handle_build(root, fmt);
    };

    let Some(last_git_head) = meta.git_head.filter(|s| !s.is_empty()) else {
        return handle_build(root, fmt);
    };

    let Some(changed) = collect_git_changed_paths(root_path, &last_git_head) else {
        return handle_build(root, fmt);
    };

    let changed_count = changed.len();
    let (file_paths, file_contents) = walk_supported_sources(root_path);
    let cs_contents: std::collections::HashMap<String, String> = file_contents
        .iter()
        .filter(|(_, _, e)| e.eq_ignore_ascii_case("cs"))
        .map(|(p, c, _)| (p.clone(), c.clone()))
        .collect();
    let resolver_ctx = lean_ctx::core::import_resolver::ResolverContext::new(
        root_path,
        file_paths.clone(),
        &cs_contents,
    );

    let (per_file, def_index, ext_method_index) = analyze_all(&file_contents);
    let rust_edges = RustEdges::resolve(root_path, &file_contents);
    let indexes = BuildIndexes {
        resolver_ctx: &resolver_ctx,
        rust: &rust_edges,
        def_index: &def_index,
        ext_method_index: &ext_method_index,
    };

    let mut total_nodes = 0usize;
    let mut total_edges = 0usize;

    let reindex = update_reindex_set(&changed, &file_contents);

    // Phase 1: drop every stale file first. `remove_file_nodes` also deletes
    // the edges *into* a file, so removing after re-indexing would erase the
    // edges just written from another re-indexed file.
    let mut to_index: Vec<&String> = Vec::new();
    for rel_path in &reindex {
        let p = Path::new(rel_path);
        let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
        let supported = GRAPH_SOURCE_EXTS.contains(&ext);
        let abs = root_path.join(rel_path);

        if !abs.exists() {
            if supported {
                let _ = graph.remove_file_nodes(rel_path);
            }
            continue;
        }

        if !supported {
            continue;
        }

        if let Err(e) = graph.remove_file_nodes(rel_path) {
            return format!("Failed to remove old nodes for {rel_path}: {e}");
        }
        to_index.push(rel_path);
    }

    // Phase 2: re-index.
    for rel_path in to_index {
        let Some((_, content, ext_owned, analysis)) =
            per_file.iter().find(|(p, _, _, _)| p == rel_path)
        else {
            continue;
        };

        #[cfg(feature = "embeddings")]
        {
            let (n, e) = index_graph_file_embeddings(
                &graph, rel_path, content, ext_owned, analysis, &indexes,
            );
            total_nodes += n;
            total_edges += e;
        }

        #[cfg(not(feature = "embeddings"))]
        {
            let (n, e) =
                index_graph_file_minimal(&graph, rel_path, content, ext_owned, analysis, &indexes);
            total_nodes += n;
            total_edges += e;
        }
    }

    let elapsed_ms = t0.elapsed().as_millis() as u64;

    let _ = lean_ctx::core::property_graph::write_meta(
        root,
        &lean_ctx::core::property_graph::PropertyGraphMetaV1 {
            schema_version: 1,
            engine_version: lean_ctx::core::property_graph::GRAPH_ENGINE_VERSION,
            built_with: env!("CARGO_PKG_VERSION").to_string(),
            project_root: lean_ctx::core::graph_index::normalize_project_root(root),
            built_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
            git_head: git_out(root_path, &["rev-parse", "--short", "HEAD"]),
            git_dirty: Some(git_dirty(root_path)),
            nodes: graph.node_count().ok(),
            edges: graph.edge_count().ok(),
            files_indexed: Some(file_contents.len()),
            build_time_ms: Some(elapsed_ms),
        },
    );

    let summary = format!(
        "Incremental update: {changed_count} files changed, {total_nodes} nodes updated, {total_edges} edges added ({elapsed_ms}ms)"
    );

    let tokens = count_tokens(&summary);
    match fmt {
        OutputFormat::Json => {
            let v = json!({
                "schema_version": lean_ctx::core::contracts::GRAPH_REPRODUCIBILITY_V1_SCHEMA_VERSION,
                "tool": "ctx_impact",
                "action": "update",
                "project": project_meta(root),
                "graph": graph_summary(root),
                "graph_meta": lean_ctx::core::property_graph::load_meta(root),
                "git_range_from": last_git_head,
                "files_changed_reported": changed_count,
                "nodes_added": total_nodes,
                "edges_added": total_edges,
                "update_time_ms": elapsed_ms,
                "db_path": graph.db_path().display().to_string()
            });
            serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".to_string())
        }
        OutputFormat::Text => format!("{summary}\n[ctx_impact update: {tokens} tok]"),
    }
}

#[cfg(test)]
mod admission_tests {
    use super::walk_supported_sources;

    const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");

    /// G01: the graph builder read every source with `fs::read_to_string`
    /// and built a persisted index from the raw bytes. It now builds from
    /// admitted, storable text only; a clean source keeps its bytes.
    #[test]
    fn the_graph_is_built_from_admitted_storable_sources_only() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
        let project = tempfile::tempdir().unwrap();
        let clean = "pub fn clean() {}\n";
        std::fs::write(project.path().join("clean.rs"), clean).unwrap();
        std::fs::write(
            project.path().join("keyed.rs"),
            format!("pub fn connect() {{\n    let aws_key = \"{AWS_KEY}\";\n}}\n"),
        )
        .unwrap();
        std::fs::write(
            project.path().join("marked.rs"),
            "// TOP SECRET\npub fn plan() {}\n",
        )
        .unwrap();

        let (paths, contents) = walk_supported_sources(project.path());
        assert_eq!(paths, ["clean.rs", "keyed.rs", "marked.rs"]);
        let content_of = |name: &str| {
            contents
                .iter()
                .find(|(path, _, _)| path == name)
                .map(|(_, content, _)| content.as_str())
        };
        assert_eq!(content_of("clean.rs"), Some(clean));
        assert!(content_of("keyed.rs").is_some_and(|text| !text.contains(AWS_KEY)));
        assert_eq!(
            content_of("marked.rs"),
            None,
            "a restricted source must not enter the graph"
        );
    }

    #[test]
    fn a_withheld_source_contributes_only_its_path() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let policy = lean_ctx::core::policy::load(
            "name = \"ctx-impact-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
             [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
        )
        .unwrap();
        let _policy = lean_ctx::core::policy::runtime::TestPolicyOverride::set(Some(policy));
        let project = tempfile::tempdir().unwrap();
        std::fs::write(
            project.path().join("plan.rs"),
            "CONFIDENTIAL\npub fn hidden_marker() {}\n",
        )
        .unwrap();
        let (paths, contents) = walk_supported_sources(project.path());
        assert_eq!(paths, ["plan.rs"]);
        assert!(contents.is_empty());
    }
}

#[cfg(all(test, feature = "embeddings"))]
mod tests {
    use super::resolve_call_callee_site;
    use lean_ctx::core::semantic::EvidenceGrade;
    use lean_ctx::core::type_ref_edges::DefIndex;

    /// Regression: an ambiguous callee used to bind to the alphabetically
    /// first defining file, inventing `calls` edges in the impact graph.
    #[test]
    fn callee_site_follows_caller_scope_and_never_guesses() {
        let mut index = DefIndex::new();
        index.insert(
            "save".into(),
            vec![("a.rs".into(), None, 3, 5), ("b.rs".into(), None, 7, 9)],
        );
        index.insert("only".into(), vec![("u.rs".into(), None, 1, 2)]);

        let none: [String; 0] = [];
        assert_eq!(
            resolve_call_callee_site(&index, "save", "c.rs", &none),
            None
        );
        assert_eq!(
            resolve_call_callee_site(&index, "save", "c.rs", &["b.rs".to_string()]),
            Some(("b.rs".into(), 7, 9, EvidenceGrade::ResolvedStructural))
        );
        assert_eq!(
            resolve_call_callee_site(&index, "save", "a.rs", &none),
            Some(("a.rs".into(), 3, 5, EvidenceGrade::ResolvedStructural))
        );
        assert_eq!(
            resolve_call_callee_site(&index, "only", "c.rs", &none),
            Some(("u.rs".into(), 1, 2, EvidenceGrade::HeuristicStructural))
        );

        // Two `Widget`s in the caller's own file (N1/N2 namespaces): refuse,
        // and never fall through to an imported file's `Widget`.
        index.insert(
            "Widget".into(),
            vec![
                ("w.cs".into(), Some("N1".into()), 3, 5),
                ("w.cs".into(), Some("N2".into()), 9, 11),
                ("lib.cs".into(), None, 1, 2),
            ],
        );
        assert_eq!(
            resolve_call_callee_site(&index, "Widget", "w.cs", &["lib.cs".to_string()]),
            None
        );
    }
}