Skip to main content

lean_ctx_server/tools/
ctx_graph.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::HashMap;
3use std::path::Path;
4
5use lean_ctx::core::graph_index;
6use lean_ctx::core::graph_provider::{self, GraphProvider};
7use lean_ctx::core::tokens::count_tokens;
8
9#[allow(clippy::too_many_arguments)]
10pub fn handle(
11    action: &str,
12    path: Option<&str>,
13    root: &str,
14    cache: &mut lean_ctx::core::cache::SessionCache,
15    crp_mode: crate::tools::CrpMode,
16    depth: Option<usize>,
17    kind: Option<&str>,
18    to: Option<&str>,
19    format: Option<&str>,
20    since: Option<&str>,
21) -> String {
22    match action {
23        "build" => handle_build(root),
24        "related" => handle_related(path, root),
25        "symbol" => handle_symbol(path, root, cache, crp_mode),
26        "impact" => handle_impact(path, root),
27        "status" => handle_status(root),
28        "enrich" => handle_enrich(root),
29        "context" => handle_context_query(path, root),
30        "diagram" => crate::tools::ctx_graph_diagram::handle(path, depth, kind, root),
31        "neighbors" => crate::tools::ctx_graph_primitives::neighbors(path, root, depth, format),
32        "path" => crate::tools::ctx_graph_primitives::shortest_path(path, to, root, format),
33        "explain" => crate::tools::ctx_graph_primitives::explain(path, root, format),
34        "diff" => crate::tools::ctx_graph_diff::diff(since, root, format),
35        _ => "Unknown action. Use: build, related, symbol, impact, status, enrich, context, \
36diagram, neighbors, path, explain, diff"
37            .to_string(),
38    }
39}
40
41fn handle_build(root: &str) -> String {
42    let index = graph_index::scan(root);
43
44    let mut by_lang: HashMap<&str, (usize, usize)> = HashMap::new();
45    for entry in index.files.values() {
46        let e = by_lang.entry(&entry.language).or_insert((0, 0));
47        e.0 += 1;
48        e.1 += entry.token_count;
49    }
50
51    let mut result = Vec::new();
52    result.push(format!(
53        "Project Graph: {} files, {} symbols, {} edges",
54        index.file_count(),
55        index.symbol_count(),
56        index.edge_count()
57    ));
58
59    let mut langs: Vec<_> = by_lang.iter().collect();
60    langs.sort_by_key(|(_, v)| std::cmp::Reverse(v.1));
61    result.push("\nLanguages:".to_string());
62    for (lang, (count, tokens)) in &langs {
63        result.push(format!("  {lang}: {count} files, {tokens} tok"));
64    }
65
66    let mut import_counts: HashMap<&str, usize> = HashMap::new();
67    for edge in &index.edges {
68        if edge.kind == "import" {
69            *import_counts.entry(&edge.to).or_insert(0) += 1;
70        }
71    }
72    let mut hotspots: Vec<_> = import_counts.iter().collect();
73    hotspots.sort_by_key(|x| std::cmp::Reverse(*x.1));
74
75    if !hotspots.is_empty() {
76        result.push(format!("\nMost imported ({}):", hotspots.len().min(10)));
77        for (module, count) in hotspots.iter().take(10) {
78            result.push(format!("  {module}: imported by {count} files"));
79        }
80    }
81
82    if let Some(dir) = GraphProvider::index_dir(root) {
83        result.push(format!(
84            "\nIndex saved: {}",
85            lean_ctx::core::protocol::shorten_path(&dir.to_string_lossy())
86        ));
87    }
88
89    let output = result.join("\n");
90    let tokens = count_tokens(&output);
91    format!("{output}\n[ctx_graph build: {tokens} tok]")
92}
93
94fn handle_related(path: Option<&str>, root: &str) -> String {
95    let Some(target) = path else {
96        return "path is required for 'related' action".to_string();
97    };
98
99    let Some(open) = graph_provider::open_or_build(root) else {
100        return "No graph index found. Run ctx_graph with action='build' first.".to_string();
101    };
102
103    let rel_target = graph_index::graph_relative_key(target, root);
104
105    let related = open.provider.related(&rel_target, 2);
106    if related.is_empty() {
107        return format!(
108            "No related files found for {}",
109            lean_ctx::core::protocol::shorten_path(target)
110        );
111    }
112
113    let mut result = format!(
114        "Files related to {} ({}):\n",
115        lean_ctx::core::protocol::shorten_path(target),
116        related.len()
117    );
118    for r in &related {
119        result.push_str(&format!(
120            "  {}\n",
121            lean_ctx::core::protocol::shorten_path(r)
122        ));
123    }
124
125    let tokens = count_tokens(&result);
126    format!("{result}[ctx_graph related: {tokens} tok]")
127}
128
129fn handle_symbol(
130    path: Option<&str>,
131    root: &str,
132    cache: &mut lean_ctx::core::cache::SessionCache,
133    crp_mode: crate::tools::CrpMode,
134) -> String {
135    let Some(spec) = path else {
136        return "path is required for 'symbol' action (format: <file>::<symbol>, or a bare <symbol> name)".to_string();
137    };
138
139    let Some(open) = graph_provider::open_or_build(root) else {
140        return "No graph index found. Run ctx_graph with action='build' first.".to_string();
141    };
142
143    // Bare symbol name (no `::`): resolve against the symbol table so GDScript
144    // (and every other language) symbols are reachable without a file qualifier
145    // (#314).
146    let Some((file_part, symbol_name)) = spec.split_once("::") else {
147        return resolve_bare_symbol(&open.provider, spec, root, cache, crp_mode);
148    };
149
150    let rel_file = graph_index::graph_relative_key(file_part, root);
151
152    let key = format!("{rel_file}::{symbol_name}");
153    let Some(symbol) = open.provider.get_symbol(&key) else {
154        let available = open
155            .provider
156            .find_symbols(symbol_name, Some(&rel_file), None);
157        if available.is_empty() {
158            return format!(
159                "Symbol '{symbol_name}' not found in {rel_file}. Run ctx_graph action='build' to update the index."
160            );
161        }
162        let names: Vec<String> = available
163            .iter()
164            .take(10)
165            .map(|s| format!("{}::{}", s.file, s.name))
166            .collect();
167        return format!(
168            "Symbol '{symbol_name}' not found in {rel_file}.\nAvailable symbols:\n  {}",
169            names.join("\n  ")
170        );
171    };
172
173    let abs_path = if Path::new(file_part).is_absolute() {
174        file_part.to_string()
175    } else {
176        Path::new(root)
177            .join(rel_file.trim_start_matches(['/', '\\']))
178            .to_string_lossy()
179            .to_string()
180    };
181
182    render_symbol_snippet(&symbol, &abs_path, &rel_file, root, cache, crp_mode)
183}
184
185/// Resolve a bare symbol name (no `<file>::` qualifier) against the symbol table.
186/// One unambiguous hit renders the snippet; otherwise the candidates are listed
187/// so the caller can disambiguate with `<file>::<symbol>` (#314).
188fn resolve_bare_symbol(
189    provider: &GraphProvider,
190    name: &str,
191    root: &str,
192    cache: &mut lean_ctx::core::cache::SessionCache,
193    crp_mode: crate::tools::CrpMode,
194) -> String {
195    let matches = provider.find_symbols(name, None, None);
196    if matches.is_empty() {
197        return format!(
198            "Symbol '{name}' not found. Run ctx_graph action='build' to update the index."
199        );
200    }
201
202    let name_lower = name.to_lowercase();
203    let exact: Vec<&graph_provider::SymbolInfo> = matches
204        .iter()
205        .filter(|s| s.name.to_lowercase() == name_lower)
206        .collect();
207
208    if let [only] = exact.as_slice() {
209        let abs_path = Path::new(root)
210            .join(only.file.trim_start_matches(['/', '\\']))
211            .to_string_lossy()
212            .to_string();
213        return render_symbol_snippet(only, &abs_path, &only.file, root, cache, crp_mode);
214    }
215
216    // Several identically-named symbols, or only substring hits → list them.
217    let shortlist: Vec<&graph_provider::SymbolInfo> = if exact.is_empty() {
218        matches.iter().collect()
219    } else {
220        exact
221    };
222    let mut lines = vec![format!(
223        "Symbol '{name}' matches {} entries — pick one with `<file>::{name}`:",
224        shortlist.len()
225    )];
226    for s in shortlist.iter().take(15) {
227        lines.push(format!(
228            "  {}::{} ({}, {}:{})",
229            lean_ctx::core::protocol::shorten_path(&s.file),
230            s.name,
231            s.kind,
232            s.start_line,
233            s.end_line
234        ));
235    }
236    lines.join("\n")
237}
238
239/// Render a symbol's source snippet with the standard token-savings footer.
240/// Shared by the qualified (`<file>::<symbol>`) and bare-name resolution paths.
241///
242/// The graph index is a discovery hint, not an authorization: the snippet is
243/// cut from the source as the common rooted admitted reader delivers it NOW
244/// (G01), under `root`. A source that is withheld yields its content-free
245/// reason, never the lines the index points at.
246fn render_symbol_snippet(
247    symbol: &graph_provider::SymbolInfo,
248    abs_path: &str,
249    rel_display: &str,
250    root: &str,
251    cache: &mut lean_ctx::core::cache::SessionCache,
252    crp_mode: crate::tools::CrpMode,
253) -> String {
254    use crate::tools::admitted_sources::SourceRead;
255    let mut remaining = lean_ctx::core::limits::max_read_bytes();
256    let content = match crate::tools::admitted_sources::read(abs_path, root, TOOL, &mut remaining) {
257        SourceRead::Admitted(read) => read.content,
258        SourceRead::Withheld(reason) | SourceRead::Unavailable(reason) => {
259            return format!("Cannot read {abs_path}: {reason}");
260        }
261    };
262
263    let lines: Vec<&str> = content.lines().collect();
264    let start = symbol.start_line.saturating_sub(1);
265    let end = symbol.end_line.min(lines.len());
266
267    if start >= lines.len() {
268        // The read path admits only inside a request scope; bind it so this
269        // fallback is admitted for every caller (MCP dispatch and the CLI).
270        return crate::tools::admitted_sources::as_agent_acquisition(root, || {
271            crate::tools::ctx_read::handle(cache, abs_path, "full", crp_mode)
272        });
273    }
274
275    let mut result = format!(
276        "{}::{} ({}:{}-{})\n",
277        lean_ctx::core::protocol::shorten_path(rel_display),
278        symbol.name,
279        symbol.kind,
280        symbol.start_line,
281        symbol.end_line
282    );
283
284    for (i, line) in lines[start..end].iter().enumerate() {
285        result.push_str(&format!("{:>4}|{}\n", start + i + 1, line));
286    }
287
288    let tokens = count_tokens(&result);
289    let full_tokens = count_tokens(&content);
290    let saved = full_tokens.saturating_sub(tokens);
291    let pct = if full_tokens > 0 {
292        (saved as f64 / full_tokens as f64 * 100.0).round() as usize
293    } else {
294        0
295    };
296
297    format!("{result}[ctx_graph symbol: {tokens} tok (full file: {full_tokens} tok, -{pct}%)]")
298}
299
300/// Tool identity the sources are read for (path jail, role rules, audit).
301const TOOL: &str = "ctx_graph";
302
303/// The admitted text of `path` (relative to `root`, or absolute inside it),
304/// for derivations that only steer matching and are never rendered. `None`
305/// when the source is absent, unreadable or withheld.
306fn admitted_text(path: &str, root: &str) -> Option<String> {
307    let mut remaining = lean_ctx::core::limits::max_read_bytes();
308    match crate::tools::admitted_sources::read(path, root, TOOL, &mut remaining) {
309        crate::tools::admitted_sources::SourceRead::Admitted(read) => Some(read.content),
310        crate::tools::admitted_sources::SourceRead::Withheld(_)
311        | crate::tools::admitted_sources::SourceRead::Unavailable(_) => None,
312    }
313}
314
315fn file_path_to_module_prefixes(
316    rel_path: &str,
317    project_root: &str,
318    provider: &GraphProvider,
319) -> Vec<String> {
320    let rel_path_slash = graph_index::graph_match_key(rel_path);
321    let without_ext = rel_path_slash
322        .strip_suffix(".rs")
323        .or_else(|| rel_path_slash.strip_suffix(".ts"))
324        .or_else(|| rel_path_slash.strip_suffix(".tsx"))
325        .or_else(|| rel_path_slash.strip_suffix(".js"))
326        .or_else(|| rel_path_slash.strip_suffix(".py"))
327        .or_else(|| rel_path_slash.strip_suffix(".kt"))
328        .or_else(|| rel_path_slash.strip_suffix(".kts"))
329        .or_else(|| rel_path_slash.strip_suffix(".gd"))
330        .unwrap_or(&rel_path_slash);
331
332    let module_path = without_ext
333        .strip_prefix("src/")
334        .unwrap_or(without_ext)
335        .replace('/', "::");
336
337    let module_path = if module_path.ends_with("::mod") {
338        module_path
339            .strip_suffix("::mod")
340            .unwrap_or(&module_path)
341            .to_string()
342    } else {
343        module_path
344    };
345
346    // Manifest and source are read through the admitted reader like any other
347    // source: a withheld manifest contributes no crate name.
348    let crate_name = admitted_text("Cargo.toml", project_root)
349        .or_else(|| admitted_text("package.json", project_root))
350        .and_then(|c| {
351            c.lines()
352                .find(|l| l.contains("\"name\"") || l.starts_with("name"))
353                .and_then(|l| l.split('"').nth(1))
354                .map(|n| n.replace('-', "_"))
355        })
356        .unwrap_or_default();
357
358    let mut prefixes = vec![
359        format!("crate::{module_path}"),
360        format!("super::{module_path}"),
361        module_path.clone(),
362    ];
363    if !crate_name.is_empty() {
364        prefixes.insert(0, format!("{crate_name}::{module_path}"));
365    }
366
367    let ext = Path::new(rel_path)
368        .extension()
369        .and_then(|e| e.to_str())
370        .unwrap_or("");
371    if ext == "gd" {
372        // GDScript import edges resolve to the target script's project-relative
373        // path (e.g. "actors/Player.gd"), not a Rust-style module path, so the
374        // path itself is the key that `graph impact` must match on (#314).
375        prefixes.push(rel_path_slash.clone());
376    }
377    if matches!(ext, "kt" | "kts") {
378        if let Some(content) = admitted_text(rel_path.trim_start_matches(['/', '\\']), project_root)
379            && let Some(package_name) = content.lines().map(str::trim).find_map(|line| {
380                line.strip_prefix("package ")
381                    .map(|rest| rest.trim().trim_end_matches(';').to_string())
382            })
383        {
384            prefixes.push(package_name.clone());
385            if let Some(entry) = provider.get_file_entry(rel_path) {
386                for export in &entry.exports {
387                    prefixes.push(format!("{package_name}.{export}"));
388                }
389            }
390            if let Some(file_stem) = Path::new(rel_path).file_stem().and_then(|s| s.to_str()) {
391                prefixes.push(format!("{package_name}.{file_stem}"));
392            }
393        }
394    }
395
396    prefixes.sort();
397    prefixes.dedup();
398    prefixes
399}
400
401fn edge_matches_file(edge_to: &str, module_prefixes: &[String]) -> bool {
402    module_prefixes.iter().any(|prefix| {
403        edge_to == *prefix
404            || edge_to.starts_with(&format!("{prefix}::"))
405            || edge_to.starts_with(&format!("{prefix},"))
406    })
407}
408
409fn handle_impact(path: Option<&str>, root: &str) -> String {
410    let Some(target) = path else {
411        return "path is required for 'impact' action".to_string();
412    };
413
414    let Some(open) = graph_provider::open_or_build(root) else {
415        return "No graph index found. Run ctx_graph with action='build' first.".to_string();
416    };
417    let gp = &open.provider;
418
419    let rel_target = graph_index::graph_relative_key(target, root);
420    if Path::new(&rel_target)
421        .extension()
422        .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
423    {
424        return rust_impact(target, &rel_target, gp);
425    }
426    let module_prefixes = file_path_to_module_prefixes(&rel_target, root, gp);
427
428    // Direct importers come from two complementary lookups, merged + deduped:
429    //   1. `dependents(rel_target)` — the import resolver records edges keyed by
430    //      the target's project-relative *file path*, so this is the primary,
431    //      backend-agnostic match (works for Rust/TS/JS/Python/…).
432    //   2. `edge_matches_file` over module-path prefixes — additionally catches
433    //      edges keyed by a module/symbol path rather than a file (Rust `mod`,
434    //      Kotlin package, barrel re-exports), which the file-path match misses.
435    let mut direct: Vec<String> = gp.dependents(&rel_target);
436    for e in gp.edges_by_kind("import") {
437        if edge_matches_file(&e.to, &module_prefixes) && !direct.contains(&e.from) {
438            direct.push(e.from);
439        }
440    }
441    direct.retain(|d| *d != rel_target);
442
443    let mut all_dependents: Vec<String> = direct.clone();
444    for d in &direct {
445        for dep in gp.dependents(d) {
446            if !all_dependents.contains(&dep) && dep != rel_target {
447                all_dependents.push(dep);
448            }
449        }
450    }
451
452    if all_dependents.is_empty() {
453        return format!(
454            "No files depend on {}",
455            lean_ctx::core::protocol::shorten_path(target)
456        );
457    }
458
459    let mut result = format!(
460        "Impact of {} ({} dependents):\n",
461        lean_ctx::core::protocol::shorten_path(target),
462        all_dependents.len()
463    );
464
465    if !direct.is_empty() {
466        result.push_str(&format!("\nDirect ({}):\n", direct.len()));
467        for d in &direct {
468            result.push_str(&format!(
469                "  {}\n",
470                lean_ctx::core::protocol::shorten_path(d)
471            ));
472        }
473    }
474
475    let indirect: Vec<&String> = all_dependents
476        .iter()
477        .filter(|d| !direct.contains(d))
478        .collect();
479    if !indirect.is_empty() {
480        result.push_str(&format!("\nIndirect ({}):\n", indirect.len()));
481        for d in &indirect {
482            result.push_str(&format!(
483                "  {}\n",
484                lean_ctx::core::protocol::shorten_path(d)
485            ));
486        }
487    }
488
489    let tokens = count_tokens(&result);
490    format!("{result}[ctx_graph impact: {tokens} tok]")
491}
492
493/// Transitive dependents listed by name; the rest are counted.
494const RUST_IMPACT_TRANSITIVE_SHOWN: usize = 50;
495
496/// Impact of a Rust file from its structurally resolved edges (gh-2269):
497/// `import` edges name the file that defines a used item, `module` edges the
498/// file that declares `mod x;`. A file outside every crate's module tree, or a
499/// crate root, has no resolved users, so its dependents are reported as
500/// unknown rather than as none.
501///
502/// Files are compared by `/`-separated keys: the property graph stores its
503/// node keys with `/`, while a relative path is resolved with the platform
504/// separator (`src\store.rs` on Windows).
505fn rust_impact(target: &str, rel_target: &str, gp: &GraphProvider) -> String {
506    let shown = lean_ctx::core::protocol::shorten_path(target);
507    let rel_target = rel_target.replace('\\', "/");
508    let rel_target = rel_target.as_str();
509    let edges: Vec<_> = gp
510        .edges()
511        .into_iter()
512        .filter(|e| {
513            (e.kind == "import" || e.kind == "module")
514                && Path::new(&e.to)
515                    .extension()
516                    .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
517        })
518        .map(|mut e| {
519            e.from = e.from.replace('\\', "/");
520            e.to = e.to.replace('\\', "/");
521            e
522        })
523        .collect();
524
525    let declared = edges
526        .iter()
527        .any(|e| e.kind == "module" && e.to == rel_target);
528    let declares_children = edges
529        .iter()
530        .any(|e| e.kind == "module" && e.from == rel_target);
531    if let Some(reason) =
532        graph_index::rust_modules::unresolved_dependents_reason(declared, declares_children)
533    {
534        return format!(
535            "Dependents of {shown}: unknown — {reason}. {}",
536            graph_index::rust_modules::UNKNOWN_DEPENDENTS_ADVICE
537        );
538    }
539
540    let mut reverse: HashMap<&str, Vec<&str>> = HashMap::new();
541    for e in &edges {
542        reverse
543            .entry(e.to.as_str())
544            .or_default()
545            .push(e.from.as_str());
546    }
547    let mut direct: Vec<(&str, &str)> = edges
548        .iter()
549        .filter(|e| e.to == rel_target && e.from != rel_target)
550        .map(|e| (e.from.as_str(), e.kind.as_str()))
551        .collect();
552    direct.sort_unstable();
553    direct.dedup_by(|a, b| a.0 == b.0);
554
555    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
556    seen.insert(rel_target);
557    let mut queue: std::collections::VecDeque<&str> = std::collections::VecDeque::new();
558    for (file, _) in &direct {
559        if seen.insert(file) {
560            queue.push_back(file);
561        }
562    }
563    let mut transitive: Vec<&str> = Vec::new();
564    while let Some(file) = queue.pop_front() {
565        for &from in reverse.get(file).into_iter().flatten() {
566            if seen.insert(from) {
567                transitive.push(from);
568                queue.push_back(from);
569            }
570        }
571    }
572    transitive.sort_unstable();
573
574    let mut result = format!(
575        "Impact of {shown} ({} direct, {} transitive):\n\nDirect ({}):\n",
576        direct.len(),
577        transitive.len(),
578        direct.len()
579    );
580    for (file, kind) in &direct {
581        let note = if *kind == "module" {
582            " (mod declaration)"
583        } else {
584            ""
585        };
586        result.push_str(&format!(
587            "  {}{note}\n",
588            lean_ctx::core::protocol::shorten_path(file)
589        ));
590    }
591    if declares_children && rel_target.ends_with("mod.rs") {
592        result.push_str(
593            "Note: facade module; uses of the items it re-exports are recorded against the defining files.\n",
594        );
595    }
596    if !transitive.is_empty() {
597        result.push_str(&format!("\nTransitive ({}):\n", transitive.len()));
598        for file in transitive.iter().take(RUST_IMPACT_TRANSITIVE_SHOWN) {
599            result.push_str(&format!(
600                "  {}\n",
601                lean_ctx::core::protocol::shorten_path(file)
602            ));
603        }
604        if transitive.len() > RUST_IMPACT_TRANSITIVE_SHOWN {
605            result.push_str(&format!(
606                "  … and {} more\n",
607                transitive.len() - RUST_IMPACT_TRANSITIVE_SHOWN
608            ));
609        }
610    }
611    let tokens = count_tokens(&result);
612    format!("{result}[ctx_graph impact: {tokens} tok]")
613}
614
615fn handle_status(root: &str) -> String {
616    let Some(open) = graph_provider::open_best_effort(root) else {
617        return "No graph index. Run ctx_graph action='build' to create one.".to_string();
618    };
619    let gp = &open.provider;
620
621    let file_paths = gp.file_paths();
622    let mut by_lang: HashMap<String, usize> = HashMap::new();
623    let mut total_tokens = 0usize;
624    for path in &file_paths {
625        if let Some(entry) = gp.get_file_entry(path) {
626            *by_lang.entry(entry.language).or_insert(0) += 1;
627            total_tokens += entry.token_count;
628        }
629    }
630
631    let mut langs: Vec<_> = by_lang.iter().collect();
632    langs.sort_by_key(|item| std::cmp::Reverse(*item.1));
633    let lang_summary: String = langs
634        .iter()
635        .take(5)
636        .map(|(l, c)| format!("{l}:{c}"))
637        .collect::<Vec<_>>()
638        .join(" ");
639
640    let semantic = lean_ctx::core::property_graph::CodeGraph::open(root).map_or_else(
641        |_| String::new(),
642        |g| {
643            let mode = lean_ctx::core::config::SemanticMode::for_project(root);
644            format!(
645                "\n{}",
646                lean_ctx::core::semantic::status_line(&g, mode, root)
647            )
648        },
649    );
650    format!(
651        "Graph: {} files, {} symbols, {} edges ({:?}) | {} tok total\nLast scan: {}\nLanguages: {lang_summary}{semantic}\nStored: {}",
652        gp.file_count(),
653        gp.symbol_count(),
654        gp.edge_count().unwrap_or(0),
655        open.source,
656        total_tokens,
657        gp.last_scan(),
658        GraphProvider::index_dir(root)
659            .map(|d| d.to_string_lossy().to_string())
660            .unwrap_or_default()
661    )
662}
663
664/// The name of the edge end `node_id`, when that reference may be served now
665/// (G04): a file or module node while its file is served, a symbol or test
666/// node while its file still serves the name. `None`: the end is skipped as
667/// if it were not in the graph. A node without a file on record (commit,
668/// knowledge, issue, CI run) follows the originless rule (`serves_node_parts`).
669fn served_node_name(
670    graph: &lean_ctx::core::property_graph::CodeGraph,
671    node_id: i64,
672) -> Option<String> {
673    let conn = graph.connection();
674    let Ok((name, kind, file_path)) = conn.query_row(
675        "SELECT n.name, n.kind, p.path FROM nodes n JOIN paths p ON p.id = n.file_id \
676         WHERE n.id = ?1",
677        rusqlite::params![node_id],
678        |row| {
679            Ok((
680                row.get::<_, String>(0)?,
681                row.get::<_, String>(1)?,
682                row.get::<_, String>(2)?,
683            ))
684        },
685    ) else {
686        return Some(format!("node#{node_id}"));
687    };
688    let served = graph.serves_node_parts(&kind, &file_path, &name, None);
689    served.then_some(name)
690}
691
692fn handle_enrich(root: &str) -> String {
693    let graph = match lean_ctx::core::property_graph::CodeGraph::open(root) {
694        Ok(g) => g,
695        Err(e) => return format!("Failed to open graph: {e}"),
696    };
697
698    match lean_ctx::core::graph_enricher::enrich_graph(&graph, Path::new(root), 500) {
699        Ok(stats) => {
700            let node_count = graph.node_count().unwrap_or(0);
701            let edge_count = graph.edge_count().unwrap_or(0);
702            format!(
703                "Graph enriched.\n{}\nTotal: {node_count} nodes, {edge_count} edges",
704                stats.format_summary()
705            )
706        }
707        Err(e) => format!("Enrichment failed: {e}"),
708    }
709}
710
711fn handle_context_query(query: Option<&str>, root: &str) -> String {
712    let Some(query) = query else {
713        return "Usage: ctx_graph action=context path=\"<query or file path>\"".to_string();
714    };
715
716    let graph = match lean_ctx::core::property_graph::CodeGraph::open(root) {
717        Ok(g) => g,
718        Err(e) => return format!("Failed to open graph: {e}"),
719    };
720
721    let gp = graph_provider::open_or_build(root);
722    let mut result = Vec::new();
723
724    // A node whose file is no longer served is treated as not in the graph.
725    if let Ok(Some(node)) = graph.get_node_by_path(query)
726        && graph.serves_file(&node.file_path)
727    {
728        result.push(format!("## Context for `{query}`\n"));
729
730        if let Some(node_id) = node.id {
731            let edges_out = graph.edges_from(node_id).unwrap_or_default();
732            let edges_in = graph.edges_to(node_id).unwrap_or_default();
733
734            let mut tests: Vec<String> = Vec::new();
735            let mut commits: Vec<String> = Vec::new();
736            let mut knowledge: Vec<String> = Vec::new();
737            let mut imports: Vec<String> = Vec::new();
738            let mut dependents: Vec<String> = Vec::new();
739
740            for edge in &edges_out {
741                let Some(target) = served_node_name(&graph, edge.target_id) else {
742                    continue;
743                };
744                match edge.kind {
745                    lean_ctx::core::property_graph::EdgeKind::TestedBy => tests.push(target),
746                    lean_ctx::core::property_graph::EdgeKind::ChangedIn => commits.push(target),
747                    lean_ctx::core::property_graph::EdgeKind::MentionedIn => {
748                        knowledge.push(target);
749                    }
750                    lean_ctx::core::property_graph::EdgeKind::Imports => imports.push(target),
751                    _ => {}
752                }
753            }
754
755            for edge in &edges_in {
756                if edge.kind == lean_ctx::core::property_graph::EdgeKind::Imports
757                    && let Some(source) = served_node_name(&graph, edge.source_id)
758                {
759                    dependents.push(source);
760                }
761            }
762
763            if !tests.is_empty() {
764                result.push(format!("**Tests ({}):** {}", tests.len(), tests.join(", ")));
765            }
766            if !commits.is_empty() {
767                result.push(format!(
768                    "**Recent commits ({}):** {}",
769                    commits.len(),
770                    commits
771                        .iter()
772                        .take(5)
773                        .cloned()
774                        .collect::<Vec<_>>()
775                        .join(", ")
776                ));
777            }
778            if !knowledge.is_empty() {
779                result.push(format!(
780                    "**Knowledge ({}):** {}",
781                    knowledge.len(),
782                    knowledge.join(", ")
783                ));
784            }
785            if !imports.is_empty() {
786                result.push(format!(
787                    "**Imports ({}):** {}",
788                    imports.len(),
789                    imports
790                        .iter()
791                        .take(10)
792                        .cloned()
793                        .collect::<Vec<_>>()
794                        .join(", ")
795                ));
796            }
797            if !dependents.is_empty() {
798                result.push(format!(
799                    "**Depended on by ({}):** {}",
800                    dependents.len(),
801                    dependents
802                        .iter()
803                        .take(10)
804                        .cloned()
805                        .collect::<Vec<_>>()
806                        .join(", ")
807                ));
808            }
809
810            if let Ok(impact) = graph.impact_analysis(query, 3) {
811                // Only files that are served now count toward the radius.
812                let affected = impact
813                    .affected_files
814                    .iter()
815                    .filter(|file| graph.serves_file(file))
816                    .count();
817                if affected > 0 {
818                    result.push(format!("**Impact radius:** {affected} files within 3 hops"));
819                }
820            }
821        }
822    } else {
823        result.push(format!("## Search: `{query}`\n"));
824
825        // Symbol names (e.g. GDScript `_ready`, or any function/type) live in the
826        // GraphIndex, not the PropertyGraph node table, so resolve them here — a
827        // bare concept query should return hits instead of "nothing found" (#314).
828        let mut symbols = gp
829            .as_ref()
830            .map(|o| o.provider.find_symbols(query, None, None))
831            .unwrap_or_default();
832        let q_lower = query.to_lowercase();
833        symbols.sort_by(|a, b| {
834            (a.name.to_lowercase() != q_lower)
835                .cmp(&(b.name.to_lowercase() != q_lower))
836                .then_with(|| a.file.cmp(&b.file))
837                .then_with(|| a.start_line.cmp(&b.start_line))
838        });
839        if !symbols.is_empty() {
840            result.push(format!("**Symbols ({}):**", symbols.len()));
841            for s in symbols.iter().take(15) {
842                result.push(format!(
843                    "  - {}::{} ({}, {}:{})",
844                    lean_ctx::core::protocol::shorten_path(&s.file),
845                    s.name,
846                    s.kind,
847                    s.start_line,
848                    s.end_line
849                ));
850            }
851        }
852
853        let related = gp
854            .as_ref()
855            .map(|o| o.provider.related(query, 2))
856            .unwrap_or_default();
857        if !related.is_empty() {
858            result.push(format!("**Related files ({}):**", related.len()));
859            for f in related.iter().take(15) {
860                result.push(format!("  - {f}"));
861            }
862        }
863
864        if symbols.is_empty() && related.is_empty() {
865            result.push("No matching nodes found in graph.".to_string());
866        }
867    }
868
869    result.join("\n")
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875
876    #[test]
877    fn test_edge_matches_file_crate_prefix() {
878        let prefixes = vec![
879            "lean_ctx::core::cache".to_string(),
880            "crate::core::cache".to_string(),
881            "super::core::cache".to_string(),
882            "core::cache".to_string(),
883        ];
884        assert!(edge_matches_file(
885            "lean_ctx::core::cache::SessionCache",
886            &prefixes
887        ));
888        assert!(edge_matches_file(
889            "crate::core::cache::SessionCache",
890            &prefixes
891        ));
892        assert!(edge_matches_file("crate::core::cache", &prefixes));
893        assert!(!edge_matches_file(
894            "lean_ctx::core::config::Config",
895            &prefixes
896        ));
897        assert!(!edge_matches_file("crate::core::cached_reader", &prefixes));
898    }
899
900    #[test]
901    fn test_file_path_to_module_prefixes_rust() {
902        let gp = GraphProvider::GraphIndex(lean_ctx::core::graph_index::ProjectIndex::new(
903            "/nonexistent",
904        ));
905        let prefixes = file_path_to_module_prefixes("src/core/cache.rs", "/nonexistent", &gp);
906        assert!(prefixes.contains(&"crate::core::cache".to_string()));
907        assert!(prefixes.contains(&"core::cache".to_string()));
908    }
909
910    #[test]
911    fn test_file_path_to_module_prefixes_mod_rs() {
912        let gp = GraphProvider::GraphIndex(lean_ctx::core::graph_index::ProjectIndex::new(
913            "/nonexistent",
914        ));
915        let prefixes = file_path_to_module_prefixes("src/core/mod.rs", "/nonexistent", &gp);
916        assert!(prefixes.contains(&"crate::core".to_string()));
917        assert!(!prefixes.iter().any(|p| p.contains("mod")));
918    }
919
920    #[test]
921    fn test_file_path_to_module_prefixes_gd_uses_path() {
922        // GDScript import edges store the resolved project-relative path, so the
923        // path itself must be among the prefixes `graph impact` matches on (#314).
924        let gp = GraphProvider::GraphIndex(lean_ctx::core::graph_index::ProjectIndex::new(
925            "/nonexistent",
926        ));
927        let prefixes = file_path_to_module_prefixes("actors/Player.gd", "/nonexistent", &gp);
928        assert!(
929            prefixes.contains(&"actors/Player.gd".to_string()),
930            "got: {prefixes:?}"
931        );
932    }
933
934    #[test]
935    fn test_edge_matches_file_gd_path() {
936        let prefixes = vec!["actors/Base.gd".to_string()];
937        assert!(edge_matches_file("actors/Base.gd", &prefixes));
938        assert!(!edge_matches_file("actors/Enemy.gd", &prefixes));
939    }
940}
941
942/// End-to-end GDScript graph coverage on a real Godot fixture (#314): four `.gd`
943/// scripts with `_ready` definitions and `res://` import edges, exercised through
944/// the public graph actions (context / impact / bare symbol).
945#[cfg(test)]
946mod gdscript_p0_tests {
947    use super::*;
948
949    fn write(root: &std::path::Path, rel: &str, content: &str) {
950        let p = root.join(rel);
951        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
952        std::fs::write(p, content).unwrap();
953    }
954
955    /// Minimal Godot project: `Player`/`Enemy` extend `Base`, `main` preloads
956    /// `Player`; every script defines `_ready`. Returns (tempdir guard, root).
957    fn godot_fixture() -> (tempfile::TempDir, String) {
958        let tmp = tempfile::tempdir().expect("tempdir");
959        let data = tmp.path().join("data");
960        std::fs::create_dir_all(&data).unwrap();
961        lean_ctx::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
962
963        let proj = tmp.path().join("game");
964        std::fs::create_dir_all(&proj).unwrap();
965        write(
966            &proj,
967            "project.godot",
968            "[application]\nconfig/name=\"Fixture\"\n",
969        );
970        write(
971            &proj,
972            "actors/Base.gd",
973            "extends Node\n\nfunc _ready():\n\tpass\n",
974        );
975        write(
976            &proj,
977            "actors/Player.gd",
978            "extends \"res://actors/Base.gd\"\n\nfunc _ready():\n\tprint(\"player\")\n",
979        );
980        write(
981            &proj,
982            "actors/Enemy.gd",
983            "extends \"res://actors/Base.gd\"\n\nfunc _ready():\n\tprint(\"enemy\")\n",
984        );
985        write(
986            &proj,
987            "main.gd",
988            "const Player = preload(\"res://actors/Player.gd\")\n\nfunc _ready():\n\tprint(\"main\")\n",
989        );
990
991        (tmp, proj.to_string_lossy().to_string())
992    }
993
994    #[test]
995    fn context_resolves_gdscript_symbol() {
996        let _lock = lean_ctx::core::data_dir::test_env_lock();
997        let (_tmp, root) = godot_fixture();
998        let _ = handle_build(&root);
999        let out = handle_context_query(Some("_ready"), &root);
1000        assert!(
1001            out.contains("_ready"),
1002            "context should surface _ready symbols: {out}"
1003        );
1004        assert!(!out.contains("No matching nodes found"), "got: {out}");
1005        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1006    }
1007
1008    #[test]
1009    fn impact_lists_gdscript_dependents() {
1010        let _lock = lean_ctx::core::data_dir::test_env_lock();
1011        let (_tmp, root) = godot_fixture();
1012        let _ = handle_build(&root);
1013        let out = handle_impact(Some("actors/Base.gd"), &root);
1014        assert!(
1015            out.contains("Player.gd"),
1016            "Base.gd dependents should include Player: {out}"
1017        );
1018        assert!(
1019            out.contains("Enemy.gd"),
1020            "Base.gd dependents should include Enemy: {out}"
1021        );
1022        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1023    }
1024
1025    #[test]
1026    fn bare_symbol_resolves_gdscript() {
1027        let _lock = lean_ctx::core::data_dir::test_env_lock();
1028        let (_tmp, root) = godot_fixture();
1029        let _ = handle_build(&root);
1030        let mut cache = lean_ctx::core::cache::SessionCache::new();
1031        let out = handle_symbol(
1032            Some("_ready"),
1033            &root,
1034            &mut cache,
1035            crate::tools::CrpMode::Off,
1036        );
1037        // Four `_ready` defs → a disambiguation list (or a snippet), never the
1038        // pre-#314 "Invalid symbol spec" / "not found" errors.
1039        assert!(out.contains("_ready"), "bare symbol should resolve: {out}");
1040        assert!(!out.contains("Invalid symbol spec"), "got: {out}");
1041        assert!(!out.to_lowercase().contains("not found"), "got: {out}");
1042        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1043    }
1044}
1045
1046/// Rust impact from structurally resolved module paths (gh-2269): direct and
1047/// transitive dependents are listed apart, an undeclared file reports its
1048/// dependents as unknown, and `status` names the last scan.
1049#[cfg(test)]
1050mod rust_impact_tests {
1051    use super::*;
1052
1053    fn write(root: &std::path::Path, rel: &str, content: &str) {
1054        let p = root.join(rel);
1055        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1056        std::fs::write(p, content).unwrap();
1057    }
1058
1059    fn rust_fixture() -> (tempfile::TempDir, String) {
1060        let tmp = tempfile::tempdir().expect("tempdir");
1061        let data = tmp.path().join("data");
1062        std::fs::create_dir_all(&data).unwrap();
1063        lean_ctx::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
1064
1065        let proj = tmp.path().join("ws");
1066        write(
1067            &proj,
1068            "Cargo.toml",
1069            "[package]\nname = \"demo-core\"\nversion = \"0.1.0\"\n",
1070        );
1071        write(
1072            &proj,
1073            "src/lib.rs",
1074            "pub mod store;\npub mod api;\npub mod cli;\n",
1075        );
1076        write(
1077            &proj,
1078            "src/store.rs",
1079            "pub struct Store;\n\npub fn open() -> Store {\n    Store\n}\n",
1080        );
1081        write(
1082            &proj,
1083            "src/api.rs",
1084            "use crate::store::{open, Store};\n\npub fn serve() -> Store {\n    open()\n}\n",
1085        );
1086        write(
1087            &proj,
1088            "src/cli.rs",
1089            "pub fn run() {\n    let _ = super::api::serve();\n}\n",
1090        );
1091        write(
1092            &proj,
1093            "src/notes.rs",
1094            "// crate::store::open is mentioned only here.\npub fn unused() {}\n",
1095        );
1096        (tmp, proj.to_string_lossy().to_string())
1097    }
1098
1099    #[test]
1100    fn impact_separates_direct_and_transitive_rust_dependents() {
1101        let _lock = lean_ctx::core::data_dir::test_env_lock();
1102        let (_tmp, root) = rust_fixture();
1103        let _ = handle_build(&root);
1104        let out = handle_impact(Some("src/store.rs"), &root);
1105        let (direct, transitive) = out.split_once("Transitive").unwrap_or((out.as_str(), ""));
1106        assert!(out.contains("(2 direct, 1 transitive)"), "{out}");
1107        assert!(direct.contains("api.rs"), "api.rs uses store: {out}");
1108        assert!(direct.contains("lib.rs (mod declaration)"), "{out}");
1109        assert!(!direct.contains("cli.rs"), "cli.rs is transitive: {out}");
1110        assert!(transitive.contains("cli.rs"), "{out}");
1111        assert!(!out.contains("notes.rs"), "comment-only mention: {out}");
1112        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1113    }
1114
1115    /// A path given with `\` (as Windows resolves a relative path) matches the
1116    /// `/`-keyed graph: the Windows CI answered "unknown" for `src/store.rs`.
1117    #[test]
1118    fn impact_of_backslash_rust_path_matches_slash_keys() {
1119        let _lock = lean_ctx::core::data_dir::test_env_lock();
1120        let (_tmp, root) = rust_fixture();
1121        let _ = handle_build(&root);
1122        let out = handle_impact(Some("src\\store.rs"), &root);
1123        assert!(out.contains("(2 direct, 1 transitive)"), "{out}");
1124        assert!(out.contains("lib.rs (mod declaration)"), "{out}");
1125        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1126    }
1127
1128    #[test]
1129    fn impact_of_unresolved_rust_file_is_unknown_not_none() {
1130        let _lock = lean_ctx::core::data_dir::test_env_lock();
1131        let (_tmp, root) = rust_fixture();
1132        let _ = handle_build(&root);
1133        for file in ["src/notes.rs", "src/lib.rs"] {
1134            let out = handle_impact(Some(file), &root);
1135            assert!(out.contains("unknown"), "{file}: {out}");
1136            assert!(!out.contains("No files depend"), "{file}: {out}");
1137        }
1138        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1139    }
1140
1141    /// `ctx_impact build` writes the property graph that `ctx_graph impact`
1142    /// then serves: its Rust edges come from the same module resolution as
1143    /// `ctx_graph build`, so every Rust answer is identical either way.
1144    #[test]
1145    fn impact_after_ctx_impact_build_matches_graph_build() {
1146        let _lock = lean_ctx::core::data_dir::test_env_lock();
1147        let (_tmp, root) = rust_fixture();
1148        let files = [
1149            "src/store.rs",
1150            "src/api.rs",
1151            "src/cli.rs",
1152            "src/lib.rs",
1153            "src/notes.rs",
1154        ];
1155        let _ = handle_build(&root);
1156        let after_graph_build: Vec<String> = files
1157            .iter()
1158            .map(|f| handle_impact(Some(f), &root))
1159            .collect();
1160
1161        let built = crate::tools::ctx_impact::handle("build", None, &root, None, Some("text"));
1162        assert!(!built.contains("ERROR"), "{built}");
1163        let open = graph_provider::open_or_build(&root).expect("graph");
1164        let pg = lean_ctx::core::property_graph::CodeGraph::open(&root).expect("pg");
1165        assert_eq!(
1166            open.source,
1167            graph_provider::GraphProviderSource::PropertyGraph,
1168            "ctx_graph must serve the graph ctx_impact wrote (outdated={}, nodes={:?}, edges={:?}, files={:?})",
1169            lean_ctx::core::property_graph::engine_outdated(&root),
1170            pg.node_count().ok(),
1171            pg.edge_count().ok(),
1172            pg.file_catalog_count().ok(),
1173        );
1174        drop(pg);
1175        drop(open);
1176        for (file, expected) in files.iter().zip(&after_graph_build) {
1177            assert_eq!(&handle_impact(Some(file), &root), expected, "{file}");
1178        }
1179        assert!(after_graph_build[0].contains("(2 direct, 1 transitive)"));
1180        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1181    }
1182
1183    #[test]
1184    fn status_reports_last_scan() {
1185        let _lock = lean_ctx::core::data_dir::test_env_lock();
1186        let (_tmp, root) = rust_fixture();
1187        let _ = handle_build(&root);
1188        let out = handle_status(&root);
1189        let line = out
1190            .lines()
1191            .find(|l| l.starts_with("Last scan:"))
1192            .unwrap_or_default();
1193        assert!(
1194            line.trim_start_matches("Last scan:").trim().len() >= 10,
1195            "Last scan must be set: {out}"
1196        );
1197        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");
1198    }
1199}
1200
1201/// G01: what `ctx_graph` renders from a source is cut from the admitted text.
1202#[cfg(test)]
1203mod admission_tests {
1204    use super::*;
1205    use lean_ctx::core::policy::runtime::TestPolicyOverride;
1206
1207    fn policy(body: &str) -> lean_ctx::core::policy::ResolvedPolicy {
1208        lean_ctx::core::policy::load(&format!(
1209            "name = \"ctx-graph-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n{body}"
1210        ))
1211        .unwrap()
1212    }
1213
1214    fn symbol(
1215        file: &str,
1216        name: &str,
1217        start_line: usize,
1218        end_line: usize,
1219    ) -> graph_provider::SymbolInfo {
1220        graph_provider::SymbolInfo {
1221            name: name.to_owned(),
1222            file: file.to_owned(),
1223            kind: "fn".to_owned(),
1224            start_line,
1225            end_line,
1226            is_exported: true,
1227        }
1228    }
1229
1230    /// The old snippet renderer read the file raw (`fs::read_to_string`): a
1231    /// value a project rule masks was printed, and a source the policy blocks
1232    /// was printed in full. The index entry alone must authorize neither.
1233    #[test]
1234    fn a_symbol_snippet_is_cut_from_the_admitted_source_or_withheld() {
1235        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1236        let project = tempfile::tempdir().unwrap();
1237        let root = project.path().to_string_lossy().into_owned();
1238        let billing = project.path().join("billing.rs");
1239        std::fs::write(
1240            &billing,
1241            "pub fn charge() {\n    let customer = \"CUS-1234\";\n}\n",
1242        )
1243        .unwrap();
1244        let billing = billing.to_string_lossy().into_owned();
1245        let charge = symbol("billing.rs", "charge", 1, 3);
1246        let mut cache = lean_ctx::core::cache::SessionCache::new();
1247        let off = crate::tools::CrpMode::Off;
1248        {
1249            // Control: a source no rule touches is rendered as before.
1250            let _community = TestPolicyOverride::set(None);
1251            let out =
1252                render_symbol_snippet(&charge, &billing, "billing.rs", &root, &mut cache, off);
1253            assert!(
1254                out.contains("   2|    let customer = \"CUS-1234\";\n"),
1255                "{out}"
1256            );
1257            assert!(out.contains("[ctx_graph symbol: "), "{out}");
1258        }
1259        {
1260            let _policy =
1261                TestPolicyOverride::set(Some(policy("[redaction]\ncustomer = \"CUS-[0-9]{4}\"\n")));
1262            let out =
1263                render_symbol_snippet(&charge, &billing, "billing.rs", &root, &mut cache, off);
1264            assert!(!out.contains("CUS-1234"), "{out}");
1265            assert!(out.contains("[REDACTED:customer]"), "{out}");
1266        }
1267        {
1268            let plan = project.path().join("plan.rs");
1269            std::fs::write(
1270                &plan,
1271                "CONFIDENTIAL\npub fn hidden() {\n    body_marker();\n}\n",
1272            )
1273            .unwrap();
1274            let _policy = TestPolicyOverride::set(Some(policy(
1275                "[filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
1276            )));
1277            let out = render_symbol_snippet(
1278                &symbol("plan.rs", "hidden", 2, 4),
1279                &plan.to_string_lossy(),
1280                "plan.rs",
1281                &root,
1282                &mut cache,
1283                off,
1284            );
1285            assert!(out.starts_with("Cannot read "), "{out}");
1286            assert!(out.contains("withheld"), "{out}");
1287            assert!(!out.contains("body_marker"), "{out}");
1288            assert!(
1289                cache.get_full_content(&plan.to_string_lossy()).is_none(),
1290                "a withheld source must not be in the session cache"
1291            );
1292        }
1293        assert!(
1294            cache.get_full_content(&billing).is_none(),
1295            "a snippet does not seed the session cache"
1296        );
1297    }
1298
1299    /// A manifest the policy blocks contributes no crate name to matching.
1300    #[test]
1301    fn a_withheld_manifest_contributes_no_crate_prefix() {
1302        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1303        let project = tempfile::tempdir().unwrap();
1304        let root = project.path().to_string_lossy().into_owned();
1305        std::fs::write(
1306            project.path().join("Cargo.toml"),
1307            "# CONFIDENTIAL\n[package]\nname = \"orbital-core\"\n",
1308        )
1309        .unwrap();
1310        let gp = GraphProvider::GraphIndex(lean_ctx::core::graph_index::ProjectIndex::new(&root));
1311        {
1312            let _community = TestPolicyOverride::set(None);
1313            let prefixes = file_path_to_module_prefixes("src/core/cache.rs", &root, &gp);
1314            assert!(
1315                prefixes.contains(&"orbital_core::core::cache".to_string()),
1316                "{prefixes:?}"
1317            );
1318        }
1319        let _policy = TestPolicyOverride::set(Some(policy(
1320            "[filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
1321        )));
1322        let prefixes = file_path_to_module_prefixes("src/core/cache.rs", &root, &gp);
1323        assert!(
1324            !prefixes
1325                .iter()
1326                .any(|prefix| prefix.contains("orbital_core")),
1327            "{prefixes:?}"
1328        );
1329        assert!(prefixes.contains(&"crate::core::cache".to_string()));
1330    }
1331}