lean-ctx-cloud 3.12.8

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// SPDX-License-Identifier: Apache-2.0
//! The code graph an owner may publish to Cloud (Cloud plan v3 N1; C0 1.9
//! section 8).
//!
//! By default Cloud knows a repo's code only through the anchors of its
//! facts. When the owner sets a project's `code_graph` to `full`, the
//! engine publishes the structure of its checkout: files and the symbols
//! they define, which file contains which symbol, and which file imports
//! which. Never source text, bodies or digests (a hash of a short body can
//! be guessed back).
//!
//! Every path follows the anchor path rules and passes the same admission
//! as an anchor: a file the engine may not read for knowledge, or one it
//! withholds, is not in the graph, nor are edges to it. The graph is sorted
//! and bounded so the same checkout always gives the same document.

use std::collections::{BTreeMap, BTreeSet};

use std::path::Path;

use crate::CloudError;
use crate::auth::Session;
use crate::knowledge::screening::Screen;
use crate::vault::VaultRecord;
use lean_ctx::core::graph_index::ProjectIndex;
use lean_ctx_protocol::cloud::anchor::{MAX_ANCHOR_SYMBOL_CHARS, validate_anchor_path};
use lean_ctx_protocol::cloud::codegraph::{
    CODE_GRAPH_PUT_SCHEMA, CODE_GRAPH_SCHEMA, CodeEdgeKind, CodeEdgeV1, CodeGraphAckV1,
    CodeGraphPutV1, CodeGraphV1, CodeNodeKind, CodeNodeV1, MAX_CODE_GRAPH_EDGES,
    MAX_CODE_GRAPH_NODES,
};

/// The exported graph; `truncated` when the checkout exceeds the limits.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodeGraph {
    pub nodes: Vec<CodeNodeV1>,
    pub edges: Vec<CodeEdgeV1>,
    pub truncated: bool,
    /// Files left out because their path or their admission did not allow it.
    pub withheld_files: usize,
}

impl CodeGraph {
    /// The wire document (section 8), with the commit it was built from.
    pub fn into_v1(self, revision_hint: Option<String>) -> CodeGraphV1 {
        CodeGraphV1 {
            schema: CODE_GRAPH_SCHEMA.into(),
            revision_hint,
            nodes: self.nodes,
            edges: self.edges,
        }
    }
}

fn file_id(path: &str) -> String {
    format!("code:{path}")
}

/// A short, plain token: language and symbol kinds are hints, not text.
fn label(value: &str) -> Option<String> {
    let value = value.trim().to_ascii_lowercase().replace('-', "_");
    (!value.is_empty()
        && value.len() <= 32
        && value
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'))
    .then_some(value)
}

fn symbol_ok(name: &str) -> bool {
    !name.is_empty()
        && name.chars().count() <= MAX_ANCHOR_SYMBOL_CHARS
        && !name
            .chars()
            .any(|c| c.is_control() || c.is_whitespace() || c == '#')
}

/// The graph of `index`, keeping only files `admit` lets through. Every
/// path and symbol name passes the outbound `screen` (connector rule:
/// every outbound content item is screened); a path it refuses withholds
/// the file, a name it refuses drops the symbol.
pub fn export(
    index: &ProjectIndex,
    admit: impl Fn(&str) -> bool,
    screen: &mut Screen,
) -> CodeGraph {
    let mut graph = CodeGraph::default();
    let mut files: BTreeMap<&str, &str> = BTreeMap::new();
    let mut paths: Vec<&String> = index.files.keys().collect();
    paths.sort();
    for path in paths {
        if validate_anchor_path(path).is_err() || !admit(path) || screen.check(path).is_err() {
            graph.withheld_files += 1;
            continue;
        }
        files.insert(path.as_str(), index.files[path].language.as_str());
    }

    let mut symbols: BTreeMap<&str, BTreeMap<&str, &str>> = BTreeMap::new();
    for symbol in index.symbols.values() {
        if files.contains_key(symbol.file.as_str())
            && symbol_ok(&symbol.name)
            && screen.check(&symbol.name).is_ok()
        {
            symbols
                .entry(symbol.file.as_str())
                .or_default()
                .entry(symbol.name.as_str())
                .or_insert(symbol.kind.as_str());
        }
    }

    // Files first, each with its symbols, until the node limit: a file is
    // either in the graph with all its symbols or not at all.
    let mut kept: BTreeSet<&str> = BTreeSet::new();
    for (path, lang) in &files {
        let defined = symbols.get(path).map_or(0, BTreeMap::len);
        if graph.nodes.len() + 1 + defined > MAX_CODE_GRAPH_NODES {
            graph.truncated = true;
            break;
        }
        kept.insert(path);
        graph.nodes.push(CodeNodeV1 {
            id: file_id(path),
            kind: CodeNodeKind::File,
            lang: label(lang),
            symbol_kind: None,
        });
        for (name, kind) in symbols.get(path).into_iter().flatten() {
            let id = format!("code:{path}#{name}");
            graph.edges.push(CodeEdgeV1 {
                from: file_id(path),
                to: id.clone(),
                kind: CodeEdgeKind::Contains,
            });
            graph.nodes.push(CodeNodeV1 {
                id,
                kind: CodeNodeKind::Symbol,
                lang: None,
                symbol_kind: label(kind),
            });
        }
    }

    for edge in &index.edges {
        if matches!(edge.kind.as_str(), "import" | "reexport" | "module")
            && edge.from != edge.to
            && kept.contains(edge.from.as_str())
            && kept.contains(edge.to.as_str())
        {
            graph.edges.push(CodeEdgeV1 {
                from: file_id(&edge.from),
                to: file_id(&edge.to),
                kind: CodeEdgeKind::Imports,
            });
        }
    }
    graph.nodes.sort_by(|a, b| a.id.cmp(&b.id));
    graph.nodes.dedup_by(|a, b| a.id == b.id);
    sort_edges(&mut graph.edges);
    if graph.edges.len() > MAX_CODE_GRAPH_EDGES {
        // Every kept file keeps its symbols; imports fill what is left.
        let (mut kept_edges, imports): (Vec<_>, Vec<_>) = graph
            .edges
            .drain(..)
            .partition(|e| e.kind == CodeEdgeKind::Contains);
        let room = MAX_CODE_GRAPH_EDGES.saturating_sub(kept_edges.len());
        kept_edges.extend(imports.into_iter().take(room));
        sort_edges(&mut kept_edges);
        graph.edges = kept_edges;
        graph.truncated = true;
    }
    graph
}

/// Sorted by `(from, to, type)` without repeats, as the contract wants.
fn sort_edges(edges: &mut Vec<CodeEdgeV1>) {
    edges.sort_by(|a, b| (&a.from, &a.to, a.kind).cmp(&(&b.from, &b.to, b.kind)));
    edges.dedup();
}

/// The graph of the checkout at `root`, through the same source admission
/// as a fact's anchors (a file that may not become knowledge is left out).
pub fn export_checkout(root: &str, index: &ProjectIndex, screen: &mut Screen) -> CodeGraph {
    export(
        index,
        |path| {
            lean_ctx::core::archive::bindings::sources_at(root, &[path], "ctx_knowledge").is_some()
        },
        screen,
    )
}

/// The commit the checkout at `root` is on (`git rev-parse HEAD`), when
/// it is a git checkout.
fn head_commit(root: &Path) -> Option<String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()?;
    let head = String::from_utf8(out.stdout).ok()?.trim().to_owned();
    (out.status.success()
        && matches!(head.len(), 40 | 64)
        && head
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
    .then_some(head)
}

/// What a publish sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Published {
    pub nodes: usize,
    pub edges: usize,
    pub truncated: bool,
    pub withheld_files: usize,
    pub revision_hint: Option<String>,
}

/// Publish the code graph of the checkout at `root` for `record` (PUT
/// replaces the stored one). Cloud takes it only when the repo's owner set
/// `code_graph` to `full`.
pub fn publish(
    session: &Session,
    record: &VaultRecord,
    root: &Path,
) -> Result<Published, CloudError> {
    let root_str = root.to_string_lossy();
    let index = ProjectIndex::load(&root_str)
        .unwrap_or_else(|| lean_ctx::core::graph_index::scan(&root_str));
    // A broken screening rule sends nothing, not an empty graph that would
    // replace the stored one.
    let mut screen = Screen::for_installation();
    if let Some(problem) = screen.problem() {
        return Err(CloudError::Config(problem));
    }
    let exported = export_checkout(&root_str, &index, &mut screen);
    let (truncated, withheld_files) = (exported.truncated, exported.withheld_files);
    let revision_hint = head_commit(root);
    let graph = exported.into_v1(revision_hint.clone());
    graph
        .validate()
        .map_err(|e| CloudError::Local(format!("code graph: {e}")))?;
    let (nodes, edges) = (graph.nodes.len(), graph.edges.len());
    let put = CodeGraphPutV1 {
        schema: CODE_GRAPH_PUT_SCHEMA.into(),
        graph,
    };
    put.validate()
        .map_err(|e| CloudError::Local(format!("code graph: {e}")))?;
    let body = serde_json::to_value(&put).map_err(|e| CloudError::Local(e.to_string()))?;
    let path = format!("/vaults/{}/code-graph", record.vault_id);
    let answer = session
        .with_client(|c| c.send("PUT", &path, Some(&body), &[], 64 * 1024))
        .map_err(|e| match e {
            CloudError::Server { status: 409, .. } => CloudError::Config(
                "LeanCTX Cloud keeps only anchors for this vault; its owner turns on the full code graph on the web"
                    .into(),
            ),
            other => other,
        })?;
    let _ack: CodeGraphAckV1 = serde_json::from_value(answer.body)
        .map_err(|e| CloudError::Protocol(format!("code graph: {e}")))?;
    Ok(Published {
        nodes,
        edges,
        truncated,
        withheld_files,
        revision_hint,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use lean_ctx::core::graph_index::{FileEntry, IndexEdge, SymbolEntry};

    fn index() -> ProjectIndex {
        let mut index = ProjectIndex::new("/w");
        for (path, lang) in [
            ("src/lib.rs", "rust"),
            ("src/hook.rs", "rust"),
            (".env", "dotenv"),
            ("../escape.rs", "rust"),
        ] {
            index.files.insert(
                path.into(),
                FileEntry {
                    path: path.into(),
                    hash: "h".into(),
                    language: lang.into(),
                    line_count: 1,
                    token_count: 1,
                    exports: Vec::new(),
                    summary: "fn secret() { token }".into(),
                },
            );
        }
        for (file, name, kind) in [
            ("src/hook.rs", "retry", "fn"),
            ("src/hook.rs", "Hook", "struct"),
            ("src/lib.rs", "run", "fn"),
            (".env", "API_KEY", "var"),
            ("src/hook.rs", "bad name", "fn"),
        ] {
            index.symbols.insert(
                format!("{file}::{name}"),
                SymbolEntry {
                    file: file.into(),
                    name: name.into(),
                    kind: kind.into(),
                    start_line: 1,
                    end_line: 2,
                    is_exported: true,
                },
            );
        }
        for (from, to, kind) in [
            ("src/lib.rs", "src/hook.rs", "import"),
            ("src/lib.rs", ".env", "import"),
            ("src/lib.rs", "src/hook.rs", "cochange"),
        ] {
            index.edges.push(IndexEdge {
                from: from.into(),
                to: to.into(),
                kind: kind.into(),
                weight: 1.0,
            });
        }
        index
    }

    fn screen() -> Screen {
        Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new())
    }

    /// Paths and symbol names pass the outbound screen: a forbidden one
    /// withholds its file or drops its symbol, and a broken rule sends
    /// nothing readable.
    #[test]
    fn paths_and_symbol_names_pass_the_outbound_screen() {
        let mut strict = Screen::with_rules(
            Vec::new(),
            std::sync::Arc::new(Vec::new()),
            vec![regex::Regex::new("hook\\.rs|^run$").unwrap()],
        );
        let graph = export(&index(), |path| path != ".env", &mut strict);
        let ids: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).collect();
        assert_eq!(ids, vec!["code:src/lib.rs"]);
        assert_eq!(
            graph.withheld_files, 3,
            "hook.rs joins .env and ../escape.rs"
        );
        #[allow(clippy::invalid_regex)] // the broken rule is the point of the test
        let mut broken = Screen::with_compiled(
            Vec::new(),
            std::sync::Arc::new(Vec::new()),
            vec![regex::Regex::new("(")],
        );
        assert!(export(&index(), |_| true, &mut broken).nodes.is_empty());
    }

    #[test]
    fn the_graph_holds_structure_only_for_admitted_files() {
        let graph = export(&index(), |path| path != ".env", &mut screen());
        let ids: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).collect();
        assert_eq!(
            ids,
            vec![
                "code:src/hook.rs",
                "code:src/hook.rs#Hook",
                "code:src/hook.rs#retry",
                "code:src/lib.rs",
                "code:src/lib.rs#run",
            ]
        );
        assert_eq!(
            graph.withheld_files, 2,
            ".env withheld, ../escape.rs malformed"
        );
        let edges: Vec<(&str, &str, CodeEdgeKind)> = graph
            .edges
            .iter()
            .map(|e| (e.from.as_str(), e.to.as_str(), e.kind))
            .collect();
        assert_eq!(
            edges,
            vec![
                (
                    "code:src/hook.rs",
                    "code:src/hook.rs#Hook",
                    CodeEdgeKind::Contains
                ),
                (
                    "code:src/hook.rs",
                    "code:src/hook.rs#retry",
                    CodeEdgeKind::Contains
                ),
                ("code:src/lib.rs", "code:src/hook.rs", CodeEdgeKind::Imports),
                (
                    "code:src/lib.rs",
                    "code:src/lib.rs#run",
                    CodeEdgeKind::Contains
                ),
            ]
        );
        let wire = serde_json::to_string(&graph.nodes).unwrap()
            + &serde_json::to_string(&graph.edges).unwrap();
        for leak in ["secret", "token", "API_KEY", ".env", "\"h\""] {
            assert!(!wire.contains(leak), "{leak} must not leave: {wire}");
        }
        assert!(!graph.truncated);
        graph
            .clone()
            .into_v1(Some("a".repeat(40)))
            .validate()
            .expect("the export is a valid section 8 graph");
        assert_eq!(
            graph,
            export(&index(), |path| path != ".env", &mut screen()),
            "deterministic"
        );
    }

    #[test]
    fn a_large_checkout_is_cut_by_whole_files() {
        let mut index = ProjectIndex::new("/w");
        for i in 0..(MAX_CODE_GRAPH_NODES / 2 + 10) {
            let path = format!("src/f{i:05}.rs");
            index.files.insert(
                path.clone(),
                FileEntry {
                    path: path.clone(),
                    hash: String::new(),
                    language: "rust".into(),
                    line_count: 1,
                    token_count: 1,
                    exports: Vec::new(),
                    summary: String::new(),
                },
            );
            index.symbols.insert(
                format!("{path}::f"),
                SymbolEntry {
                    file: path,
                    name: "f".into(),
                    kind: "fn".into(),
                    start_line: 1,
                    end_line: 1,
                    is_exported: true,
                },
            );
        }
        let graph = export(&index, |_| true, &mut screen());
        assert!(graph.truncated);
        assert!(graph.nodes.len() <= MAX_CODE_GRAPH_NODES);
        assert_eq!(graph.nodes.len() % 2, 0, "every kept file keeps its symbol");
    }
}