lean-ctx 3.12.0

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
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
//! Data collection and HTML rendering for the interactive visualizer.
//!
//! Gathers graph, knowledge, heatmap (token savings), and session data
//! from the current project, then renders a self-contained HTML report
//! with embedded D3.js.

use serde::Serialize;

use crate::core::heatmap::HeatMap;
use crate::core::knowledge::{KnowledgeFact, ProjectKnowledge};
use crate::core::property_graph::CodeGraph;
use crate::core::session::{SessionState, SessionStats};

// ---------------------------------------------------------------------------
// Data types serialized into JSON for the HTML template
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct VisualizerData {
    pub graph: GraphData,
    pub knowledge: Vec<KnowledgeEntry>,
    pub savings: SavingsData,
    pub history: SessionHistory,
}

#[derive(Serialize)]
pub(crate) struct GraphData {
    pub nodes: Vec<GraphNode>,
    pub edges: Vec<GraphEdge>,
}

#[derive(Serialize)]
pub(crate) struct GraphNode {
    pub id: String,
    pub kind: String,
    pub label: String,
}

#[derive(Serialize)]
pub(crate) struct GraphEdge {
    pub source: String,
    pub target: String,
    pub kind: String,
    pub weight: f64,
}

#[derive(Serialize)]
pub(crate) struct KnowledgeEntry {
    pub category: String,
    pub key: String,
    pub value: String,
    pub confidence: f32,
    pub archetype: String,
    pub created_at: String,
    pub valid_from: Option<String>,
    pub valid_until: Option<String>,
    pub retrieval_count: u32,
    pub confirmation_count: u32,
}

#[derive(Serialize)]
pub(crate) struct SavingsData {
    pub files: Vec<FileSavingsEntry>,
    pub total_original: u64,
    pub total_saved: u64,
    pub overall_ratio: f32,
}

#[derive(Serialize)]
pub(crate) struct FileSavingsEntry {
    pub path: String,
    pub access_count: u32,
    pub original_tokens: u64,
    pub saved_tokens: u64,
    pub compression_ratio: f32,
}

#[derive(Serialize)]
pub(crate) struct SessionHistory {
    pub session_id: String,
    pub started_at: String,
    pub task: Option<String>,
    pub stats: SessionStatsEntry,
    pub files_touched: Vec<FileTouchedEntry>,
    pub findings: Vec<FindingEntry>,
    pub decisions: Vec<DecisionEntry>,
    pub progress: Vec<ProgressEntryViz>,
}

#[derive(Serialize)]
pub(crate) struct SessionStatsEntry {
    pub total_tool_calls: u32,
    pub total_tokens_saved: u64,
    pub total_tokens_input: u64,
    pub cache_hits: u32,
    pub files_read: u32,
    pub commands_run: u32,
}

#[derive(Serialize)]
pub(crate) struct FileTouchedEntry {
    pub path: String,
    pub read_count: u32,
    pub modified: bool,
    pub mode: String,
    pub tokens: usize,
}

#[derive(Serialize)]
pub(crate) struct FindingEntry {
    pub file: Option<String>,
    pub summary: String,
    pub timestamp: String,
}

#[derive(Serialize)]
pub(crate) struct DecisionEntry {
    pub summary: String,
    pub rationale: Option<String>,
    pub timestamp: String,
}

#[derive(Serialize)]
pub(crate) struct ProgressEntryViz {
    pub action: String,
    pub detail: Option<String>,
    pub timestamp: String,
}

// ---------------------------------------------------------------------------
// Data collection
// ---------------------------------------------------------------------------

pub(crate) fn collect_data(project_root: &str) -> VisualizerData {
    let graph = collect_graph(project_root);
    let knowledge = collect_knowledge(project_root);
    let savings = collect_savings();
    let history = collect_session(project_root);

    VisualizerData {
        graph,
        knowledge,
        savings,
        history,
    }
}

fn collect_graph(project_root: &str) -> GraphData {
    let Ok(cg) = CodeGraph::open(project_root) else {
        return GraphData {
            nodes: Vec::new(),
            edges: Vec::new(),
        };
    };

    let flat_edges = cg.all_edges_flat().unwrap_or_default();

    let mut node_set = std::collections::HashSet::new();
    let mut nodes = Vec::new();
    let mut edges = Vec::new();

    for (src, tgt, kind, weight) in &flat_edges {
        // Serve-time source check (G04): both ends must still be served; a
        // `path::symbol` end is checked by its file.
        let served = |end: &str| cg.serves_file(end.split_once("::").map_or(end, |(file, _)| file));
        if !served(src) || !served(tgt) {
            continue;
        }
        for path in [src, tgt] {
            if node_set.insert(path.clone()) {
                let label = path.rsplit('/').next().unwrap_or(path).to_string();
                nodes.push(GraphNode {
                    id: path.clone(),
                    kind: "file".to_string(),
                    label,
                });
            }
        }
        edges.push(GraphEdge {
            source: src.clone(),
            target: tgt.clone(),
            kind: kind.clone(),
            weight: *weight,
        });
    }

    GraphData { nodes, edges }
}

fn collect_knowledge(project_root: &str) -> Vec<KnowledgeEntry> {
    let Some(pk) = ProjectKnowledge::load(project_root) else {
        return Vec::new();
    };
    // The report is written with a plain file write, not through the export
    // jail: it carries only facts that may be delivered now
    // (`ProjectKnowledge::delivery_filter`).
    let deliverable = pk.delivery_filter();
    pk.facts
        .iter()
        .filter(|&f| deliverable(f))
        .map(|f: &KnowledgeFact| KnowledgeEntry {
            category: f.category.clone(),
            key: f.key.clone(),
            value: f.value.clone(),
            confidence: f.confidence,
            archetype: format!("{:?}", f.archetype),
            created_at: f.created_at.to_rfc3339(),
            valid_from: f.valid_from.map(|d| d.to_rfc3339()),
            valid_until: f.valid_until.map(|d| d.to_rfc3339()),
            retrieval_count: f.retrieval_count,
            confirmation_count: f.confirmation_count,
        })
        .collect()
}

fn collect_savings() -> SavingsData {
    let hm = HeatMap::load();
    let top = hm.top_files(500);

    let mut total_original = 0u64;
    let mut total_saved = 0u64;

    let files: Vec<FileSavingsEntry> = top
        .into_iter()
        .map(|e| {
            total_original += e.total_original_tokens;
            total_saved += e.total_tokens_saved;
            FileSavingsEntry {
                path: e.path.clone(),
                access_count: e.access_count,
                original_tokens: e.total_original_tokens,
                saved_tokens: e.total_tokens_saved,
                compression_ratio: e.avg_compression_ratio,
            }
        })
        .collect();

    let overall_ratio = if total_original > 0 {
        total_saved as f32 / total_original as f32
    } else {
        0.0
    };

    SavingsData {
        files,
        total_original,
        total_saved,
        overall_ratio,
    }
}

fn collect_session(project_root: &str) -> SessionHistory {
    let session = SessionState::load_latest_for_project_root(project_root).unwrap_or_default();

    map_session(&session)
}

fn map_session(s: &SessionState) -> SessionHistory {
    SessionHistory {
        session_id: s.id.clone(),
        started_at: s.started_at.to_rfc3339(),
        task: s.task.as_ref().map(|t| t.description.clone()),
        stats: map_stats(&s.stats),
        files_touched: s
            .files_touched
            .iter()
            .map(|f| FileTouchedEntry {
                path: f.path.clone(),
                read_count: f.read_count,
                modified: f.modified,
                mode: f.last_mode.clone(),
                tokens: f.tokens,
            })
            .collect(),
        findings: s
            .findings
            .iter()
            .map(|f| FindingEntry {
                file: f.file.clone(),
                summary: f.summary.clone(),
                timestamp: f.timestamp.to_rfc3339(),
            })
            .collect(),
        decisions: s
            .decisions
            .iter()
            .map(|d| DecisionEntry {
                summary: d.summary.clone(),
                rationale: d.rationale.clone(),
                timestamp: d.timestamp.to_rfc3339(),
            })
            .collect(),
        progress: s
            .progress
            .iter()
            .map(|p| ProgressEntryViz {
                action: p.action.clone(),
                detail: p.detail.clone(),
                timestamp: p.timestamp.to_rfc3339(),
            })
            .collect(),
    }
}

fn map_stats(s: &SessionStats) -> SessionStatsEntry {
    SessionStatsEntry {
        total_tool_calls: s.total_tool_calls,
        total_tokens_saved: s.total_tokens_saved,
        total_tokens_input: s.total_tokens_input,
        cache_hits: s.cache_hits,
        files_read: s.files_read,
        commands_run: s.commands_run,
    }
}

// ---------------------------------------------------------------------------
// HTML rendering
// ---------------------------------------------------------------------------

pub(crate) fn render_html(data: &VisualizerData) -> String {
    let json = serde_json::to_string(data).unwrap_or_else(|_| "{}".to_string());
    let template = include_str!("../assets/visualizer.html");
    template.replace("/*__VISUALIZER_DATA__*/", &format!("const DATA = {json};"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_data_renders_valid_html() {
        let data = VisualizerData {
            graph: GraphData {
                nodes: Vec::new(),
                edges: Vec::new(),
            },
            knowledge: Vec::new(),
            savings: SavingsData {
                files: Vec::new(),
                total_original: 0,
                total_saved: 0,
                overall_ratio: 0.0,
            },
            history: SessionHistory {
                session_id: "test".to_string(),
                started_at: "2024-01-01T00:00:00Z".to_string(),
                task: None,
                stats: SessionStatsEntry {
                    total_tool_calls: 0,
                    total_tokens_saved: 0,
                    total_tokens_input: 0,
                    cache_hits: 0,
                    files_read: 0,
                    commands_run: 0,
                },
                files_touched: Vec::new(),
                findings: Vec::new(),
                decisions: Vec::new(),
                progress: Vec::new(),
            },
        };
        let html = render_html(&data);
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("const DATA ="));
        assert!(!html.contains("/*__VISUALIZER_DATA__*/"));
    }

    #[test]
    fn savings_ratio_zero_on_empty() {
        let s = collect_savings();
        assert!(s.overall_ratio >= 0.0);
    }

    #[test]
    fn graph_node_label_uses_filename() {
        let node = GraphNode {
            id: "src/core/main.rs".to_string(),
            kind: "file".to_string(),
            label: "main.rs".to_string(),
        };
        assert_eq!(node.label, "main.rs");
    }

    /// The report carries only facts that are served now.
    #[test]
    fn a_fact_that_is_not_served_is_not_in_the_report() {
        use crate::core::context_admission::stored::lineage_support::{
            BOUND_FACT, TYPED_FACT, governed, project, scoped, two_facts, withdraw_source,
        };
        let _data = governed();
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let (_directory, root) = project();
        two_facts(&root, "architecture");
        let values = || -> Vec<String> {
            scoped(&root, || collect_knowledge(&root))
                .into_iter()
                .map(|entry| entry.value)
                .collect()
        };
        assert!(values().contains(&BOUND_FACT.to_owned()));
        withdraw_source(&root);
        assert_eq!(values(), [TYPED_FACT.to_owned()]);
    }
}