Skip to main content

lean_ctx/tools/
ctx_explore.rs

1//! `ctx_explore` — FastContext-style bounded, deterministic repo exploration.
2//!
3//! Where [`crate::tools::ctx_compose`] is a single-shot composer that returns
4//! prose plus *inlined symbol bodies*, `ctx_explore` runs a **bounded multi-turn
5//! loop** and returns compact `path:start-end` **citations** (the FastContext
6//! idea, arXiv 2606.14066): the calling agent gets a map of *where* the answer
7//! lives at a fraction of the tokens, then reads only what it needs.
8//!
9//! ## Loop
10//! 1. Query understanding — `parse_task_hints` → keywords + path hints.
11//! 2. Lexical anchor — one broad BM25 search over the resident index.
12//! 3. Structural expansion — bounded BFS over the **static** import/call graph,
13//!    grounded in the lexical hit set (only files that actually match the query
14//!    are followed). A turn that discovers no new files stops the loop early
15//!    (coverage saturation).
16//! 4. Symbol channel — exact AST definitions for each keyword (`find_symbols`).
17//! 5. Selection — submodular `greedy_max_coverage` picks the minimal,
18//!    non-redundant citation set that covers the query terms under a token budget.
19//!
20//! ## Determinism (#498)
21//! The output is a pure function of (repo content, query, options). Only
22//! side-effect-free paths are used: the BM25 index and the **static** graph.
23//! It never writes session state — an adaptive signal would make call N+1
24//! differ from call N.
25
26use std::collections::{BTreeMap, BTreeSet, HashSet};
27use std::path::Path;
28
29use crate::core::bm25_index::{BM25Index, ChunkKind, SearchResult};
30use crate::core::context_packing::{CoverageItem, greedy_max_coverage};
31use crate::core::graph_provider;
32use crate::core::task_relevance::parse_task_hints;
33use crate::core::tokens::count_tokens;
34use crate::tools::CrpMode;
35
36const DEFAULT_MAX_TURNS: usize = 3;
37const DEFAULT_PER_TURN_K: usize = 8;
38const DEFAULT_BUDGET_TOKENS: usize = 1200;
39/// Hard caps keep the loop bounded regardless of repo size / query breadth.
40const MAX_HITS: usize = 100;
41const MAX_CANDIDATES: usize = 60;
42const MAX_CITATIONS: usize = 15;
43const MAX_KEYWORDS: usize = 6;
44const MAX_SYMS_PER_KW: usize = 3;
45
46fn env_usize(key: &str, default: usize) -> usize {
47    std::env::var(key)
48        .ok()
49        .and_then(|v| v.parse::<usize>().ok())
50        .filter(|&v| v > 0)
51        .unwrap_or(default)
52}
53
54/// Caller-facing knobs. `max_turns` is clamped to a sane range; `citation_only`
55/// mirrors FastContext's terse mode (emit only the `<final_answer>` block).
56#[derive(Debug, Clone)]
57pub struct ExploreOptions {
58    pub max_turns: usize,
59    pub citation_only: bool,
60}
61
62impl ExploreOptions {
63    pub fn new(max_turns: Option<usize>, citation_only: bool) -> Self {
64        let mt = max_turns
65            .unwrap_or_else(|| env_usize("LEAN_CTX_EXPLORE_MAX_TURNS", DEFAULT_MAX_TURNS))
66            .clamp(1, 8);
67        Self {
68            max_turns: mt,
69            citation_only,
70        }
71    }
72}
73
74impl Default for ExploreOptions {
75    fn default() -> Self {
76        Self::new(None, false)
77    }
78}
79
80/// A single cited source span.
81#[derive(Debug, Clone)]
82pub struct Citation {
83    pub file: String,
84    pub start: usize,
85    pub end: usize,
86    pub label: String,
87}
88
89/// Result of an exploration run.
90#[derive(Debug, Clone)]
91pub struct ExploreOutcome {
92    pub text: String,
93    pub tokens: usize,
94    pub citations: Vec<Citation>,
95}
96
97/// Internal candidate span carrying selection metadata.
98#[derive(Debug, Clone)]
99struct Candidate {
100    file: String,
101    start: usize,
102    end: usize,
103    label: String,
104    score: f64,
105    cost: usize,
106    terms: HashSet<String>,
107}
108
109/// Map a kind string (BM25 `ChunkKind` debug or graph kind) to a short tag.
110fn short_kind(kind: &str) -> &str {
111    match kind.to_ascii_lowercase().as_str() {
112        "function" | "fn" | "method" => "fn",
113        "struct" => "struct",
114        "impl" => "impl",
115        "module" | "mod" => "mod",
116        "class" => "class",
117        "trait" => "trait",
118        "enum" => "enum",
119        "issue" => "issue",
120        "pullrequest" => "pr",
121        other if !other.is_empty() => "sym",
122        _ => "",
123    }
124}
125
126fn chunk_kind_tag(kind: &ChunkKind) -> &'static str {
127    match kind {
128        ChunkKind::Function | ChunkKind::Method => "fn",
129        ChunkKind::Struct => "struct",
130        ChunkKind::Impl => "impl",
131        ChunkKind::Module => "mod",
132        ChunkKind::Class => "class",
133        ChunkKind::Issue => "issue",
134        ChunkKind::PullRequest => "pr",
135        _ => "",
136    }
137}
138
139/// Repo-relative, forward-slash path for stable citations (#324).
140fn rel_path(file: &str, root: &str) -> String {
141    let stripped = file
142        .strip_prefix(root)
143        .map_or(file, |s| s.trim_start_matches(['/', '\\']));
144    crate::core::protocol::display_path(stripped)
145}
146
147/// Distinct, lowercased query terms used for coverage selection.
148fn query_terms(keywords: &[String]) -> Vec<String> {
149    let mut seen = HashSet::new();
150    let mut out = Vec::new();
151    for k in keywords {
152        let lk = k.to_ascii_lowercase();
153        if lk.len() >= 3 && seen.insert(lk.clone()) {
154            out.push(lk);
155            if out.len() >= MAX_KEYWORDS {
156                break;
157            }
158        }
159    }
160    out
161}
162
163/// Which query terms a piece of text covers (case-insensitive substring).
164fn covered_terms(text: &str, terms: &[String]) -> HashSet<String> {
165    let lower = text.to_ascii_lowercase();
166    terms
167        .iter()
168        .filter(|t| lower.contains(t.as_str()))
169        .cloned()
170        .collect()
171}
172
173/// File-level adjacency from the **static** import/call graph (bidirectional),
174/// keyed by repo-relative path. Empty when no graph is available.
175fn build_adjacency(project_root: &str) -> BTreeMap<String, BTreeSet<String>> {
176    let mut adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
177    if let Some(open) = graph_provider::open_or_build(project_root) {
178        for e in open.provider.edges() {
179            let from = rel_path(&e.from, project_root);
180            let to = rel_path(&e.to, project_root);
181            if from == to {
182                continue;
183            }
184            adj.entry(from.clone()).or_default().insert(to.clone());
185            adj.entry(to).or_default().insert(from);
186        }
187    }
188    adj
189}
190
191/// Symbol candidates: exact AST definitions for the keywords (deterministic).
192fn symbol_candidates(project_root: &str, keywords: &[String], terms: &[String]) -> Vec<Candidate> {
193    let Some(open) = graph_provider::open_or_build(project_root) else {
194        return Vec::new();
195    };
196    let gp = &open.provider;
197    let mut out: Vec<Candidate> = Vec::new();
198    for kw in keywords.iter().take(MAX_KEYWORDS) {
199        let mut syms = gp.find_symbols(kw, None, None);
200        // Deterministic, exported-first ordering, then a small cap per keyword.
201        syms.sort_by(|a, b| {
202            b.is_exported
203                .cmp(&a.is_exported)
204                .then_with(|| a.file.cmp(&b.file))
205                .then_with(|| a.start_line.cmp(&b.start_line))
206        });
207        for sym in syms.into_iter().take(MAX_SYMS_PER_KW) {
208            let file = rel_path(&sym.file, project_root);
209            let label = format!("{} ({})", sym.name, short_kind(&sym.kind));
210            let text = format!("{} {}", sym.name, sym.kind);
211            let mut covered = covered_terms(&text, terms);
212            covered.insert(kw.to_ascii_lowercase());
213            out.push(Candidate {
214                file,
215                start: sym.start_line,
216                end: sym.end_line.max(sym.start_line),
217                label,
218                score: 0.0,
219                cost: 1,
220                terms: covered,
221            });
222        }
223    }
224    out
225}
226
227/// Convert a BM25 hit into a candidate.
228fn candidate_from_hit(hit: &SearchResult, project_root: &str, terms: &[String]) -> Candidate {
229    let file = rel_path(&hit.file_path, project_root);
230    let tag = chunk_kind_tag(&hit.kind);
231    let label = if hit.symbol_name.is_empty() {
232        if tag.is_empty() {
233            String::new()
234        } else {
235            format!("({tag})")
236        }
237    } else if tag.is_empty() {
238        hit.symbol_name.clone()
239    } else {
240        format!("{} ({})", hit.symbol_name, tag)
241    };
242    let terms_covered = covered_terms(&format!("{} {}", hit.symbol_name, hit.snippet), terms);
243    Candidate {
244        file,
245        start: hit.start_line,
246        end: hit.end_line.max(hit.start_line),
247        label,
248        score: hit.score,
249        cost: count_tokens(&hit.snippet).max(1),
250        terms: terms_covered,
251    }
252}
253
254/// Bounded BFS over the static graph, grounded in the lexical hit set. Returns
255/// the set of discovered (query-relevant) files and the number of turns run.
256fn expand_frontier(
257    seed_files: &[String],
258    relevant: &BTreeSet<String>,
259    adjacency: &BTreeMap<String, BTreeSet<String>>,
260    max_turns: usize,
261) -> (BTreeSet<String>, usize) {
262    let mut discovered: BTreeSet<String> = seed_files.iter().cloned().collect();
263    let mut frontier: Vec<String> = seed_files.to_vec();
264    let mut turns = 1usize;
265
266    while turns < max_turns && !frontier.is_empty() {
267        let mut next: BTreeSet<String> = BTreeSet::new();
268        for f in &frontier {
269            if let Some(nbrs) = adjacency.get(f) {
270                for nbr in nbrs {
271                    if !discovered.contains(nbr) && relevant.contains(nbr) {
272                        next.insert(nbr.clone());
273                    }
274                }
275            }
276        }
277        if next.is_empty() {
278            break; // coverage saturation — additional turns add nothing
279        }
280        for n in &next {
281            discovered.insert(n.clone());
282        }
283        frontier = next.into_iter().collect();
284        turns += 1;
285    }
286    (discovered, turns)
287}
288
289/// Select the citation set: coverage-first (submodular), then score-fill, under
290/// a token budget. Falls back to score order when the query has no usable terms.
291fn select_citations(mut candidates: Vec<Candidate>, budget: usize) -> Vec<Candidate> {
292    if candidates.is_empty() {
293        return Vec::new();
294    }
295    // Deterministic candidate order: (file, start, end). greedy breaks gain/cost
296    // ties by earliest index, so a stable order ⇒ stable selection.
297    candidates.sort_by(|a, b| {
298        a.file
299            .cmp(&b.file)
300            .then_with(|| a.start.cmp(&b.start))
301            .then_with(|| a.end.cmp(&b.end))
302    });
303    candidates.truncate(MAX_CANDIDATES);
304
305    let any_terms = candidates.iter().any(|c| !c.terms.is_empty());
306    let mut chosen: Vec<usize> = if any_terms {
307        let items: Vec<CoverageItem> = candidates
308            .iter()
309            .map(|c| CoverageItem {
310                terms: c.terms.clone(),
311                cost: c.cost,
312            })
313            .collect();
314        greedy_max_coverage(&items, budget, |_| 1.0)
315    } else {
316        Vec::new()
317    };
318
319    let mut spent: usize = chosen.iter().map(|&i| candidates[i].cost).sum();
320    let in_chosen: HashSet<usize> = chosen.iter().copied().collect();
321
322    // Score-fill the remaining budget with the most relevant uncovered spans.
323    let mut by_score: Vec<usize> = (0..candidates.len())
324        .filter(|i| !in_chosen.contains(i))
325        .collect();
326    by_score.sort_by(|&a, &b| {
327        candidates[b]
328            .score
329            .partial_cmp(&candidates[a].score)
330            .unwrap_or(std::cmp::Ordering::Equal)
331            .then_with(|| candidates[a].file.cmp(&candidates[b].file))
332            .then_with(|| candidates[a].start.cmp(&candidates[b].start))
333    });
334    for idx in by_score {
335        if chosen.len() >= MAX_CITATIONS {
336            break;
337        }
338        let cost = candidates[idx].cost;
339        if spent + cost <= budget {
340            chosen.push(idx);
341            spent += cost;
342        }
343    }
344
345    // Emit in stable (file, start) order for a readable, byte-stable block.
346    chosen.sort_by(|&a, &b| {
347        candidates[a]
348            .file
349            .cmp(&candidates[b].file)
350            .then_with(|| candidates[a].start.cmp(&candidates[b].start))
351    });
352    chosen.into_iter().map(|i| candidates[i].clone()).collect()
353}
354
355/// Render the final answer: a `<final_answer>` block of `path:start-end label`,
356/// optionally preceded by a short, deterministic summary.
357fn render(
358    query: &str,
359    keywords: &[String],
360    turns: usize,
361    files_examined: usize,
362    citations: &[Citation],
363    crp_mode: CrpMode,
364    citation_only: bool,
365) -> String {
366    let mut block = String::from("<final_answer>\n");
367    for c in citations {
368        if c.label.is_empty() {
369            block.push_str(&format!("{}:{}-{}\n", c.file, c.start, c.end));
370        } else {
371            block.push_str(&format!("{}:{}-{}  {}\n", c.file, c.start, c.end, c.label));
372        }
373    }
374    block.push_str("</final_answer>\n");
375
376    if citation_only {
377        return block;
378    }
379
380    let mut out = String::new();
381    if crp_mode.is_tdd() {
382        out.push_str(&format!(
383            "explore({query}) → {} citations\n\n",
384            citations.len()
385        ));
386    } else {
387        out.push_str(&format!("EXPLORE: {query}\n"));
388        if keywords.is_empty() {
389            out.push_str("keywords: (none extracted)\n");
390        } else {
391            out.push_str(&format!("keywords: {}\n", keywords.join(", ")));
392        }
393        out.push_str(&format!(
394            "turns: {turns}  files_examined: {files_examined}  citations: {}\n\n",
395            citations.len()
396        ));
397    }
398    out.push_str(&block);
399    out
400}
401
402/// Run a bounded, deterministic exploration for `query`.
403pub fn handle(
404    query: &str,
405    project_root: &str,
406    crp_mode: CrpMode,
407    opts: &ExploreOptions,
408) -> ExploreOutcome {
409    let query = query.trim();
410    if query.is_empty() {
411        return ExploreOutcome {
412            text: "ERROR: query is required".to_string(),
413            tokens: 0,
414            citations: Vec::new(),
415        };
416    }
417
418    let (_hint_files, keywords) = parse_task_hints(query);
419    let terms = query_terms(&keywords);
420
421    // Lexical anchor: one broad BM25 search over the resident index.
422    let root = Path::new(project_root);
423    let index = BM25Index::load_or_build(root);
424    let hits: Vec<SearchResult> = if index.doc_count == 0 {
425        Vec::new()
426    } else {
427        index.search(query, MAX_HITS)
428    };
429
430    // Best (highest-ranked) hit per file, in score order.
431    let mut best_hit_for_file: BTreeMap<String, Candidate> = BTreeMap::new();
432    let mut seed_order: Vec<String> = Vec::new();
433    for hit in &hits {
434        let cand = candidate_from_hit(hit, project_root, &terms);
435        if let std::collections::btree_map::Entry::Vacant(slot) =
436            best_hit_for_file.entry(cand.file.clone())
437        {
438            seed_order.push(cand.file.clone());
439            slot.insert(cand);
440        }
441    }
442    let relevant: BTreeSet<String> = best_hit_for_file.keys().cloned().collect();
443
444    // Turn 1 frontier: the top-k distinct files by lexical relevance.
445    let per_turn_k = env_usize("LEAN_CTX_EXPLORE_K", DEFAULT_PER_TURN_K);
446    let seeds: Vec<String> = seed_order.iter().take(per_turn_k).cloned().collect();
447
448    // Bounded BFS over the static graph, grounded in the lexical hit set.
449    let adjacency = build_adjacency(project_root);
450    let (discovered, turns) = expand_frontier(&seeds, &relevant, &adjacency, opts.max_turns);
451
452    // Candidates: best hit per discovered file + exact symbol definitions.
453    let mut by_loc: BTreeMap<(String, usize, usize), Candidate> = BTreeMap::new();
454    let mut insert = |c: Candidate| {
455        let key = (c.file.clone(), c.start, c.end);
456        by_loc
457            .entry(key)
458            .and_modify(|e| {
459                if c.score > e.score {
460                    e.score = c.score;
461                }
462                if e.label.is_empty() && !c.label.is_empty() {
463                    e.label.clone_from(&c.label);
464                }
465                for t in &c.terms {
466                    e.terms.insert(t.clone());
467                }
468            })
469            .or_insert(c);
470    };
471    for file in &discovered {
472        if let Some(c) = best_hit_for_file.get(file) {
473            insert(c.clone());
474        }
475    }
476    for c in symbol_candidates(project_root, &keywords, &terms) {
477        insert(c);
478    }
479
480    let files_examined = discovered.len();
481    let candidates: Vec<Candidate> = by_loc.into_values().collect();
482    let budget = env_usize("LEAN_CTX_EXPLORE_BUDGET_TOKENS", DEFAULT_BUDGET_TOKENS);
483    let selected = select_citations(candidates, budget);
484
485    let citations: Vec<Citation> = selected
486        .into_iter()
487        .map(|c| Citation {
488            file: c.file,
489            start: c.start,
490            end: c.end,
491            label: c.label,
492        })
493        .collect();
494
495    let text = render(
496        query,
497        &keywords,
498        turns,
499        files_examined,
500        &citations,
501        crp_mode,
502        opts.citation_only,
503    );
504    let tokens = count_tokens(&text);
505    ExploreOutcome {
506        text,
507        tokens,
508        citations,
509    }
510}
511
512/// Parse the `path:start-end` citations out of an explore answer. Reused by the
513/// eval harness to score the Explore arm. Tolerant of the optional trailing
514/// label and of text outside the `<final_answer>` block.
515pub fn parse_final_answer(text: &str) -> Vec<(String, usize, usize)> {
516    let mut out = Vec::new();
517    let mut inside = false;
518    for line in text.lines() {
519        let trimmed = line.trim();
520        if trimmed == "<final_answer>" {
521            inside = true;
522            continue;
523        }
524        if trimmed == "</final_answer>" {
525            break;
526        }
527        if !inside || trimmed.is_empty() {
528            continue;
529        }
530        // First whitespace-delimited token is `path:start-end`.
531        let token = trimmed.split_whitespace().next().unwrap_or("");
532        if let Some((path, range)) = token.rsplit_once(':')
533            && let Some((s, e)) = range.split_once('-')
534            && let (Ok(start), Ok(end)) = (s.parse::<usize>(), e.parse::<usize>())
535        {
536            out.push((path.to_string(), start, end));
537        }
538    }
539    out
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    #[test]
547    fn empty_query_is_rejected() {
548        let outcome = handle("   ", "/tmp", CrpMode::Off, &ExploreOptions::default());
549        assert!(outcome.text.starts_with("ERROR"));
550        assert_eq!(outcome.tokens, 0);
551        assert!(outcome.citations.is_empty());
552    }
553
554    #[test]
555    fn short_kind_maps_known_kinds() {
556        assert_eq!(short_kind("Function"), "fn");
557        assert_eq!(short_kind("method"), "fn");
558        assert_eq!(short_kind("struct"), "struct");
559        assert_eq!(short_kind("Constant"), "sym");
560        assert_eq!(short_kind(""), "");
561    }
562
563    #[test]
564    fn rel_path_strips_root_and_normalizes() {
565        assert_eq!(rel_path("/repo/src/a.rs", "/repo"), "src/a.rs");
566        assert_eq!(rel_path("src/a.rs", "/repo"), "src/a.rs");
567    }
568
569    #[test]
570    fn query_terms_dedup_and_cap() {
571        let kws: Vec<String> = vec!["Cache", "cache", "Index", "ab", "Search"]
572            .into_iter()
573            .map(String::from)
574            .collect();
575        let terms = query_terms(&kws);
576        assert!(terms.contains(&"cache".to_string()));
577        assert!(terms.contains(&"index".to_string()));
578        assert!(!terms.iter().any(|t| t == "ab")); // too short
579        // "cache" appears once despite two casings.
580        assert_eq!(terms.iter().filter(|t| *t == "cache").count(), 1);
581    }
582
583    #[test]
584    fn parse_final_answer_extracts_citations() {
585        let text = "EXPLORE: foo\n\n<final_answer>\nsrc/a.rs:10-20  foo (fn)\nsrc/b.rs:5-5\n</final_answer>\n";
586        let cits = parse_final_answer(text);
587        assert_eq!(
588            cits,
589            vec![
590                ("src/a.rs".to_string(), 10, 20),
591                ("src/b.rs".to_string(), 5, 5),
592            ]
593        );
594    }
595
596    #[test]
597    fn parse_final_answer_ignores_text_outside_block() {
598        let text = "noise:1-2 should be ignored\n<final_answer>\nsrc/x.rs:1-3\n</final_answer>\ntrailing:9-9";
599        let cits = parse_final_answer(text);
600        assert_eq!(cits, vec![("src/x.rs".to_string(), 1, 3)]);
601    }
602
603    #[test]
604    fn select_citations_respects_budget_and_is_deterministic() {
605        let mk = |file: &str, start: usize, term: &str, cost: usize, score: f64| Candidate {
606            file: file.to_string(),
607            start,
608            end: start + 5,
609            label: format!("{term} (fn)"),
610            score,
611            cost,
612            terms: HashSet::from([term.to_string()]),
613        };
614        let cands = vec![
615            mk("src/a.rs", 1, "cache", 100, 2.0),
616            mk("src/b.rs", 1, "index", 100, 1.5),
617            mk("src/c.rs", 1, "cache", 100, 1.0), // redundant term, low score
618        ];
619        let a = select_citations(cands.clone(), 250);
620        let b = select_citations(cands, 250);
621        // Deterministic across calls.
622        let fa: Vec<_> = a.iter().map(|c| (c.file.clone(), c.start)).collect();
623        let fb: Vec<_> = b.iter().map(|c| (c.file.clone(), c.start)).collect();
624        assert_eq!(fa, fb);
625        // Budget 250 with cost 100 each ⇒ at most 2 spans.
626        assert!(a.len() <= 2, "budget should cap to 2: {}", a.len());
627    }
628
629    #[test]
630    fn expand_frontier_stops_on_coverage_saturation() {
631        // No neighbours ⇒ the loop saturates after the first turn regardless of
632        // the `max_turns` budget (the early-stop that bounds delegated cost).
633        let adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
634        let relevant: BTreeSet<String> = ["a.rs".to_string()].into_iter().collect();
635        let (discovered, turns) = expand_frontier(&["a.rs".to_string()], &relevant, &adj, 8);
636        assert_eq!(turns, 1, "no new files ⇒ stop after turn 1");
637        assert_eq!(discovered.len(), 1);
638    }
639
640    #[test]
641    fn expand_frontier_respects_max_turns() {
642        // Relevant chain a→b→c→d. With max_turns=2 only b is reached (turn 2);
643        // c/d lie beyond the depth budget.
644        let mut adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
645        adj.insert("a.rs".into(), ["b.rs".to_string()].into_iter().collect());
646        adj.insert("b.rs".into(), ["c.rs".to_string()].into_iter().collect());
647        adj.insert("c.rs".into(), ["d.rs".to_string()].into_iter().collect());
648        let relevant: BTreeSet<String> = ["a.rs", "b.rs", "c.rs", "d.rs"]
649            .iter()
650            .map(ToString::to_string)
651            .collect();
652        let (discovered, turns) = expand_frontier(&["a.rs".to_string()], &relevant, &adj, 2);
653        assert_eq!(turns, 2, "max_turns caps BFS depth");
654        assert!(discovered.contains("b.rs"));
655        assert!(
656            !discovered.contains("c.rs"),
657            "depth beyond max_turns is unexplored"
658        );
659    }
660
661    #[test]
662    fn expand_frontier_follows_only_relevant_files() {
663        // `b.rs` is a graph neighbour but not in the lexical hit set, so the
664        // graph walk never follows it (grounding prevents drift into noise).
665        let mut adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
666        adj.insert("a.rs".into(), ["b.rs".to_string()].into_iter().collect());
667        let relevant: BTreeSet<String> = ["a.rs".to_string()].into_iter().collect();
668        let (discovered, turns) = expand_frontier(&["a.rs".to_string()], &relevant, &adj, 8);
669        assert_eq!(turns, 1);
670        assert!(
671            !discovered.contains("b.rs"),
672            "irrelevant neighbours are skipped"
673        );
674    }
675
676    #[test]
677    fn handle_output_is_byte_stable_across_runs() {
678        // #498: the output is a pure function of (content, query, options). Two
679        // back-to-back runs on the same fixture must be byte-identical — no
680        // session writes, no Hebbian co-access, no timestamps.
681        let _env_lock = crate::core::data_dir::test_env_lock();
682        let dir = tempfile::tempdir().unwrap();
683        let root = dir.path();
684        std::fs::write(
685            root.join("cache.rs"),
686            "pub struct CacheStore { entries: usize }\n\
687             impl CacheStore {\n    pub fn lookup(&self, key: &str) -> Option<usize> { let _ = key; None }\n}\n",
688        )
689        .unwrap();
690        std::fs::write(
691            root.join("index.rs"),
692            "pub fn build_index(cache: &str) -> usize { cache.len() }\n",
693        )
694        .unwrap();
695        let root_str = root.to_string_lossy().to_string();
696        let opts = ExploreOptions::new(Some(3), false);
697
698        let run = || {
699            handle(
700                "how does the cache lookup work",
701                &root_str,
702                CrpMode::Off,
703                &opts,
704            )
705        };
706
707        // #498 is about state accumulation between runs, so the index must be
708        // settled *before* the two runs being compared — otherwise the test
709        // measures index warm-up instead.
710        //
711        // The symbol half of the answer (`lookup (fn)`) comes from
712        // `graph_provider::open_or_build`, which returns `None` when the build
713        // gate is already held (another test in this binary) or when the 30s
714        // build times out under parallel load. So one run cites two spans and
715        // the next cites three — a red build about scheduling, not about
716        // determinism.
717        //
718        // A discarded warm-up call does not fix that: it enters the same racy
719        // path and offers no guarantee about the call after it. Building the
720        // graph index synchronously does — `scan` persists it, so both runs
721        // below take the `open_existing` fast path and never touch the gate.
722        let prebuilt = crate::core::graph_index::load_or_build(&root_str);
723        assert!(
724            !prebuilt.files.is_empty(),
725            "the fixture must yield a graph index; without one both runs would \
726             degrade to the same symbol-less output and the comparison would pass \
727             while proving nothing"
728        );
729
730        let a = run();
731        let b = run();
732
733        assert_eq!(a.text, b.text, "explore output must be byte-stable");
734        assert_eq!(a.tokens, b.tokens);
735        assert!(
736            a.text.contains("lookup (fn)"),
737            "the symbol citation must be present — its absence is exactly the \
738             degraded state this test used to compare against itself: {}",
739            a.text
740        );
741        let locs = |o: &ExploreOutcome| -> Vec<(String, usize, usize)> {
742            o.citations
743                .iter()
744                .map(|c| (c.file.clone(), c.start, c.end))
745                .collect()
746        };
747        assert_eq!(locs(&a), locs(&b));
748        assert!(a.text.contains("<final_answer>"));
749        assert!(a.text.contains("</final_answer>"));
750    }
751}