Skip to main content

lean_ctx_cloud/knowledge/
code_graph.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The code graph an owner may publish to Cloud (Cloud plan v3 N1; C0 1.9
3//! section 8).
4//!
5//! By default Cloud knows a repo's code only through the anchors of its
6//! facts. When the owner sets a project's `code_graph` to `full`, the
7//! engine publishes the structure of its checkout: files and the symbols
8//! they define, which file contains which symbol, and which file imports
9//! which. Never source text, bodies or digests (a hash of a short body can
10//! be guessed back).
11//!
12//! Every path follows the anchor path rules and passes the same admission
13//! as an anchor: a file the engine may not read for knowledge, or one it
14//! withholds, is not in the graph, nor are edges to it. The graph is sorted
15//! and bounded so the same checkout always gives the same document.
16
17use std::collections::{BTreeMap, BTreeSet};
18
19use std::path::Path;
20
21use crate::CloudError;
22use crate::auth::Session;
23use crate::knowledge::screening::Screen;
24use crate::vault::VaultRecord;
25use lean_ctx::core::graph_index::ProjectIndex;
26use lean_ctx_protocol::cloud::anchor::{MAX_ANCHOR_SYMBOL_CHARS, validate_anchor_path};
27use lean_ctx_protocol::cloud::codegraph::{
28    CODE_GRAPH_PUT_SCHEMA, CODE_GRAPH_SCHEMA, CodeEdgeKind, CodeEdgeV1, CodeGraphAckV1,
29    CodeGraphPutV1, CodeGraphV1, CodeNodeKind, CodeNodeV1, MAX_CODE_GRAPH_EDGES,
30    MAX_CODE_GRAPH_NODES,
31};
32
33/// The exported graph; `truncated` when the checkout exceeds the limits.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct CodeGraph {
36    pub nodes: Vec<CodeNodeV1>,
37    pub edges: Vec<CodeEdgeV1>,
38    pub truncated: bool,
39    /// Files left out because their path or their admission did not allow it.
40    pub withheld_files: usize,
41}
42
43impl CodeGraph {
44    /// The wire document (section 8), with the commit it was built from.
45    pub fn into_v1(self, revision_hint: Option<String>) -> CodeGraphV1 {
46        CodeGraphV1 {
47            schema: CODE_GRAPH_SCHEMA.into(),
48            revision_hint,
49            nodes: self.nodes,
50            edges: self.edges,
51        }
52    }
53}
54
55fn file_id(path: &str) -> String {
56    format!("code:{path}")
57}
58
59/// A short, plain token: language and symbol kinds are hints, not text.
60fn label(value: &str) -> Option<String> {
61    let value = value.trim().to_ascii_lowercase().replace('-', "_");
62    (!value.is_empty()
63        && value.len() <= 32
64        && value
65            .bytes()
66            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'))
67    .then_some(value)
68}
69
70fn symbol_ok(name: &str) -> bool {
71    !name.is_empty()
72        && name.chars().count() <= MAX_ANCHOR_SYMBOL_CHARS
73        && !name
74            .chars()
75            .any(|c| c.is_control() || c.is_whitespace() || c == '#')
76}
77
78/// The graph of `index`, keeping only files `admit` lets through. Every
79/// path and symbol name passes the outbound `screen` (connector rule:
80/// every outbound content item is screened); a path it refuses withholds
81/// the file, a name it refuses drops the symbol.
82pub fn export(
83    index: &ProjectIndex,
84    admit: impl Fn(&str) -> bool,
85    screen: &mut Screen,
86) -> CodeGraph {
87    let mut graph = CodeGraph::default();
88    let mut files: BTreeMap<&str, &str> = BTreeMap::new();
89    let mut paths: Vec<&String> = index.files.keys().collect();
90    paths.sort();
91    for path in paths {
92        if validate_anchor_path(path).is_err() || !admit(path) || screen.check(path).is_err() {
93            graph.withheld_files += 1;
94            continue;
95        }
96        files.insert(path.as_str(), index.files[path].language.as_str());
97    }
98
99    let mut symbols: BTreeMap<&str, BTreeMap<&str, &str>> = BTreeMap::new();
100    for symbol in index.symbols.values() {
101        if files.contains_key(symbol.file.as_str())
102            && symbol_ok(&symbol.name)
103            && screen.check(&symbol.name).is_ok()
104        {
105            symbols
106                .entry(symbol.file.as_str())
107                .or_default()
108                .entry(symbol.name.as_str())
109                .or_insert(symbol.kind.as_str());
110        }
111    }
112
113    // Files first, each with its symbols, until the node limit: a file is
114    // either in the graph with all its symbols or not at all.
115    let mut kept: BTreeSet<&str> = BTreeSet::new();
116    for (path, lang) in &files {
117        let defined = symbols.get(path).map_or(0, BTreeMap::len);
118        if graph.nodes.len() + 1 + defined > MAX_CODE_GRAPH_NODES {
119            graph.truncated = true;
120            break;
121        }
122        kept.insert(path);
123        graph.nodes.push(CodeNodeV1 {
124            id: file_id(path),
125            kind: CodeNodeKind::File,
126            lang: label(lang),
127            symbol_kind: None,
128        });
129        for (name, kind) in symbols.get(path).into_iter().flatten() {
130            let id = format!("code:{path}#{name}");
131            graph.edges.push(CodeEdgeV1 {
132                from: file_id(path),
133                to: id.clone(),
134                kind: CodeEdgeKind::Contains,
135            });
136            graph.nodes.push(CodeNodeV1 {
137                id,
138                kind: CodeNodeKind::Symbol,
139                lang: None,
140                symbol_kind: label(kind),
141            });
142        }
143    }
144
145    for edge in &index.edges {
146        if matches!(edge.kind.as_str(), "import" | "reexport" | "module")
147            && edge.from != edge.to
148            && kept.contains(edge.from.as_str())
149            && kept.contains(edge.to.as_str())
150        {
151            graph.edges.push(CodeEdgeV1 {
152                from: file_id(&edge.from),
153                to: file_id(&edge.to),
154                kind: CodeEdgeKind::Imports,
155            });
156        }
157    }
158    graph.nodes.sort_by(|a, b| a.id.cmp(&b.id));
159    graph.nodes.dedup_by(|a, b| a.id == b.id);
160    sort_edges(&mut graph.edges);
161    if graph.edges.len() > MAX_CODE_GRAPH_EDGES {
162        // Every kept file keeps its symbols; imports fill what is left.
163        let (mut kept_edges, imports): (Vec<_>, Vec<_>) = graph
164            .edges
165            .drain(..)
166            .partition(|e| e.kind == CodeEdgeKind::Contains);
167        let room = MAX_CODE_GRAPH_EDGES.saturating_sub(kept_edges.len());
168        kept_edges.extend(imports.into_iter().take(room));
169        sort_edges(&mut kept_edges);
170        graph.edges = kept_edges;
171        graph.truncated = true;
172    }
173    graph
174}
175
176/// Sorted by `(from, to, type)` without repeats, as the contract wants.
177fn sort_edges(edges: &mut Vec<CodeEdgeV1>) {
178    edges.sort_by(|a, b| (&a.from, &a.to, a.kind).cmp(&(&b.from, &b.to, b.kind)));
179    edges.dedup();
180}
181
182/// The graph of the checkout at `root`, through the same source admission
183/// as a fact's anchors (a file that may not become knowledge is left out).
184pub fn export_checkout(root: &str, index: &ProjectIndex, screen: &mut Screen) -> CodeGraph {
185    export(
186        index,
187        |path| {
188            lean_ctx::core::archive::bindings::sources_at(root, &[path], "ctx_knowledge").is_some()
189        },
190        screen,
191    )
192}
193
194/// The commit the checkout at `root` is on (`git rev-parse HEAD`), when
195/// it is a git checkout.
196fn head_commit(root: &Path) -> Option<String> {
197    let out = std::process::Command::new("git")
198        .arg("-C")
199        .arg(root)
200        .args(["rev-parse", "HEAD"])
201        .output()
202        .ok()?;
203    let head = String::from_utf8(out.stdout).ok()?.trim().to_owned();
204    (out.status.success()
205        && matches!(head.len(), 40 | 64)
206        && head
207            .bytes()
208            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
209    .then_some(head)
210}
211
212/// What a publish sent.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct Published {
215    pub nodes: usize,
216    pub edges: usize,
217    pub truncated: bool,
218    pub withheld_files: usize,
219    pub revision_hint: Option<String>,
220}
221
222/// Publish the code graph of the checkout at `root` for `record` (PUT
223/// replaces the stored one). Cloud takes it only when the repo's owner set
224/// `code_graph` to `full`.
225pub fn publish(
226    session: &Session,
227    record: &VaultRecord,
228    root: &Path,
229) -> Result<Published, CloudError> {
230    let root_str = root.to_string_lossy();
231    let index = ProjectIndex::load(&root_str)
232        .unwrap_or_else(|| lean_ctx::core::graph_index::scan(&root_str));
233    // A broken screening rule sends nothing, not an empty graph that would
234    // replace the stored one.
235    let mut screen = Screen::for_installation();
236    if let Some(problem) = screen.problem() {
237        return Err(CloudError::Config(problem));
238    }
239    let exported = export_checkout(&root_str, &index, &mut screen);
240    let (truncated, withheld_files) = (exported.truncated, exported.withheld_files);
241    let revision_hint = head_commit(root);
242    let graph = exported.into_v1(revision_hint.clone());
243    graph
244        .validate()
245        .map_err(|e| CloudError::Local(format!("code graph: {e}")))?;
246    let (nodes, edges) = (graph.nodes.len(), graph.edges.len());
247    let put = CodeGraphPutV1 {
248        schema: CODE_GRAPH_PUT_SCHEMA.into(),
249        graph,
250    };
251    put.validate()
252        .map_err(|e| CloudError::Local(format!("code graph: {e}")))?;
253    let body = serde_json::to_value(&put).map_err(|e| CloudError::Local(e.to_string()))?;
254    let path = format!("/vaults/{}/code-graph", record.vault_id);
255    let answer = session
256        .with_client(|c| c.send("PUT", &path, Some(&body), &[], 64 * 1024))
257        .map_err(|e| match e {
258            CloudError::Server { status: 409, .. } => CloudError::Config(
259                "LeanCTX Cloud keeps only anchors for this vault; its owner turns on the full code graph on the web"
260                    .into(),
261            ),
262            other => other,
263        })?;
264    let _ack: CodeGraphAckV1 = serde_json::from_value(answer.body)
265        .map_err(|e| CloudError::Protocol(format!("code graph: {e}")))?;
266    Ok(Published {
267        nodes,
268        edges,
269        truncated,
270        withheld_files,
271        revision_hint,
272    })
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use lean_ctx::core::graph_index::{FileEntry, IndexEdge, SymbolEntry};
279
280    fn index() -> ProjectIndex {
281        let mut index = ProjectIndex::new("/w");
282        for (path, lang) in [
283            ("src/lib.rs", "rust"),
284            ("src/hook.rs", "rust"),
285            (".env", "dotenv"),
286            ("../escape.rs", "rust"),
287        ] {
288            index.files.insert(
289                path.into(),
290                FileEntry {
291                    path: path.into(),
292                    hash: "h".into(),
293                    language: lang.into(),
294                    line_count: 1,
295                    token_count: 1,
296                    exports: Vec::new(),
297                    summary: "fn secret() { token }".into(),
298                },
299            );
300        }
301        for (file, name, kind) in [
302            ("src/hook.rs", "retry", "fn"),
303            ("src/hook.rs", "Hook", "struct"),
304            ("src/lib.rs", "run", "fn"),
305            (".env", "API_KEY", "var"),
306            ("src/hook.rs", "bad name", "fn"),
307        ] {
308            index.symbols.insert(
309                format!("{file}::{name}"),
310                SymbolEntry {
311                    file: file.into(),
312                    name: name.into(),
313                    kind: kind.into(),
314                    start_line: 1,
315                    end_line: 2,
316                    is_exported: true,
317                },
318            );
319        }
320        for (from, to, kind) in [
321            ("src/lib.rs", "src/hook.rs", "import"),
322            ("src/lib.rs", ".env", "import"),
323            ("src/lib.rs", "src/hook.rs", "cochange"),
324        ] {
325            index.edges.push(IndexEdge {
326                from: from.into(),
327                to: to.into(),
328                kind: kind.into(),
329                weight: 1.0,
330            });
331        }
332        index
333    }
334
335    fn screen() -> Screen {
336        Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new())
337    }
338
339    /// Paths and symbol names pass the outbound screen: a forbidden one
340    /// withholds its file or drops its symbol, and a broken rule sends
341    /// nothing readable.
342    #[test]
343    fn paths_and_symbol_names_pass_the_outbound_screen() {
344        let mut strict = Screen::with_rules(
345            Vec::new(),
346            std::sync::Arc::new(Vec::new()),
347            vec![regex::Regex::new("hook\\.rs|^run$").unwrap()],
348        );
349        let graph = export(&index(), |path| path != ".env", &mut strict);
350        let ids: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).collect();
351        assert_eq!(ids, vec!["code:src/lib.rs"]);
352        assert_eq!(
353            graph.withheld_files, 3,
354            "hook.rs joins .env and ../escape.rs"
355        );
356        #[allow(clippy::invalid_regex)] // the broken rule is the point of the test
357        let mut broken = Screen::with_compiled(
358            Vec::new(),
359            std::sync::Arc::new(Vec::new()),
360            vec![regex::Regex::new("(")],
361        );
362        assert!(export(&index(), |_| true, &mut broken).nodes.is_empty());
363    }
364
365    #[test]
366    fn the_graph_holds_structure_only_for_admitted_files() {
367        let graph = export(&index(), |path| path != ".env", &mut screen());
368        let ids: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).collect();
369        assert_eq!(
370            ids,
371            vec![
372                "code:src/hook.rs",
373                "code:src/hook.rs#Hook",
374                "code:src/hook.rs#retry",
375                "code:src/lib.rs",
376                "code:src/lib.rs#run",
377            ]
378        );
379        assert_eq!(
380            graph.withheld_files, 2,
381            ".env withheld, ../escape.rs malformed"
382        );
383        let edges: Vec<(&str, &str, CodeEdgeKind)> = graph
384            .edges
385            .iter()
386            .map(|e| (e.from.as_str(), e.to.as_str(), e.kind))
387            .collect();
388        assert_eq!(
389            edges,
390            vec![
391                (
392                    "code:src/hook.rs",
393                    "code:src/hook.rs#Hook",
394                    CodeEdgeKind::Contains
395                ),
396                (
397                    "code:src/hook.rs",
398                    "code:src/hook.rs#retry",
399                    CodeEdgeKind::Contains
400                ),
401                ("code:src/lib.rs", "code:src/hook.rs", CodeEdgeKind::Imports),
402                (
403                    "code:src/lib.rs",
404                    "code:src/lib.rs#run",
405                    CodeEdgeKind::Contains
406                ),
407            ]
408        );
409        let wire = serde_json::to_string(&graph.nodes).unwrap()
410            + &serde_json::to_string(&graph.edges).unwrap();
411        for leak in ["secret", "token", "API_KEY", ".env", "\"h\""] {
412            assert!(!wire.contains(leak), "{leak} must not leave: {wire}");
413        }
414        assert!(!graph.truncated);
415        graph
416            .clone()
417            .into_v1(Some("a".repeat(40)))
418            .validate()
419            .expect("the export is a valid section 8 graph");
420        assert_eq!(
421            graph,
422            export(&index(), |path| path != ".env", &mut screen()),
423            "deterministic"
424        );
425    }
426
427    #[test]
428    fn a_large_checkout_is_cut_by_whole_files() {
429        let mut index = ProjectIndex::new("/w");
430        for i in 0..(MAX_CODE_GRAPH_NODES / 2 + 10) {
431            let path = format!("src/f{i:05}.rs");
432            index.files.insert(
433                path.clone(),
434                FileEntry {
435                    path: path.clone(),
436                    hash: String::new(),
437                    language: "rust".into(),
438                    line_count: 1,
439                    token_count: 1,
440                    exports: Vec::new(),
441                    summary: String::new(),
442                },
443            );
444            index.symbols.insert(
445                format!("{path}::f"),
446                SymbolEntry {
447                    file: path,
448                    name: "f".into(),
449                    kind: "fn".into(),
450                    start_line: 1,
451                    end_line: 1,
452                    is_exported: true,
453                },
454            );
455        }
456        let graph = export(&index, |_| true, &mut screen());
457        assert!(graph.truncated);
458        assert!(graph.nodes.len() <= MAX_CODE_GRAPH_NODES);
459        assert_eq!(graph.nodes.len() % 2, 0, "every kept file keeps its symbol");
460    }
461}