1use 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
42const GRAPH_TOOL: &str = "ctx_graph";
44
45const PROTECTED_FILES: usize = crate::core::bm25_index::source_gate::MAX_SOURCES;
49
50const MAX_FILES: usize = 65_536;
53
54pub(crate) struct GraphGate {
56 project_root: String,
57 protected: OnceCell<bool>,
58 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 pub(crate) fn file(&self, path: &str) -> bool {
75 self.reference(path, "")
76 }
77
78 pub(crate) fn symbol(&self, path: &str, name: &str) -> bool {
80 self.reference(path, identifier(name))
81 }
82
83 fn protected(&self) -> bool {
85 *self
86 .protected
87 .get_or_init(crate::core::context_admission::stored::source_authority_required)
88 }
89
90 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 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
180fn 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 #[must_use]
193 #[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 pub fn serves_file(&self, path: &str) -> bool {
204 self.gate.as_ref().is_none_or(|gate| gate.file(path))
205 }
206
207 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 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 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 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
268pub trait GraphSource {
276 fn store(&self) -> &Connection;
278
279 fn checks_sources(&self) -> bool;
283
284 fn file_served(&self, path: &str) -> bool;
286
287 fn symbol_served(&self, path: &str, name: &str) -> bool;
289
290 fn rankable_files(
293 &self,
294 files: Vec<String>,
295 edges: &[(String, String)],
296 seeds: &[String],
297 ) -> HashSet<String>;
298}
299
300impl<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 #[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 #[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 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 assert!(local.iter().all(|file| gate.file(file)));
481 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 #[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 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}