1use std::collections::{BTreeMap, BTreeSet};
18
19use std::path::Path;
20
21use crate::core::graph_index::ProjectIndex;
22use crate::core::hive::HiveError;
23use crate::core::hive::auth::Session;
24use crate::core::hive::sealed;
25use crate::core::hive::vault::VaultRecord;
26use lean_ctx_protocol::hive::anchor::{MAX_ANCHOR_SYMBOL_CHARS, validate_anchor_path};
27use lean_ctx_protocol::hive::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#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct CodeGraph {
36 pub nodes: Vec<CodeNodeV1>,
37 pub edges: Vec<CodeEdgeV1>,
38 pub truncated: bool,
39 pub withheld_files: usize,
41}
42
43impl CodeGraph {
44 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
59fn 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
78pub fn export(index: &ProjectIndex, admit: impl Fn(&str) -> bool) -> CodeGraph {
80 let mut graph = CodeGraph::default();
81 let mut files: BTreeMap<&str, &str> = BTreeMap::new();
82 let mut paths: Vec<&String> = index.files.keys().collect();
83 paths.sort();
84 for path in paths {
85 if validate_anchor_path(path).is_err() || !admit(path) {
86 graph.withheld_files += 1;
87 continue;
88 }
89 files.insert(path.as_str(), index.files[path].language.as_str());
90 }
91
92 let mut symbols: BTreeMap<&str, BTreeMap<&str, &str>> = BTreeMap::new();
93 for symbol in index.symbols.values() {
94 if files.contains_key(symbol.file.as_str()) && symbol_ok(&symbol.name) {
95 symbols
96 .entry(symbol.file.as_str())
97 .or_default()
98 .entry(symbol.name.as_str())
99 .or_insert(symbol.kind.as_str());
100 }
101 }
102
103 let mut kept: BTreeSet<&str> = BTreeSet::new();
106 for (path, lang) in &files {
107 let defined = symbols.get(path).map_or(0, BTreeMap::len);
108 if graph.nodes.len() + 1 + defined > MAX_CODE_GRAPH_NODES {
109 graph.truncated = true;
110 break;
111 }
112 kept.insert(path);
113 graph.nodes.push(CodeNodeV1 {
114 id: file_id(path),
115 kind: CodeNodeKind::File,
116 lang: label(lang),
117 symbol_kind: None,
118 });
119 for (name, kind) in symbols.get(path).into_iter().flatten() {
120 let id = format!("code:{path}#{name}");
121 graph.edges.push(CodeEdgeV1 {
122 from: file_id(path),
123 to: id.clone(),
124 kind: CodeEdgeKind::Contains,
125 });
126 graph.nodes.push(CodeNodeV1 {
127 id,
128 kind: CodeNodeKind::Symbol,
129 lang: None,
130 symbol_kind: label(kind),
131 });
132 }
133 }
134
135 for edge in &index.edges {
136 if matches!(edge.kind.as_str(), "import" | "reexport" | "module")
137 && edge.from != edge.to
138 && kept.contains(edge.from.as_str())
139 && kept.contains(edge.to.as_str())
140 {
141 graph.edges.push(CodeEdgeV1 {
142 from: file_id(&edge.from),
143 to: file_id(&edge.to),
144 kind: CodeEdgeKind::Imports,
145 });
146 }
147 }
148 graph.nodes.sort_by(|a, b| a.id.cmp(&b.id));
149 graph.nodes.dedup_by(|a, b| a.id == b.id);
150 sort_edges(&mut graph.edges);
151 if graph.edges.len() > MAX_CODE_GRAPH_EDGES {
152 let (mut kept_edges, imports): (Vec<_>, Vec<_>) = graph
154 .edges
155 .drain(..)
156 .partition(|e| e.kind == CodeEdgeKind::Contains);
157 let room = MAX_CODE_GRAPH_EDGES.saturating_sub(kept_edges.len());
158 kept_edges.extend(imports.into_iter().take(room));
159 sort_edges(&mut kept_edges);
160 graph.edges = kept_edges;
161 graph.truncated = true;
162 }
163 graph
164}
165
166fn sort_edges(edges: &mut Vec<CodeEdgeV1>) {
168 edges.sort_by(|a, b| (&a.from, &a.to, a.kind).cmp(&(&b.from, &b.to, b.kind)));
169 edges.dedup();
170}
171
172pub fn export_checkout(root: &str, index: &ProjectIndex) -> CodeGraph {
175 export(index, |path| {
176 crate::core::archive::bindings::sources_at(root, &[path], "ctx_knowledge").is_some()
177 })
178}
179
180fn head_commit(root: &Path) -> Option<String> {
183 let out = std::process::Command::new("git")
184 .arg("-C")
185 .arg(root)
186 .args(["rev-parse", "HEAD"])
187 .output()
188 .ok()?;
189 let head = String::from_utf8(out.stdout).ok()?.trim().to_owned();
190 (out.status.success()
191 && matches!(head.len(), 40 | 64)
192 && head
193 .bytes()
194 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
195 .then_some(head)
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct Published {
201 pub nodes: usize,
202 pub edges: usize,
203 pub truncated: bool,
204 pub withheld_files: usize,
205 pub sealed: bool,
206 pub revision_hint: Option<String>,
207}
208
209pub fn publish(
213 session: &Session,
214 record: &VaultRecord,
215 root: &Path,
216) -> Result<Published, HiveError> {
217 let root_str = root.to_string_lossy();
218 let index =
219 ProjectIndex::load(&root_str).unwrap_or_else(|| crate::core::graph_index::scan(&root_str));
220 let exported = export_checkout(&root_str, &index);
221 let (truncated, withheld_files) = (exported.truncated, exported.withheld_files);
222 let revision_hint = head_commit(root);
223 let graph = exported.into_v1(revision_hint.clone());
224 graph
225 .validate()
226 .map_err(|e| HiveError::Local(format!("code graph: {e}")))?;
227 let (nodes, edges) = (graph.nodes.len(), graph.edges.len());
228 let put = if record.sealed {
229 let base = super::load_base(session.store.data_dir(), &record.vault_id).revision;
232 let key = match sealed::sealing_key(session, &record.vault_id, base)? {
233 sealed::SealingKey::Ready(epoch, key) => (epoch, key),
234 sealed::SealingKey::Waiting => {
235 return Err(HiveError::Config(
236 "this sealed vault's key has not reached this machine yet".into(),
237 ));
238 }
239 sealed::SealingKey::Rotating { .. } => {
240 return Err(HiveError::Config(
241 "this sealed vault's key is being rotated; try again shortly".into(),
242 ));
243 }
244 };
245 let doc = serde_json::to_value(&graph).map_err(|e| HiveError::Local(e.to_string()))?;
246 let plaintext = lean_ctx_protocol::hive::canonical_json(&doc)
247 .map_err(|e| HiveError::Local(e.to_string()))?;
248 CodeGraphPutV1 {
249 schema: CODE_GRAPH_PUT_SCHEMA.into(),
250 graph: None,
251 sealed: Some(sealed::seal(
252 &key.1,
253 &record.vault_id,
254 0,
255 key.0,
256 CODE_GRAPH_SCHEMA,
257 &plaintext,
258 )?),
259 }
260 } else {
261 CodeGraphPutV1 {
262 schema: CODE_GRAPH_PUT_SCHEMA.into(),
263 graph: Some(graph),
264 sealed: None,
265 }
266 };
267 put.validate()
268 .map_err(|e| HiveError::Local(format!("code graph: {e}")))?;
269 let body = serde_json::to_value(&put).map_err(|e| HiveError::Local(e.to_string()))?;
270 let path = format!("/vaults/{}/code-graph", record.vault_id);
271 let answer = session
272 .with_client(|c| c.send("PUT", &path, Some(&body), &[], 64 * 1024))
273 .map_err(|e| match e {
274 HiveError::Server { status: 409, .. } => HiveError::Config(
275 if record.sealed {
276 "Hive did not take the graph: the vault keeps only anchors (its owner turns on the full code graph on the web), or its key moved to a newer epoch (run `lean-ctx hive sync`, then publish again)"
277 } else {
278 "Hive keeps only anchors for this vault; its owner turns on the full code graph on the web"
279 }
280 .into(),
281 ),
282 other => other,
283 })?;
284 let _ack: CodeGraphAckV1 = serde_json::from_value(answer.body)
285 .map_err(|e| HiveError::Protocol(format!("code graph: {e}")))?;
286 Ok(Published {
287 nodes,
288 edges,
289 truncated,
290 withheld_files,
291 sealed: record.sealed,
292 revision_hint,
293 })
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use crate::core::graph_index::{FileEntry, IndexEdge, SymbolEntry};
300
301 fn index() -> ProjectIndex {
302 let mut index = ProjectIndex::new("/w");
303 for (path, lang) in [
304 ("src/lib.rs", "rust"),
305 ("src/hook.rs", "rust"),
306 (".env", "dotenv"),
307 ("../escape.rs", "rust"),
308 ] {
309 index.files.insert(
310 path.into(),
311 FileEntry {
312 path: path.into(),
313 hash: "h".into(),
314 language: lang.into(),
315 line_count: 1,
316 token_count: 1,
317 exports: Vec::new(),
318 summary: "fn secret() { token }".into(),
319 },
320 );
321 }
322 for (file, name, kind) in [
323 ("src/hook.rs", "retry", "fn"),
324 ("src/hook.rs", "Hook", "struct"),
325 ("src/lib.rs", "run", "fn"),
326 (".env", "API_KEY", "var"),
327 ("src/hook.rs", "bad name", "fn"),
328 ] {
329 index.symbols.insert(
330 format!("{file}::{name}"),
331 SymbolEntry {
332 file: file.into(),
333 name: name.into(),
334 kind: kind.into(),
335 start_line: 1,
336 end_line: 2,
337 is_exported: true,
338 },
339 );
340 }
341 for (from, to, kind) in [
342 ("src/lib.rs", "src/hook.rs", "import"),
343 ("src/lib.rs", ".env", "import"),
344 ("src/lib.rs", "src/hook.rs", "cochange"),
345 ] {
346 index.edges.push(IndexEdge {
347 from: from.into(),
348 to: to.into(),
349 kind: kind.into(),
350 weight: 1.0,
351 });
352 }
353 index
354 }
355
356 #[test]
357 fn the_graph_holds_structure_only_for_admitted_files() {
358 let graph = export(&index(), |path| path != ".env");
359 let ids: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).collect();
360 assert_eq!(
361 ids,
362 vec![
363 "code:src/hook.rs",
364 "code:src/hook.rs#Hook",
365 "code:src/hook.rs#retry",
366 "code:src/lib.rs",
367 "code:src/lib.rs#run",
368 ]
369 );
370 assert_eq!(
371 graph.withheld_files, 2,
372 ".env withheld, ../escape.rs malformed"
373 );
374 let edges: Vec<(&str, &str, CodeEdgeKind)> = graph
375 .edges
376 .iter()
377 .map(|e| (e.from.as_str(), e.to.as_str(), e.kind))
378 .collect();
379 assert_eq!(
380 edges,
381 vec![
382 (
383 "code:src/hook.rs",
384 "code:src/hook.rs#Hook",
385 CodeEdgeKind::Contains
386 ),
387 (
388 "code:src/hook.rs",
389 "code:src/hook.rs#retry",
390 CodeEdgeKind::Contains
391 ),
392 ("code:src/lib.rs", "code:src/hook.rs", CodeEdgeKind::Imports),
393 (
394 "code:src/lib.rs",
395 "code:src/lib.rs#run",
396 CodeEdgeKind::Contains
397 ),
398 ]
399 );
400 let wire = serde_json::to_string(&graph.nodes).unwrap()
401 + &serde_json::to_string(&graph.edges).unwrap();
402 for leak in ["secret", "token", "API_KEY", ".env", "\"h\""] {
403 assert!(!wire.contains(leak), "{leak} must not leave: {wire}");
404 }
405 assert!(!graph.truncated);
406 graph
407 .clone()
408 .into_v1(Some("a".repeat(40)))
409 .validate()
410 .expect("the export is a valid section 8 graph");
411 assert_eq!(
412 graph,
413 export(&index(), |path| path != ".env"),
414 "deterministic"
415 );
416 }
417
418 #[test]
419 fn a_large_checkout_is_cut_by_whole_files() {
420 let mut index = ProjectIndex::new("/w");
421 for i in 0..(MAX_CODE_GRAPH_NODES / 2 + 10) {
422 let path = format!("src/f{i:05}.rs");
423 index.files.insert(
424 path.clone(),
425 FileEntry {
426 path: path.clone(),
427 hash: String::new(),
428 language: "rust".into(),
429 line_count: 1,
430 token_count: 1,
431 exports: Vec::new(),
432 summary: String::new(),
433 },
434 );
435 index.symbols.insert(
436 format!("{path}::f"),
437 SymbolEntry {
438 file: path,
439 name: "f".into(),
440 kind: "fn".into(),
441 start_line: 1,
442 end_line: 1,
443 is_exported: true,
444 },
445 );
446 }
447 let graph = export(&index, |_| true);
448 assert!(graph.truncated);
449 assert!(graph.nodes.len() <= MAX_CODE_GRAPH_NODES);
450 assert_eq!(graph.nodes.len() % 2, 0, "every kept file keeps its symbol");
451 }
452}