Skip to main content

lean_ctx/core/property_graph/
served.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The one check through which a graph reference — a file, a symbol, an edge
3//! end — leaves toward a tool or host (G04).
4//!
5//! A graph row names the project file it was derived from. Nothing in the row
6//! changes when that file is deleted, restricted or rewritten, so every
7//! reference is asked again when it is served:
8//!
9//! 1. **All modes:** the path must resolve inside the project root through
10//!    the path jail the rooted reader uses (`pathjail::jail_path`) and be a
11//!    regular file there (links are not followed). Gone or outside ⇒ not
12//!    served. In Community developer mode this is the whole rule — the mode
13//!    makes no protection claim, as with the originless rule.
14//! 2. **Under protection** (`stored::source_authority_required`): the full
15//!    rule of `bm25_index::source_gate::SourceGate` for every reference — the
16//!    admitted rooted reader must return the file now, storable, under the
17//!    current project policy and role, and a symbol's name must still occur
18//!    in it. Same gate, same bound: over the bound the reference is refused.
19//!
20//! There is deliberately no shortcut under protection. The graph records a
21//! content fingerprint for its own staleness check and could record the
22//! gateway policy digest, but neither covers the project policy pack or the
23//! role, so "unchanged since an admitted build" does not prove today's
24//! rights. A staleness fingerprint is not an authorization.
25//!
26//! A reference that is not a project file (`scheme://…`, a cross-source node)
27//! has no source authority on record: withheld under protection, served in
28//! Community developer mode.
29//!
30//! One gate serves one opened graph, which is one request: decisions are
31//! memoised per file and never outlive it.
32
33use std::cell::{OnceCell, RefCell};
34use std::collections::{BTreeSet, HashMap, HashSet};
35use std::path::Path;
36
37use rusqlite::Connection;
38
39use super::{CodeGraph, Node};
40use crate::core::bm25_index::source_gate::SourceGate;
41
42/// Tool identity graph sources are re-read for under protection.
43const GRAPH_TOOL: &str = "ctx_graph";
44
45/// Distinct files one request can decide under protection: the content-read
46/// bound of `SourceGate`. It chooses between a whole-graph and a local
47/// ranking; the gate itself enforces the bound.
48const PROTECTED_FILES: usize = crate::core::bm25_index::source_gate::MAX_SOURCES;
49
50/// Files one gate decides and remembers. Over it a file the gate has not
51/// decided yet is refused: not checked, not served, not remembered.
52const MAX_FILES: usize = 65_536;
53
54/// The serve-time check of one opened graph.
55pub(crate) struct GraphGate {
56    project_root: String,
57    protected: OnceCell<bool>,
58    /// Per file asked so far: whether it is a regular file inside the root.
59    present: RefCell<HashMap<String, bool>>,
60    sources: RefCell<SourceGate>,
61}
62
63impl GraphGate {
64    pub(crate) fn for_root(project_root: &str) -> Self {
65        Self {
66            project_root: project_root.to_owned(),
67            protected: OnceCell::new(),
68            present: RefCell::new(HashMap::new()),
69            sources: RefCell::new(SourceGate::new(Path::new(project_root), GRAPH_TOOL)),
70        }
71    }
72
73    /// Whether the file `path` may be named now.
74    pub(crate) fn file(&self, path: &str) -> bool {
75        self.reference(path, "")
76    }
77
78    /// Whether the symbol `name` of `path` may be named now.
79    pub(crate) fn symbol(&self, path: &str, name: &str) -> bool {
80        self.reference(path, identifier(name))
81    }
82
83    /// Whether protection is active for this request (read once).
84    fn protected(&self) -> bool {
85        *self
86            .protected
87            .get_or_init(crate::core::context_admission::stored::source_authority_required)
88    }
89
90    /// Whether `text` of a node that names no project file (a commit, a
91    /// knowledge fact, an issue, a CI run) may be served now. Such a node
92    /// records no source binding, so it follows the originless rule of
93    /// `serve_stored`: withheld while protection is active in any layer,
94    /// served in Community developer mode when today's content rules leave
95    /// it unchanged.
96    fn originless(&self, text: &str) -> bool {
97        !self.protected()
98            && crate::core::context_admission::stored::serve_stored(text, None, None)
99                .is_ok_and(|served| served == text)
100    }
101
102    /// The files of `files` that may enter a traversal or ranking over the
103    /// whole graph. `edges` are the file pairs of that graph, `seeds` the
104    /// files the request is about.
105    ///
106    /// Community developer mode, or a graph small enough to be decided in
107    /// full: every file is asked. Under protection with more files than one
108    /// request can decide ([`PROTECTED_FILES`]): the ranking is local — the
109    /// seeds are asked first, then their neighbours, frontier by frontier and
110    /// only through files that are served, until the bound is spent. Without
111    /// seeds that is the empty set: no ranking rather than one over files
112    /// nobody decided.
113    pub(crate) fn ranking_files(
114        &self,
115        mut files: Vec<String>,
116        edges: &[(String, String)],
117        seeds: &[String],
118    ) -> HashSet<String> {
119        files.sort();
120        files.dedup();
121        if !self.protected() || files.len() <= PROTECTED_FILES {
122            return files.into_iter().filter(|file| self.file(file)).collect();
123        }
124        let known: HashSet<&str> = files.iter().map(String::as_str).collect();
125        let mut asked: HashSet<&str> = HashSet::new();
126        let mut served: HashSet<String> = HashSet::new();
127        let mut frontier: BTreeSet<&str> = seeds
128            .iter()
129            .map(String::as_str)
130            .filter(|seed| known.contains(*seed))
131            .collect();
132        while !frontier.is_empty() && asked.len() < PROTECTED_FILES {
133            let mut next: BTreeSet<&str> = BTreeSet::new();
134            for file in frontier {
135                if asked.len() >= PROTECTED_FILES {
136                    break;
137                }
138                if !asked.insert(file) || !self.file(file) {
139                    continue;
140                }
141                served.insert(file.to_owned());
142                for (from, to) in edges {
143                    if from == file {
144                        next.insert(to.as_str());
145                    } else if to == file {
146                        next.insert(from.as_str());
147                    }
148                }
149            }
150            next.retain(|file| known.contains(*file) && !asked.contains(*file));
151            frontier = next;
152        }
153        served
154    }
155
156    fn reference(&self, path: &str, needle: &str) -> bool {
157        let protected = self.protected();
158        if path.contains("://") {
159            return !protected;
160        }
161        self.present(path) && (!protected || self.sources.borrow_mut().serves(path, needle))
162    }
163
164    fn present(&self, path: &str) -> bool {
165        let known = self.present.borrow().get(path).copied();
166        if let Some(known) = known {
167            return known;
168        }
169        if self.present.borrow().len() >= MAX_FILES {
170            return false;
171        }
172        let root = Path::new(&self.project_root);
173        let present = crate::core::pathjail::jail_path(&root.join(path), root)
174            .is_ok_and(|jailed| std::fs::symlink_metadata(jailed).is_ok_and(|meta| meta.is_file()));
175        self.present.borrow_mut().insert(path.to_owned(), present);
176        present
177    }
178}
179
180/// The last identifier of a symbol name: `Config::load` → `load`,
181/// `fmt::Display for Wrapper` → `Wrapper`. That is what must still occur in
182/// the admitted text.
183fn identifier(name: &str) -> &str {
184    name.rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
185        .find(|part| !part.is_empty())
186        .unwrap_or("")
187}
188
189impl CodeGraph {
190    /// This graph, gated for `project_root`: for an in-memory copy of a
191    /// project's graph that is read back through the serving surface.
192    #[must_use]
193    // pub only for lean-ctx-engine-ext; not public API
194    #[doc(hidden)]
195    pub fn gated_for(mut self, project_root: &str) -> Self {
196        self.gate = Some(GraphGate::for_root(project_root));
197        self
198    }
199
200    /// Whether a reference to the file `path` of this graph may be served
201    /// now. A graph without a project root (in memory) has no source on
202    /// record to ask and is not gated.
203    pub fn serves_file(&self, path: &str) -> bool {
204        self.gate.as_ref().is_none_or(|gate| gate.file(path))
205    }
206
207    /// Whether a reference to the symbol `name` of `path` may be served now.
208    pub fn serves_symbol(&self, path: &str, name: &str) -> bool {
209        self.gate
210            .as_ref()
211            .is_none_or(|gate| gate.symbol(path, name))
212    }
213
214    /// Whether `node` may be named now — the one entry point for a node of
215    /// any kind. See [`Self::serves_node_parts`].
216    pub fn serves_node(&self, node: &Node) -> bool {
217        self.serves_node_parts(
218            node.kind.as_str(),
219            &node.file_path,
220            &node.name,
221            node.metadata.as_deref(),
222        )
223    }
224
225    /// [`Self::serves_node`] for a row read as columns (`nodes.kind`, the
226    /// path, `nodes.name`, `nodes.metadata`).
227    ///
228    /// - A node of a project file: a `symbol`, or a `test` named other than
229    ///   its file, by the symbol rule; every other kind by the file rule.
230    /// - A node without a file on record (commit, knowledge, issue, CI run):
231    ///   no node records a source binding that could be re-checked, so the
232    ///   originless rule decides its name and, when given, its metadata —
233    ///   withheld under protection, served in Community developer mode while
234    ///   today's content rules leave the text unchanged. Pass the metadata
235    ///   whenever it is shown or exported.
236    pub fn serves_node_parts(
237        &self,
238        kind: &str,
239        file_path: &str,
240        name: &str,
241        metadata: Option<&str>,
242    ) -> bool {
243        let Some(gate) = self.gate.as_ref() else {
244            return true;
245        };
246        if file_path.is_empty() {
247            return gate.originless(name) && metadata.is_none_or(|text| gate.originless(text));
248        }
249        match kind {
250            "symbol" | "test" if name != file_path => gate.symbol(file_path, name),
251            _ => gate.file(file_path),
252        }
253    }
254
255    /// `neighbours` of the file `anchor`: nothing when the anchor itself may
256    /// not be served, otherwise the neighbours that may.
257    pub(super) fn served_neighbours(&self, anchor: &str, neighbours: Vec<String>) -> Vec<String> {
258        if !self.serves_file(anchor) {
259            return Vec::new();
260        }
261        neighbours
262            .into_iter()
263            .filter(|path| self.serves_file(path))
264            .collect()
265    }
266}
267
268/// A graph store as a whole-graph computation reads it — a ranking, a
269/// community detection, a rule scan: the rows, and the serve-time source
270/// check that decides which of them exist for the computation (G04).
271///
272/// [`CodeGraph`] answers with the gate of the request that opened it. A bare
273/// [`Connection`] has no project root on record and admits everything; it is
274/// the form of a graph that is not served from a project (in memory).
275pub trait GraphSource {
276    /// The connection the rows are read from.
277    fn store(&self) -> &Connection;
278
279    /// Whether this source asks current sources at all. `false` for a store
280    /// without a project root: a caller that would name several files in one
281    /// row must then leave that row to a check that can decide them.
282    fn checks_sources(&self) -> bool;
283
284    /// Whether the file `path` may be used now.
285    fn file_served(&self, path: &str) -> bool;
286
287    /// Whether the symbol `name` of `path` may be used now.
288    fn symbol_served(&self, path: &str, name: &str) -> bool;
289
290    /// The files of `files` that may enter a computation over the whole
291    /// graph (`GraphGate::ranking_files`).
292    fn rankable_files(
293        &self,
294        files: Vec<String>,
295        edges: &[(String, String)],
296        seeds: &[String],
297    ) -> HashSet<String>;
298}
299
300/// A reference to a source is that source (`&graph` where `graph` is already
301/// a `&CodeGraph`).
302impl<T: GraphSource + ?Sized> GraphSource for &T {
303    fn store(&self) -> &Connection {
304        (**self).store()
305    }
306
307    fn checks_sources(&self) -> bool {
308        (**self).checks_sources()
309    }
310
311    fn file_served(&self, path: &str) -> bool {
312        (**self).file_served(path)
313    }
314
315    fn symbol_served(&self, path: &str, name: &str) -> bool {
316        (**self).symbol_served(path, name)
317    }
318
319    fn rankable_files(
320        &self,
321        files: Vec<String>,
322        edges: &[(String, String)],
323        seeds: &[String],
324    ) -> HashSet<String> {
325        (**self).rankable_files(files, edges, seeds)
326    }
327}
328
329impl GraphSource for Connection {
330    fn store(&self) -> &Connection {
331        self
332    }
333
334    fn checks_sources(&self) -> bool {
335        false
336    }
337
338    fn file_served(&self, _path: &str) -> bool {
339        true
340    }
341
342    fn symbol_served(&self, _path: &str, _name: &str) -> bool {
343        true
344    }
345
346    fn rankable_files(
347        &self,
348        files: Vec<String>,
349        _edges: &[(String, String)],
350        _seeds: &[String],
351    ) -> HashSet<String> {
352        files.into_iter().collect()
353    }
354}
355
356impl GraphSource for CodeGraph {
357    fn store(&self) -> &Connection {
358        self.connection()
359    }
360
361    fn checks_sources(&self) -> bool {
362        self.gate.is_some()
363    }
364
365    fn file_served(&self, path: &str) -> bool {
366        self.serves_file(path)
367    }
368
369    fn symbol_served(&self, path: &str, name: &str) -> bool {
370        self.serves_symbol(path, name)
371    }
372
373    fn rankable_files(
374        &self,
375        files: Vec<String>,
376        edges: &[(String, String)],
377        seeds: &[String],
378    ) -> HashSet<String> {
379        match self.gate.as_ref() {
380            Some(gate) => gate.ranking_files(files, edges, seeds),
381            None => files.into_iter().collect(),
382        }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use crate::core::graph_index::{FileEntry, ProjectIndex, SymbolEntry};
389    use crate::core::graph_provider::GraphProvider;
390    use crate::core::policy::runtime::TestPolicyOverride;
391
392    /// A file and its symbol are served while the file exists and are
393    /// withheld — path, entry and symbol name — once it is removed.
394    #[test]
395    fn a_graph_reference_is_withheld_once_its_source_file_is_gone() {
396        let _data = crate::core::data_dir::isolated_data_dir();
397        let _community = TestPolicyOverride::set(None);
398        let project = tempfile::tempdir().expect("project");
399        let root = project.path().to_string_lossy().into_owned();
400        std::fs::write(project.path().join("auth.rs"), "pub fn verify() {}\n").expect("source");
401
402        let mut index = ProjectIndex::new(&root);
403        index.files.insert(
404            "auth.rs".to_owned(),
405            FileEntry {
406                path: "auth.rs".to_owned(),
407                hash: String::new(),
408                language: "rust".to_owned(),
409                line_count: 1,
410                token_count: 4,
411                exports: vec!["verify".to_owned()],
412                summary: "pub fn verify() {}".to_owned(),
413            },
414        );
415        index.symbols.insert(
416            "auth.rs::verify".to_owned(),
417            SymbolEntry {
418                file: "auth.rs".to_owned(),
419                name: "verify".to_owned(),
420                kind: "fn".to_owned(),
421                start_line: 1,
422                end_line: 1,
423                is_exported: true,
424            },
425        );
426        let provider = GraphProvider::GraphIndex(index);
427
428        assert_eq!(provider.file_paths(), vec!["auth.rs".to_owned()]);
429        assert_eq!(provider.all_symbols().len(), 1);
430        assert!(provider.get_file_entry("auth.rs").is_some());
431
432        std::fs::remove_file(project.path().join("auth.rs")).expect("remove");
433        assert!(provider.file_paths().is_empty());
434        assert!(provider.all_symbols().is_empty());
435        assert!(provider.get_symbol("auth.rs::verify").is_none());
436        assert!(provider.get_file_entry("auth.rs").is_none());
437        assert!(provider.materialize_project_index(&root).files.is_empty());
438    }
439
440    /// Under protection a graph with more files than one request can decide
441    /// is ranked locally: from the seeds outwards, never more files than the
442    /// bound, never one the gate did not decide — and not at all without
443    /// seeds.
444    #[test]
445    fn a_ranking_under_protection_uses_only_files_decided_from_its_seeds() {
446        use super::{GraphGate, PROTECTED_FILES};
447
448        let _data = crate::core::data_dir::isolated_data_dir();
449        let pack = crate::core::policy::parse(
450            "name = \"graph-ranking-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
451             [redaction]\ncustomer = 'K-[0-9]{6}'",
452        )
453        .expect("valid policy");
454        let _protected = TestPolicyOverride::set(Some(
455            crate::core::policy::resolve(&pack).expect("resolved policy"),
456        ));
457        let project = tempfile::tempdir().expect("project");
458        let root = project.path().to_string_lossy().into_owned();
459        // A chain f000 → f001 → … two files longer than the bound.
460        let files: Vec<String> = (0..PROTECTED_FILES + 2)
461            .map(|n| format!("f{n:03}.rs"))
462            .collect();
463        for file in &files {
464            std::fs::write(project.path().join(file), "pub fn item() {}\n").expect("source");
465        }
466        let edges: Vec<(String, String)> = files
467            .windows(2)
468            .map(|pair| (pair[0].clone(), pair[1].clone()))
469            .collect();
470
471        let gate = GraphGate::for_root(&root);
472        let local = gate.ranking_files(files.clone(), &edges, &files[..1]);
473        assert!(local.contains(&files[0]), "the seed is decided first");
474        assert!(local.len() <= PROTECTED_FILES);
475        assert!(
476            !local.contains(&files[PROTECTED_FILES + 1]),
477            "beyond the bound"
478        );
479        // Whatever the ranking uses, this gate decided and serves.
480        assert!(local.iter().all(|file| gate.file(file)));
481        // The far end was never decided; the spent gate refuses it.
482        assert!(!gate.file(&files[PROTECTED_FILES + 1]));
483
484        let unseeded = GraphGate::for_root(&root).ranking_files(files, &edges, &[]);
485        assert!(unseeded.is_empty());
486    }
487
488    /// A withdrawn file is no step of a walk: with `a → w → b` and `a → n`,
489    /// `b` is reached from `a` (and `a` from `b`) only while `w` is served.
490    /// Once `w` is gone nothing is reached through it, its edges are not
491    /// counted, and `a`'s neighbour that still exists is still found.
492    #[test]
493    fn a_traversal_does_not_pass_through_a_withdrawn_file() {
494        use crate::core::property_graph::{CodeGraph, Edge, EdgeKind, Node};
495
496        let _data = crate::core::data_dir::isolated_data_dir();
497        let _community = TestPolicyOverride::set(None);
498        let project = tempfile::tempdir().expect("project");
499        let root = project.path().to_string_lossy().into_owned();
500        for file in ["a.rs", "w.rs", "b.rs", "n.rs"] {
501            std::fs::write(project.path().join(file), "pub fn item() {}\n").expect("source");
502        }
503
504        let graph = CodeGraph::open(&root).expect("graph");
505        let node = |file: &str| graph.upsert_node(&Node::file(file)).expect("node");
506        let (a, w, b, n) = (node("a.rs"), node("w.rs"), node("b.rs"), node("n.rs"));
507        for (from, to) in [(a, w), (w, b), (a, n)] {
508            graph
509                .upsert_edge(&Edge::new(from, to, EdgeKind::Imports))
510                .expect("edge");
511        }
512
513        let chain = graph.dependency_chain("a.rs", "b.rs").expect("chain");
514        assert_eq!(
515            chain.map(|chain| chain.path),
516            Some(vec![
517                "a.rs".to_owned(),
518                "w.rs".to_owned(),
519                "b.rs".to_owned()
520            ])
521        );
522        let impact = graph.impact_analysis("b.rs", 5).expect("impact");
523        assert_eq!(impact.affected_files, ["a.rs", "w.rs"]);
524        assert_eq!(impact.edges_traversed, 2);
525
526        std::fs::remove_file(project.path().join("w.rs")).expect("withdraw");
527        // A new request: a gate decides a file once.
528        let graph = CodeGraph::open(&root).expect("graph");
529        assert!(
530            graph
531                .dependency_chain("a.rs", "b.rs")
532                .expect("chain")
533                .is_none()
534        );
535        let impact = graph.impact_analysis("b.rs", 5).expect("impact");
536        assert!(impact.affected_files.is_empty(), "{impact:?}");
537        assert_eq!(impact.edges_traversed, 0);
538        assert_eq!(impact.max_depth_reached, 0);
539        let near = graph.dependency_chain("a.rs", "n.rs").expect("chain");
540        assert_eq!(near.map(|chain| chain.depth), Some(1));
541        let related: Vec<String> = graph
542            .related_files("a.rs", 10)
543            .expect("related")
544            .into_iter()
545            .map(|(path, _)| path)
546            .collect();
547        assert_eq!(related, ["n.rs"]);
548    }
549}