Skip to main content

lean_ctx/core/benchmark_compare/
report.rs

1use super::competitors::CompetitorProfile;
2use super::metrics::{self, ComparativeMetrics};
3use super::system_info::SystemInfo;
4
5#[derive(Debug)]
6pub struct CompareReport {
7    pub metrics: ComparativeMetrics,
8    pub system: SystemInfo,
9    pub competitors: Vec<CompetitorProfile>,
10}
11
12pub fn generate_markdown(report: &CompareReport) -> String {
13    let mut out = Vec::new();
14
15    write_header(&mut out, report);
16    write_methodology(&mut out);
17    write_compression_table(&mut out, report);
18    write_mode_detail(&mut out, report);
19    write_search_latency(&mut out, report);
20    write_cold_start(&mut out, report);
21    write_disk_footprint(&mut out, report);
22    write_feature_matrix(&mut out, report);
23    write_session_simulation(&mut out, report);
24    write_chart(&mut out, report);
25    write_system_info(&mut out, &report.system);
26    write_reproducibility(&mut out);
27    write_footer(&mut out);
28
29    out.join("\n")
30}
31
32pub fn generate_terminal(report: &CompareReport) -> String {
33    let mut out = Vec::new();
34    let sep = "\u{2550}".repeat(72);
35
36    out.push(sep.clone());
37    out.push("  lean-ctx Research-only representation comparison".to_string());
38    out.push(sep.clone());
39    out.push(String::new());
40
41    out.push("  Local representation comparison (not a product benchmark):".to_string());
42    out.push(format!(
43        "  {:<28} {:>12} {:>12} {:>10}",
44        "Tool", "Compression", "Search", "Features"
45    ));
46    out.push(format!("  {}", "\u{2500}".repeat(66)));
47
48    for c in &report.competitors {
49        let comp = c
50            .compression_pct
51            .map_or("N/A".to_string(), |p| format!("{p:.0}%"));
52        let search = if c.supports_search { "Yes" } else { "No" };
53        out.push(format!(
54            "  {:<28} {:>12} {:>12} {:>10}",
55            c.name, comp, search, c.feature_count
56        ));
57    }
58
59    for mc in &report.metrics.mode_comparisons {
60        if mc.mode == "full" {
61            continue;
62        }
63        out.push(format!(
64            "  {:<28} {:>11.1}% {:>12} {:>10}",
65            format!("lean-ctx ({})", mc.mode),
66            mc.avg_compression_pct,
67            "Yes",
68            report.metrics.feature_count
69        ));
70    }
71
72    out.push(String::new());
73
74    let avg_search = metrics::avg_search_latency_us(&report.metrics.search_latencies);
75    out.push(format!(
76        "  Avg search latency: {}",
77        metrics::format_duration_us(avg_search)
78    ));
79    out.push(format!(
80        "  Cold start: {}",
81        metrics::format_duration_us(report.metrics.cold_start.total_us)
82    ));
83    out.push(format!(
84        "  Disk footprint: {}",
85        metrics::format_bytes(report.metrics.disk_footprint.total_index_bytes)
86    ));
87
88    out.push(sep);
89    out.join("\n")
90}
91
92fn write_header(out: &mut Vec<String>, report: &CompareReport) {
93    out.push("# lean-ctx Research-only representation comparison".to_string());
94    out.push(String::new());
95    out.push(format!(
96        "> Generated by lean-ctx v{}; results are specific to the named local repository.",
97        report.system.lean_ctx_version
98    ));
99    out.push(String::new());
100    out.push(format!(
101        "**Project:** `{}`  ",
102        report.metrics.project_benchmark.root
103    ));
104    out.push(format!(
105        "**Files measured:** {}  ",
106        report.metrics.project_benchmark.files_measured
107    ));
108    out.push(format!(
109        "**Total raw tokens:** {}  ",
110        format_num(report.metrics.project_benchmark.total_raw_tokens)
111    ));
112    out.push(String::new());
113}
114
115fn write_methodology(out: &mut Vec<String>) {
116    out.push("## Research methodology and boundary".to_string());
117    out.push(String::new());
118    out.push(
119        "This report is a **Research** artifact, not a public Performance Benchmark or a universal comparative claim. \
120              Local representation measurements apply to the named repository only. \
121              Any external figures are unverified reference inputs, not matched-workload evidence."
122            .to_string(),
123    );
124    out.push(String::new());
125    out.push("- **Token counting**: tiktoken `o200k_base` (GPT-4o tokenizer)".to_string());
126    out.push("- **Compression**: Each lean-ctx read mode is applied to the same files".to_string());
127    out.push("- **Latency**: Wall-clock time, median of all measured files".to_string());
128    out.push("- **Quality**: Preservation score (structural + semantic fidelity)".to_string());
129    out.push(String::new());
130}
131
132fn write_compression_table(out: &mut Vec<String>, report: &CompareReport) {
133    out.push("## Local representation comparison".to_string());
134    out.push(String::new());
135    out.push("| Tool | Compression | Tokens | Source |".to_string());
136    out.push("|------|------------:|-------:|--------|".to_string());
137
138    let raw_tokens = report.metrics.project_benchmark.total_raw_tokens;
139
140    for c in &report.competitors {
141        let comp = c
142            .compression_pct
143            .map_or("N/A".to_string(), |p| format!("{p:.0}%"));
144        let tokens = c.compression_pct.map_or("—".to_string(), |p| {
145            format_num((raw_tokens as f64 * (1.0 - p / 100.0)) as usize)
146        });
147        out.push(format!(
148            "| {} | {} | {} | {} |",
149            c.name, comp, tokens, c.source
150        ));
151    }
152
153    for mc in &report.metrics.mode_comparisons {
154        if mc.mode == "full" {
155            continue;
156        }
157        out.push(format!(
158            "| **lean-ctx ({})** | **{:.1}%** | **{}** | Measured |",
159            mc.mode,
160            mc.avg_compression_pct,
161            format_num(mc.total_compressed_tokens),
162        ));
163    }
164
165    out.push(String::new());
166}
167
168fn write_mode_detail(out: &mut Vec<String>, report: &CompareReport) {
169    out.push("## LeanCTX mode observations".to_string());
170    out.push(String::new());
171    out.push("| Mode | Compression | Latency | Quality | Use Case |".to_string());
172    out.push("|------|------------:|--------:|--------:|----------|".to_string());
173
174    for mc in &report.metrics.mode_comparisons {
175        let use_case = match mc.mode.as_str() {
176            "full" => "Editing files (cached, ~13 tok on re-read)",
177            "map" => "Understanding structure, deps, exports",
178            "signatures" => "API surface only",
179            "aggressive" => "Maximum compression for large files",
180            "entropy" => "Information-theoretic filtering",
181            _ => "",
182        };
183        let quality = if mc.avg_quality > 0.0 {
184            format!("{:.0}%", mc.avg_quality * 100.0)
185        } else {
186            "100%".to_string()
187        };
188        out.push(format!(
189            "| {} | {:.1}% | {} | {} | {} |",
190            mc.mode,
191            mc.avg_compression_pct,
192            metrics::format_duration_us(mc.avg_latency_us),
193            quality,
194            use_case,
195        ));
196    }
197
198    out.push(String::new());
199}
200
201fn write_search_latency(out: &mut Vec<String>, report: &CompareReport) {
202    out.push("## Search Latency".to_string());
203    out.push(String::new());
204    out.push("| Query | BM25 Latency | Results |".to_string());
205    out.push("|-------|-------------:|--------:|".to_string());
206
207    for sl in &report.metrics.search_latencies {
208        out.push(format!(
209            "| `{}` | {} | {} |",
210            sl.query,
211            metrics::format_duration_us(sl.bm25_us),
212            sl.result_count,
213        ));
214    }
215
216    let avg = metrics::avg_search_latency_us(&report.metrics.search_latencies);
217    out.push(format!(
218        "| **Average** | **{}** | — |",
219        metrics::format_duration_us(avg)
220    ));
221    out.push(String::new());
222}
223
224fn write_cold_start(out: &mut Vec<String>, report: &CompareReport) {
225    let cs = &report.metrics.cold_start;
226    out.push("## Cold Start Performance".to_string());
227    out.push(String::new());
228    out.push("| Phase | Duration |".to_string());
229    out.push("|-------|--------:|".to_string());
230    out.push(format!(
231        "| File scan | {} |",
232        metrics::format_duration_us(cs.scan_us)
233    ));
234    out.push(format!(
235        "| BM25 index build | {} |",
236        metrics::format_duration_us(cs.bm25_build_us)
237    ));
238    out.push(format!(
239        "| First file read + tokenize | {} |",
240        metrics::format_duration_us(cs.first_read_us)
241    ));
242    out.push(format!(
243        "| **Total cold start** | **{}** |",
244        metrics::format_duration_us(cs.total_us)
245    ));
246    out.push(String::new());
247}
248
249fn write_disk_footprint(out: &mut Vec<String>, report: &CompareReport) {
250    let df = &report.metrics.disk_footprint;
251    out.push("## Disk Footprint".to_string());
252    out.push(String::new());
253    out.push("| Component | Size |".to_string());
254    out.push("|-----------|-----:|".to_string());
255    out.push(format!(
256        "| BM25 index | {} |",
257        metrics::format_bytes(df.bm25_index_bytes)
258    ));
259    out.push(format!(
260        "| Total `.lean-ctx/` | {} |",
261        metrics::format_bytes(df.total_index_bytes)
262    ));
263    out.push(String::new());
264}
265
266fn write_feature_matrix(out: &mut Vec<String>, report: &CompareReport) {
267    out.push("## Feature Comparison".to_string());
268    out.push(String::new());
269    out.push("| Feature | Raw | Repomix | aider | codebase-memory | **lean-ctx** |".to_string());
270    out.push("|---------|:---:|:-------:|:-----:|:---------------:|:------------:|".to_string());
271
272    let features = [
273        ("Multi-mode compression", [false, false, false, false, true]),
274        ("BM25 code search", [false, false, false, true, true]),
275        ("Session caching", [false, false, true, true, true]),
276        (
277            "Cross-session memory (CCP)",
278            [false, false, false, true, true],
279        ),
280        (
281            "Shell output compression",
282            [false, false, false, false, true],
283        ),
284        ("Call graph analysis", [false, false, false, false, true]),
285        ("Repo map generation", [false, true, true, false, true]),
286        ("Knowledge base", [false, false, false, true, true]),
287        (
288            "Tree-sitter AST (27 langs)",
289            [false, true, true, false, true],
290        ),
291        ("MCP server", [false, false, false, true, true]),
292    ];
293
294    for (feature, support) in &features {
295        let cells: Vec<&str> = support
296            .iter()
297            .map(|s| if *s { "✅" } else { "—" })
298            .collect();
299        out.push(format!(
300            "| {} | {} | {} | {} | {} | {} |",
301            feature, cells[0], cells[1], cells[2], cells[3], cells[4]
302        ));
303    }
304
305    out.push(String::new());
306    out.push(format!(
307        "**lean-ctx feature count:** {} operations across {} MCP tools",
308        report.metrics.feature_count,
309        crate::server::registry::tool_count()
310    ));
311    out.push(String::new());
312}
313
314fn write_session_simulation(out: &mut Vec<String>, report: &CompareReport) {
315    let s = &report.metrics.project_benchmark.session_sim;
316    out.push("## Illustrative session simulation (Research)".to_string());
317    out.push(String::new());
318    out.push("| Approach | Tokens | Cost | Savings |".to_string());
319    out.push("|----------|-------:|-----:|--------:|".to_string());
320
321    out.push(format!(
322        "| Raw (no compression) | {} | ${:.3} | — |",
323        format_num(s.raw_tokens),
324        s.raw_cost
325    ));
326
327    let lean_pct = if s.raw_tokens > 0 {
328        (1.0 - s.lean_tokens as f64 / s.raw_tokens as f64) * 100.0
329    } else {
330        0.0
331    };
332    out.push(format!(
333        "| lean-ctx (no CCP) | {} | ${:.3} | {:.1}% |",
334        format_num(s.lean_tokens),
335        s.lean_cost,
336        lean_pct
337    ));
338
339    let ccp_pct = if s.raw_tokens > 0 {
340        (1.0 - s.lean_ccp_tokens as f64 / s.raw_tokens as f64) * 100.0
341    } else {
342        0.0
343    };
344    out.push(format!(
345        "| **lean-ctx + CCP** | **{}** | **${:.3}** | **{:.1}%** |",
346        format_num(s.lean_ccp_tokens),
347        s.ccp_cost,
348        ccp_pct
349    ));
350
351    out.push(String::new());
352}
353
354fn write_chart(out: &mut Vec<String>, report: &CompareReport) {
355    out.push("## Compression Visualization".to_string());
356    out.push(String::new());
357    out.push("```".to_string());
358    out.push("Compression % (higher = better)".to_string());
359    out.push(String::new());
360
361    let mut entries: Vec<(String, f64)> = Vec::new();
362
363    for c in &report.competitors {
364        if let Some(pct) = c.compression_pct {
365            entries.push((c.name.to_string(), pct));
366        }
367    }
368    for mc in &report.metrics.mode_comparisons {
369        if mc.mode != "full" {
370            entries.push((format!("lean-ctx ({})", mc.mode), mc.avg_compression_pct));
371        }
372    }
373
374    entries.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
375
376    let max_bar = 50;
377    for (name, pct) in &entries {
378        let bar_len = (pct / 100.0 * max_bar as f64) as usize;
379        let bar = "\u{2588}".repeat(bar_len);
380        out.push(format!("{name:<28} {bar} {pct:.1}%"));
381    }
382
383    out.push("```".to_string());
384    out.push(String::new());
385}
386
387fn write_system_info(out: &mut Vec<String>, sys: &SystemInfo) {
388    out.push("## System Information".to_string());
389    out.push(String::new());
390    out.push(format!("- **OS:** {} {}", sys.os, sys.arch));
391    out.push(format!(
392        "- **CPU:** {} ({} cores)",
393        sys.cpu_brand, sys.cpu_cores
394    ));
395    out.push(format!("- **RAM:** {:.1} GB", sys.memory_gb));
396    out.push(format!("- **lean-ctx:** v{}", sys.lean_ctx_version));
397    out.push(format!("- **Rust:** {}", sys.rust_version));
398    out.push(String::new());
399}
400
401fn write_reproducibility(out: &mut Vec<String>) {
402    out.push("## Reproducibility".to_string());
403    out.push(String::new());
404    out.push("```bash".to_string());
405    out.push("# Install lean-ctx".to_string());
406    out.push("cargo install lean-ctx".to_string());
407    out.push(String::new());
408    out.push("# Run the Research comparison on this repo".to_string());
409    out.push("lean-ctx benchmark compare".to_string());
410    out.push(String::new());
411    out.push("# Run a local Research comparison on a specific repository".to_string());
412    out.push("lean-ctx benchmark compare --repo /path/to/repo".to_string());
413    out.push(String::new());
414    out.push("# Output to file".to_string());
415    out.push("lean-ctx benchmark compare --output BENCHMARKS.md".to_string());
416    out.push("```".to_string());
417    out.push(String::new());
418}
419
420fn write_footer(out: &mut Vec<String>) {
421    out.push("---".to_string());
422    out.push(String::new());
423    out.push(format!(
424        "*Generated by [lean-ctx](https://leanctx.com) v{} — Context SDK for AI Agents*",
425        env!("CARGO_PKG_VERSION")
426    ));
427    out.push(String::new());
428    out.push("**Status:** Research only. This output does not satisfy the matched workload, declared quality gate, and evidence requirements for a Performance Benchmark claim. Different repositories produce different local observations.".to_string());
429}
430
431fn format_num(n: usize) -> String {
432    if n >= 1_000_000 {
433        format!("{:.1}M", n as f64 / 1_000_000.0)
434    } else if n >= 1_000 {
435        format!("{:.1}K", n as f64 / 1_000.0)
436    } else {
437        format!("{n}")
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use crate::core::benchmark_compare::{competitors, system_info};
445    use std::path::Path;
446
447    fn make_test_report() -> CompareReport {
448        let metrics = metrics::measure_all(Path::new("src"));
449        CompareReport {
450            metrics,
451            system: system_info::collect(),
452            competitors: competitors::all_competitors(),
453        }
454    }
455
456    #[test]
457    fn markdown_contains_all_sections() {
458        let report = make_test_report();
459        let md = generate_markdown(&report);
460
461        assert!(md.contains("# lean-ctx Research-only representation comparison"));
462        assert!(md.contains("## Research methodology and boundary"));
463        assert!(md.contains("## Local representation comparison"));
464        assert!(md.contains("## LeanCTX mode observations"));
465        assert!(md.contains("## Search Latency"));
466        assert!(md.contains("## Cold Start Performance"));
467        assert!(md.contains("## Disk Footprint"));
468        assert!(md.contains("## Feature Comparison"));
469        assert!(md.contains("## Illustrative session simulation (Research)"));
470        assert!(md.contains("## Compression Visualization"));
471        assert!(md.contains("## System Information"));
472        assert!(md.contains("## Reproducibility"));
473        assert!(md.contains("not a public Performance Benchmark"));
474    }
475
476    #[test]
477    fn markdown_contains_competitors() {
478        let report = make_test_report();
479        let md = generate_markdown(&report);
480
481        assert!(md.contains("Repomix"));
482        assert!(md.contains("codebase-memory"));
483        assert!(md.contains("Raw file read"));
484    }
485
486    #[test]
487    fn terminal_output_is_readable() {
488        let report = make_test_report();
489        let term = generate_terminal(&report);
490
491        assert!(term.contains("Research-only representation comparison"));
492        assert!(term.contains("Local representation comparison"));
493        assert!(term.contains("Avg search latency"));
494    }
495
496    #[test]
497    fn format_num_ranges() {
498        assert_eq!(format_num(500), "500");
499        assert_eq!(format_num(1500), "1.5K");
500        assert_eq!(format_num(2_500_000), "2.5M");
501    }
502}