basemind 0.24.0

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 10+ coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! Body of the `architecture_map` MCP tool + the reusable in-memory `RepoGraph`.
//!
//! `RepoGraph` builds a whole-repo, file-level directed call graph once from the L1
//! outline cache + the call sites (Fjall `calls_by_path`, or the in-RAM call index on a
//! read-only session). Edges are name→definition: file A links to file B when A contains
//! a call whose callee name is defined (as a function-like symbol) in B. This inherits
//! `call_graph`'s name-based imprecision (overloaded names produce a few spurious edges);
//! edge `weight` lets consumers discount thin edges.
//!
//! On top of the graph the tool computes deterministic structure signals — degree, a
//! fixed-iteration PageRank, and Tarjan SCCs (cycle clusters) — blends them with an
//! optional git-churn overlay, ranks, knee-cuts, and budgets the result. Outputs are
//! paths/lines/signatures + edges, never prose.
//!
//! The graph is rebuilt per call (bounded by [`codegraph::CODEGRAPH_SCAN_CAP`]) — a full-repo scan
//! shared by every `codegraph` consumer (`architecture_map` plus the ADR-0003/0004/0005 tools
//! `neighbors`/`path`/`subgraph`/`communities`/`graph_export`, all of which an agent may call
//! repeatedly). Memoizing the built graph against `cache_generation` is the standing follow-up
//! (tracked) — deferred until it can be measured on a quiet machine with the harden harness.

use ahash::{AHashMap, AHashSet};
use rmcp::ErrorData as McpError;
use rmcp::model::CallToolResult;

use super::MapCache;
use super::budget::apply_budget;
use super::codegraph::{self, BuildOpts, EdgeKind, EdgeKindSet, Provenance};
use super::helpers::{elapsed_us, json_result, kind_to_str};
use super::helpers_calls::for_each_call_in_file;
use super::helpers_graph::is_function_like;
use super::helpers_graphview::{DEFAULT_MAX_EXPORT_EDGES, MAX_MAX_EDGES};
use super::kneedle::knee_cutoff;
use super::types_archmap::{ArchEdge, ArchNode, ArchitectureMapParams, ArchitectureMapResponse, CycleCluster};
use crate::index::IndexDb;
use crate::path::RelPath;

const PAGERANK_ITERS: usize = 20;
const PAGERANK_DAMPING: f64 = 0.85;

/// Inter-group non-call edges: `(from_group, to_group, kind) -> (weight, provenance)`.
type LaneEdges = AHashMap<(u32, u32, EdgeKind), (u32, Provenance)>;

/// Symbol-tier second-pass output: per-survivor distinct-callee fan-out (indexed by local id)
/// plus the name-based inter-survivor edge weights `(from_local, to_local) -> weight`.
type SymbolCallEdges = (Vec<u32>, AHashMap<(u32, u32), u32>);

/// A directed weighted graph in adjacency form. `out[i]` / `in_[i]` are sorted for
/// deterministic iteration (PageRank / Tarjan discovery order).
struct Graph {
    n: usize,
    out: Vec<Vec<(u32, u32)>>,
    in_: Vec<Vec<(u32, u32)>>,
}

impl Graph {
    fn empty(n: usize) -> Self {
        Graph {
            n,
            out: vec![Vec::new(); n],
            in_: vec![Vec::new(); n],
        }
    }

    /// Sort every adjacency list so all downstream traversals are order-stable.
    fn sort(&mut self) {
        for v in &mut self.out {
            v.sort_unstable();
        }
        for v in &mut self.in_ {
            v.sort_unstable();
        }
    }

    fn fan_in(&self, i: usize) -> u32 {
        self.in_[i].len() as u32
    }

    fn fan_out(&self, i: usize) -> u32 {
        self.out[i].len() as u32
    }

    /// Fixed-iteration PageRank over incoming edges. Deterministic: `1/n` init,
    /// id-ordered accumulation, fixed iteration count (no float convergence test, no
    /// RNG). Dangling nodes (no out-edges) leak their mass — acceptable, since only the
    /// relative ranking matters here.
    fn pagerank(&self) -> Vec<f32> {
        let n = self.n;
        if n == 0 {
            return Vec::new();
        }
        let base = (1.0 - PAGERANK_DAMPING) / n as f64;
        let outdeg: Vec<usize> = (0..n).map(|i| self.out[i].len()).collect();
        let mut rank = vec![1.0 / n as f64; n];
        let mut next = vec![0.0f64; n];
        for _ in 0..PAGERANK_ITERS {
            for x in next.iter_mut() {
                *x = base;
            }
            for s in 0..n {
                if outdeg[s] == 0 {
                    continue;
                }
                let share = PAGERANK_DAMPING * rank[s] / outdeg[s] as f64;
                for &(dst, _w) in &self.out[s] {
                    next[dst as usize] += share;
                }
            }
            std::mem::swap(&mut rank, &mut next);
        }
        rank.into_iter().map(|r| r as f32).collect()
    }

    /// Iterative Tarjan SCC. Returns a component id per node. Iterative (explicit work
    /// stack) so deep graphs don't blow the call stack. Discovery order is deterministic
    /// given the sorted adjacency + ascending node iteration.
    fn tarjan_scc(&self) -> Vec<u32> {
        let n = self.n;
        let mut index = vec![u32::MAX; n];
        let mut low = vec![0u32; n];
        let mut on_stack = vec![false; n];
        let mut comp = vec![u32::MAX; n];
        let mut stack: Vec<u32> = Vec::new();
        let mut idx_counter: u32 = 0;
        let mut comp_counter: u32 = 0;

        for start in 0..n {
            if index[start] != u32::MAX {
                continue;
            }
            let mut work: Vec<(u32, usize)> = vec![(start as u32, 0)];
            while let Some(&(v, pi)) = work.last() {
                let vu = v as usize;
                if pi == 0 {
                    index[vu] = idx_counter;
                    low[vu] = idx_counter;
                    idx_counter += 1;
                    stack.push(v);
                    on_stack[vu] = true;
                }
                if pi < self.out[vu].len() {
                    work.last_mut()
                        .expect("work frame present inside the last()-guarded loop")
                        .1 += 1;
                    let w = self.out[vu][pi].0;
                    let wu = w as usize;
                    if index[wu] == u32::MAX {
                        work.push((w, 0));
                    } else if on_stack[wu] {
                        low[vu] = low[vu].min(index[wu]);
                    }
                } else {
                    if low[vu] == index[vu] {
                        loop {
                            let w = stack.pop().expect("root v is on the stack until the SCC closes");
                            on_stack[w as usize] = false;
                            comp[w as usize] = comp_counter;
                            if w == v {
                                break;
                            }
                        }
                        comp_counter += 1;
                    }
                    work.pop();
                    if let Some(&(parent, _)) = work.last() {
                        low[parent as usize] = low[parent as usize].min(low[vu]);
                    }
                }
            }
        }
        comp
    }
}

/// Whole-repo file-level call graph plus a per-callee-name fan-in table (reused by the
/// symbol tier, and by the Session-2 coverage tool).
pub(crate) struct RepoGraph {
    /// node id → file path (ascending — mirrors `MapCache::by_path` iteration).
    files: Vec<RelPath>,
    graph: Graph,
    /// Callee name → total call-site count across the repo (name-based fan-in).
    callee_counts: AHashMap<String, u32>,
    /// Callee name → number of files that define a function-like symbol with that name.
    /// The specificity denominator for the symbol tier: a name defined in 200 files is not
    /// one hub, so raw name-based fan-in is divided by this to demote ubiquitous names
    /// (`new` / `from` / `default`) that would otherwise dominate a repo-wide ranking.
    def_counts: AHashMap<String, u32>,
    truncated: bool,
    truncation_reason: Option<&'static str>,
}

impl RepoGraph {
    /// Build the graph from the L1 cache + call sites. `idx = Some` prefix-scans the
    /// Fjall `calls_by_path` keyspace per file; `idx = None` reads the in-RAM call index
    /// (read-only session). Bounded by `edge_scan_cap` total call sites.
    pub(crate) fn build(idx: Option<&IndexDb>, cache: &MapCache, edge_scan_cap: usize) -> Result<Self, McpError> {
        let files: Vec<RelPath> = cache.by_path.keys().cloned().collect();
        let mut id_of: AHashMap<RelPath, u32> = AHashMap::with_capacity(files.len());
        for (i, p) in files.iter().enumerate() {
            id_of.insert(p.clone(), i as u32);
        }

        let mut def_files_by_name: AHashMap<String, Vec<u32>> = AHashMap::new();
        for (path, l1) in &cache.by_path {
            let fid = id_of[path];
            for sym in &l1.symbols {
                if is_function_like(sym.kind) {
                    def_files_by_name.entry(sym.name.clone()).or_default().push(fid);
                }
            }
        }

        let mut edges: AHashMap<(u32, u32), u32> = AHashMap::new();
        let mut callee_counts: AHashMap<String, u32> = AHashMap::new();
        let mut scanned = 0usize;
        let mut truncated = false;
        let mut truncation_reason: Option<&'static str> = None;

        for path in cache.by_path.keys() {
            let src = id_of[path];
            let mut cap_hit = false;
            for_each_call_in_file(idx, cache, path, |callee, _start_byte| {
                scanned += 1;
                if scanned > edge_scan_cap {
                    cap_hit = true;
                    return false;
                }
                if let Some(count) = callee_counts.get_mut(callee) {
                    *count += 1;
                } else {
                    callee_counts.insert(callee.to_string(), 1);
                }
                if let Some(defs) = def_files_by_name.get(callee) {
                    for &dst in defs {
                        if dst != src {
                            *edges.entry((src, dst)).or_default() += 1;
                        }
                    }
                }
                true
            })?;
            if cap_hit {
                truncated = true;
                truncation_reason = Some("scan_cap");
                break;
            }
        }

        let def_counts: AHashMap<String, u32> = def_files_by_name
            .into_iter()
            .map(|(name, files)| (name, files.len() as u32))
            .collect();

        let mut graph = Graph::empty(files.len());
        for (&(s, d), &w) in &edges {
            graph.out[s as usize].push((d, w));
            graph.in_[d as usize].push((s, w));
        }
        graph.sort();

        Ok(RepoGraph {
            files,
            graph,
            callee_counts,
            def_counts,
            truncated,
            truncation_reason,
        })
    }
}

/// Body of the `architecture_map` tool. `churn` (commits-touching per file) is `None`
/// when the overlay is disabled or there's no git repo.
pub(crate) fn run_architecture_map(
    shared: &super::shared_state::SharedReadStack,
    idx: Option<&IndexDb>,
    cache: &MapCache,
    churn: Option<&AHashMap<RelPath, u32>>,
    params: ArchitectureMapParams,
    notice: Option<super::types::LifecycleNotice>,
    started: std::time::Instant,
) -> Result<CallToolResult, McpError> {
    let max_nodes = params.max_nodes.unwrap_or(60).min(300) as usize;
    let max_edges = params.max_edges.unwrap_or(DEFAULT_MAX_EXPORT_EDGES).min(MAX_MAX_EDGES) as usize;
    let depth = params.depth.unwrap_or(2).max(1) as usize;
    let focus = params.focus.as_ref();

    let rg = RepoGraph::build(idx, cache, codegraph::CODEGRAPH_SCAN_CAP)?;

    match params.granularity.as_str() {
        "module" => run_tier_grouped(
            shared,
            &rg,
            idx,
            cache,
            churn,
            focus,
            Some(depth),
            &params,
            max_nodes,
            max_edges,
            notice,
            started,
        ),
        "file" => run_tier_grouped(
            shared, &rg, idx, cache, churn, focus, None, &params, max_nodes, max_edges, notice, started,
        ),
        "symbol" => run_tier_symbol(
            &rg, cache, idx, churn, focus, &params, max_nodes, max_edges, notice, started,
        ),
        other => Err(McpError::invalid_params(
            format!("granularity must be \"module\", \"file\", or \"symbol\", got {other:?}"),
            None,
        )),
    }
}

/// Min-max normalize to `[0, 1]`; a flat input maps to all-zero (that signal doesn't
/// discriminate, so it contributes nothing to the blend).
fn minmax_norm(vals: &[f64]) -> Vec<f64> {
    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
    for &v in vals {
        lo = lo.min(v);
        hi = hi.max(v);
    }
    let span = hi - lo;
    if span <= f64::EPSILON {
        return vec![0.0; vals.len()];
    }
    vals.iter().map(|&v| (v - lo) / span).collect()
}

/// Directory label = the first `depth` path components (the file name dropped). A
/// top-level file with no directory maps to `"."`.
fn dir_label(path: &str, depth: usize) -> String {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() <= 1 {
        return ".".to_string();
    }
    let dirs = &parts[..parts.len() - 1];
    let take = dirs.len().min(depth);
    dirs[..take].join("/")
}

/// Group-assignment bookkeeping produced by [`assign_file_groups`], carried as a unit so the
/// four parallel per-group vectors stay index-aligned by group id.
struct FileGroups {
    /// file id → group id (`None` = file filtered out by `focus`).
    group_of: Vec<Option<u32>>,
    /// group id → label (directory prefix, or the file path at file granularity).
    labels: Vec<String>,
    /// group id → representative path (only populated at file granularity).
    group_paths: Vec<Option<RelPath>>,
    /// group id → summed churn of its member files.
    group_churn: Vec<u32>,
}

/// Ranking outputs [`rank_groups`] hands to [`build_group_nodes`]. `scores`/`prn` stay
/// full-length (indexed by group id) so the node builder can look them up directly.
struct GroupRanking {
    /// Surviving group ids in ranked order, already knee-cut to `max_nodes`.
    survivor_gids: Vec<u32>,
    /// group id → blended score.
    scores: Vec<f64>,
    /// group id → normalized PageRank (reported on each node).
    prn: Vec<f64>,
}

/// First pass: fold each in-focus file into its group (directory rollup or the file itself),
/// minting stable ascending group ids and accumulating per-group churn. Isolated so the
/// grouping bookkeeping stays separate from graph construction and ranking.
fn assign_file_groups(
    rg: &RepoGraph,
    focus: Option<&RelPath>,
    rollup: Option<usize>,
    churn: Option<&AHashMap<RelPath, u32>>,
) -> FileGroups {
    let mut group_of: Vec<Option<u32>> = vec![None; rg.files.len()];
    let mut label_to_gid: AHashMap<String, u32> = AHashMap::new();
    let mut labels: Vec<String> = Vec::new();
    let mut group_paths: Vec<Option<RelPath>> = Vec::new();
    let mut group_churn: Vec<u32> = Vec::new();

    for (fid, path) in rg.files.iter().enumerate() {
        let ps = path.as_str().unwrap_or("");
        if let Some(fx) = focus
            && !path.as_bytes().starts_with(fx.as_bytes())
        {
            continue;
        }
        let (label, gpath) = match rollup {
            Some(d) => (dir_label(ps, d), None),
            None => (ps.to_string(), Some(path.clone())),
        };
        let gid = match label_to_gid.get(&label) {
            Some(&g) => g,
            None => {
                let g = labels.len() as u32;
                label_to_gid.insert(label.clone(), g);
                labels.push(label);
                group_paths.push(gpath);
                group_churn.push(0);
                g
            }
        };
        group_of[fid] = Some(gid);
        if let Some(ch) = churn {
            let c = ch.get(path).copied().unwrap_or(0);
            let slot = &mut group_churn[gid as usize];
            *slot = slot.saturating_add(c);
        }
    }

    FileGroups {
        group_of,
        labels,
        group_paths,
        group_churn,
    }
}

/// Collapse file-level call edges to inter-group edges and materialize the group-level
/// [`Graph`]. Kept separate so PageRank/SCC run over an already-aggregated adjacency.
fn build_group_graph(rg: &RepoGraph, group_of: &[Option<u32>], ngroups: usize) -> (AHashMap<(u32, u32), u32>, Graph) {
    let mut gedges: AHashMap<(u32, u32), u32> = AHashMap::new();
    for s in 0..rg.files.len() {
        let Some(gs) = group_of[s] else { continue };
        for &(d, w) in &rg.graph.out[s] {
            let Some(gd) = group_of[d as usize] else { continue };
            if gs != gd {
                *gedges.entry((gs, gd)).or_default() += w;
            }
        }
    }

    let mut g = Graph::empty(ngroups);
    for (&(s, d), &w) in &gedges {
        g.out[s as usize].push((d, w));
        g.in_[d as usize].push((s, w));
    }
    g.sort();
    (gedges, g)
}

/// Blend degree + PageRank + churn into a per-group score, then knee-cut the ranked head to at
/// most `max_nodes` survivors. Returns the ranking inputs the node builder reuses (`scores`,
/// `prn`) alongside the surviving ids, so all scoring math lives in one place.
fn rank_groups(g: &Graph, group_churn: &[u32], labels: &[String], has_churn: bool, max_nodes: usize) -> GroupRanking {
    let ngroups = g.n;
    let pr = g.pagerank();
    let deg: Vec<f64> = (0..ngroups).map(|i| (g.fan_in(i) + g.fan_out(i)) as f64).collect();
    let prv: Vec<f64> = pr.iter().map(|&r| r as f64).collect();
    let chv: Vec<f64> = group_churn.iter().map(|&c| c as f64).collect();
    let degn = minmax_norm(&deg);
    let prn = minmax_norm(&prv);
    let chn = minmax_norm(&chv);
    let (w_pr, w_deg, w_churn) = weights(has_churn);
    let scores: Vec<f64> = (0..ngroups)
        .map(|i| w_pr * prn[i] + w_deg * degn[i] + w_churn * chn[i])
        .collect();

    let mut order: Vec<usize> = (0..ngroups).collect();
    order.sort_by(|&a, &b| {
        scores[b]
            .partial_cmp(&scores[a])
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(labels[a].cmp(&labels[b]))
    });
    let ranked_scores: Vec<f64> = order.iter().map(|&i| scores[i]).collect();
    let cut = knee_cutoff(&ranked_scores).min(max_nodes).min(ngroups);
    let survivor_gids: Vec<u32> = order[..cut].iter().map(|&i| i as u32).collect();
    GroupRanking {
        survivor_gids,
        scores,
        prn,
    }
}

/// Materialize surviving groups into [`ArchNode`] rows, apply the token budget, then stamp SCC
/// cluster ids. Bundled because budget truncation decides `kept`, which the cycle pass consumes.
/// Returns the kept nodes, the `gid -> local` remap edges need, the cycle clusters, and whether
/// the budget trimmed the list.
fn build_group_nodes(
    ranking: &GroupRanking,
    g: &Graph,
    groups: &FileGroups,
    churn: Option<&AHashMap<RelPath, u32>>,
    comp: &[u32],
    gedges: &AHashMap<(u32, u32), u32>,
    max_tokens: Option<u32>,
) -> (Vec<ArchNode>, AHashMap<u32, u32>, Vec<CycleCluster>, bool) {
    let GroupRanking {
        survivor_gids,
        scores,
        prn,
    } = ranking;
    let prelim: Vec<ArchNode> = survivor_gids
        .iter()
        .enumerate()
        .map(|(local, &gid)| {
            let gi = gid as usize;
            ArchNode {
                id: local as u32,
                label: groups.labels[gi].clone(),
                path: groups.group_paths[gi].clone(),
                name: None,
                kind: None,
                start_row: None,
                signature: None,
                fan_in: g.fan_in(gi),
                fan_out: g.fan_out(gi),
                pagerank: Some(prn[gi] as f32),
                commits_touching: churn.map(|_| groups.group_churn[gi]),
                score: scores[gi] as f32,
                scc_id: None,
            }
        })
        .collect();
    let budgeted = apply_budget(prelim, max_tokens);
    let mut nodes = budgeted.items;
    let kept = nodes.len();

    let mut local_of: AHashMap<u32, u32> = AHashMap::with_capacity(kept);
    for (local, &gid) in survivor_gids[..kept].iter().enumerate() {
        local_of.insert(gid, local as u32);
    }

    let (cycles, scc_of_local) = build_cycles(comp, &survivor_gids[..kept], gedges, &local_of);
    for node in &mut nodes {
        if let Some(&sid) = scc_of_local.get(&node.id) {
            node.scc_id = Some(sid);
        }
    }
    (nodes, local_of, cycles, budgeted.budgeted)
}

#[allow(clippy::too_many_arguments)]
fn run_tier_grouped(
    shared: &super::shared_state::SharedReadStack,
    rg: &RepoGraph,
    idx: Option<&IndexDb>,
    cache: &MapCache,
    churn: Option<&AHashMap<RelPath, u32>>,
    focus: Option<&RelPath>,
    rollup: Option<usize>,
    params: &ArchitectureMapParams,
    max_nodes: usize,
    max_edges: usize,
    notice: Option<super::types::LifecycleNotice>,
    started: std::time::Instant,
) -> Result<CallToolResult, McpError> {
    let groups = assign_file_groups(rg, focus, rollup, churn);
    let ngroups = groups.labels.len();

    let (gedges, g) = build_group_graph(rg, &groups.group_of, ngroups);
    let comp = g.tarjan_scc();
    let ranking = rank_groups(&g, &groups.group_churn, &groups.labels, churn.is_some(), max_nodes);
    let (nodes, local_of, cycles, budgeted) =
        build_group_nodes(&ranking, &g, &groups, churn, &comp, &gedges, params.max_tokens);

    let sel = EdgeKindSet::from_edges_param(&params.edges);
    let (lane, lane_truncated) = grouped_lane_edges(shared, idx, cache, rg, &groups.group_of, sel, focus)?;
    let edge_count_total = ((if sel.calls { gedges.len() } else { 0 }) + lane.len()) as u32;
    let edges = emit_grouped_edges(&gedges, &lane, &local_of, sel.calls, max_edges);

    json_result(&ArchitectureMapResponse {
        granularity: params.granularity.clone(),
        node_count_total: ngroups as u32,
        edge_count_total,
        nodes,
        edges,
        cycles,
        truncated: rg.truncated || lane_truncated,
        truncation_reason: rg.truncation_reason,
        budgeted,
        notice,
        elapsed_us: elapsed_us(started),
    })
}

/// Ranking weights: (pagerank, degree, churn). Churn drops out (renormalized) when the
/// overlay is absent.
fn weights(has_churn: bool) -> (f64, f64, f64) {
    if has_churn {
        (0.5, 0.3, 0.2)
    } else {
        (0.625, 0.375, 0.0)
    }
}

/// Cluster kept nodes by shared SCC component; emit clusters with >1 member. Returns the
/// clusters plus a `local id → scc_id` map for stamping nodes.
fn build_cycles(
    comp: &[u32],
    kept_gids: &[u32],
    gedges: &AHashMap<(u32, u32), u32>,
    local_of: &AHashMap<u32, u32>,
) -> (Vec<CycleCluster>, AHashMap<u32, u32>) {
    let mut by_comp: AHashMap<u32, Vec<u32>> = AHashMap::new();
    for &gid in kept_gids {
        let c = comp[gid as usize];
        by_comp.entry(c).or_default().push(local_of[&gid]);
    }
    let mut clusters: Vec<(u32, Vec<u32>)> = by_comp.into_iter().filter(|(_, m)| m.len() > 1).collect();
    for (_, m) in &mut clusters {
        m.sort_unstable();
    }
    clusters.sort_by_key(|(_, m)| m[0]);

    let mut scc_of_local: AHashMap<u32, u32> = AHashMap::new();
    let mut out: Vec<CycleCluster> = Vec::with_capacity(clusters.len());
    for (scc_id, (comp_id, members)) in clusters.into_iter().enumerate() {
        for &loc in &members {
            scc_of_local.insert(loc, scc_id as u32);
        }
        let member_gids: AHashSet<u32> = kept_gids
            .iter()
            .copied()
            .filter(|g| comp[*g as usize] == comp_id)
            .collect();
        let internal = gedges
            .keys()
            .filter(|(s, d)| member_gids.contains(s) && member_gids.contains(d))
            .count() as u32;
        out.push(CycleCluster {
            scc_id: scc_id as u32,
            members,
            internal_edges: internal,
        });
    }
    (out, scc_of_local)
}

/// Aggregate codegraph import/inherit edges to the tier's group granularity. Returns
/// `(gs, gd, kind) -> (weight, provenance)` for inter-group edges, provenance folded to the
/// strongest tier. Empty when no non-call lane is selected — so the default `edges="calls"`
/// path builds no codegraph and pays nothing extra.
fn grouped_lane_edges(
    shared: &super::shared_state::SharedReadStack,
    idx: Option<&IndexDb>,
    cache: &MapCache,
    rg: &RepoGraph,
    group_of: &[Option<u32>],
    sel: EdgeKindSet,
    focus: Option<&RelPath>,
) -> Result<(LaneEdges, bool), McpError> {
    let mut out: LaneEdges = AHashMap::new();
    if !sel.imports && !sel.inherits {
        return Ok((out, false));
    }
    let lane_kinds = EdgeKindSet {
        calls: false,
        imports: sel.imports,
        inherits: sel.inherits,
        contains: false,
        annotates: false,
        cites: false,
        documents: false,
    };
    let cg = shared.graph(
        idx,
        cache,
        &BuildOpts {
            kinds: lane_kinds,
            focus: focus.cloned(),
            scan_cap: codegraph::CODEGRAPH_SCAN_CAP,
        },
    )?;
    let mut file_id: AHashMap<&RelPath, u32> = AHashMap::with_capacity(rg.files.len());
    for (i, p) in rg.files.iter().enumerate() {
        file_id.insert(p, i as u32);
    }
    for e in &cg.edges {
        let (Some(sf), Some(df)) = (e.from.file(), e.to.file()) else {
            continue;
        };
        let (Some(&sfi), Some(&dfi)) = (file_id.get(sf), file_id.get(df)) else {
            continue;
        };
        let (Some(gs), Some(gd)) = (group_of[sfi as usize], group_of[dfi as usize]) else {
            continue;
        };
        if gs == gd {
            continue;
        }
        out.entry((gs, gd, e.kind))
            .and_modify(|(w, p)| {
                *w += e.weight;
                if e.provenance.rank() > p.rank() {
                    *p = e.provenance;
                }
            })
            .or_insert((e.weight, e.provenance));
    }
    Ok((out, cg.truncated))
}

/// Merge call + lane edges among surviving groups, heaviest first, capped. Call edges are
/// name-based at this granularity, so they carry the INFERRED floor (ADR-0002); lane edges
/// carry the provenance derived by the codegraph.
fn emit_grouped_edges(
    gedges: &AHashMap<(u32, u32), u32>,
    lane: &LaneEdges,
    local_of: &AHashMap<u32, u32>,
    include_calls: bool,
    max_edges: usize,
) -> Vec<ArchEdge> {
    let mut edges: Vec<ArchEdge> = Vec::new();
    if include_calls {
        for (&(s, d), &w) in gedges {
            if let (Some(&from), Some(&to)) = (local_of.get(&s), local_of.get(&d)) {
                edges.push(ArchEdge {
                    from,
                    to,
                    weight: w,
                    kind: "calls".to_string(),
                    provenance: Provenance::Inferred.as_str().to_string(),
                    confidence: Provenance::Inferred.confidence(),
                });
            }
        }
    }
    for (&(s, d, kind), &(w, prov)) in lane {
        if let (Some(&from), Some(&to)) = (local_of.get(&s), local_of.get(&d)) {
            edges.push(ArchEdge {
                from,
                to,
                weight: w,
                kind: kind.as_str().to_string(),
                provenance: prov.as_str().to_string(),
                confidence: prov.confidence(),
            });
        }
    }
    edges.sort_by(|a, b| {
        b.weight
            .cmp(&a.weight)
            .then(a.from.cmp(&b.from))
            .then(a.to.cmp(&b.to))
            .then_with(|| a.kind.cmp(&b.kind))
    });
    edges.truncate(max_edges);
    edges
}

struct SymCand {
    path: RelPath,
    name: String,
    kind: &'static str,
    start_row: u32,
    start_byte: u32,
    end_byte: u32,
    signature: Option<String>,
    /// Raw name-based call count (reported verbatim — the honest count).
    fan_in: u32,
    /// Specificity-weighted hub-ness = `fan_in / def_count`. The ranking signal: it demotes
    /// ubiquitous names whose fan-in is spread across many definitions.
    hub: f64,
    churn: u32,
}

/// Collect in-focus function-like symbols, score each by specificity-weighted hub-ness
/// (`fan_in / def_count`), sort deterministically, and knee-cut to `max_nodes`. Returns the
/// surviving candidates plus the pre-cut population size (`node_count_total`, reported honestly).
fn collect_symbol_candidates(
    rg: &RepoGraph,
    cache: &MapCache,
    churn: Option<&AHashMap<RelPath, u32>>,
    focus: Option<&RelPath>,
    max_nodes: usize,
) -> (Vec<SymCand>, u32) {
    let mut cands: Vec<SymCand> = Vec::new();
    for (path, l1) in &cache.by_path {
        if let Some(fx) = focus
            && !path.as_bytes().starts_with(fx.as_bytes())
        {
            continue;
        }
        let c = churn.and_then(|ch| ch.get(path)).copied().unwrap_or(0);
        for sym in &l1.symbols {
            if !is_function_like(sym.kind) {
                continue;
            }
            let fan_in = rg.callee_counts.get(&sym.name).copied().unwrap_or(0);
            let def_count = rg.def_counts.get(&sym.name).copied().unwrap_or(1).max(1);
            cands.push(SymCand {
                path: path.clone(),
                name: sym.name.clone(),
                kind: kind_to_str(sym.kind),
                start_row: sym.start_row,
                start_byte: sym.start_byte,
                end_byte: sym.end_byte,
                signature: sym.signature.clone(),
                fan_in,
                hub: fan_in as f64 / def_count as f64,
                churn: c,
            });
        }
    }
    let node_count_total = cands.len() as u32;

    cands.sort_by(|a, b| {
        b.hub
            .partial_cmp(&a.hub)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.path.cmp(&b.path))
            .then(a.name.cmp(&b.name))
            .then(a.start_row.cmp(&b.start_row))
    });
    let hub_curve: Vec<f64> = cands.iter().map(|c| c.hub).collect();
    let cut = knee_cutoff(&hub_curve).min(max_nodes).min(cands.len());
    cands.truncate(cut);
    (cands, node_count_total)
}

/// Second pass over each survivor file's call sites: attribute every call to the enclosing
/// survivor by byte-range containment, building name-based inter-survivor edges and per-symbol
/// distinct-callee fan-out. Isolated because it is the only `?`-fallible (call-index) step here.
fn build_symbol_call_edges(
    survivors: &[SymCand],
    idx: Option<&IndexDb>,
    cache: &MapCache,
) -> Result<SymbolCallEdges, McpError> {
    let mut by_file: AHashMap<RelPath, Vec<u32>> = AHashMap::new();
    let mut name_to_locals: AHashMap<&str, Vec<u32>> = AHashMap::new();
    for (loc, s) in survivors.iter().enumerate() {
        by_file.entry(s.path.clone()).or_default().push(loc as u32);
        name_to_locals.entry(s.name.as_str()).or_default().push(loc as u32);
    }
    let mut fan_out_sets: Vec<AHashSet<String>> = vec![AHashSet::new(); survivors.len()];
    let mut edge_map: AHashMap<(u32, u32), u32> = AHashMap::new();
    for (file, locals) in &by_file {
        for_each_call_in_file(idx, cache, file, |callee, start_byte| {
            for &loc in locals {
                let s = &survivors[loc as usize];
                if s.start_byte <= start_byte && start_byte < s.end_byte {
                    let fo = &mut fan_out_sets[loc as usize];
                    if !fo.contains(callee) {
                        fo.insert(callee.to_string());
                    }
                    if let Some(targets) = name_to_locals.get(callee) {
                        for &t in targets {
                            if t != loc {
                                *edge_map.entry((loc, t)).or_default() += 1;
                            }
                        }
                    }
                }
            }
            true
        })?;
    }
    let fan_out: Vec<u32> = fan_out_sets.iter().map(|s| s.len() as u32).collect();
    Ok((fan_out, edge_map))
}

/// Build the symbol-tier [`ArchNode`] rows (normalized hub `score`, reported `fan_in`, computed
/// `fan_out`) and apply the token budget. Returns the kept rows and whether the budget trimmed.
fn build_symbol_nodes(
    survivors: &[SymCand],
    fan_out: &[u32],
    churn: Option<&AHashMap<RelPath, u32>>,
    max_tokens: Option<u32>,
) -> (Vec<ArchNode>, bool) {
    let hubv: Vec<f64> = survivors.iter().map(|c| c.hub).collect();
    let hubn = minmax_norm(&hubv);

    let prelim: Vec<ArchNode> = survivors
        .iter()
        .enumerate()
        .map(|(loc, s)| ArchNode {
            id: loc as u32,
            label: s.path.as_str().unwrap_or("").to_string(),
            path: Some(s.path.clone()),
            name: Some(s.name.clone()),
            kind: Some(s.kind.to_string()),
            start_row: Some(s.start_row),
            signature: s.signature.clone(),
            fan_in: s.fan_in,
            fan_out: fan_out[loc],
            pagerank: None,
            commits_touching: churn.map(|_| s.churn),
            score: hubn[loc] as f32,
            scc_id: None,
        })
        .collect();
    let budgeted = apply_budget(prelim, max_tokens);
    (budgeted.items, budgeted.budgeted)
}

/// Keep only edges between budget-surviving symbols (`local < kept`), sort heaviest-first, and
/// cap to `max_edges`. Returns the capped edges plus the pre-cap total for `edge_count_total`.
fn finalize_symbol_edges(edge_map: &AHashMap<(u32, u32), u32>, kept: usize, max_edges: usize) -> (Vec<ArchEdge>, u32) {
    let mut edges: Vec<ArchEdge> = edge_map
        .iter()
        .filter(|((from, to), _)| (*from as usize) < kept && (*to as usize) < kept)
        .map(|(&(from, to), &w)| ArchEdge {
            from,
            to,
            weight: w,
            kind: "calls".to_string(),
            // Symbol-tier edges are name-based call edges; import/inherit lanes are a
            // file/module-tier surface this iteration (ADR-0002).
            provenance: Provenance::Inferred.as_str().to_string(),
            confidence: Provenance::Inferred.confidence(),
        })
        .collect();
    edges.sort_by(|a, b| b.weight.cmp(&a.weight).then(a.from.cmp(&b.from)).then(a.to.cmp(&b.to)));
    let edge_count_total = edges.len() as u32;
    edges.truncate(max_edges);
    (edges, edge_count_total)
}

#[allow(clippy::too_many_arguments)]
fn run_tier_symbol(
    rg: &RepoGraph,
    cache: &MapCache,
    idx: Option<&IndexDb>,
    churn: Option<&AHashMap<RelPath, u32>>,
    focus: Option<&RelPath>,
    params: &ArchitectureMapParams,
    max_nodes: usize,
    max_edges: usize,
    notice: Option<super::types::LifecycleNotice>,
    started: std::time::Instant,
) -> Result<CallToolResult, McpError> {
    let (survivors, node_count_total) = collect_symbol_candidates(rg, cache, churn, focus, max_nodes);
    let (fan_out, edge_map) = build_symbol_call_edges(&survivors, idx, cache)?;
    let (nodes, budgeted) = build_symbol_nodes(&survivors, &fan_out, churn, params.max_tokens);
    let kept = nodes.len();
    let (edges, edge_count_total) = finalize_symbol_edges(&edge_map, kept, max_edges);

    json_result(&ArchitectureMapResponse {
        granularity: params.granularity.clone(),
        node_count_total,
        edge_count_total,
        nodes,
        edges,
        cycles: Vec::new(),
        truncated: rg.truncated,
        truncation_reason: rg.truncation_reason,
        budgeted,
        notice,
        elapsed_us: elapsed_us(started),
    })
}

/// Commits-touching per file over the last `window` commits — the churn overlay. Mirrors
/// the aggregation in `hot_files` (counts only). Returns `None`-worthy errors as `Err`;
/// the caller degrades to no overlay.
pub(crate) fn churn_commit_counts(state: &super::ServerState, window: u32) -> Result<AHashMap<RelPath, u32>, McpError> {
    let repo = super::helpers::require_git_repo(state)?;
    let head = super::helpers::head_sha(repo)?;
    let commits: Vec<crate::git::CommitInfo> = match super::helpers::git_history_if_fresh(state, &head) {
        Some(index) => index.window_commits(window as usize),
        None => state
            .shared
            .git_cache
            .log(repo, &head, None, window, true)
            .map_err(|e| McpError::internal_error(format!("log: {e}"), None))?
            .as_ref()
            .clone(),
    };
    let mut counts: AHashMap<RelPath, u32> = AHashMap::new();
    for c in &commits {
        for (path, _kind) in &c.files {
            *counts.entry(path.clone()).or_default() += 1;
        }
    }
    Ok(counts)
}