gitcortex-mcp 0.7.2

MCP server library for GitCortex — exposes the knowledge graph via the Model Context Protocol
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
//! Shared compact responses for agent-facing MCP and CLI queries.
//!
//! This module is the contract boundary between graph retrieval and agent
//! presentation. Both interfaces must call these functions so ranking,
//! ambiguity handling, and response budgets cannot drift.

use std::collections::{HashMap, HashSet};

use gitcortex_core::{
    error::Result,
    graph::Node,
    schema::{EdgeConfidence, EdgeKind, NodeKind, Visibility},
    store::GraphStore,
};
use serde::Serialize;

use super::{
    helpers::{confidence_rank, is_test_file, sig_line},
    search::SearchHit,
};

const DEFAULT_LIMIT: usize = 25;
const MAX_LIMIT: usize = 100;
const DEFAULT_BUDGET_TOKENS: usize = 2_000;
const MIN_BUDGET_TOKENS: usize = 400;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentStatus {
    Ok,
    Ambiguous,
    NotFound,
}

#[derive(Debug, Clone, Serialize)]
pub struct SymbolCandidate {
    pub id: String,
    pub name: String,
    pub qualified_name: String,
    pub kind: String,
    pub file: String,
    pub start_line: u32,
    pub visibility: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfidenceMix {
    pub extracted: usize,
    pub resolved: usize,
    pub inferred: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct Coverage {
    pub total: usize,
    pub returned: usize,
    pub truncated: bool,
    pub confidence_mix: ConfidenceMix,
}

#[derive(Debug, Clone, Serialize)]
pub struct CallerEvidence {
    pub hop: u8,
    pub symbol: String,
    pub qualified_name: String,
    pub kind: String,
    pub file: String,
    pub line: u32,
    pub signature: String,
    pub confidence: String,
    pub is_test: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentCallersResponse {
    pub status: AgentStatus,
    pub answer: String,
    pub query: String,
    pub branch: String,
    pub depth: u8,
    pub risk_level: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<SymbolCandidate>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<SymbolCandidate>,
    pub evidence: Vec<CallerEvidence>,
    pub coverage: Coverage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_action: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RelationEvidence {
    pub relation: String,
    pub direction: String,
    pub symbol: String,
    pub qualified_name: String,
    pub kind: String,
    pub file: String,
    pub line: u32,
    pub confidence: String,
    pub is_test: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct NeighborhoodCoverage {
    pub graph_nodes: usize,
    pub graph_edges: usize,
    pub direct_relations: usize,
    pub returned: usize,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentSubgraphResponse {
    pub status: AgentStatus,
    pub answer: String,
    pub query: String,
    pub branch: String,
    pub depth: u8,
    pub direction: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<SymbolCandidate>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<SymbolCandidate>,
    pub relation_counts: std::collections::BTreeMap<String, usize>,
    pub evidence: Vec<RelationEvidence>,
    pub coverage: NeighborhoodCoverage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_action: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SearchEvidence {
    pub symbol: String,
    pub qualified_name: String,
    pub kind: String,
    pub file: String,
    pub line: u32,
    pub signature: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
    pub score: i32,
}

#[derive(Debug, Clone, Serialize)]
pub struct SearchCoverage {
    pub total: usize,
    pub returned: usize,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentSearchResponse {
    pub status: AgentStatus,
    pub answer: String,
    pub query: String,
    pub semantic_available: bool,
    pub file_count: usize,
    pub evidence: Vec<SearchEvidence>,
    pub coverage: SearchCoverage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_action: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub struct AgentQueryOptions {
    pub limit: usize,
    pub budget_tokens: usize,
}

impl Default for AgentQueryOptions {
    fn default() -> Self {
        Self {
            limit: DEFAULT_LIMIT,
            budget_tokens: DEFAULT_BUDGET_TOKENS,
        }
    }
}

enum Resolution {
    Exact(Box<Node>),
    Ambiguous(Vec<Node>),
    NotFound(Vec<Node>),
}

/// Format ranked search hits as compact implementation evidence shared by CLI
/// and MCP. Retrieval may be lexical-only or RRF hybrid; presentation is stable.
pub fn format_search<S: GraphStore + ?Sized>(
    store: &S,
    branch: &str,
    query: &str,
    hits: Vec<SearchHit>,
    semantic_available: bool,
    budget_tokens: usize,
) -> Result<AgentSearchResponse> {
    let total = hits.len();
    let ids: Vec<String> = hits.iter().map(|hit| hit.id.clone()).collect();
    let nodes = store.get_nodes_by_ids(branch, &ids)?;
    let by_id: HashMap<String, Node> = nodes
        .into_iter()
        .map(|node| (node.id.as_str(), node))
        .collect();
    let mut files = HashSet::new();
    let mut evidence = Vec::new();
    for hit in hits {
        files.insert(hit.file.clone());
        let node = by_id.get(&hit.id);
        let doc = node
            .and_then(|node| node.metadata.definition.doc_comment.as_deref())
            .and_then(|text| text.lines().find(|line| !line.trim().is_empty()))
            .map(|line| line.trim().chars().take(180).collect());
        evidence.push(SearchEvidence {
            symbol: hit.name,
            qualified_name: hit.qualified_name,
            kind: hit.kind,
            file: hit.file,
            line: hit.start_line,
            signature: node.map(sig_line).unwrap_or_default(),
            doc,
            score: hit.score,
        });
    }
    let answer = if total == 0 {
        format!("No code symbols matched '{query}'.")
    } else {
        let top_files = evidence
            .iter()
            .map(|item| item.file.as_str())
            .take(3)
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "{total} ranked symbol match(es) across {} file(s). Top files: {top_files}.",
            files.len()
        )
    };
    let mut response = AgentSearchResponse {
        status: if total == 0 {
            AgentStatus::NotFound
        } else {
            AgentStatus::Ok
        },
        answer,
        query: query.to_owned(),
        semantic_available,
        file_count: files.len(),
        evidence,
        coverage: SearchCoverage {
            total,
            returned: 0,
            truncated: false,
        },
        next_action: if total == 0 {
            Some("Try a concrete symbol fragment or alternate spelling.".to_owned())
        } else {
            None
        },
    };
    apply_search_budget(&mut response, budget_tokens.max(MIN_BUDGET_TOKENS));
    Ok(response)
}

/// Find callers for exactly one symbol and return a globally-budgeted response.
/// Ambiguous short names return candidates without traversing the graph.
pub fn find_callers<S: GraphStore + ?Sized>(
    store: &S,
    branch: &str,
    query: &str,
    depth: u8,
    options: AgentQueryOptions,
) -> Result<AgentCallersResponse> {
    let depth = depth.clamp(1, 5);
    let options = AgentQueryOptions {
        limit: options.limit.clamp(1, MAX_LIMIT),
        budget_tokens: options.budget_tokens.max(MIN_BUDGET_TOKENS),
    };

    let target = match resolve_symbol(store, branch, query)? {
        Resolution::Exact(node) => *node,
        Resolution::Ambiguous(nodes) => {
            let total_candidates = nodes.len();
            let candidates = candidate_head(nodes, 5);
            return Ok(AgentCallersResponse {
                status: AgentStatus::Ambiguous,
                answer: format!(
                    "'{}' matches {total_candidates} code symbols; choose a qualified symbol before computing impact.",
                    query
                ),
                query: query.to_owned(),
                branch: branch.to_owned(),
                depth,
                risk_level: "UNKNOWN".to_owned(),
                symbol: None,
                candidates,
                evidence: Vec::new(),
                coverage: Coverage {
                    total: 0,
                    returned: 0,
                    truncated: false,
                    confidence_mix: ConfidenceMix::default(),
                },
                next_action: Some(
                    "Repeat find_callers with one candidate's qualified_name.".to_owned(),
                ),
            });
        }
        Resolution::NotFound(nodes) => {
            let candidates = candidate_head(nodes, 5);
            return Ok(AgentCallersResponse {
                status: AgentStatus::NotFound,
                answer: format!("No exact code symbol matching '{query}' was found."),
                query: query.to_owned(),
                branch: branch.to_owned(),
                depth,
                risk_level: "UNKNOWN".to_owned(),
                symbol: None,
                candidates,
                evidence: Vec::new(),
                coverage: Coverage {
                    total: 0,
                    returned: 0,
                    truncated: false,
                    confidence_mix: ConfidenceMix::default(),
                },
                next_action: Some("Use search_code to find the exact qualified symbol.".to_owned()),
            });
        }
    };

    let target_summary = to_candidate(&target);
    let mut seen: HashSet<String> = HashSet::new();
    seen.insert(target.id.as_str());
    let mut frontier = vec![target.id.as_str()];
    let mut evidence = Vec::new();
    let mut mix = ConfidenceMix::default();

    for hop in 1..=depth {
        let mut pairs = Vec::new();
        for target_id in &frontier {
            pairs.extend(store.find_callers_by_id_with_confidence(branch, target_id)?);
        }
        pairs.retain(|(node, _)| seen.insert(node.id.as_str()));
        pairs.sort_by(rank_callers);

        frontier = pairs.iter().map(|(node, _)| node.id.as_str()).collect();
        for (node, confidence) in pairs {
            match confidence {
                EdgeConfidence::Extracted => mix.extracted += 1,
                EdgeConfidence::Resolved => mix.resolved += 1,
                EdgeConfidence::Inferred => mix.inferred += 1,
            }
            evidence.push(to_evidence(node, confidence, hop));
        }
        if frontier.is_empty() {
            break;
        }
    }

    let total = evidence.len();
    let risk_level = match total {
        0..=2 => "LOW",
        3..=10 => "MEDIUM",
        11..=30 => "HIGH",
        _ => "CRITICAL",
    };
    evidence.truncate(options.limit);

    let answer = if total == 0 {
        format!(
            "No callers found for '{}' ({}).",
            target.name, target.qualified_name
        )
    } else {
        format!(
            "{total} caller(s) within {depth} hop(s) of '{}' — change risk {risk_level}.",
            target.qualified_name
        )
    };

    let mut response = AgentCallersResponse {
        status: AgentStatus::Ok,
        answer,
        query: query.to_owned(),
        branch: branch.to_owned(),
        depth,
        risk_level: risk_level.to_owned(),
        symbol: Some(target_summary),
        candidates: Vec::new(),
        evidence,
        coverage: Coverage {
            total,
            returned: 0,
            truncated: false,
            confidence_mix: mix,
        },
        next_action: None,
    };
    apply_budget(&mut response, options.budget_tokens);
    Ok(response)
}

/// Return a compact, exact-ID neighborhood digest. Only direct relationships
/// are serialized as evidence; deeper traversal contributes coverage counts.
pub fn get_subgraph<S: GraphStore + ?Sized>(
    store: &S,
    branch: &str,
    query: &str,
    depth: u8,
    direction: &str,
    options: AgentQueryOptions,
) -> Result<AgentSubgraphResponse> {
    let depth = depth.clamp(1, 5);
    let direction = match direction {
        "in" | "out" | "both" => direction,
        _ => "both",
    };
    let options = AgentQueryOptions {
        limit: options.limit.clamp(1, MAX_LIMIT),
        budget_tokens: options.budget_tokens.max(MIN_BUDGET_TOKENS),
    };

    let target = match resolve_symbol(store, branch, query)? {
        Resolution::Exact(node) => *node,
        Resolution::Ambiguous(nodes) => {
            let total = nodes.len();
            return Ok(AgentSubgraphResponse {
                status: AgentStatus::Ambiguous,
                answer: format!(
                    "'{query}' matches {total} code symbols; choose a qualified symbol before traversing its neighborhood."
                ),
                query: query.to_owned(),
                branch: branch.to_owned(),
                depth,
                direction: direction.to_owned(),
                symbol: None,
                candidates: candidate_head(nodes, 5),
                relation_counts: Default::default(),
                evidence: Vec::new(),
                coverage: NeighborhoodCoverage {
                    graph_nodes: 0,
                    graph_edges: 0,
                    direct_relations: 0,
                    returned: 0,
                    truncated: false,
                },
                next_action: Some(
                    "Repeat get_subgraph with one candidate's qualified_name.".to_owned(),
                ),
            });
        }
        Resolution::NotFound(nodes) => {
            return Ok(AgentSubgraphResponse {
                status: AgentStatus::NotFound,
                answer: format!("No exact code symbol matching '{query}' was found."),
                query: query.to_owned(),
                branch: branch.to_owned(),
                depth,
                direction: direction.to_owned(),
                symbol: None,
                candidates: candidate_head(nodes, 5),
                relation_counts: Default::default(),
                evidence: Vec::new(),
                coverage: NeighborhoodCoverage {
                    graph_nodes: 0,
                    graph_edges: 0,
                    direct_relations: 0,
                    returned: 0,
                    truncated: false,
                },
                next_action: Some("Use search_code to find the exact qualified symbol.".to_owned()),
            });
        }
    };

    let graph = store.get_subgraph_by_id(branch, &target.id.as_str(), depth, direction)?;
    let by_id: HashMap<String, &Node> = graph
        .nodes
        .iter()
        .filter(|node| is_code_node(node))
        .map(|node| (node.id.as_str(), node))
        .collect();
    let target_id = target.id.as_str();
    let mut evidence = Vec::new();
    let mut seen = HashSet::new();
    let mut counts = std::collections::BTreeMap::new();

    for edge in &graph.edges {
        let src = edge.src.as_str();
        let dst = edge.dst.as_str();
        let (other_id, edge_direction) = if src == target_id {
            (dst, "out")
        } else if dst == target_id {
            (src, "in")
        } else {
            continue;
        };
        if direction != "both" && direction != edge_direction {
            continue;
        }
        let Some(other) = by_id.get(&other_id) else {
            continue;
        };
        let relation = relation_label(&edge.kind, edge_direction);
        if !seen.insert((relation, other_id)) {
            continue;
        }
        *counts.entry(relation.to_owned()).or_insert(0) += 1;
        evidence.push(RelationEvidence {
            relation: relation.to_owned(),
            direction: edge_direction.to_owned(),
            symbol: other.name.clone(),
            qualified_name: other.qualified_name.clone(),
            kind: other.kind.to_string(),
            file: other.file.display().to_string(),
            line: edge.line.unwrap_or(other.span.start_line),
            confidence: edge.confidence.to_string(),
            is_test: is_test_file(&other.file),
        });
    }
    evidence.sort_by(|a, b| {
        relation_rank(&a.relation)
            .cmp(&relation_rank(&b.relation))
            .then_with(|| {
                confidence_label_rank(&a.confidence).cmp(&confidence_label_rank(&b.confidence))
            })
            .then_with(|| a.is_test.cmp(&b.is_test))
            .then_with(|| a.file.cmp(&b.file))
            .then_with(|| a.qualified_name.cmp(&b.qualified_name))
    });
    let direct_relations = evidence.len();
    evidence.truncate(options.limit);
    let count_summary = counts
        .iter()
        .map(|(relation, count)| format!("{relation}={count}"))
        .collect::<Vec<_>>()
        .join(", ");
    let answer = if count_summary.is_empty() {
        format!(
            "'{}' has no direct relationships in the selected direction.",
            target.qualified_name
        )
    } else {
        format!(
            "Direct relationships for '{}': {count_summary}.",
            target.qualified_name
        )
    };
    let mut response = AgentSubgraphResponse {
        status: AgentStatus::Ok,
        answer,
        query: query.to_owned(),
        branch: branch.to_owned(),
        depth,
        direction: direction.to_owned(),
        symbol: Some(to_candidate(&target)),
        candidates: Vec::new(),
        relation_counts: counts,
        evidence,
        coverage: NeighborhoodCoverage {
            graph_nodes: by_id.len(),
            graph_edges: graph.edges.len(),
            direct_relations,
            returned: 0,
            truncated: false,
        },
        next_action: None,
    };
    apply_subgraph_budget(&mut response, options.budget_tokens);
    Ok(response)
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentSymbolContextResponse {
    pub status: AgentStatus,
    pub answer: String,
    pub query: String,
    pub branch: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<SymbolCandidate>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<SymbolCandidate>,
    pub callers: Vec<RelationEvidence>,
    pub callees: Vec<RelationEvidence>,
    pub used_by: Vec<RelationEvidence>,
    pub coverage: Coverage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_action: Option<String>,
}

/// 360° view of exactly one resolved symbol: direct callers, callees, and
/// type usages. Unlike the old name-based `GraphStore::symbol_context`, this
/// goes through `resolve_symbol` first so an ambiguous short name (e.g. two
/// unrelated `beginArray` methods) surfaces candidates instead of silently
/// picking one — the same ambiguity handling `find_callers`/`get_subgraph`
/// already have.
pub fn symbol_context<S: GraphStore + ?Sized>(
    store: &S,
    branch: &str,
    query: &str,
    options: AgentQueryOptions,
) -> Result<AgentSymbolContextResponse> {
    let options = AgentQueryOptions {
        limit: options.limit.clamp(1, MAX_LIMIT),
        budget_tokens: options.budget_tokens.max(MIN_BUDGET_TOKENS),
    };

    let target = match resolve_symbol(store, branch, query)? {
        Resolution::Exact(node) => *node,
        Resolution::Ambiguous(nodes) => {
            let total = nodes.len();
            return Ok(AgentSymbolContextResponse {
                status: AgentStatus::Ambiguous,
                answer: format!(
                    "'{query}' matches {total} code symbols; choose a qualified symbol before requesting its context."
                ),
                query: query.to_owned(),
                branch: branch.to_owned(),
                symbol: None,
                candidates: candidate_head(nodes, 5),
                callers: Vec::new(),
                callees: Vec::new(),
                used_by: Vec::new(),
                coverage: Coverage {
                    total: 0,
                    returned: 0,
                    truncated: false,
                    confidence_mix: ConfidenceMix::default(),
                },
                next_action: Some(
                    "Repeat symbol_context with one candidate's qualified_name.".to_owned(),
                ),
            });
        }
        Resolution::NotFound(nodes) => {
            return Ok(AgentSymbolContextResponse {
                status: AgentStatus::NotFound,
                answer: format!("No exact code symbol matching '{query}' was found."),
                query: query.to_owned(),
                branch: branch.to_owned(),
                symbol: None,
                candidates: candidate_head(nodes, 5),
                callers: Vec::new(),
                callees: Vec::new(),
                used_by: Vec::new(),
                coverage: Coverage {
                    total: 0,
                    returned: 0,
                    truncated: false,
                    confidence_mix: ConfidenceMix::default(),
                },
                next_action: Some("Use search_code to find the exact qualified symbol.".to_owned()),
            });
        }
    };

    let graph = store.get_subgraph_by_id(branch, &target.id.as_str(), 1, "both")?;
    let by_id: HashMap<String, &Node> = graph
        .nodes
        .iter()
        .filter(|node| is_code_node(node))
        .map(|node| (node.id.as_str(), node))
        .collect();
    let target_id = target.id.as_str();

    let mut callers = Vec::new();
    let mut callees = Vec::new();
    let mut used_by = Vec::new();
    let mut seen = HashSet::new();
    let mut mix = ConfidenceMix::default();

    for edge in &graph.edges {
        let src = edge.src.as_str();
        let dst = edge.dst.as_str();
        let (other_id, edge_direction) = if src == target_id {
            (dst, "out")
        } else if dst == target_id {
            (src, "in")
        } else {
            continue;
        };
        let Some(other) = by_id.get(&other_id) else {
            continue;
        };
        let bucket = match (&edge.kind, edge_direction) {
            (EdgeKind::Calls, "in") => &mut callers,
            (EdgeKind::Calls, "out") => &mut callees,
            (EdgeKind::Uses, "in") => &mut used_by,
            _ => continue,
        };
        if !seen.insert((edge_direction, other_id)) {
            continue;
        }
        match edge.confidence {
            EdgeConfidence::Extracted => mix.extracted += 1,
            EdgeConfidence::Resolved => mix.resolved += 1,
            EdgeConfidence::Inferred => mix.inferred += 1,
        }
        bucket.push(RelationEvidence {
            relation: relation_label(&edge.kind, edge_direction).to_owned(),
            direction: edge_direction.to_owned(),
            symbol: other.name.clone(),
            qualified_name: other.qualified_name.clone(),
            kind: other.kind.to_string(),
            file: other.file.display().to_string(),
            line: edge.line.unwrap_or(other.span.start_line),
            confidence: edge.confidence.to_string(),
            is_test: is_test_file(&other.file),
        });
    }
    for bucket in [&mut callers, &mut callees, &mut used_by] {
        bucket.sort_by(|a, b| {
            a.file
                .cmp(&b.file)
                .then_with(|| a.qualified_name.cmp(&b.qualified_name))
        });
    }

    let total = callers.len() + callees.len() + used_by.len();
    for bucket in [&mut callers, &mut callees, &mut used_by] {
        bucket.truncate(options.limit);
    }
    let answer = format!(
        "'{}' has {} caller(s), {} callee(s), {} usage site(s).",
        target.qualified_name,
        callers.len(),
        callees.len(),
        used_by.len()
    );
    let mut response = AgentSymbolContextResponse {
        status: AgentStatus::Ok,
        answer,
        query: query.to_owned(),
        branch: branch.to_owned(),
        symbol: Some(to_candidate(&target)),
        candidates: Vec::new(),
        callers,
        callees,
        used_by,
        coverage: Coverage {
            total,
            returned: 0,
            truncated: false,
            confidence_mix: mix,
        },
        next_action: None,
    };
    apply_symbol_context_budget(&mut response, options.budget_tokens);
    Ok(response)
}

fn apply_symbol_context_budget(response: &mut AgentSymbolContextResponse, budget_tokens: usize) {
    let budget_bytes = budget_tokens * 4;
    while (!response.used_by.is_empty()
        || !response.callees.is_empty()
        || !response.callers.is_empty())
        && serde_json::to_vec(response)
            .map(|bytes| bytes.len() > budget_bytes)
            .unwrap_or(false)
    {
        if !response.used_by.is_empty() {
            response.used_by.pop();
        } else if !response.callees.is_empty() {
            response.callees.pop();
        } else {
            response.callers.pop();
        }
    }
    response.coverage.returned =
        response.callers.len() + response.callees.len() + response.used_by.len();
    response.coverage.truncated = response.coverage.returned < response.coverage.total;
}

fn relation_label(kind: &EdgeKind, direction: &str) -> &'static str {
    match (kind, direction) {
        (EdgeKind::Calls, "out") => "calls",
        (EdgeKind::Calls, _) => "called_by",
        (EdgeKind::Uses, "out") => "uses",
        (EdgeKind::Uses, _) => "used_by",
        (EdgeKind::Implements, "out") => "implements",
        (EdgeKind::Implements, _) => "implemented_by",
        (EdgeKind::Imports, "out") => "imports",
        (EdgeKind::Imports, _) => "imported_by",
        (EdgeKind::Contains, "out") => "contains",
        (EdgeKind::Contains, _) => "contained_by",
        (EdgeKind::Inherits, "out") => "inherits",
        (EdgeKind::Inherits, _) => "inherited_by",
        (EdgeKind::References, "out") => "references",
        (EdgeKind::References, _) => "referenced_by",
        _ => "related",
    }
}

fn relation_rank(relation: &str) -> u8 {
    match relation {
        "called_by" | "calls" => 0,
        "used_by" | "uses" => 1,
        "implemented_by" | "implements" | "inherited_by" | "inherits" => 2,
        "imported_by" | "imports" => 3,
        "contained_by" | "contains" => 4,
        _ => 5,
    }
}

fn confidence_label_rank(confidence: &str) -> u8 {
    match confidence {
        "extracted" => 0,
        "resolved" => 1,
        _ => 2,
    }
}

fn resolve_symbol<S: GraphStore + ?Sized>(
    store: &S,
    branch: &str,
    query: &str,
) -> Result<Resolution> {
    let query = query.trim();
    let mut exact = store.lookup_symbol(branch, query, false)?;
    exact.retain(is_code_node);

    // A qualified query may not match `lookup_symbol`, which is intentionally
    // short-name based. Search a bounded candidate set and compare exactly.
    let mut searched = store.search_nodes(branch, query, 50)?;
    searched.retain(is_code_node);
    if query.contains("::") || query.contains('.') {
        let qualified: Vec<Node> = searched
            .iter()
            .filter(|node| node.qualified_name.eq_ignore_ascii_case(query))
            .cloned()
            .collect();
        if qualified.len() == 1 {
            return Ok(Resolution::Exact(Box::new(qualified[0].clone())));
        }
        if qualified.len() > 1 {
            return Ok(Resolution::Ambiguous(qualified));
        }
    }

    dedup_nodes(&mut exact);
    match exact.len() {
        1 => Ok(Resolution::Exact(Box::new(exact.remove(0)))),
        n if n > 1 => Ok(Resolution::Ambiguous(exact)),
        _ => {
            searched.sort_by(rank_candidates);
            dedup_nodes(&mut searched);
            Ok(Resolution::NotFound(searched))
        }
    }
}

fn is_code_node(node: &Node) -> bool {
    !matches!(
        node.kind,
        NodeKind::Section | NodeKind::File | NodeKind::Folder | NodeKind::Module
    )
}

fn dedup_nodes(nodes: &mut Vec<Node>) {
    let mut seen = HashSet::new();
    nodes.retain(|node| seen.insert(node.id.as_str()));
}

fn candidate_head(mut nodes: Vec<Node>, limit: usize) -> Vec<SymbolCandidate> {
    nodes.sort_by(rank_candidates);
    nodes
        .into_iter()
        .take(limit)
        .map(|n| to_candidate(&n))
        .collect()
}

fn rank_candidates(a: &Node, b: &Node) -> std::cmp::Ordering {
    candidate_rank(a)
        .cmp(&candidate_rank(b))
        .then_with(|| a.file.cmp(&b.file))
        .then_with(|| a.qualified_name.cmp(&b.qualified_name))
}

fn candidate_rank(node: &Node) -> (u8, u8) {
    let test = is_test_file(&node.file) as u8;
    let visibility = match node.metadata.visibility {
        Visibility::Pub => 0,
        Visibility::PubCrate => 1,
        Visibility::Private => 2,
    };
    (test, visibility)
}

fn rank_callers(
    (a, ac): &(Node, EdgeConfidence),
    (b, bc): &(Node, EdgeConfidence),
) -> std::cmp::Ordering {
    confidence_rank(ac)
        .cmp(&confidence_rank(bc))
        .then_with(|| candidate_rank(a).cmp(&candidate_rank(b)))
        .then_with(|| a.file.cmp(&b.file))
        .then_with(|| a.qualified_name.cmp(&b.qualified_name))
}

fn to_candidate(node: &Node) -> SymbolCandidate {
    SymbolCandidate {
        id: node.id.as_str(),
        name: node.name.clone(),
        qualified_name: node.qualified_name.clone(),
        kind: node.kind.to_string(),
        file: node.file.display().to_string(),
        start_line: node.span.start_line,
        visibility: node.metadata.visibility.to_string(),
    }
}

fn to_evidence(node: Node, confidence: EdgeConfidence, hop: u8) -> CallerEvidence {
    CallerEvidence {
        hop,
        symbol: node.name.clone(),
        qualified_name: node.qualified_name.clone(),
        kind: node.kind.to_string(),
        file: node.file.display().to_string(),
        line: node.span.start_line,
        signature: sig_line(&node),
        confidence: confidence.to_string(),
        is_test: is_test_file(&node.file),
    }
}

fn apply_search_budget(response: &mut AgentSearchResponse, budget_tokens: usize) {
    let budget_bytes = budget_tokens * 4;
    while !response.evidence.is_empty()
        && serde_json::to_vec(response)
            .map(|bytes| bytes.len() > budget_bytes)
            .unwrap_or(false)
    {
        response.evidence.pop();
    }
    response.coverage.returned = response.evidence.len();
    response.coverage.truncated = response.coverage.returned < response.coverage.total;
}

fn apply_subgraph_budget(response: &mut AgentSubgraphResponse, budget_tokens: usize) {
    let budget_bytes = budget_tokens * 4;
    while !response.evidence.is_empty()
        && serde_json::to_vec(response)
            .map(|bytes| bytes.len() > budget_bytes)
            .unwrap_or(false)
    {
        response.evidence.pop();
    }
    response.coverage.returned = response.evidence.len();
    response.coverage.truncated = response.coverage.returned < response.coverage.direct_relations;
}

fn apply_budget(response: &mut AgentCallersResponse, budget_tokens: usize) {
    let budget_bytes = budget_tokens * 4;
    while !response.evidence.is_empty()
        && serde_json::to_vec(response)
            .map(|bytes| bytes.len() > budget_bytes)
            .unwrap_or(false)
    {
        response.evidence.pop();
    }
    response.coverage.returned = response.evidence.len();
    response.coverage.truncated = response.coverage.returned < response.coverage.total;
}

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

    #[test]
    fn test_file_detection_covers_supported_languages() {
        for path in [
            "tests/api.rs",
            "src/api_test.go",
            "src/api.test.ts",
            "src/__tests__/api.tsx",
            "src/ApiTest.java",
        ] {
            assert!(
                is_test_file(std::path::Path::new(path)),
                "expected test path: {path}"
            );
        }
        assert!(!is_test_file(std::path::Path::new("src/api.rs")));
    }

    #[test]
    fn confidence_order_is_strongest_first() {
        assert!(
            confidence_rank(&EdgeConfidence::Extracted)
                < confidence_rank(&EdgeConfidence::Resolved)
        );
        assert!(
            confidence_rank(&EdgeConfidence::Resolved) < confidence_rank(&EdgeConfidence::Inferred)
        );
    }
}