lean-ctx 3.9.0

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
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
//! Graph primitives for `ctx_graph`: `neighbors`, `path` (shortest path) and
//! `explain`. These are graphify-style traversal/inspection helpers that work on
//! the same file-level graph the dashboard renders (`GraphProvider::edges`), so
//! the MCP answers and the visual graph always agree.
//!
//! All three accept `format="json"` for machine consumption; otherwise they emit
//! compact, token-light text with a `[ctx_graph <action>: N tok]` footer like the
//! other actions.

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

use crate::core::graph_analysis::edge_confidence;
use crate::core::graph_index;
use crate::core::graph_provider::{self, EdgeInfo};
use crate::core::protocol::shorten_path;
use crate::core::tokens::count_tokens;

/// One adjacency entry: a neighbour reached via an edge of `kind`/`weight`.
struct NeighborRef {
    node: String,
    kind: String,
    weight: f64,
}

/// A directed, file-level adjacency view built once from `GraphProvider::edges`.
/// Node ids are repo-relative file paths — identical to the dashboard graph.
struct Adj {
    nodes: Vec<String>,
    node_set: HashSet<String>,
    out: HashMap<String, Vec<NeighborRef>>,
    inc: HashMap<String, Vec<NeighborRef>>,
}

impl Adj {
    fn build(edges: &[EdgeInfo], file_paths: &[String]) -> Self {
        let mut out: HashMap<String, Vec<NeighborRef>> = HashMap::new();
        let mut inc: HashMap<String, Vec<NeighborRef>> = HashMap::new();
        let mut node_set: HashSet<String> = HashSet::new();
        for p in file_paths {
            node_set.insert(p.clone());
        }
        for e in edges {
            node_set.insert(e.from.clone());
            node_set.insert(e.to.clone());
            out.entry(e.from.clone()).or_default().push(NeighborRef {
                node: e.to.clone(),
                kind: e.kind.clone(),
                weight: e.weight,
            });
            inc.entry(e.to.clone()).or_default().push(NeighborRef {
                node: e.from.clone(),
                kind: e.kind.clone(),
                weight: e.weight,
            });
        }
        let mut nodes: Vec<String> = node_set.iter().cloned().collect();
        nodes.sort();
        Self {
            nodes,
            node_set,
            out,
            inc,
        }
    }

    /// Resolve a user-supplied path to a concrete graph node. Tries an exact
    /// repo-relative match first, then a unique path/basename suffix match.
    fn resolve(&self, input: &str, root: &str) -> Result<String, String> {
        let rel = graph_index::graph_relative_key(input, root);
        if self.node_set.contains(&rel) {
            return Ok(rel);
        }
        let needle = graph_index::graph_match_key(&rel);
        if self.node_set.contains(&needle) {
            return Ok(needle);
        }
        let base = needle.rsplit('/').next().unwrap_or(&needle).to_string();
        let suffix = format!("/{needle}");
        let base_suffix = format!("/{base}");
        let cands: Vec<&String> = self
            .nodes
            .iter()
            .filter(|n| {
                let nk = graph_index::graph_match_key(n);
                nk == needle || nk.ends_with(&suffix) || nk == base || nk.ends_with(&base_suffix)
            })
            .collect();
        match cands.len() {
            0 => Err(format!(
                "Node not found in graph: {input}\nRun ctx_graph action='build' to (re)index, or pass a path that exists in the project."
            )),
            1 => Ok(cands[0].clone()),
            _ => {
                // Show full repo-relative paths (not basenames) so the caller
                // can actually tell the candidates apart.
                let list = cands
                    .iter()
                    .take(10)
                    .map(|c| format!("  {c}"))
                    .collect::<Vec<_>>()
                    .join("\n");
                let more = if cands.len() > 10 {
                    format!("\n  … and {} more", cands.len() - 10)
                } else {
                    String::new()
                };
                Err(format!(
                    "'{input}' is ambiguous ({} matches) — pass a more specific path:\n{list}{more}",
                    cands.len()
                ))
            }
        }
    }

    fn outgoing(&self, node: &str) -> Vec<&NeighborRef> {
        let mut v: Vec<&NeighborRef> = self
            .out
            .get(node)
            .map(|x| x.iter().collect())
            .unwrap_or_default();
        v.sort_by(|a, b| a.node.cmp(&b.node).then_with(|| a.kind.cmp(&b.kind)));
        v
    }

    fn incoming(&self, node: &str) -> Vec<&NeighborRef> {
        let mut v: Vec<&NeighborRef> = self
            .inc
            .get(node)
            .map(|x| x.iter().collect())
            .unwrap_or_default();
        v.sort_by(|a, b| a.node.cmp(&b.node).then_with(|| a.kind.cmp(&b.kind)));
        v
    }

    /// Unique undirected neighbours (out ∪ inc), deterministically sorted.
    fn undirected_neighbors(&self, node: &str) -> Vec<String> {
        let mut set: HashSet<&str> = HashSet::new();
        if let Some(v) = self.out.get(node) {
            for nb in v {
                set.insert(nb.node.as_str());
            }
        }
        if let Some(v) = self.inc.get(node) {
            for nb in v {
                set.insert(nb.node.as_str());
            }
        }
        let mut out: Vec<String> = set.into_iter().map(str::to_string).collect();
        out.sort();
        out
    }

    /// The strongest edge directly connecting `a` and `b`, with its direction.
    /// Direction: `Forward` = a→b, `Backward` = b→a.
    fn edge_between(&self, a: &str, b: &str) -> Option<(Direction, String, f64)> {
        let mut best: Option<(Direction, String, f64)> = None;
        let mut consider = |dir: Direction, kind: &str, weight: f64| {
            let conf = edge_confidence(kind, weight);
            if best.as_ref().is_none_or(|(_, _, c)| conf > *c) {
                best = Some((dir, kind.to_string(), conf));
            }
        };
        if let Some(v) = self.out.get(a) {
            for nb in v.iter().filter(|nb| nb.node == b) {
                consider(Direction::Forward, &nb.kind, nb.weight);
            }
        }
        if let Some(v) = self.inc.get(a) {
            for nb in v.iter().filter(|nb| nb.node == b) {
                consider(Direction::Backward, &nb.kind, nb.weight);
            }
        }
        best
    }

    /// Shortest undirected path `from → to` (BFS, deterministic). Includes both
    /// endpoints. `None` when the two nodes are in different components.
    fn bfs_path(&self, from: &str, to: &str) -> Option<Vec<String>> {
        if from == to {
            return Some(vec![from.to_string()]);
        }
        let mut prev: HashMap<String, String> = HashMap::new();
        let mut visited: HashSet<String> = HashSet::new();
        let mut queue: VecDeque<String> = VecDeque::new();
        visited.insert(from.to_string());
        queue.push_back(from.to_string());
        while let Some(cur) = queue.pop_front() {
            for nb in self.undirected_neighbors(&cur) {
                if visited.contains(&nb) {
                    continue;
                }
                visited.insert(nb.clone());
                prev.insert(nb.clone(), cur.clone());
                if nb == to {
                    return Some(reconstruct(&prev, from, to));
                }
                queue.push_back(nb);
            }
        }
        None
    }

    /// BFS distance rings from `start` (undirected), capped at `max_depth`.
    /// Returns distance → sorted node list (excludes the start node).
    fn bfs_rings(&self, start: &str, max_depth: usize) -> Vec<(usize, Vec<String>)> {
        let mut dist: HashMap<String, usize> = HashMap::new();
        let mut queue: VecDeque<String> = VecDeque::new();
        dist.insert(start.to_string(), 0);
        queue.push_back(start.to_string());
        while let Some(cur) = queue.pop_front() {
            let d = dist[&cur];
            if d >= max_depth {
                continue;
            }
            for nb in self.undirected_neighbors(&cur) {
                if !dist.contains_key(&nb) {
                    dist.insert(nb.clone(), d + 1);
                    queue.push_back(nb);
                }
            }
        }
        let mut rings: HashMap<usize, Vec<String>> = HashMap::new();
        for (node, d) in dist {
            if d == 0 {
                continue;
            }
            rings.entry(d).or_default().push(node);
        }
        let mut out: Vec<(usize, Vec<String>)> = rings
            .into_iter()
            .map(|(d, mut nodes)| {
                nodes.sort();
                (d, nodes)
            })
            .collect();
        out.sort_by_key(|(d, _)| *d);
        out
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Direction {
    Forward,
    Backward,
}

impl Direction {
    fn arrow(self) -> &'static str {
        match self {
            Direction::Forward => "->",
            Direction::Backward => "<-",
        }
    }
}

fn reconstruct(prev: &HashMap<String, String>, from: &str, to: &str) -> Vec<String> {
    let mut chain = vec![to.to_string()];
    let mut cur = to.to_string();
    while cur != from {
        match prev.get(&cur) {
            Some(p) => {
                chain.push(p.clone());
                cur = p.clone();
            }
            None => break,
        }
    }
    chain.reverse();
    chain
}

fn open_graph(root: &str) -> Result<graph_provider::OpenGraphProvider, String> {
    graph_provider::open_or_build(root)
        .ok_or_else(|| "No graph index found. Run ctx_graph with action='build' first.".to_string())
}

fn is_json(format: Option<&str>) -> bool {
    matches!(format, Some(f) if f.eq_ignore_ascii_case("json"))
}

/// `ctx_graph action=neighbors` — immediate (and optionally multi-hop) graph
/// neighbours of a file, split by direction and annotated with edge kind.
pub fn neighbors(
    path: Option<&str>,
    root: &str,
    depth: Option<usize>,
    format: Option<&str>,
) -> String {
    let Some(input) = path else {
        return "path is required for 'neighbors' action".to_string();
    };
    let open = match open_graph(root) {
        Ok(o) => o,
        Err(e) => return e,
    };
    let gp = &open.provider;
    let adj = Adj::build(&gp.edges(), &gp.file_paths());
    let node = match adj.resolve(input, root) {
        Ok(n) => n,
        Err(e) => return e,
    };
    let depth = depth.unwrap_or(1).clamp(1, 6);
    let outgoing = adj.outgoing(&node);
    let incoming = adj.incoming(&node);
    let rings = if depth > 1 {
        adj.bfs_rings(&node, depth)
    } else {
        Vec::new()
    };

    if is_json(format) {
        let out_json: Vec<_> = outgoing
            .iter()
            .map(|n| {
                serde_json::json!({
                    "node": n.node,
                    "kind": n.kind,
                    "confidence": round3(edge_confidence(&n.kind, n.weight)),
                })
            })
            .collect();
        let in_json: Vec<_> = incoming
            .iter()
            .map(|n| {
                serde_json::json!({
                    "node": n.node,
                    "kind": n.kind,
                    "confidence": round3(edge_confidence(&n.kind, n.weight)),
                })
            })
            .collect();
        let rings_json: Vec<_> = rings
            .iter()
            .map(|(d, nodes)| serde_json::json!({ "distance": d, "count": nodes.len(), "nodes": nodes }))
            .collect();
        let val = serde_json::json!({
            "node": node,
            "outgoing": out_json,
            "incoming": in_json,
            "rings": rings_json,
        });
        return serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string());
    }

    let mut out = format!("Neighbors of {}\n", shorten_path(&node));
    out.push_str(&format!(
        "\nOutgoing ({}) — this file depends on / references:\n",
        outgoing.len()
    ));
    if outgoing.is_empty() {
        out.push_str("  (none)\n");
    } else {
        for n in &outgoing {
            out.push_str(&format!(
                "  -> {:<48} {:<10} conf {:.2}\n",
                shorten_path(&n.node),
                n.kind,
                edge_confidence(&n.kind, n.weight)
            ));
        }
    }
    out.push_str(&format!(
        "\nIncoming ({}) — files that depend on / reference this:\n",
        incoming.len()
    ));
    if incoming.is_empty() {
        out.push_str("  (none)\n");
    } else {
        for n in &incoming {
            out.push_str(&format!(
                "  <- {:<48} {:<10} conf {:.2}\n",
                shorten_path(&n.node),
                n.kind,
                edge_confidence(&n.kind, n.weight)
            ));
        }
    }
    if depth > 1 {
        let total: usize = rings.iter().map(|(_, n)| n.len()).sum();
        out.push_str(&format!("\nReachable within {depth} hops: {total} nodes\n"));
        for (d, nodes) in &rings {
            out.push_str(&format!("  {} hop(s): {} nodes\n", d, nodes.len()));
        }
    }
    let tokens = count_tokens(&out);
    format!("{out}[ctx_graph neighbors: {tokens} tok]")
}

/// `ctx_graph action=path` — shortest connection between two files, with the
/// edge kind/direction of each hop.
pub fn shortest_path(
    from: Option<&str>,
    to: Option<&str>,
    root: &str,
    format: Option<&str>,
) -> String {
    let (Some(a), Some(b)) = (from, to) else {
        return "Both 'path' (from) and 'to' are required for 'path' action".to_string();
    };
    let open = match open_graph(root) {
        Ok(o) => o,
        Err(e) => return e,
    };
    let gp = &open.provider;
    let adj = Adj::build(&gp.edges(), &gp.file_paths());
    let na = match adj.resolve(a, root) {
        Ok(n) => n,
        Err(e) => return e,
    };
    let nb = match adj.resolve(b, root) {
        Ok(n) => n,
        Err(e) => return e,
    };

    let Some(chain) = adj.bfs_path(&na, &nb) else {
        if is_json(format) {
            return serde_json::json!({
                "from": na, "to": nb, "connected": false, "path": [],
            })
            .to_string();
        }
        return format!(
            "No path between {} and {} — they live in different components of the dependency graph.",
            shorten_path(&na),
            shorten_path(&nb)
        );
    };

    let hops = chain.len().saturating_sub(1);
    if is_json(format) {
        let steps: Vec<_> = chain
            .windows(2)
            .map(|w| {
                let (dir, kind, conf) = adj.edge_between(&w[0], &w[1]).unwrap_or((
                    Direction::Forward,
                    "related".to_string(),
                    0.5,
                ));
                serde_json::json!({
                    "from": w[0],
                    "to": w[1],
                    "direction": if dir == Direction::Forward { "forward" } else { "backward" },
                    "kind": kind,
                    "confidence": round3(conf),
                })
            })
            .collect();
        let val = serde_json::json!({
            "from": na, "to": nb, "connected": true, "hops": hops,
            "path": chain, "steps": steps,
        });
        return serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string());
    }

    let mut out = format!(
        "Shortest path {} -> {} ({} hops):\n\n",
        shorten_path(&na),
        shorten_path(&nb),
        hops
    );
    out.push_str(&format!("  {}\n", shorten_path(&chain[0])));
    for w in chain.windows(2) {
        let (dir, kind, conf) = adj.edge_between(&w[0], &w[1]).unwrap_or((
            Direction::Forward,
            "related".to_string(),
            0.5,
        ));
        out.push_str(&format!(
            "    {} {} (conf {:.2})\n  {}\n",
            dir.arrow(),
            kind,
            conf,
            shorten_path(&w[1])
        ));
    }
    let tokens = count_tokens(&out);
    format!("{out}[ctx_graph path: {tokens} tok]")
}

/// `ctx_graph action=explain` — why a file matters: degree, community, bridge
/// score, god-node rank and its most important couplings. Reuses the same
/// analyses the dashboard shows.
pub fn explain(path: Option<&str>, root: &str, format: Option<&str>) -> String {
    let Some(input) = path else {
        return "path is required for 'explain' action".to_string();
    };
    let open = match open_graph(root) {
        Ok(o) => o,
        Err(e) => return e,
    };
    let gp = &open.provider;
    let edges = gp.edges();
    let adj = Adj::build(&edges, &gp.file_paths());
    let node = match adj.resolve(input, root) {
        Ok(n) => n,
        Err(e) => return e,
    };

    let community = crate::core::community::detect_communities_for_provider(gp, root);
    let community_map = community.assignment_min_size(2);
    let god = crate::core::graph_analysis::compute_god_nodes(&edges, usize::MAX);
    let bridges = crate::core::graph_analysis::compute_bridge_nodes(&edges, usize::MAX);
    let surprising = crate::core::graph_analysis::find_surprising_connections(
        &edges,
        &community_map,
        usize::MAX,
    );

    let god_entry = god.iter().enumerate().find(|(_, g)| g.path == node);
    let (dep_in, dep_out, dep_degree) =
        god_entry.map_or((0, 0, 0), |(_, g)| (g.in_degree, g.out_degree, g.degree));
    let god_rank = god_entry.map(|(i, _)| i + 1);
    let bridge_entry = bridges.iter().enumerate().find(|(_, b)| b.path == node);
    let community_id = community_map.get(&node).copied();
    let community_info =
        community_id.and_then(|id| community.communities.iter().find(|c| c.id == id));
    let surprising_here: Vec<_> = surprising
        .iter()
        .filter(|s| s.from == node || s.to == node)
        .take(8)
        .collect();

    let out_all = adj.outgoing(&node);
    let inc_all = adj.incoming(&node);

    if is_json(format) {
        let val = serde_json::json!({
            "node": node,
            "dependency_degree": { "in": dep_in, "out": dep_out, "total": dep_degree },
            "god_node_rank": god_rank,
            "is_god_node": god_rank.is_some_and(|r| r <= 12),
            "bridge": bridge_entry.map(|(i, b)| serde_json::json!({
                "rank": i + 1, "betweenness": round3(b.betweenness),
            })),
            "community": community_info.map(|c| serde_json::json!({
                "id": c.id, "files": c.files.len(),
                "cohesion": round3(c.cohesion),
                "internal_edges": c.internal_edges, "external_edges": c.external_edges,
            })),
            "neighbors_all_kinds": { "out": out_all.len(), "in": inc_all.len() },
            "surprising_connections": surprising_here.iter().map(|s| serde_json::json!({
                "from": s.from, "to": s.to, "score": round3(s.score),
                "cross_community": s.cross_community,
            })).collect::<Vec<_>>(),
        });
        return serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string());
    }

    let mut out = format!("Why {} matters\n\n", shorten_path(&node));
    out.push_str(&format!(
        "Dependency degree: {dep_degree} (in {dep_in} · out {dep_out})\n"
    ));
    match god_rank {
        Some(r) if r <= 12 => {
            out.push_str(&format!("God-node: yes — rank #{r} (most connected)\n"));
        }
        Some(r) => out.push_str(&format!("God-node rank: #{r}\n")),
        None => out.push_str("God-node: no dependency edges\n"),
    }
    match bridge_entry {
        Some((i, b)) => out.push_str(&format!(
            "Bridge (betweenness): {:.2} — rank #{} (sits on many shortest paths)\n",
            b.betweenness,
            i + 1
        )),
        None => out.push_str("Bridge: not on critical paths\n"),
    }
    match community_info {
        Some(c) => out.push_str(&format!(
            "Community: #{} — {} files, cohesion {:.2} (internal {} / external {})\n",
            c.id,
            c.files.len(),
            c.cohesion,
            c.internal_edges,
            c.external_edges
        )),
        None => out.push_str("Community: isolated (no module ≥2 files)\n"),
    }
    out.push_str(&format!(
        "Total neighbors (all edge kinds): {} (out {} · in {})\n",
        out_all.len() + inc_all.len(),
        out_all.len(),
        inc_all.len()
    ));

    let top_dependents: Vec<&String> = inc_all
        .iter()
        .filter(|n| crate::core::graph_analysis::is_dependency_kind(&n.kind))
        .map(|n| &n.node)
        .take(8)
        .collect();
    if !top_dependents.is_empty() {
        out.push_str(&format!(
            "\nTop dependents (fan-in, {}):\n",
            top_dependents.len()
        ));
        for d in &top_dependents {
            out.push_str(&format!("  {}\n", shorten_path(d)));
        }
    }
    let top_deps: Vec<&String> = out_all
        .iter()
        .filter(|n| crate::core::graph_analysis::is_dependency_kind(&n.kind))
        .map(|n| &n.node)
        .take(8)
        .collect();
    if !top_deps.is_empty() {
        out.push_str(&format!(
            "\nTop dependencies (fan-out, {}):\n",
            top_deps.len()
        ));
        for d in &top_deps {
            out.push_str(&format!("  {}\n", shorten_path(d)));
        }
    }
    if !surprising_here.is_empty() {
        out.push_str(&format!(
            "\nSurprising connections ({}):\n",
            surprising_here.len()
        ));
        for s in &surprising_here {
            let other = if s.from == node { &s.to } else { &s.from };
            out.push_str(&format!(
                "  {} (score {:.2}{})\n",
                shorten_path(other),
                s.score,
                if s.cross_community {
                    ", cross-community"
                } else {
                    ""
                }
            ));
        }
    }
    let tokens = count_tokens(&out);
    format!("{out}[ctx_graph explain: {tokens} tok]")
}

fn round3(v: f64) -> f64 {
    (v * 1000.0).round() / 1000.0
}

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

    fn edge(from: &str, to: &str, kind: &str) -> EdgeInfo {
        EdgeInfo {
            from: from.into(),
            to: to.into(),
            kind: kind.into(),
            weight: 1.0,
        }
    }

    /// a -> b -> c, plus an isolated d. Used by most traversal tests.
    fn sample() -> Adj {
        let edges = vec![
            edge("src/a.rs", "src/b.rs", "import"),
            edge("src/b.rs", "src/c.rs", "import"),
        ];
        let files = vec![
            "src/a.rs".to_string(),
            "src/b.rs".to_string(),
            "src/c.rs".to_string(),
            "src/d.rs".to_string(),
        ];
        Adj::build(&edges, &files)
    }

    #[test]
    fn resolve_exact_and_basename() {
        let adj = sample();
        // Exact repo-relative match.
        assert_eq!(adj.resolve("src/a.rs", "/proj").unwrap(), "src/a.rs");
        // Unique basename match.
        assert_eq!(adj.resolve("c.rs", "/proj").unwrap(), "src/c.rs");
    }

    #[test]
    fn resolve_unknown_errors() {
        let adj = sample();
        assert!(adj.resolve("nope.rs", "/proj").is_err());
    }

    #[test]
    fn resolve_ambiguous_errors() {
        let edges = vec![edge("a/mod.rs", "b/mod.rs", "import")];
        let files = vec!["a/mod.rs".to_string(), "b/mod.rs".to_string()];
        let adj = Adj::build(&edges, &files);
        let err = adj.resolve("mod.rs", "/proj").unwrap_err();
        assert!(err.contains("ambiguous"), "got: {err}");
    }

    #[test]
    fn bfs_path_finds_shortest_chain() {
        let adj = sample();
        let path = adj.bfs_path("src/a.rs", "src/c.rs").unwrap();
        assert_eq!(path, vec!["src/a.rs", "src/b.rs", "src/c.rs"]);
    }

    #[test]
    fn bfs_path_is_undirected() {
        // Reverse direction still connects (edges are followed both ways).
        let adj = sample();
        let path = adj.bfs_path("src/c.rs", "src/a.rs").unwrap();
        assert_eq!(path, vec!["src/c.rs", "src/b.rs", "src/a.rs"]);
    }

    #[test]
    fn bfs_path_none_when_disconnected() {
        let adj = sample();
        assert!(adj.bfs_path("src/a.rs", "src/d.rs").is_none());
    }

    #[test]
    fn bfs_path_same_node_is_singleton() {
        let adj = sample();
        assert_eq!(
            adj.bfs_path("src/b.rs", "src/b.rs").unwrap(),
            vec!["src/b.rs"]
        );
    }

    #[test]
    fn rings_group_by_distance() {
        let adj = sample();
        let rings = adj.bfs_rings("src/a.rs", 3);
        assert_eq!(rings[0], (1, vec!["src/b.rs".to_string()]));
        assert_eq!(rings[1], (2, vec!["src/c.rs".to_string()]));
    }

    #[test]
    fn edge_between_reports_direction() {
        let adj = sample();
        let (dir, kind, conf) = adj.edge_between("src/a.rs", "src/b.rs").unwrap();
        assert_eq!(dir, Direction::Forward);
        assert_eq!(kind, "import");
        assert!((conf - 1.0).abs() < 1e-9);
        // Reverse view is Backward.
        let (dir2, _, _) = adj.edge_between("src/b.rs", "src/a.rs").unwrap();
        assert_eq!(dir2, Direction::Backward);
    }

    #[test]
    fn edge_between_prefers_higher_confidence() {
        // Two parallel edges: a weak sibling and a strong import. import wins.
        let edges = vec![
            edge("x.rs", "y.rs", "sibling"),
            edge("x.rs", "y.rs", "import"),
        ];
        let adj = Adj::build(&edges, &[]);
        let (_, kind, conf) = adj.edge_between("x.rs", "y.rs").unwrap();
        assert_eq!(kind, "import");
        assert!((conf - 1.0).abs() < 1e-9);
    }

    #[test]
    fn neighbors_split_in_and_out() {
        let adj = sample();
        let out = adj.outgoing("src/b.rs");
        let inc = adj.incoming("src/b.rs");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].node, "src/c.rs");
        assert_eq!(inc.len(), 1);
        assert_eq!(inc[0].node, "src/a.rs");
    }
}