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,
};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodeGraph {
pub nodes: Vec<CodeNodeV1>,
pub edges: Vec<CodeEdgeV1>,
pub truncated: bool,
pub withheld_files: usize,
}
impl CodeGraph {
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}")
}
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 == '#')
}
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());
}
}
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 {
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
}
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();
}
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,
)
}
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)
}
#[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>,
}
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));
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(
"The 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())
}
#[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)] 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");
}
}